text
stringlengths 54
60.6k
|
---|
<commit_before>/*************************************************************************
*
* Copyright 2016 Realm Inc.
*
* 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 <utility> // pair
#include <realm/array_binary.hpp>
#include <realm/array_blob.hpp>
#include <realm/array_integer.hpp>
#include <realm/impl/destroy_guard.hpp>
using namespace realm;
void ArrayBinary::init_from_mem(MemRef mem) noexcept
{
Array::init_from_mem(mem);
ref_type offsets_ref = get_as_ref(0);
ref_type blob_ref = get_as_ref(1);
m_offsets.init_from_ref(offsets_ref);
m_blob.init_from_ref(blob_ref);
if (!legacy_array_type()) {
ref_type nulls_ref = get_as_ref(2);
m_nulls.init_from_ref(nulls_ref);
}
}
size_t ArrayBinary::read(size_t ndx, size_t pos, char* buffer, size_t max_size) const noexcept
{
REALM_ASSERT_3(ndx, <, m_offsets.size());
if (!legacy_array_type() && m_nulls.get(ndx)) {
return 0;
}
else {
size_t begin_idx = ndx ? to_size_t(m_offsets.get(ndx - 1)) : 0;
size_t end_idx = to_size_t(m_offsets.get(ndx));
size_t sz = end_idx - begin_idx;
size_t size_to_copy = (pos > sz) ? 0 : std::min(max_size, sz - pos);
const char* begin = m_blob.get(begin_idx) + pos;
const char* end = m_blob.get(begin_idx) + pos + size_to_copy;
std::copy_n(begin, end - begin, buffer);
return size_to_copy;
}
}
void ArrayBinary::add(BinaryData value, bool add_zero_term)
{
REALM_ASSERT_7(value.size(), ==, 0, ||, value.data(), !=, 0);
if (value.is_null() && legacy_array_type())
throw LogicError(LogicError::column_not_nullable);
m_blob.add(value.data(), value.size(), add_zero_term);
size_t stored_size = value.size();
if (add_zero_term)
++stored_size;
size_t offset = stored_size;
if (!m_offsets.is_empty())
offset += to_size_t(m_offsets.back());
m_offsets.add(offset);
if (!legacy_array_type())
m_nulls.add(value.is_null());
}
void ArrayBinary::set(size_t ndx, BinaryData value, bool add_zero_term)
{
REALM_ASSERT_3(ndx, <, m_offsets.size());
REALM_ASSERT_3(value.size(), == 0 ||, value.data());
if (value.is_null() && legacy_array_type())
throw LogicError(LogicError::column_not_nullable);
int_fast64_t start = ndx ? m_offsets.get(ndx - 1) : 0;
int_fast64_t current_end = m_offsets.get(ndx);
size_t stored_size = value.size();
if (add_zero_term)
++stored_size;
int_fast64_t diff = (start + stored_size) - current_end;
m_blob.replace(to_size_t(start), to_size_t(current_end), value.data(), value.size(), add_zero_term);
m_offsets.adjust(ndx, m_offsets.size(), diff);
if (!legacy_array_type())
m_nulls.set(ndx, value.is_null());
}
void ArrayBinary::insert(size_t ndx, BinaryData value, bool add_zero_term)
{
REALM_ASSERT_3(ndx, <=, m_offsets.size());
REALM_ASSERT_3(value.size(), == 0 ||, value.data());
if (value.is_null() && legacy_array_type())
throw LogicError(LogicError::column_not_nullable);
size_t pos = ndx ? to_size_t(m_offsets.get(ndx - 1)) : 0;
m_blob.insert(pos, value.data(), value.size(), add_zero_term);
size_t stored_size = value.size();
if (add_zero_term)
++stored_size;
m_offsets.insert(ndx, pos + stored_size);
m_offsets.adjust(ndx + 1, m_offsets.size(), stored_size);
if (!legacy_array_type())
m_nulls.insert(ndx, value.is_null());
}
void ArrayBinary::erase(size_t ndx)
{
REALM_ASSERT_3(ndx, <, m_offsets.size());
size_t start = ndx ? to_size_t(m_offsets.get(ndx - 1)) : 0;
size_t end = to_size_t(m_offsets.get(ndx));
m_blob.erase(start, end);
m_offsets.erase(ndx);
m_offsets.adjust(ndx, m_offsets.size(), int64_t(start) - end);
if (!legacy_array_type())
m_nulls.erase(ndx);
}
BinaryData ArrayBinary::get(const char* header, size_t ndx, Allocator& alloc) noexcept
{
// Column *may* be nullable if top has 3 refs (3'rd being m_nulls). Else, if it has 2, it's non-nullable
// See comment in legacy_array_type() and also in array_binary.hpp.
size_t siz = Array::get_size_from_header(header);
REALM_ASSERT_7(siz, ==, 2, ||, siz, ==, 3);
if (siz == 3) {
std::pair<int64_t, int64_t> p = get_two(header, 1);
const char* nulls_header = alloc.translate(to_ref(p.second));
int64_t n = ArrayInteger::get(nulls_header, ndx);
// 0 or 1 is all that is ever written to m_nulls; any other content would be a bug
REALM_ASSERT_3(n == 1, ||, n == 0);
bool null = (n != 0);
if (null)
return BinaryData{};
}
std::pair<int64_t, int64_t> p = get_two(header, 0);
const char* offsets_header = alloc.translate(to_ref(p.first));
const char* blob_header = alloc.translate(to_ref(p.second));
size_t begin, end;
if (ndx) {
p = get_two(offsets_header, ndx - 1);
begin = to_size_t(p.first);
end = to_size_t(p.second);
}
else {
begin = 0;
end = to_size_t(Array::get(offsets_header, ndx));
}
BinaryData bd = BinaryData(ArrayBlob::get(blob_header, begin), end - begin);
return bd;
}
// FIXME: Not exception safe (leaks are possible).
ref_type ArrayBinary::bptree_leaf_insert(size_t ndx, BinaryData value, bool add_zero_term, TreeInsertBase& state)
{
size_t leaf_size = size();
REALM_ASSERT_3(leaf_size, <=, REALM_MAX_BPNODE_SIZE);
if (leaf_size < ndx)
ndx = leaf_size;
if (REALM_LIKELY(leaf_size < REALM_MAX_BPNODE_SIZE)) {
insert(ndx, value, add_zero_term); // Throws
return 0; // Leaf was not split
}
// Split leaf node
ArrayBinary new_leaf(get_alloc());
new_leaf.create(); // Throws
if (ndx == leaf_size) {
new_leaf.add(value, add_zero_term); // Throws
state.m_split_offset = ndx;
}
else {
for (size_t i = ndx; i != leaf_size; ++i)
new_leaf.add(get(i)); // Throws
truncate(ndx); // Throws
add(value, add_zero_term); // Throws
state.m_split_offset = ndx + 1;
}
state.m_split_size = leaf_size + 1;
return new_leaf.get_ref();
}
MemRef ArrayBinary::create_array(size_t size, Allocator& alloc, BinaryData values)
{
// Only null and zero-length non-null allowed as initialization value
REALM_ASSERT(values.size() == 0);
Array top(alloc);
_impl::DeepArrayDestroyGuard dg(&top);
top.create(type_HasRefs); // Throws
_impl::DeepArrayRefDestroyGuard dg_2(alloc);
{
bool context_flag = false;
int64_t value = 0;
MemRef mem = ArrayInteger::create_array(type_Normal, context_flag, size, value, alloc); // Throws
dg_2.reset(mem.get_ref());
int64_t v = from_ref(mem.get_ref());
top.add(v); // Throws
dg_2.release();
}
{
size_t blobs_size = 0;
MemRef mem = ArrayBlob::create_array(blobs_size, alloc); // Throws
dg_2.reset(mem.get_ref());
int64_t v = from_ref(mem.get_ref());
top.add(v); // Throws
dg_2.release();
}
{
// Always create a m_nulls array, regardless if its column is marked as nullable or not. NOTE: This is new
// - existing binary arrays from earier versions of core will not have this third array. All methods on
// ArrayBinary must thus check if this array exists before trying to access it. If it doesn't, it must be
// interpreted as if its column isn't nullable.
bool context_flag = false;
int64_t value = values.is_null() ? 1 : 0;
MemRef mem = ArrayInteger::create_array(type_Normal, context_flag, size, value, alloc); // Throws
dg_2.reset(mem.get_ref());
int64_t v = from_ref(mem.get_ref());
top.add(v); // Throws
dg_2.release();
}
dg.release();
return top.get_mem();
}
MemRef ArrayBinary::slice(size_t offset, size_t slice_size, Allocator& target_alloc) const
{
REALM_ASSERT(is_attached());
ArrayBinary array_slice(target_alloc);
_impl::ShallowArrayDestroyGuard dg(&array_slice);
array_slice.create(); // Throws
size_t begin = offset;
size_t end = offset + slice_size;
for (size_t i = begin; i != end; ++i) {
BinaryData value = get(i);
array_slice.add(value); // Throws
}
dg.release();
return array_slice.get_mem();
}
#ifdef REALM_DEBUG // LCOV_EXCL_START ignore debug functions
void ArrayBinary::to_dot(std::ostream& out, bool, StringData title) const
{
ref_type ref = get_ref();
out << "subgraph cluster_binary" << ref << " {" << std::endl;
out << " label = \"ArrayBinary";
if (title.size() != 0)
out << "\\n'" << title << "'";
out << "\";" << std::endl;
Array::to_dot(out, "binary_top");
m_offsets.to_dot(out, "offsets");
m_blob.to_dot(out, "blob");
out << "}" << std::endl;
}
#endif // LCOV_EXCL_STOP ignore debug functions
<commit_msg>Simplification<commit_after>/*************************************************************************
*
* Copyright 2016 Realm Inc.
*
* 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 <utility> // pair
#include <realm/array_binary.hpp>
#include <realm/array_blob.hpp>
#include <realm/array_integer.hpp>
#include <realm/impl/destroy_guard.hpp>
using namespace realm;
void ArrayBinary::init_from_mem(MemRef mem) noexcept
{
Array::init_from_mem(mem);
ref_type offsets_ref = get_as_ref(0);
ref_type blob_ref = get_as_ref(1);
m_offsets.init_from_ref(offsets_ref);
m_blob.init_from_ref(blob_ref);
if (!legacy_array_type()) {
ref_type nulls_ref = get_as_ref(2);
m_nulls.init_from_ref(nulls_ref);
}
}
size_t ArrayBinary::read(size_t ndx, size_t pos, char* buffer, size_t max_size) const noexcept
{
REALM_ASSERT_3(ndx, <, m_offsets.size());
if (!legacy_array_type() && m_nulls.get(ndx)) {
return 0;
}
else {
size_t begin_idx = ndx ? to_size_t(m_offsets.get(ndx - 1)) : 0;
size_t end_idx = to_size_t(m_offsets.get(ndx));
size_t sz = end_idx - begin_idx;
size_t size_to_copy = (pos > sz) ? 0 : std::min(max_size, sz - pos);
const char* begin = m_blob.get(begin_idx) + pos;
std::copy_n(begin, size_to_copy, buffer);
return size_to_copy;
}
}
void ArrayBinary::add(BinaryData value, bool add_zero_term)
{
REALM_ASSERT_7(value.size(), ==, 0, ||, value.data(), !=, 0);
if (value.is_null() && legacy_array_type())
throw LogicError(LogicError::column_not_nullable);
m_blob.add(value.data(), value.size(), add_zero_term);
size_t stored_size = value.size();
if (add_zero_term)
++stored_size;
size_t offset = stored_size;
if (!m_offsets.is_empty())
offset += to_size_t(m_offsets.back());
m_offsets.add(offset);
if (!legacy_array_type())
m_nulls.add(value.is_null());
}
void ArrayBinary::set(size_t ndx, BinaryData value, bool add_zero_term)
{
REALM_ASSERT_3(ndx, <, m_offsets.size());
REALM_ASSERT_3(value.size(), == 0 ||, value.data());
if (value.is_null() && legacy_array_type())
throw LogicError(LogicError::column_not_nullable);
int_fast64_t start = ndx ? m_offsets.get(ndx - 1) : 0;
int_fast64_t current_end = m_offsets.get(ndx);
size_t stored_size = value.size();
if (add_zero_term)
++stored_size;
int_fast64_t diff = (start + stored_size) - current_end;
m_blob.replace(to_size_t(start), to_size_t(current_end), value.data(), value.size(), add_zero_term);
m_offsets.adjust(ndx, m_offsets.size(), diff);
if (!legacy_array_type())
m_nulls.set(ndx, value.is_null());
}
void ArrayBinary::insert(size_t ndx, BinaryData value, bool add_zero_term)
{
REALM_ASSERT_3(ndx, <=, m_offsets.size());
REALM_ASSERT_3(value.size(), == 0 ||, value.data());
if (value.is_null() && legacy_array_type())
throw LogicError(LogicError::column_not_nullable);
size_t pos = ndx ? to_size_t(m_offsets.get(ndx - 1)) : 0;
m_blob.insert(pos, value.data(), value.size(), add_zero_term);
size_t stored_size = value.size();
if (add_zero_term)
++stored_size;
m_offsets.insert(ndx, pos + stored_size);
m_offsets.adjust(ndx + 1, m_offsets.size(), stored_size);
if (!legacy_array_type())
m_nulls.insert(ndx, value.is_null());
}
void ArrayBinary::erase(size_t ndx)
{
REALM_ASSERT_3(ndx, <, m_offsets.size());
size_t start = ndx ? to_size_t(m_offsets.get(ndx - 1)) : 0;
size_t end = to_size_t(m_offsets.get(ndx));
m_blob.erase(start, end);
m_offsets.erase(ndx);
m_offsets.adjust(ndx, m_offsets.size(), int64_t(start) - end);
if (!legacy_array_type())
m_nulls.erase(ndx);
}
BinaryData ArrayBinary::get(const char* header, size_t ndx, Allocator& alloc) noexcept
{
// Column *may* be nullable if top has 3 refs (3'rd being m_nulls). Else, if it has 2, it's non-nullable
// See comment in legacy_array_type() and also in array_binary.hpp.
size_t siz = Array::get_size_from_header(header);
REALM_ASSERT_7(siz, ==, 2, ||, siz, ==, 3);
if (siz == 3) {
std::pair<int64_t, int64_t> p = get_two(header, 1);
const char* nulls_header = alloc.translate(to_ref(p.second));
int64_t n = ArrayInteger::get(nulls_header, ndx);
// 0 or 1 is all that is ever written to m_nulls; any other content would be a bug
REALM_ASSERT_3(n == 1, ||, n == 0);
bool null = (n != 0);
if (null)
return BinaryData{};
}
std::pair<int64_t, int64_t> p = get_two(header, 0);
const char* offsets_header = alloc.translate(to_ref(p.first));
const char* blob_header = alloc.translate(to_ref(p.second));
size_t begin, end;
if (ndx) {
p = get_two(offsets_header, ndx - 1);
begin = to_size_t(p.first);
end = to_size_t(p.second);
}
else {
begin = 0;
end = to_size_t(Array::get(offsets_header, ndx));
}
BinaryData bd = BinaryData(ArrayBlob::get(blob_header, begin), end - begin);
return bd;
}
// FIXME: Not exception safe (leaks are possible).
ref_type ArrayBinary::bptree_leaf_insert(size_t ndx, BinaryData value, bool add_zero_term, TreeInsertBase& state)
{
size_t leaf_size = size();
REALM_ASSERT_3(leaf_size, <=, REALM_MAX_BPNODE_SIZE);
if (leaf_size < ndx)
ndx = leaf_size;
if (REALM_LIKELY(leaf_size < REALM_MAX_BPNODE_SIZE)) {
insert(ndx, value, add_zero_term); // Throws
return 0; // Leaf was not split
}
// Split leaf node
ArrayBinary new_leaf(get_alloc());
new_leaf.create(); // Throws
if (ndx == leaf_size) {
new_leaf.add(value, add_zero_term); // Throws
state.m_split_offset = ndx;
}
else {
for (size_t i = ndx; i != leaf_size; ++i)
new_leaf.add(get(i)); // Throws
truncate(ndx); // Throws
add(value, add_zero_term); // Throws
state.m_split_offset = ndx + 1;
}
state.m_split_size = leaf_size + 1;
return new_leaf.get_ref();
}
MemRef ArrayBinary::create_array(size_t size, Allocator& alloc, BinaryData values)
{
// Only null and zero-length non-null allowed as initialization value
REALM_ASSERT(values.size() == 0);
Array top(alloc);
_impl::DeepArrayDestroyGuard dg(&top);
top.create(type_HasRefs); // Throws
_impl::DeepArrayRefDestroyGuard dg_2(alloc);
{
bool context_flag = false;
int64_t value = 0;
MemRef mem = ArrayInteger::create_array(type_Normal, context_flag, size, value, alloc); // Throws
dg_2.reset(mem.get_ref());
int64_t v = from_ref(mem.get_ref());
top.add(v); // Throws
dg_2.release();
}
{
size_t blobs_size = 0;
MemRef mem = ArrayBlob::create_array(blobs_size, alloc); // Throws
dg_2.reset(mem.get_ref());
int64_t v = from_ref(mem.get_ref());
top.add(v); // Throws
dg_2.release();
}
{
// Always create a m_nulls array, regardless if its column is marked as nullable or not. NOTE: This is new
// - existing binary arrays from earier versions of core will not have this third array. All methods on
// ArrayBinary must thus check if this array exists before trying to access it. If it doesn't, it must be
// interpreted as if its column isn't nullable.
bool context_flag = false;
int64_t value = values.is_null() ? 1 : 0;
MemRef mem = ArrayInteger::create_array(type_Normal, context_flag, size, value, alloc); // Throws
dg_2.reset(mem.get_ref());
int64_t v = from_ref(mem.get_ref());
top.add(v); // Throws
dg_2.release();
}
dg.release();
return top.get_mem();
}
MemRef ArrayBinary::slice(size_t offset, size_t slice_size, Allocator& target_alloc) const
{
REALM_ASSERT(is_attached());
ArrayBinary array_slice(target_alloc);
_impl::ShallowArrayDestroyGuard dg(&array_slice);
array_slice.create(); // Throws
size_t begin = offset;
size_t end = offset + slice_size;
for (size_t i = begin; i != end; ++i) {
BinaryData value = get(i);
array_slice.add(value); // Throws
}
dg.release();
return array_slice.get_mem();
}
#ifdef REALM_DEBUG // LCOV_EXCL_START ignore debug functions
void ArrayBinary::to_dot(std::ostream& out, bool, StringData title) const
{
ref_type ref = get_ref();
out << "subgraph cluster_binary" << ref << " {" << std::endl;
out << " label = \"ArrayBinary";
if (title.size() != 0)
out << "\\n'" << title << "'";
out << "\";" << std::endl;
Array::to_dot(out, "binary_top");
m_offsets.to_dot(out, "offsets");
m_blob.to_dot(out, "blob");
out << "}" << std::endl;
}
#endif // LCOV_EXCL_STOP ignore debug functions
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qdebug.h>
#include "qcups_p.h"
#ifndef QT_NO_CUPS
#ifndef QT_LINUXBASE // LSB merges everything into cups.h
# include <cups/language.h>
#endif
#include <qtextcodec.h>
QT_BEGIN_NAMESPACE
typedef int (*CupsGetDests)(cups_dest_t **dests);
typedef void (*CupsFreeDests)(int num_dests, cups_dest_t *dests);
typedef const char* (*CupsGetPPD)(const char *printer);
typedef int (*CupsMarkOptions)(ppd_file_t *ppd, int num_options, cups_option_t *options);
typedef ppd_file_t* (*PPDOpenFile)(const char *filename);
typedef void (*PPDMarkDefaults)(ppd_file_t *ppd);
typedef int (*PPDMarkOption)(ppd_file_t *ppd, const char *keyword, const char *option);
typedef void (*PPDClose)(ppd_file_t *ppd);
typedef int (*PPDMarkOption)(ppd_file_t *ppd, const char *keyword, const char *option);
typedef void (*CupsFreeOptions)(int num_options, cups_option_t *options);
typedef void (*CupsSetDests)(int num_dests, cups_dest_t *dests);
typedef cups_lang_t* (*CupsLangGet)(const char *language);
typedef const char* (*CupsLangEncoding)(cups_lang_t *language);
typedef int (*CupsAddOption)(const char *name, const char *value, int num_options, cups_option_t **options);
typedef int (*CupsTempFd)(char *name, int len);
typedef int (*CupsPrintFile)(const char * name, const char * filename, const char * title, int num_options, cups_option_t * options);
static bool cupsLoaded = false;
static int qt_cups_num_printers = 0;
static CupsGetDests _cupsGetDests = 0;
static CupsFreeDests _cupsFreeDests = 0;
static CupsGetPPD _cupsGetPPD = 0;
static PPDOpenFile _ppdOpenFile = 0;
static PPDMarkDefaults _ppdMarkDefaults = 0;
static PPDClose _ppdClose = 0;
static CupsMarkOptions _cupsMarkOptions = 0;
static PPDMarkOption _ppdMarkOption = 0;
static CupsFreeOptions _cupsFreeOptions = 0;
static CupsSetDests _cupsSetDests = 0;
static CupsLangGet _cupsLangGet = 0;
static CupsLangEncoding _cupsLangEncoding = 0;
static CupsAddOption _cupsAddOption = 0;
static CupsTempFd _cupsTempFd = 0;
static CupsPrintFile _cupsPrintFile = 0;
static void resolveCups()
{
QLibrary cupsLib(QLatin1String("cups"), 2);
if(cupsLib.load()) {
_cupsGetDests = (CupsGetDests) cupsLib.resolve("cupsGetDests");
_cupsFreeDests = (CupsFreeDests) cupsLib.resolve("cupsFreeDests");
_cupsGetPPD = (CupsGetPPD) cupsLib.resolve("cupsGetPPD");
_cupsLangGet = (CupsLangGet) cupsLib.resolve("cupsLangGet");
_cupsLangEncoding = (CupsLangEncoding) cupsLib.resolve("cupsLangEncoding");
_ppdOpenFile = (PPDOpenFile) cupsLib.resolve("ppdOpenFile");
_ppdMarkDefaults = (PPDMarkDefaults) cupsLib.resolve("ppdMarkDefaults");
_ppdClose = (PPDClose) cupsLib.resolve("ppdClose");
_cupsMarkOptions = (CupsMarkOptions) cupsLib.resolve("cupsMarkOptions");
_ppdMarkOption = (PPDMarkOption) cupsLib.resolve("ppdMarkOption");
_cupsFreeOptions = (CupsFreeOptions) cupsLib.resolve("cupsFreeOptions");
_cupsSetDests = (CupsSetDests) cupsLib.resolve("cupsSetDests");
_cupsAddOption = (CupsAddOption) cupsLib.resolve("cupsAddOption");
_cupsTempFd = (CupsTempFd) cupsLib.resolve("cupsTempFd");
_cupsPrintFile = (CupsPrintFile) cupsLib.resolve("cupsPrintFile");
if (_cupsGetDests && _cupsFreeDests) {
cups_dest_t *printers;
int num_printers = _cupsGetDests(&printers);
if (num_printers)
_cupsFreeDests(num_printers, printers);
qt_cups_num_printers = num_printers;
}
}
cupsLoaded = true;
}
// ================ CUPS Support class ========================
QCUPSSupport::QCUPSSupport()
:
prnCount(0),
printers(0),
page_sizes(0),
currPrinterIndex(0),
currPPD(0)
{
if (!cupsLoaded)
resolveCups();
// getting all available printers
if (!isAvailable())
return;
prnCount = _cupsGetDests(&printers);
for (int i = 0; i < prnCount; ++i) {
if (printers[i].is_default) {
currPrinterIndex = i;
setCurrentPrinter(i);
break;
}
}
#ifndef QT_NO_TEXTCODEC
cups_lang_t *cupsLang = _cupsLangGet(0);
codec = QTextCodec::codecForName(_cupsLangEncoding(cupsLang));
if (!codec)
codec = QTextCodec::codecForLocale();
#endif
}
QCUPSSupport::~QCUPSSupport()
{
if (currPPD)
_ppdClose(currPPD);
if (prnCount)
_cupsFreeDests(prnCount, printers);
}
int QCUPSSupport::availablePrintersCount() const
{
return prnCount;
}
const cups_dest_t* QCUPSSupport::availablePrinters() const
{
return printers;
}
const ppd_file_t* QCUPSSupport::currentPPD() const
{
return currPPD;
}
const ppd_file_t* QCUPSSupport::setCurrentPrinter(int index)
{
Q_ASSERT(index >= 0 && index <= prnCount);
if (index == prnCount)
return 0;
currPrinterIndex = index;
if (currPPD)
_ppdClose(currPPD);
currPPD = 0;
page_sizes = 0;
const char *ppdFile = _cupsGetPPD(printers[index].name);
if (!ppdFile)
return 0;
currPPD = _ppdOpenFile(ppdFile);
unlink(ppdFile);
// marking default options
_ppdMarkDefaults(currPPD);
// marking options explicitly set
_cupsMarkOptions(currPPD, printers[currPrinterIndex].num_options, printers[currPrinterIndex].options);
// getting pointer to page sizes
page_sizes = ppdOption("PageSize");
return currPPD;
}
int QCUPSSupport::currentPrinterIndex() const
{
return currPrinterIndex;
}
bool QCUPSSupport::isAvailable()
{
if(!cupsLoaded)
resolveCups();
return _cupsGetDests &&
_cupsFreeDests &&
_cupsGetPPD &&
_ppdOpenFile &&
_ppdMarkDefaults &&
_ppdClose &&
_cupsMarkOptions &&
_ppdMarkOption &&
_cupsFreeOptions &&
_cupsSetDests &&
_cupsLangGet &&
_cupsLangEncoding &&
_cupsAddOption &&
(qt_cups_num_printers > 0);
}
const ppd_option_t* QCUPSSupport::ppdOption(const char *key) const
{
if (currPPD) {
for (int gr = 0; gr < currPPD->num_groups; ++gr) {
for (int opt = 0; opt < currPPD->groups[gr].num_options; ++opt) {
if (qstrcmp(currPPD->groups[gr].options[opt].keyword, key) == 0)
return &currPPD->groups[gr].options[opt];
}
}
}
return 0;
}
const cups_option_t* QCUPSSupport::printerOption(const QString &key) const
{
for (int i = 0; i < printers[currPrinterIndex].num_options; ++i) {
if (QLatin1String(printers[currPrinterIndex].options[i].name) == key)
return &printers[currPrinterIndex].options[i];
}
return 0;
}
const ppd_option_t* QCUPSSupport::pageSizes() const
{
return page_sizes;
}
int QCUPSSupport::markOption(const char* name, const char* value)
{
return _ppdMarkOption(currPPD, name, value);
}
void QCUPSSupport::saveOptions(QList<const ppd_option_t*> options, QList<const char*> markedOptions)
{
int oldOptionCount = printers[currPrinterIndex].num_options;
cups_option_t* oldOptions = printers[currPrinterIndex].options;
int newOptionCount = 0;
cups_option_t* newOptions = 0;
// copying old options that are not on the new list
for (int i = 0; i < oldOptionCount; ++i) {
bool contains = false;
for (int j = 0; j < options.count(); ++j) {
if (qstrcmp(options.at(j)->keyword, oldOptions[i].name) == 0) {
contains = true;
break;
}
}
if (!contains) {
newOptionCount = _cupsAddOption(oldOptions[i].name, oldOptions[i].value, newOptionCount, &newOptions);
}
}
// we can release old option list
_cupsFreeOptions(oldOptionCount, oldOptions);
// adding marked options
for (int i = 0; i < markedOptions.count(); ++i) {
const char* name = markedOptions.at(i);
++i;
newOptionCount = _cupsAddOption(name, markedOptions.at(i), newOptionCount, &newOptions);
}
// placing the new option list
printers[currPrinterIndex].num_options = newOptionCount;
printers[currPrinterIndex].options = newOptions;
// saving new default values
_cupsSetDests(prnCount, printers);
}
QRect QCUPSSupport::paperRect(const char *choice) const
{
if (!currPPD)
return QRect();
for (int i = 0; i < currPPD->num_sizes; ++i) {
if (qstrcmp(currPPD->sizes[i].name, choice) == 0)
return QRect(0, 0, qRound(currPPD->sizes[i].width), qRound(currPPD->sizes[i].length));
}
return QRect();
}
QRect QCUPSSupport::pageRect(const char *choice) const
{
if (!currPPD)
return QRect();
for (int i = 0; i < currPPD->num_sizes; ++i) {
if (qstrcmp(currPPD->sizes[i].name, choice) == 0)
return QRect(qRound(currPPD->sizes[i].left),
qRound(currPPD->sizes[i].length - currPPD->sizes[i].top),
qRound(currPPD->sizes[i].right - currPPD->sizes[i].left),
qRound(currPPD->sizes[i].top - currPPD->sizes[i].bottom));
}
return QRect();
}
QStringList QCUPSSupport::options() const
{
QStringList list;
collectMarkedOptions(list);
return list;
}
bool QCUPSSupport::printerHasPPD(const char *printerName)
{
if (!isAvailable())
return false;
const char *ppdFile = _cupsGetPPD(printerName);
unlink(ppdFile);
return (ppdFile != 0);
}
QString QCUPSSupport::unicodeString(const char *s)
{
#ifndef QT_NO_TEXTCODEC
return codec->toUnicode(s);
#else
return QLatin1String(s);
#endif
}
void QCUPSSupport::collectMarkedOptions(QStringList& list, const ppd_group_t* group) const
{
if (group == 0) {
if (!currPPD)
return;
for (int i = 0; i < currPPD->num_groups; ++i) {
collectMarkedOptions(list, &currPPD->groups[i]);
collectMarkedOptionsHelper(list, &currPPD->groups[i]);
}
} else {
for (int i = 0; i < group->num_subgroups; ++i)
collectMarkedOptionsHelper(list, &group->subgroups[i]);
}
}
void QCUPSSupport::collectMarkedOptionsHelper(QStringList& list, const ppd_group_t* group) const
{
for (int i = 0; i < group->num_options; ++i) {
for (int j = 0; j < group->options[i].num_choices; ++j) {
if (group->options[i].choices[j].marked == 1 && qstrcmp(group->options[i].choices[j].choice, group->options[i].defchoice) != 0)
list << QString::fromLocal8Bit(group->options[i].keyword) << QString::fromLocal8Bit(group->options[i].choices[j].choice);
}
}
}
QPair<int, QString> QCUPSSupport::tempFd()
{
char filename[512];
int fd = _cupsTempFd(filename, 512);
return QPair<int, QString>(fd, QString::fromLocal8Bit(filename));
}
// Prints the given file and returns a job id.
int QCUPSSupport::printFile(const char * printerName, const char * filename, const char * title,
int num_options, cups_option_t * options)
{
return _cupsPrintFile(printerName, filename, title, num_options, options);
}
QT_END_NAMESPACE
#endif // QT_NO_CUPS
<commit_msg>Removed a Valgrind warning.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qdebug.h>
#include "qcups_p.h"
#ifndef QT_NO_CUPS
#ifndef QT_LINUXBASE // LSB merges everything into cups.h
# include <cups/language.h>
#endif
#include <qtextcodec.h>
QT_BEGIN_NAMESPACE
typedef int (*CupsGetDests)(cups_dest_t **dests);
typedef void (*CupsFreeDests)(int num_dests, cups_dest_t *dests);
typedef const char* (*CupsGetPPD)(const char *printer);
typedef int (*CupsMarkOptions)(ppd_file_t *ppd, int num_options, cups_option_t *options);
typedef ppd_file_t* (*PPDOpenFile)(const char *filename);
typedef void (*PPDMarkDefaults)(ppd_file_t *ppd);
typedef int (*PPDMarkOption)(ppd_file_t *ppd, const char *keyword, const char *option);
typedef void (*PPDClose)(ppd_file_t *ppd);
typedef int (*PPDMarkOption)(ppd_file_t *ppd, const char *keyword, const char *option);
typedef void (*CupsFreeOptions)(int num_options, cups_option_t *options);
typedef void (*CupsSetDests)(int num_dests, cups_dest_t *dests);
typedef cups_lang_t* (*CupsLangGet)(const char *language);
typedef const char* (*CupsLangEncoding)(cups_lang_t *language);
typedef int (*CupsAddOption)(const char *name, const char *value, int num_options, cups_option_t **options);
typedef int (*CupsTempFd)(char *name, int len);
typedef int (*CupsPrintFile)(const char * name, const char * filename, const char * title, int num_options, cups_option_t * options);
static bool cupsLoaded = false;
static int qt_cups_num_printers = 0;
static CupsGetDests _cupsGetDests = 0;
static CupsFreeDests _cupsFreeDests = 0;
static CupsGetPPD _cupsGetPPD = 0;
static PPDOpenFile _ppdOpenFile = 0;
static PPDMarkDefaults _ppdMarkDefaults = 0;
static PPDClose _ppdClose = 0;
static CupsMarkOptions _cupsMarkOptions = 0;
static PPDMarkOption _ppdMarkOption = 0;
static CupsFreeOptions _cupsFreeOptions = 0;
static CupsSetDests _cupsSetDests = 0;
static CupsLangGet _cupsLangGet = 0;
static CupsLangEncoding _cupsLangEncoding = 0;
static CupsAddOption _cupsAddOption = 0;
static CupsTempFd _cupsTempFd = 0;
static CupsPrintFile _cupsPrintFile = 0;
static void resolveCups()
{
QLibrary cupsLib(QLatin1String("cups"), 2);
if(cupsLib.load()) {
_cupsGetDests = (CupsGetDests) cupsLib.resolve("cupsGetDests");
_cupsFreeDests = (CupsFreeDests) cupsLib.resolve("cupsFreeDests");
_cupsGetPPD = (CupsGetPPD) cupsLib.resolve("cupsGetPPD");
_cupsLangGet = (CupsLangGet) cupsLib.resolve("cupsLangGet");
_cupsLangEncoding = (CupsLangEncoding) cupsLib.resolve("cupsLangEncoding");
_ppdOpenFile = (PPDOpenFile) cupsLib.resolve("ppdOpenFile");
_ppdMarkDefaults = (PPDMarkDefaults) cupsLib.resolve("ppdMarkDefaults");
_ppdClose = (PPDClose) cupsLib.resolve("ppdClose");
_cupsMarkOptions = (CupsMarkOptions) cupsLib.resolve("cupsMarkOptions");
_ppdMarkOption = (PPDMarkOption) cupsLib.resolve("ppdMarkOption");
_cupsFreeOptions = (CupsFreeOptions) cupsLib.resolve("cupsFreeOptions");
_cupsSetDests = (CupsSetDests) cupsLib.resolve("cupsSetDests");
_cupsAddOption = (CupsAddOption) cupsLib.resolve("cupsAddOption");
_cupsTempFd = (CupsTempFd) cupsLib.resolve("cupsTempFd");
_cupsPrintFile = (CupsPrintFile) cupsLib.resolve("cupsPrintFile");
if (_cupsGetDests && _cupsFreeDests) {
cups_dest_t *printers;
int num_printers = _cupsGetDests(&printers);
if (num_printers)
_cupsFreeDests(num_printers, printers);
qt_cups_num_printers = num_printers;
}
}
cupsLoaded = true;
}
// ================ CUPS Support class ========================
QCUPSSupport::QCUPSSupport()
:
prnCount(0),
printers(0),
page_sizes(0),
currPrinterIndex(0),
currPPD(0)
{
if (!cupsLoaded)
resolveCups();
// getting all available printers
if (!isAvailable())
return;
prnCount = _cupsGetDests(&printers);
for (int i = 0; i < prnCount; ++i) {
if (printers[i].is_default) {
currPrinterIndex = i;
setCurrentPrinter(i);
break;
}
}
#ifndef QT_NO_TEXTCODEC
cups_lang_t *cupsLang = _cupsLangGet(0);
codec = QTextCodec::codecForName(_cupsLangEncoding(cupsLang));
if (!codec)
codec = QTextCodec::codecForLocale();
#endif
}
QCUPSSupport::~QCUPSSupport()
{
if (currPPD)
_ppdClose(currPPD);
if (prnCount)
_cupsFreeDests(prnCount, printers);
}
int QCUPSSupport::availablePrintersCount() const
{
return prnCount;
}
const cups_dest_t* QCUPSSupport::availablePrinters() const
{
return printers;
}
const ppd_file_t* QCUPSSupport::currentPPD() const
{
return currPPD;
}
const ppd_file_t* QCUPSSupport::setCurrentPrinter(int index)
{
Q_ASSERT(index >= 0 && index <= prnCount);
if (index == prnCount)
return 0;
currPrinterIndex = index;
if (currPPD)
_ppdClose(currPPD);
currPPD = 0;
page_sizes = 0;
const char *ppdFile = _cupsGetPPD(printers[index].name);
if (!ppdFile)
return 0;
currPPD = _ppdOpenFile(ppdFile);
unlink(ppdFile);
// marking default options
_ppdMarkDefaults(currPPD);
// marking options explicitly set
_cupsMarkOptions(currPPD, printers[currPrinterIndex].num_options, printers[currPrinterIndex].options);
// getting pointer to page sizes
page_sizes = ppdOption("PageSize");
return currPPD;
}
int QCUPSSupport::currentPrinterIndex() const
{
return currPrinterIndex;
}
bool QCUPSSupport::isAvailable()
{
if(!cupsLoaded)
resolveCups();
return _cupsGetDests &&
_cupsFreeDests &&
_cupsGetPPD &&
_ppdOpenFile &&
_ppdMarkDefaults &&
_ppdClose &&
_cupsMarkOptions &&
_ppdMarkOption &&
_cupsFreeOptions &&
_cupsSetDests &&
_cupsLangGet &&
_cupsLangEncoding &&
_cupsAddOption &&
(qt_cups_num_printers > 0);
}
const ppd_option_t* QCUPSSupport::ppdOption(const char *key) const
{
if (currPPD) {
for (int gr = 0; gr < currPPD->num_groups; ++gr) {
for (int opt = 0; opt < currPPD->groups[gr].num_options; ++opt) {
if (qstrcmp(currPPD->groups[gr].options[opt].keyword, key) == 0)
return &currPPD->groups[gr].options[opt];
}
}
}
return 0;
}
const cups_option_t* QCUPSSupport::printerOption(const QString &key) const
{
for (int i = 0; i < printers[currPrinterIndex].num_options; ++i) {
if (QLatin1String(printers[currPrinterIndex].options[i].name) == key)
return &printers[currPrinterIndex].options[i];
}
return 0;
}
const ppd_option_t* QCUPSSupport::pageSizes() const
{
return page_sizes;
}
int QCUPSSupport::markOption(const char* name, const char* value)
{
return _ppdMarkOption(currPPD, name, value);
}
void QCUPSSupport::saveOptions(QList<const ppd_option_t*> options, QList<const char*> markedOptions)
{
int oldOptionCount = printers[currPrinterIndex].num_options;
cups_option_t* oldOptions = printers[currPrinterIndex].options;
int newOptionCount = 0;
cups_option_t* newOptions = 0;
// copying old options that are not on the new list
for (int i = 0; i < oldOptionCount; ++i) {
bool contains = false;
for (int j = 0; j < options.count(); ++j) {
if (qstrcmp(options.at(j)->keyword, oldOptions[i].name) == 0) {
contains = true;
break;
}
}
if (!contains) {
newOptionCount = _cupsAddOption(oldOptions[i].name, oldOptions[i].value, newOptionCount, &newOptions);
}
}
// we can release old option list
_cupsFreeOptions(oldOptionCount, oldOptions);
// adding marked options
for (int i = 0; i < markedOptions.count(); ++i) {
const char* name = markedOptions.at(i);
++i;
newOptionCount = _cupsAddOption(name, markedOptions.at(i), newOptionCount, &newOptions);
}
// placing the new option list
printers[currPrinterIndex].num_options = newOptionCount;
printers[currPrinterIndex].options = newOptions;
// saving new default values
_cupsSetDests(prnCount, printers);
}
QRect QCUPSSupport::paperRect(const char *choice) const
{
if (!currPPD)
return QRect();
for (int i = 0; i < currPPD->num_sizes; ++i) {
if (qstrcmp(currPPD->sizes[i].name, choice) == 0)
return QRect(0, 0, qRound(currPPD->sizes[i].width), qRound(currPPD->sizes[i].length));
}
return QRect();
}
QRect QCUPSSupport::pageRect(const char *choice) const
{
if (!currPPD)
return QRect();
for (int i = 0; i < currPPD->num_sizes; ++i) {
if (qstrcmp(currPPD->sizes[i].name, choice) == 0)
return QRect(qRound(currPPD->sizes[i].left),
qRound(currPPD->sizes[i].length - currPPD->sizes[i].top),
qRound(currPPD->sizes[i].right - currPPD->sizes[i].left),
qRound(currPPD->sizes[i].top - currPPD->sizes[i].bottom));
}
return QRect();
}
QStringList QCUPSSupport::options() const
{
QStringList list;
collectMarkedOptions(list);
return list;
}
bool QCUPSSupport::printerHasPPD(const char *printerName)
{
if (!isAvailable())
return false;
const char *ppdFile = _cupsGetPPD(printerName);
if (ppdFile)
unlink(ppdFile);
return (ppdFile != 0);
}
QString QCUPSSupport::unicodeString(const char *s)
{
#ifndef QT_NO_TEXTCODEC
return codec->toUnicode(s);
#else
return QLatin1String(s);
#endif
}
void QCUPSSupport::collectMarkedOptions(QStringList& list, const ppd_group_t* group) const
{
if (group == 0) {
if (!currPPD)
return;
for (int i = 0; i < currPPD->num_groups; ++i) {
collectMarkedOptions(list, &currPPD->groups[i]);
collectMarkedOptionsHelper(list, &currPPD->groups[i]);
}
} else {
for (int i = 0; i < group->num_subgroups; ++i)
collectMarkedOptionsHelper(list, &group->subgroups[i]);
}
}
void QCUPSSupport::collectMarkedOptionsHelper(QStringList& list, const ppd_group_t* group) const
{
for (int i = 0; i < group->num_options; ++i) {
for (int j = 0; j < group->options[i].num_choices; ++j) {
if (group->options[i].choices[j].marked == 1 && qstrcmp(group->options[i].choices[j].choice, group->options[i].defchoice) != 0)
list << QString::fromLocal8Bit(group->options[i].keyword) << QString::fromLocal8Bit(group->options[i].choices[j].choice);
}
}
}
QPair<int, QString> QCUPSSupport::tempFd()
{
char filename[512];
int fd = _cupsTempFd(filename, 512);
return QPair<int, QString>(fd, QString::fromLocal8Bit(filename));
}
// Prints the given file and returns a job id.
int QCUPSSupport::printFile(const char * printerName, const char * filename, const char * title,
int num_options, cups_option_t * options)
{
return _cupsPrintFile(printerName, filename, title, num_options, options);
}
QT_END_NAMESPACE
#endif // QT_NO_CUPS
<|endoftext|> |
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#define SUITE format
#include "vast/format/mrt.hpp"
#include "vast/test/test.hpp"
#include "vast/test/data.hpp"
#include "vast/concept/parseable/to.hpp"
#include "vast/detail/make_io_stream.hpp"
#include "vast/filesystem.hpp"
using namespace vast;
TEST(MRT) {
auto in = detail::make_input_stream(mrt::updates20150505, false);
format::mrt::reader reader{std::move(*in)};
auto result = expected<event>{no_error};
std::vector<event> events;
while (result || !result.error()) {
result = reader.read();
if (result)
events.push_back(std::move(*result));
}
REQUIRE(!result);
CHECK_EQUAL(result.error(), ec::end_of_input);
REQUIRE(!events.empty());
CHECK_EQUAL(events.size(), 26479u);
REQUIRE(events.size() == 26479u);
// Event 2
CHECK_EQUAL(events[2].type().name(), "mrt::bgp4mp::update::announcement");
auto record = caf::get_if<vector>(&events[2].data());
REQUIRE(record);
auto addr = caf::get_if<address>(&record->at(0));
CHECK_EQUAL(*addr, unbox(to<address>("12.0.1.63")));
CHECK_EQUAL(record->at(1), count{7018});
auto subn = caf::get_if<subnet>(&record->at(2));
CHECK_EQUAL(*subn, unbox(to<subnet>("200.29.24.0/24")));
// Event 17
CHECK_EQUAL(events[17].type().name(), "mrt::bgp4mp::update::withdrawn");
record = caf::get_if<vector>(&events[17].data());
REQUIRE(record);
addr = caf::get_if<address>(&record->at(0));
CHECK_EQUAL(*addr, unbox(to<address>("12.0.1.63")));
CHECK_EQUAL(record->at(1), count{7018});
subn = caf::get_if<subnet>(&record->at(2));
CHECK_EQUAL(*subn, unbox(to<subnet>("200.29.24.0/24")));
// Event 73
CHECK_EQUAL(events[73].type().name(), "mrt::bgp4mp::state_change");
record = caf::get_if<vector>(&events[73].data());
REQUIRE(record);
addr = caf::get_if<address>(&record->at(0));
CHECK_EQUAL(*addr, unbox(to<address>("111.91.233.1")));
CHECK_EQUAL(record->at(1), count{45896});
CHECK_EQUAL(record->at(2), count{3});
CHECK_EQUAL(record->at(3), count{2});
// Event 26478
CHECK_EQUAL(events[26478].type().name(), "mrt::bgp4mp::update::announcement");
record = caf::get_if<vector>(&events[26478].data());
REQUIRE(record);
addr = caf::get_if<address>(&record->at(0));
CHECK_EQUAL(*addr, unbox(to<address>("2a01:2a8::3")));
subn = caf::get_if<subnet>(&record->at(2));
CHECK_EQUAL(*subn, unbox(to<subnet>("2a00:bdc0:e003::/48")));
auto as_path = caf::get_if<vector>(&record->at(3));
CHECK_EQUAL(as_path->size(), 4u);
CHECK_EQUAL(as_path->at(0), count{1836});
CHECK_EQUAL(as_path->at(1), count{6939});
CHECK_EQUAL(as_path->at(2), count{47541});
CHECK_EQUAL(as_path->at(3), count{28709});
}
<commit_msg>Make judicious use of unbox<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#define SUITE format
#include "vast/format/mrt.hpp"
#include "vast/test/test.hpp"
#include "vast/test/data.hpp"
#include "vast/concept/parseable/to.hpp"
#include "vast/detail/make_io_stream.hpp"
#include "vast/filesystem.hpp"
using namespace vast;
TEST(MRT) {
auto in = detail::make_input_stream(mrt::updates20150505, false);
format::mrt::reader reader{std::move(*in)};
auto result = expected<event>{no_error};
std::vector<event> events;
while (result || !result.error()) {
result = reader.read();
if (result)
events.push_back(std::move(*result));
}
REQUIRE(!result);
CHECK_EQUAL(result.error(), ec::end_of_input);
REQUIRE(!events.empty());
REQUIRE_EQUAL(events.size(), 26479u);
// Event 2
CHECK_EQUAL(events[2].type().name(), "mrt::bgp4mp::update::announcement");
auto xs = unbox(caf::get_if<vector>(&events[2].data()));
auto addr = unbox(caf::get_if<address>(&xs.at(0)));
CHECK_EQUAL(addr, unbox(to<address>("12.0.1.63")));
CHECK_EQUAL(xs.at(1), count{7018});
auto sn = unbox(caf::get_if<subnet>(&xs.at(2)));
CHECK_EQUAL(sn, unbox(to<subnet>("200.29.24.0/24")));
// Event 17
CHECK_EQUAL(events[17].type().name(), "mrt::bgp4mp::update::withdrawn");
xs = unbox(caf::get_if<vector>(&events[17].data()));
addr = unbox(caf::get_if<address>(&xs.at(0)));
CHECK_EQUAL(addr, unbox(to<address>("12.0.1.63")));
CHECK_EQUAL(xs.at(1), count{7018});
sn = unbox(caf::get_if<subnet>(&xs.at(2)));
CHECK_EQUAL(sn, unbox(to<subnet>("200.29.24.0/24")));
// Event 73
CHECK_EQUAL(events[73].type().name(), "mrt::bgp4mp::state_change");
xs = unbox(caf::get_if<vector>(&events[73].data()));
addr = unbox(caf::get_if<address>(&xs.at(0)));
CHECK_EQUAL(addr, unbox(to<address>("111.91.233.1")));
CHECK_EQUAL(xs.at(1), count{45896});
CHECK_EQUAL(xs.at(2), count{3});
CHECK_EQUAL(xs.at(3), count{2});
// Event 26478
CHECK_EQUAL(events[26478].type().name(), "mrt::bgp4mp::update::announcement");
xs = unbox(caf::get_if<vector>(&events[26478].data()));
addr = unbox(caf::get_if<address>(&xs.at(0)));
CHECK_EQUAL(addr, unbox(to<address>("2a01:2a8::3")));
sn = unbox(caf::get_if<subnet>(&xs.at(2)));
CHECK_EQUAL(sn, unbox(to<subnet>("2a00:bdc0:e003::/48")));
auto as_path = caf::get_if<vector>(&xs.at(3));
CHECK_EQUAL(as_path->size(), 4u);
CHECK_EQUAL(as_path->at(0), count{1836});
CHECK_EQUAL(as_path->at(1), count{6939});
CHECK_EQUAL(as_path->at(2), count{47541});
CHECK_EQUAL(as_path->at(3), count{28709});
}
<|endoftext|> |
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#define SUITE meta_index
#include "test.hpp"
#include <caf/test/dsl.hpp>
#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast/expression.hpp"
#include "vast/const_table_slice_handle.hpp"
#include "vast/default_table_slice.hpp"
#include "vast/meta_index.hpp"
#include "vast/table_slice.hpp"
#include "vast/table_slice_builder.hpp"
#include "vast/table_slice_handle.hpp"
using namespace vast;
using std::literals::operator""s;
namespace {
constexpr size_t num_partitions = 4;
constexpr size_t num_events_per_parttion = 25;
const timestamp epoch;
timestamp get_timestamp(caf::optional<data_view> element){
return materialize(caf::get<view<timestamp>>(*element));
}
// Builds a chain of events that are 1s apart, where consecutive chunks of
// num_events_per_type events have the same type.
struct generator {
id offset;
explicit generator(size_t first_event_id) : offset(first_event_id) {
layout = record_type{
{"timestamp", timestamp_type{}},
{"content", string_type{}}
};
}
const_table_slice_handle operator()(size_t num) {
auto builder = default_table_slice::make_builder(layout);
auto str = "foo";
for (size_t i = 0; i < num; ++i) {
auto ts = epoch + std::chrono::seconds(i + offset);
builder->add(make_data_view(ts));
builder->add(make_data_view(str));
}
auto slice = builder->finish();
slice->offset(offset);
offset += num;
return slice;
}
record_type layout;
};
// A closed interval of time.
struct interval {
timestamp from;
timestamp to;
};
struct mock_partition {
mock_partition(uuid uid, size_t num) : id(std::move(uid)) {
generator g{num_events_per_parttion * num};
slice = g(num_events_per_parttion);
range.from = get_timestamp(slice->at(0, 0));
range.to = get_timestamp(slice->at(slice->rows() - 1, 0));
}
uuid id;
const_table_slice_handle slice;
interval range;
};
struct fixture {
fixture() : sys{cfg} {
}
caf::actor_system_config cfg;
caf::actor_system sys;
// Our unit-under-test.
meta_index uut;
// Partition IDs.
std::vector<uuid> ids;
auto slice(size_t first, size_t last) const {
std::vector<uuid> result;
if (first < ids.size())
for (; first != std::min(last, ids.size()); ++first)
result.emplace_back(ids[first]);
std::sort(result.begin(), result.end());
return result;
}
auto slice(size_t index) const {
return slice(index, index + 1);
}
auto query(std::string_view hhmmss) {
std::string q = "&time == 1970-01-01+";
q += hhmmss;
q += ".0";
return uut.lookup(unbox(to<expression>(q)));
}
auto empty() const {
return slice(ids.size());
}
auto query(std::string_view hhmmss_from, std::string_view hhmmss_to) {
std::string q = "&time >= 1970-01-01+";
q += hhmmss_from;
q += ".0";
q += " && &time <= 1970-01-01+";
q += hhmmss_to;
q += ".0";
return uut.lookup(unbox(to<expression>(q)));
}
};
} // namespace <anonymous>
FIXTURE_SCOPE(meta_index_tests, fixture)
TEST(uuid lookup) {
MESSAGE("generate " << num_partitions << " UUIDs for the partitions");
for (size_t i = 0; i < num_partitions; ++i)
ids.emplace_back(uuid::random());
for (size_t i = 0; i < num_partitions; ++i)
for (size_t j = 0; j < num_partitions; ++j)
if (i != j && ids[i] == ids[j])
FAIL("ID " << i << " and " << j << " are equal!");
MESSAGE("generate events and add events to the partition index");
std::vector<mock_partition> mock_partitions;
for (size_t i = 0; i < num_partitions; ++i) {
auto& mp = mock_partitions.emplace_back(ids[i], i);
uut.add(mp.id, *mp.slice);
}
MESSAGE("verify generated timestamps");
{
auto& p0 = mock_partitions[0];
CHECK_EQUAL(p0.range.from, epoch);
CHECK_EQUAL(p0.range.to, epoch + 24s);
auto& p1 = mock_partitions[1];
CHECK_EQUAL(p1.range.from, epoch + 25s);
CHECK_EQUAL(p1.range.to, epoch + 49s);
auto& p2 = mock_partitions[2];
CHECK_EQUAL(p2.range.from, epoch + 50s);
CHECK_EQUAL(p2.range.to, epoch + 74s);
auto& p3 = mock_partitions[3];
CHECK_EQUAL(p3.range.from, epoch + 75s);
CHECK_EQUAL(p3.range.to, epoch + 99s);
}
MESSAGE("check whether point queries return correct slices");
CHECK_EQUAL(query("00:00:00"), slice(0));
CHECK_EQUAL(query("00:00:24"), slice(0));
CHECK_EQUAL(query("00:00:25"), slice(1));
CHECK_EQUAL(query("00:00:49"), slice(1));
CHECK_EQUAL(query("00:00:50"), slice(2));
CHECK_EQUAL(query("00:01:14"), slice(2));
CHECK_EQUAL(query("00:01:15"), slice(3));
CHECK_EQUAL(query("00:01:39"), slice(3));
CHECK_EQUAL(query("00:01:40"), empty());
MESSAGE("check whether time-range queries return correct slices");
CHECK_EQUAL(query("00:00:01", "00:00:10"), slice(0));
CHECK_EQUAL(query("00:00:10", "00:00:30"), slice(0, 2));
}
FIXTURE_SCOPE_END()
<commit_msg>Perform small meta_index unit test tweaks<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#define SUITE meta_index
#include "test.hpp"
#include <caf/test/dsl.hpp>
#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast/expression.hpp"
#include "vast/const_table_slice_handle.hpp"
#include "vast/default_table_slice.hpp"
#include "vast/meta_index.hpp"
#include "vast/table_slice.hpp"
#include "vast/table_slice_builder.hpp"
#include "vast/table_slice_handle.hpp"
using namespace vast;
using std::literals::operator""s;
namespace {
constexpr size_t num_partitions = 4;
constexpr size_t num_events_per_parttion = 25;
const timestamp epoch;
timestamp get_timestamp(caf::optional<data_view> element){
return materialize(caf::get<view<timestamp>>(*element));
}
// Builds a chain of events that are 1s apart, where consecutive chunks of
// num_events_per_type events have the same type.
struct generator {
id offset;
explicit generator(size_t first_event_id) : offset(first_event_id) {
layout = record_type{
{"timestamp", timestamp_type{}},
{"content", string_type{}}
};
}
const_table_slice_handle operator()(size_t num) {
auto builder = default_table_slice::make_builder(layout);
auto str = "foo";
for (size_t i = 0; i < num; ++i) {
auto ts = epoch + std::chrono::seconds(i + offset);
builder->add(make_data_view(ts));
builder->add(make_data_view(str));
}
auto slice = builder->finish();
slice->offset(offset);
offset += num;
return slice;
}
record_type layout;
};
// A closed interval of time.
struct interval {
timestamp from;
timestamp to;
};
struct mock_partition {
mock_partition(uuid uid, size_t num) : id(std::move(uid)) {
generator g{num_events_per_parttion * num};
slice = g(num_events_per_parttion);
range.from = get_timestamp(slice->at(0, 0));
range.to = get_timestamp(slice->at(slice->rows() - 1, 0));
}
uuid id;
const_table_slice_handle slice;
interval range;
};
struct fixture {
// Our unit-under-test.
meta_index meta_idx;
// Partition IDs.
std::vector<uuid> ids;
auto slice(size_t first, size_t last) const {
std::vector<uuid> result;
if (first < ids.size())
for (; first != std::min(last, ids.size()); ++first)
result.emplace_back(ids[first]);
std::sort(result.begin(), result.end());
return result;
}
auto slice(size_t index) const {
return slice(index, index + 1);
}
auto query(std::string_view hhmmss) {
std::string q = "&time == 1970-01-01+";
q += hhmmss;
q += ".0";
return meta_idx.lookup(unbox(to<expression>(q)));
}
auto empty() const {
return slice(ids.size());
}
auto query(std::string_view hhmmss_from, std::string_view hhmmss_to) {
std::string q = "&time >= 1970-01-01+";
q += hhmmss_from;
q += ".0";
q += " && &time <= 1970-01-01+";
q += hhmmss_to;
q += ".0";
return meta_idx.lookup(unbox(to<expression>(q)));
}
};
} // namespace <anonymous>
FIXTURE_SCOPE(meta_index_tests, fixture)
TEST(uuid lookup) {
MESSAGE("generate " << num_partitions << " UUIDs for the partitions");
for (size_t i = 0; i < num_partitions; ++i)
ids.emplace_back(uuid::random());
for (size_t i = 0; i < num_partitions; ++i)
for (size_t j = 0; j < num_partitions; ++j)
if (i != j && ids[i] == ids[j])
FAIL("ID " << i << " and " << j << " are equal!");
MESSAGE("generate events and add events to the partition index");
std::vector<mock_partition> mock_partitions;
for (size_t i = 0; i < num_partitions; ++i) {
auto& part = mock_partitions.emplace_back(ids[i], i);
meta_idx.add(part.id, *part.slice);
}
MESSAGE("verify generated timestamps");
{
auto& p0 = mock_partitions[0];
CHECK_EQUAL(p0.range.from, epoch);
CHECK_EQUAL(p0.range.to, epoch + 24s);
auto& p1 = mock_partitions[1];
CHECK_EQUAL(p1.range.from, epoch + 25s);
CHECK_EQUAL(p1.range.to, epoch + 49s);
auto& p2 = mock_partitions[2];
CHECK_EQUAL(p2.range.from, epoch + 50s);
CHECK_EQUAL(p2.range.to, epoch + 74s);
auto& p3 = mock_partitions[3];
CHECK_EQUAL(p3.range.from, epoch + 75s);
CHECK_EQUAL(p3.range.to, epoch + 99s);
}
MESSAGE("check whether point queries return correct slices");
CHECK_EQUAL(query("00:00:00"), slice(0));
CHECK_EQUAL(query("00:00:24"), slice(0));
CHECK_EQUAL(query("00:00:25"), slice(1));
CHECK_EQUAL(query("00:00:49"), slice(1));
CHECK_EQUAL(query("00:00:50"), slice(2));
CHECK_EQUAL(query("00:01:14"), slice(2));
CHECK_EQUAL(query("00:01:15"), slice(3));
CHECK_EQUAL(query("00:01:39"), slice(3));
CHECK_EQUAL(query("00:01:40"), empty());
MESSAGE("check whether time-range queries return correct slices");
CHECK_EQUAL(query("00:00:01", "00:00:10"), slice(0));
CHECK_EQUAL(query("00:00:10", "00:00:30"), slice(0, 2));
}
FIXTURE_SCOPE_END()
<|endoftext|> |
<commit_before>//
// Created by monty on 2015/02/06
//
#include <GLES2/gl2.h>
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include <memory>
#include <vector>
#include <random>
#include <android/log.h>
#include "Trig.h"
#include "GLES2Lesson.h"
#include "NdkGlue.h"
namespace odb {
GLuint uploadTextureData(int *textureData, int width, int height) {
// Texture object handle
GLuint textureId = 0;
//Generate texture storage
glGenTextures(1, &textureId);
//specify what we want for that texture
glBindTexture(GL_TEXTURE_2D, textureId);
//upload the data
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
textureData);
return textureId;
}
extern void printGLString(const char *name, GLenum s) {
const char *v = (const char *) glGetString(s);
LOGI("GL %s = %s\n", name, v);
}
extern void checkGlError(const char *op) {
for (GLint error = glGetError(); error; error = glGetError()) {
LOGI("after %s() glError (0x%x)\n", op, error);
}
}
GLuint GLES2Lesson::loadShader(GLenum shaderType, const char *pSource) {
GLuint shader = glCreateShader(shaderType);
if (shader) {
glShaderSource(shader, 1, &pSource, NULL);
glCompileShader(shader);
GLint compiled = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
GLint infoLen = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);
if (infoLen) {
char *buf = (char *) malloc(infoLen);
if (buf) {
glGetShaderInfoLog(shader, infoLen, NULL, buf);
LOGE("Could not compile shader %d:\n%s\n", shaderType, buf);
free(buf);
}
glDeleteShader(shader);
shader = 0;
}
}
}
return shader;
}
GLuint GLES2Lesson::createProgram(const char *pVertexSource, const char *pFragmentSource) {
GLuint vertexShader = loadShader(GL_VERTEX_SHADER, pVertexSource);
if (!vertexShader) {
return 0;
}
GLuint pixelShader = loadShader(GL_FRAGMENT_SHADER, pFragmentSource);
if (!pixelShader) {
return 0;
}
GLuint program = glCreateProgram();
if (program) {
glAttachShader(program, vertexShader);
checkGlError("glAttachShader");
glAttachShader(program, pixelShader);
checkGlError("glAttachShader");
glLinkProgram(program);
GLint linkStatus = GL_FALSE;
glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
if (linkStatus != GL_TRUE) {
GLint bufLength = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufLength);
if (bufLength) {
char *buf = (char *) malloc(bufLength);
if (buf) {
glGetProgramInfoLog(program, bufLength, NULL, buf);
LOGE("Could not link program:\n%s\n", buf);
free(buf);
}
}
glDeleteProgram(program);
program = 0;
}
}
return program;
}
void GLES2Lesson::printVerboseDriverInformation() {
printGLString("Version", GL_VERSION);
printGLString("Vendor", GL_VENDOR);
printGLString("Renderer", GL_RENDERER);
printGLString("Extensions", GL_EXTENSIONS);
}
GLES2Lesson::GLES2Lesson() {
//start off as identity - later we will init it with proper values.
projectionMatrix = glm::mat4(1.0f);
textureData = nullptr;
vertexAttributePosition = 0;
modelMatrixAttributePosition = 0;
projectionMatrixAttributePosition = 0;
gProgram = 0;
reset();
}
GLES2Lesson::~GLES2Lesson() {
glDeleteTextures(1, &textureId);
}
bool GLES2Lesson::init(float w, float h, const std::string &vertexShader,
const std::string &fragmentShader) {
printVerboseDriverInformation();
gProgram = createProgram(vertexShader.c_str(), fragmentShader.c_str());
if (!gProgram) {
LOGE("Could not create program.");
return false;
}
fetchShaderLocations();
glViewport(0, 0, w, h);
checkGlError("glViewport");
projectionMatrix = glm::perspective(45.0f, w / h, 0.1f, 1024.0f);
glActiveTexture(GL_TEXTURE0);
textureId = uploadTextureData(textureData, textureWidth, textureHeight);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
glFrontFace(GL_CW);
glDepthMask(true);
return true;
}
void GLES2Lesson::resetTransformMatrices() {
viewMatrix = glm::lookAt(glm::vec3(0.0f, 0.25f, 0.0f), glm::vec3(0.0f, 0.25f, 1.0f),
glm::vec3(0.0, 1.0f, 0.0f));
glUniformMatrix4fv(viewMatrixAttributePosition, 1, false, &viewMatrix[0][0]);
}
void GLES2Lesson::fetchShaderLocations() {
vertexAttributePosition = glGetAttribLocation(gProgram, "aPosition");
modelMatrixAttributePosition = glGetUniformLocation(gProgram, "uModel");
viewMatrixAttributePosition = glGetUniformLocation(gProgram, "uView");
projectionMatrixAttributePosition = glGetUniformLocation(gProgram, "uProjection");
samplerUniformPosition = glGetUniformLocation(gProgram, "sTexture");
textureCoordinatesAttributePosition = glGetAttribLocation(gProgram, "aTexCoord");
}
void GLES2Lesson::clearBuffers() {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClearDepthf(1.0f);
checkGlError("glClearColor");
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
checkGlError("glClear");
}
void GLES2Lesson::setPerspective() {
glUniformMatrix4fv(projectionMatrixAttributePosition, 1, false, &projectionMatrix[0][0]);
}
void GLES2Lesson::prepareShaderProgram() {
glUseProgram(gProgram);
checkGlError("glUseProgram");
glUniform1i(samplerUniformPosition, 0);
glActiveTexture(GL_TEXTURE0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
void GLES2Lesson::render() {
clearBuffers();
prepareShaderProgram();
setPerspective();
resetTransformMatrices();
glUniformMatrix4fv(modelMatrixAttributePosition, 1, false, &glm::mat4(1.0f)[0][0]);
for (auto &trig : mTrigs) {
drawTrig(trig, glm::mat4(1.0f));
}
}
void GLES2Lesson::setTexture(int *bitmapData, int width, int height, int format) {
textureData = bitmapData;
textureWidth = width;
textureHeight = height;
}
void GLES2Lesson::tick() {
}
void GLES2Lesson::shutdown() {
delete textureData;
LOGI("Shutdown!\n");
}
void GLES2Lesson::reset() {
}
void GLES2Lesson::addTrigs(std::vector<Trig> newTrigs) {
mTrigs.insert(mTrigs.end(), newTrigs.begin(), newTrigs.end());
}
void GLES2Lesson::drawTrig(Trig &trig, const glm::mat4 &transform) {
glEnableVertexAttribArray(vertexAttributePosition);
glEnableVertexAttribArray(textureCoordinatesAttributePosition);
checkGlError("enable attribute");
glUniformMatrix4fv(modelMatrixAttributePosition, 1, false, &transform[0][0]);
checkGlError("upload model matrix");
glVertexAttribPointer(vertexAttributePosition, 3, GL_FLOAT, GL_TRUE, 0,
trig.getVertexData());
checkGlError("upload vertex data");
glVertexAttribPointer(textureCoordinatesAttributePosition, 2, GL_FLOAT, GL_TRUE,
0, trig.getUVData());
glDrawArrays(GL_TRIANGLES, 0, 3);
checkGlError("draw");
glDisableVertexAttribArray(vertexAttributePosition);
checkGlError("disable attribute");
glDisableVertexAttribArray(textureCoordinatesAttributePosition);
}
}<commit_msg>Disable blending in Lesson 10<commit_after>//
// Created by monty on 2015/02/06
//
#include <GLES2/gl2.h>
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include <memory>
#include <vector>
#include <random>
#include <android/log.h>
#include "Trig.h"
#include "GLES2Lesson.h"
#include "NdkGlue.h"
namespace odb {
GLuint uploadTextureData(int *textureData, int width, int height) {
// Texture object handle
GLuint textureId = 0;
//Generate texture storage
glGenTextures(1, &textureId);
//specify what we want for that texture
glBindTexture(GL_TEXTURE_2D, textureId);
//upload the data
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
textureData);
return textureId;
}
extern void printGLString(const char *name, GLenum s) {
const char *v = (const char *) glGetString(s);
LOGI("GL %s = %s\n", name, v);
}
extern void checkGlError(const char *op) {
for (GLint error = glGetError(); error; error = glGetError()) {
LOGI("after %s() glError (0x%x)\n", op, error);
}
}
GLuint GLES2Lesson::loadShader(GLenum shaderType, const char *pSource) {
GLuint shader = glCreateShader(shaderType);
if (shader) {
glShaderSource(shader, 1, &pSource, NULL);
glCompileShader(shader);
GLint compiled = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
GLint infoLen = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);
if (infoLen) {
char *buf = (char *) malloc(infoLen);
if (buf) {
glGetShaderInfoLog(shader, infoLen, NULL, buf);
LOGE("Could not compile shader %d:\n%s\n", shaderType, buf);
free(buf);
}
glDeleteShader(shader);
shader = 0;
}
}
}
return shader;
}
GLuint GLES2Lesson::createProgram(const char *pVertexSource, const char *pFragmentSource) {
GLuint vertexShader = loadShader(GL_VERTEX_SHADER, pVertexSource);
if (!vertexShader) {
return 0;
}
GLuint pixelShader = loadShader(GL_FRAGMENT_SHADER, pFragmentSource);
if (!pixelShader) {
return 0;
}
GLuint program = glCreateProgram();
if (program) {
glAttachShader(program, vertexShader);
checkGlError("glAttachShader");
glAttachShader(program, pixelShader);
checkGlError("glAttachShader");
glLinkProgram(program);
GLint linkStatus = GL_FALSE;
glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
if (linkStatus != GL_TRUE) {
GLint bufLength = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufLength);
if (bufLength) {
char *buf = (char *) malloc(bufLength);
if (buf) {
glGetProgramInfoLog(program, bufLength, NULL, buf);
LOGE("Could not link program:\n%s\n", buf);
free(buf);
}
}
glDeleteProgram(program);
program = 0;
}
}
return program;
}
void GLES2Lesson::printVerboseDriverInformation() {
printGLString("Version", GL_VERSION);
printGLString("Vendor", GL_VENDOR);
printGLString("Renderer", GL_RENDERER);
printGLString("Extensions", GL_EXTENSIONS);
}
GLES2Lesson::GLES2Lesson() {
//start off as identity - later we will init it with proper values.
projectionMatrix = glm::mat4(1.0f);
textureData = nullptr;
vertexAttributePosition = 0;
modelMatrixAttributePosition = 0;
projectionMatrixAttributePosition = 0;
gProgram = 0;
reset();
}
GLES2Lesson::~GLES2Lesson() {
glDeleteTextures(1, &textureId);
}
bool GLES2Lesson::init(float w, float h, const std::string &vertexShader,
const std::string &fragmentShader) {
printVerboseDriverInformation();
gProgram = createProgram(vertexShader.c_str(), fragmentShader.c_str());
if (!gProgram) {
LOGE("Could not create program.");
return false;
}
fetchShaderLocations();
glViewport(0, 0, w, h);
checkGlError("glViewport");
projectionMatrix = glm::perspective(45.0f, w / h, 0.1f, 1024.0f);
glActiveTexture(GL_TEXTURE0);
textureId = uploadTextureData(textureData, textureWidth, textureHeight);
glFrontFace(GL_CW);
glDepthMask(true);
return true;
}
void GLES2Lesson::resetTransformMatrices() {
viewMatrix = glm::lookAt(glm::vec3(0.0f, 0.25f, 0.0f), glm::vec3(0.0f, 0.25f, 1.0f),
glm::vec3(0.0, 1.0f, 0.0f));
glUniformMatrix4fv(viewMatrixAttributePosition, 1, false, &viewMatrix[0][0]);
}
void GLES2Lesson::fetchShaderLocations() {
vertexAttributePosition = glGetAttribLocation(gProgram, "aPosition");
modelMatrixAttributePosition = glGetUniformLocation(gProgram, "uModel");
viewMatrixAttributePosition = glGetUniformLocation(gProgram, "uView");
projectionMatrixAttributePosition = glGetUniformLocation(gProgram, "uProjection");
samplerUniformPosition = glGetUniformLocation(gProgram, "sTexture");
textureCoordinatesAttributePosition = glGetAttribLocation(gProgram, "aTexCoord");
}
void GLES2Lesson::clearBuffers() {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClearDepthf(1.0f);
checkGlError("glClearColor");
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
checkGlError("glClear");
}
void GLES2Lesson::setPerspective() {
glUniformMatrix4fv(projectionMatrixAttributePosition, 1, false, &projectionMatrix[0][0]);
}
void GLES2Lesson::prepareShaderProgram() {
glUseProgram(gProgram);
checkGlError("glUseProgram");
glUniform1i(samplerUniformPosition, 0);
glActiveTexture(GL_TEXTURE0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
void GLES2Lesson::render() {
clearBuffers();
prepareShaderProgram();
setPerspective();
resetTransformMatrices();
glUniformMatrix4fv(modelMatrixAttributePosition, 1, false, &glm::mat4(1.0f)[0][0]);
for (auto &trig : mTrigs) {
drawTrig(trig, glm::mat4(1.0f));
}
}
void GLES2Lesson::setTexture(int *bitmapData, int width, int height, int format) {
textureData = bitmapData;
textureWidth = width;
textureHeight = height;
}
void GLES2Lesson::tick() {
}
void GLES2Lesson::shutdown() {
delete textureData;
LOGI("Shutdown!\n");
}
void GLES2Lesson::reset() {
}
void GLES2Lesson::addTrigs(std::vector<Trig> newTrigs) {
mTrigs.insert(mTrigs.end(), newTrigs.begin(), newTrigs.end());
}
void GLES2Lesson::drawTrig(Trig &trig, const glm::mat4 &transform) {
glEnableVertexAttribArray(vertexAttributePosition);
glEnableVertexAttribArray(textureCoordinatesAttributePosition);
checkGlError("enable attribute");
glUniformMatrix4fv(modelMatrixAttributePosition, 1, false, &transform[0][0]);
checkGlError("upload model matrix");
glVertexAttribPointer(vertexAttributePosition, 3, GL_FLOAT, GL_TRUE, 0,
trig.getVertexData());
checkGlError("upload vertex data");
glVertexAttribPointer(textureCoordinatesAttributePosition, 2, GL_FLOAT, GL_TRUE,
0, trig.getUVData());
glDrawArrays(GL_TRIANGLES, 0, 3);
checkGlError("draw");
glDisableVertexAttribArray(vertexAttributePosition);
checkGlError("disable attribute");
glDisableVertexAttribArray(textureCoordinatesAttributePosition);
}
}<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "rtl/ustring.hxx"
#include "tox.hxx"
#include "txmsrt.hxx"
#include "ToxTextGenerator.hxx"
#include <cppunit/TestAssert.h>
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/plugin/TestPlugIn.h>
using sw::ToxTextGenerator;
class ToxTextGeneratorTest : public CppUnit::TestFixture {
public:
void EmptyStringIsReturnedForPageNumberPlaceholderOfZeroItems();
void OneAtSignIsReturnedForPageNumberPlaceholderOfOneItem();
void TwoAtSignsAreReturnedForPageNumberPlaceholderOfOneItem();
void EmptyStringIsReturnedAsNumStringIfNoTextMarkIsSet();
void EmptyStringIsReturnedAsNumStringIfToxSourcesIsEmpty();
CPPUNIT_TEST_SUITE(ToxTextGeneratorTest);
CPPUNIT_TEST(EmptyStringIsReturnedForPageNumberPlaceholderOfZeroItems);
CPPUNIT_TEST(OneAtSignIsReturnedForPageNumberPlaceholderOfOneItem);
CPPUNIT_TEST(TwoAtSignsAreReturnedForPageNumberPlaceholderOfOneItem);
CPPUNIT_TEST(EmptyStringIsReturnedAsNumStringIfNoTextMarkIsSet);
CPPUNIT_TEST_SUITE_END();
};
struct MockedSortTab : public SwTOXSortTabBase {
MockedSortTab()
: SwTOXSortTabBase(TOX_SORT_INDEX,0,0,0) {;}
/*virtual*/ TextAndReading GetText_Impl() const {
return TextAndReading();
}
/*virtual*/ sal_uInt16 GetLevel() const {
return 0;
}
};
void
ToxTextGeneratorTest::EmptyStringIsReturnedForPageNumberPlaceholderOfZeroItems()
{
OUString expected("");
OUString actual = ToxTextGenerator::ConstructPageNumberPlaceholder(0);
CPPUNIT_ASSERT_EQUAL(expected, actual);
}
void
ToxTextGeneratorTest::OneAtSignIsReturnedForPageNumberPlaceholderOfOneItem()
{
OUString expected("@~");
OUString actual = ToxTextGenerator::ConstructPageNumberPlaceholder(1);
CPPUNIT_ASSERT_EQUAL(expected, actual);
}
void
ToxTextGeneratorTest::TwoAtSignsAreReturnedForPageNumberPlaceholderOfOneItem()
{
OUString expected("@, @~");
OUString actual = ToxTextGenerator::ConstructPageNumberPlaceholder(2);
CPPUNIT_ASSERT_EQUAL(expected, actual);
}
void
ToxTextGeneratorTest::EmptyStringIsReturnedAsNumStringIfNoTextMarkIsSet()
{
MockedSortTab sortTab;
sortTab.pTxtMark = NULL;
OUString expected("");
OUString actual = ToxTextGenerator::GetNumStringOfFirstNode(sortTab, false, 0);
CPPUNIT_ASSERT_EQUAL(expected, actual);
}
void
ToxTextGeneratorTest::EmptyStringIsReturnedAsNumStringIfToxSourcesIsEmpty()
{
MockedSortTab sortTab;
sortTab.pTxtMark = reinterpret_cast<SwTxtTOXMark*>(1);
OUString expected("");
OUString actual = ToxTextGenerator::GetNumStringOfFirstNode(sortTab, false, 0);
CPPUNIT_ASSERT_EQUAL(expected, actual);
}
// Put the test suite in the registry
CPPUNIT_TEST_SUITE_REGISTRATION(ToxTextGeneratorTest);
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>loplugin:saloverride + loplugin:unreffun<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "rtl/ustring.hxx"
#include "tox.hxx"
#include "txmsrt.hxx"
#include "ToxTextGenerator.hxx"
#include <cppunit/TestAssert.h>
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/plugin/TestPlugIn.h>
using sw::ToxTextGenerator;
class ToxTextGeneratorTest : public CppUnit::TestFixture {
public:
void EmptyStringIsReturnedForPageNumberPlaceholderOfZeroItems();
void OneAtSignIsReturnedForPageNumberPlaceholderOfOneItem();
void TwoAtSignsAreReturnedForPageNumberPlaceholderOfOneItem();
void EmptyStringIsReturnedAsNumStringIfNoTextMarkIsSet();
CPPUNIT_TEST_SUITE(ToxTextGeneratorTest);
CPPUNIT_TEST(EmptyStringIsReturnedForPageNumberPlaceholderOfZeroItems);
CPPUNIT_TEST(OneAtSignIsReturnedForPageNumberPlaceholderOfOneItem);
CPPUNIT_TEST(TwoAtSignsAreReturnedForPageNumberPlaceholderOfOneItem);
CPPUNIT_TEST(EmptyStringIsReturnedAsNumStringIfNoTextMarkIsSet);
CPPUNIT_TEST_SUITE_END();
};
struct MockedSortTab : public SwTOXSortTabBase {
MockedSortTab()
: SwTOXSortTabBase(TOX_SORT_INDEX,0,0,0) {;}
virtual TextAndReading GetText_Impl() const SAL_OVERRIDE {
return TextAndReading();
}
virtual sal_uInt16 GetLevel() const SAL_OVERRIDE {
return 0;
}
};
void
ToxTextGeneratorTest::EmptyStringIsReturnedForPageNumberPlaceholderOfZeroItems()
{
OUString expected("");
OUString actual = ToxTextGenerator::ConstructPageNumberPlaceholder(0);
CPPUNIT_ASSERT_EQUAL(expected, actual);
}
void
ToxTextGeneratorTest::OneAtSignIsReturnedForPageNumberPlaceholderOfOneItem()
{
OUString expected("@~");
OUString actual = ToxTextGenerator::ConstructPageNumberPlaceholder(1);
CPPUNIT_ASSERT_EQUAL(expected, actual);
}
void
ToxTextGeneratorTest::TwoAtSignsAreReturnedForPageNumberPlaceholderOfOneItem()
{
OUString expected("@, @~");
OUString actual = ToxTextGenerator::ConstructPageNumberPlaceholder(2);
CPPUNIT_ASSERT_EQUAL(expected, actual);
}
void
ToxTextGeneratorTest::EmptyStringIsReturnedAsNumStringIfNoTextMarkIsSet()
{
MockedSortTab sortTab;
sortTab.pTxtMark = NULL;
OUString expected("");
OUString actual = ToxTextGenerator::GetNumStringOfFirstNode(sortTab, false, 0);
CPPUNIT_ASSERT_EQUAL(expected, actual);
}
// Put the test suite in the registry
CPPUNIT_TEST_SUITE_REGISTRATION(ToxTextGeneratorTest);
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/* -*- mode: C++; c-basic-offset: 8; indent-tabs-mode: t; -*- */
/*
* Copyright (c) 2013, Georgia Tech Research Corporation
* All rights reserved.
*
* Author(s): Heni Ben Amor
*
* This file is provided under the following "BSD-style" License:
*
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <pthread.h>
#if defined(__APPLE__)
#include <GLUT/glut.h>
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#else
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
#endif
#include <AR/gsub.h>
#include <AR/param.h>
#include <AR/ar.h>
#include <AR/video.h>
#include <kinectAR.h>
#include <osgDB/ReadFile>
#include <osgUtil/Optimizer>
#include <osg/CoordinateSystemNode>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/TrackballManipulator>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/ShapeDrawable>
#include <osg/PositionAttitudeTransform>
#include <iostream>
#include <sns.h>
using namespace cv;
using namespace std;
KinectAR kinect;
int main(int argc, char **argv)
{
// use an ArgumentParser object to manage the program arguments.
int numArgs = 6;
char* args[6];
args[0]= "program";
args[1]= "--window";
args[2]= "100";
args[3]= "100";
args[4]= "400";
args[5]= "400";
osg::ArgumentParser arguments(&numArgs, args);
osgViewer::Viewer viewer(arguments);
// create the root node of the scenegraph
osg::Group *root = new osg::Group;
// add the table
osg::Geode* table = new osg::Geode;
osg::ShapeDrawable* shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0.0f,0.0f,0.0f),80.0f,40.0f,0.05f));
osg::PositionAttitudeTransform* transf = new osg::PositionAttitudeTransform;
transf->setPosition(osg::Vec3(0,0,120));
root->addChild(transf);
transf->addChild(table);
table->addDrawable(shape);
// add a viewport to the viewer and attach the scene graph.
viewer.setSceneData(root);
// set the trackball manipulator
viewer.setCameraManipulator(new osgGA::TrackballManipulator());
viewer.realize();
double alpha = 0.0;
// add to the sceneGraph
for(int i = 0; i < 32; i++)
{
(kinect.kinectMarkers[i]).AddToSceneGraph(root);
(kinect.kinectMarkers[i]).DrawCoordinateSys();
}
// channel name
kinect.OpenChannel(argv[1]);
// draw image
while(!sns_cx.shutdown)
{
// autoposition wird inkrementiert
alpha+=0.01;
// fire off the cull and draw traversals of the scene.
viewer.frame();
if( !kinect.capture.grab() )
{
cout << "Can not grab images." << endl;
return -1;
}
else
{
kinect.DrawScene();
kinect.DetectMarkers();
kinect.CreatePointCloud();
kinect.SendMsg(32);
}
if( waitKey( 30 ) >= 0 )
kinect.Keyboard('n', 1, 1);
//break;
}
return 0;
}
<commit_msg>Use getopt<commit_after>/* -*- mode: C++; c-basic-offset: 8; indent-tabs-mode: t; -*- */
/*
* Copyright (c) 2013, Georgia Tech Research Corporation
* All rights reserved.
*
* Author(s): Heni Ben Amor
*
* This file is provided under the following "BSD-style" License:
*
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <pthread.h>
#if defined(__APPLE__)
#include <GLUT/glut.h>
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#else
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
#endif
#include <AR/gsub.h>
#include <AR/param.h>
#include <AR/ar.h>
#include <AR/video.h>
#include <kinectAR.h>
#include <osgDB/ReadFile>
#include <osgUtil/Optimizer>
#include <osg/CoordinateSystemNode>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <getopt.h>
#include <osgGA/TrackballManipulator>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/ShapeDrawable>
#include <osg/PositionAttitudeTransform>
#include <iostream>
#include <sns.h>
using namespace cv;
using namespace std;
KinectAR kinect;
const char *opt_channel = "marker";
int main(int argc, char **argv)
{
for( int c; -1 != (c = getopt(argc, argv, "c:?" SNS_OPTSTRING)); ) {
switch(c) {
SNS_OPTCASES
case 'c':
opt_channel = optarg;
break;
case '?': /* help */
default:
puts( "Usage: detect_marker -c channel\n"
"Detect markers with kinect\n"
"\n"
"Options:\n"
" -c CANNEL, Set output Ach channel\n"
" -?, Give program help list\n"
"\n"
"Report bugs to <[email protected]>" );
}
}
// use an ArgumentParser object to manage the program arguments.
int numArgs = 6;
char* args[6];
args[0]= "program";
args[1]= "--window";
args[2]= "100";
args[3]= "100";
args[4]= "400";
args[5]= "400";
osg::ArgumentParser arguments(&numArgs, args);
osgViewer::Viewer viewer(arguments);
// create the root node of the scenegraph
osg::Group *root = new osg::Group;
// add the table
osg::Geode* table = new osg::Geode;
osg::ShapeDrawable* shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0.0f,0.0f,0.0f),80.0f,40.0f,0.05f));
osg::PositionAttitudeTransform* transf = new osg::PositionAttitudeTransform;
transf->setPosition(osg::Vec3(0,0,120));
root->addChild(transf);
transf->addChild(table);
table->addDrawable(shape);
// add a viewport to the viewer and attach the scene graph.
viewer.setSceneData(root);
// set the trackball manipulator
viewer.setCameraManipulator(new osgGA::TrackballManipulator());
viewer.realize();
double alpha = 0.0;
// add to the sceneGraph
for(int i = 0; i < 32; i++)
{
(kinect.kinectMarkers[i]).AddToSceneGraph(root);
(kinect.kinectMarkers[i]).DrawCoordinateSys();
}
// channel name
kinect.OpenChannel(opt_channel);
// draw image
while(!sns_cx.shutdown)
{
// autoposition wird inkrementiert
alpha+=0.01;
// fire off the cull and draw traversals of the scene.
viewer.frame();
if( !kinect.capture.grab() )
{
cout << "Can not grab images." << endl;
return -1;
}
else
{
kinect.DrawScene();
kinect.DetectMarkers();
kinect.CreatePointCloud();
kinect.SendMsg(32);
}
if( waitKey( 30 ) >= 0 )
kinect.Keyboard('n', 1, 1);
//break;
}
return 0;
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkMovie.h"
#include "SkColor.h"
#include "SkColorPriv.h"
#include "SkStream.h"
#include "SkTemplates.h"
#include "SkUtils.h"
#include "gif_lib.h"
class SkGIFMovie : public SkMovie {
public:
SkGIFMovie(SkStream* stream);
virtual ~SkGIFMovie();
protected:
virtual bool onGetInfo(Info*);
virtual bool onSetTime(SkMSec);
virtual bool onGetBitmap(SkBitmap*);
private:
GifFileType* fGIF;
int fCurrIndex;
int fLastDrawIndex;
SkBitmap fBackup;
};
static int Decode(GifFileType* fileType, GifByteType* out, int size) {
SkStream* stream = (SkStream*) fileType->UserData;
return (int) stream->read(out, size);
}
SkGIFMovie::SkGIFMovie(SkStream* stream)
{
#if GIFLIB_MAJOR < 5
fGIF = DGifOpen( stream, Decode );
#else
fGIF = DGifOpen( stream, Decode, NULL );
#endif
if (NULL == fGIF)
return;
if (DGifSlurp(fGIF) != GIF_OK)
{
DGifCloseFile(fGIF);
fGIF = NULL;
}
fCurrIndex = -1;
fLastDrawIndex = -1;
}
SkGIFMovie::~SkGIFMovie()
{
if (fGIF)
DGifCloseFile(fGIF);
}
static SkMSec savedimage_duration(const SavedImage* image)
{
for (int j = 0; j < image->ExtensionBlockCount; j++)
{
if (image->ExtensionBlocks[j].Function == GRAPHICS_EXT_FUNC_CODE)
{
SkDEBUGCODE(int size = )image->ExtensionBlocks[j].ByteCount;
SkASSERT(size >= 4);
const uint8_t* b = (const uint8_t*)image->ExtensionBlocks[j].Bytes;
return ((b[2] << 8) | b[1]) * 10;
}
}
return 0;
}
bool SkGIFMovie::onGetInfo(Info* info)
{
if (NULL == fGIF)
return false;
SkMSec dur = 0;
for (int i = 0; i < fGIF->ImageCount; i++)
dur += savedimage_duration(&fGIF->SavedImages[i]);
info->fDuration = dur;
info->fWidth = fGIF->SWidth;
info->fHeight = fGIF->SHeight;
info->fIsOpaque = false; // how to compute?
return true;
}
bool SkGIFMovie::onSetTime(SkMSec time)
{
if (NULL == fGIF)
return false;
SkMSec dur = 0;
for (int i = 0; i < fGIF->ImageCount; i++)
{
dur += savedimage_duration(&fGIF->SavedImages[i]);
if (dur >= time)
{
fCurrIndex = i;
return fLastDrawIndex != fCurrIndex;
}
}
fCurrIndex = fGIF->ImageCount - 1;
return true;
}
static void copyLine(uint32_t* dst, const unsigned char* src, const ColorMapObject* cmap,
int transparent, int width)
{
for (; width > 0; width--, src++, dst++) {
if (*src != transparent) {
const GifColorType& col = cmap->Colors[*src];
*dst = SkPackARGB32(0xFF, col.Red, col.Green, col.Blue);
}
}
}
static void copyInterlaceGroup(SkBitmap* bm, const unsigned char*& src,
const ColorMapObject* cmap, int transparent, int copyWidth,
int copyHeight, const GifImageDesc& imageDesc, int rowStep,
int startRow)
{
int row;
// every 'rowStep'th row, starting with row 'startRow'
for (row = startRow; row < copyHeight; row += rowStep) {
uint32_t* dst = bm->getAddr32(imageDesc.Left, imageDesc.Top + row);
copyLine(dst, src, cmap, transparent, copyWidth);
src += imageDesc.Width;
}
// pad for rest height
src += imageDesc.Width * ((imageDesc.Height - row + rowStep - 1) / rowStep);
}
static void blitInterlace(SkBitmap* bm, const SavedImage* frame, const ColorMapObject* cmap,
int transparent)
{
int width = bm->width();
int height = bm->height();
GifWord copyWidth = frame->ImageDesc.Width;
if (frame->ImageDesc.Left + copyWidth > width) {
copyWidth = width - frame->ImageDesc.Left;
}
GifWord copyHeight = frame->ImageDesc.Height;
if (frame->ImageDesc.Top + copyHeight > height) {
copyHeight = height - frame->ImageDesc.Top;
}
// deinterlace
const unsigned char* src = (unsigned char*)frame->RasterBits;
// group 1 - every 8th row, starting with row 0
copyInterlaceGroup(bm, src, cmap, transparent, copyWidth, copyHeight, frame->ImageDesc, 8, 0);
// group 2 - every 8th row, starting with row 4
copyInterlaceGroup(bm, src, cmap, transparent, copyWidth, copyHeight, frame->ImageDesc, 8, 4);
// group 3 - every 4th row, starting with row 2
copyInterlaceGroup(bm, src, cmap, transparent, copyWidth, copyHeight, frame->ImageDesc, 4, 2);
copyInterlaceGroup(bm, src, cmap, transparent, copyWidth, copyHeight, frame->ImageDesc, 2, 1);
}
static void blitNormal(SkBitmap* bm, const SavedImage* frame, const ColorMapObject* cmap,
int transparent)
{
int width = bm->width();
int height = bm->height();
const unsigned char* src = (unsigned char*)frame->RasterBits;
uint32_t* dst = bm->getAddr32(frame->ImageDesc.Left, frame->ImageDesc.Top);
GifWord copyWidth = frame->ImageDesc.Width;
if (frame->ImageDesc.Left + copyWidth > width) {
copyWidth = width - frame->ImageDesc.Left;
}
GifWord copyHeight = frame->ImageDesc.Height;
if (frame->ImageDesc.Top + copyHeight > height) {
copyHeight = height - frame->ImageDesc.Top;
}
for (; copyHeight > 0; copyHeight--) {
copyLine(dst, src, cmap, transparent, copyWidth);
src += frame->ImageDesc.Width;
dst += width;
}
}
static void fillRect(SkBitmap* bm, GifWord left, GifWord top, GifWord width, GifWord height,
uint32_t col)
{
int bmWidth = bm->width();
int bmHeight = bm->height();
uint32_t* dst = bm->getAddr32(left, top);
GifWord copyWidth = width;
if (left + copyWidth > bmWidth) {
copyWidth = bmWidth - left;
}
GifWord copyHeight = height;
if (top + copyHeight > bmHeight) {
copyHeight = bmHeight - top;
}
for (; copyHeight > 0; copyHeight--) {
sk_memset32(dst, col, copyWidth);
dst += bmWidth;
}
}
static void drawFrame(SkBitmap* bm, const SavedImage* frame, const ColorMapObject* cmap)
{
int transparent = -1;
for (int i = 0; i < frame->ExtensionBlockCount; ++i) {
ExtensionBlock* eb = frame->ExtensionBlocks + i;
if (eb->Function == GRAPHICS_EXT_FUNC_CODE &&
eb->ByteCount == 4) {
bool has_transparency = ((eb->Bytes[0] & 1) == 1);
if (has_transparency) {
transparent = (unsigned char)eb->Bytes[3];
}
}
}
if (frame->ImageDesc.ColorMap != NULL) {
// use local color table
cmap = frame->ImageDesc.ColorMap;
}
if (cmap == NULL || cmap->ColorCount != (1 << cmap->BitsPerPixel)) {
SkDEBUGFAIL("bad colortable setup");
return;
}
if (frame->ImageDesc.Interlace) {
blitInterlace(bm, frame, cmap, transparent);
} else {
blitNormal(bm, frame, cmap, transparent);
}
}
static bool checkIfWillBeCleared(const SavedImage* frame)
{
for (int i = 0; i < frame->ExtensionBlockCount; ++i) {
ExtensionBlock* eb = frame->ExtensionBlocks + i;
if (eb->Function == GRAPHICS_EXT_FUNC_CODE &&
eb->ByteCount == 4) {
// check disposal method
int disposal = ((eb->Bytes[0] >> 2) & 7);
if (disposal == 2 || disposal == 3) {
return true;
}
}
}
return false;
}
static void getTransparencyAndDisposalMethod(const SavedImage* frame, bool* trans, int* disposal)
{
*trans = false;
*disposal = 0;
for (int i = 0; i < frame->ExtensionBlockCount; ++i) {
ExtensionBlock* eb = frame->ExtensionBlocks + i;
if (eb->Function == GRAPHICS_EXT_FUNC_CODE &&
eb->ByteCount == 4) {
*trans = ((eb->Bytes[0] & 1) == 1);
*disposal = ((eb->Bytes[0] >> 2) & 7);
}
}
}
// return true if area of 'target' is completely covers area of 'covered'
static bool checkIfCover(const SavedImage* target, const SavedImage* covered)
{
if (target->ImageDesc.Left <= covered->ImageDesc.Left
&& covered->ImageDesc.Left + covered->ImageDesc.Width <=
target->ImageDesc.Left + target->ImageDesc.Width
&& target->ImageDesc.Top <= covered->ImageDesc.Top
&& covered->ImageDesc.Top + covered->ImageDesc.Height <=
target->ImageDesc.Top + target->ImageDesc.Height) {
return true;
}
return false;
}
static void disposeFrameIfNeeded(SkBitmap* bm, const SavedImage* cur, const SavedImage* next,
SkBitmap* backup, SkColor color)
{
// We can skip disposal process if next frame is not transparent
// and completely covers current area
bool curTrans;
int curDisposal;
getTransparencyAndDisposalMethod(cur, &curTrans, &curDisposal);
bool nextTrans;
int nextDisposal;
getTransparencyAndDisposalMethod(next, &nextTrans, &nextDisposal);
if ((curDisposal == 2 || curDisposal == 3)
&& (nextTrans || !checkIfCover(next, cur))) {
switch (curDisposal) {
// restore to background color
// -> 'background' means background under this image.
case 2:
fillRect(bm, cur->ImageDesc.Left, cur->ImageDesc.Top,
cur->ImageDesc.Width, cur->ImageDesc.Height,
color);
break;
// restore to previous
case 3:
bm->swap(*backup);
break;
}
}
// Save current image if next frame's disposal method == 3
if (nextDisposal == 3) {
const uint32_t* src = bm->getAddr32(0, 0);
uint32_t* dst = backup->getAddr32(0, 0);
int cnt = bm->width() * bm->height();
memcpy(dst, src, cnt*sizeof(uint32_t));
}
}
bool SkGIFMovie::onGetBitmap(SkBitmap* bm)
{
const GifFileType* gif = fGIF;
if (NULL == gif)
return false;
if (gif->ImageCount < 1) {
return false;
}
const int width = gif->SWidth;
const int height = gif->SHeight;
if (width <= 0 || height <= 0) {
return false;
}
// no need to draw
if (fLastDrawIndex >= 0 && fLastDrawIndex == fCurrIndex) {
return true;
}
int startIndex = fLastDrawIndex + 1;
if (fLastDrawIndex < 0 || !bm->readyToDraw()) {
// first time
startIndex = 0;
// create bitmap
bm->setConfig(SkBitmap::kARGB_8888_Config, width, height, 0);
if (!bm->allocPixels(NULL)) {
return false;
}
// create bitmap for backup
fBackup.setConfig(SkBitmap::kARGB_8888_Config, width, height, 0);
if (!fBackup.allocPixels(NULL)) {
return false;
}
} else if (startIndex > fCurrIndex) {
// rewind to 1st frame for repeat
startIndex = 0;
}
int lastIndex = fCurrIndex;
if (lastIndex < 0) {
// first time
lastIndex = 0;
} else if (lastIndex > fGIF->ImageCount - 1) {
// this block must not be reached.
lastIndex = fGIF->ImageCount - 1;
}
SkColor bgColor = SkPackARGB32(0, 0, 0, 0);
if (gif->SColorMap != NULL) {
const GifColorType& col = gif->SColorMap->Colors[fGIF->SBackGroundColor];
bgColor = SkColorSetARGB(0xFF, col.Red, col.Green, col.Blue);
}
static SkColor paintingColor = SkPackARGB32(0, 0, 0, 0);
// draw each frames - not intelligent way
for (int i = startIndex; i <= lastIndex; i++) {
const SavedImage* cur = &fGIF->SavedImages[i];
if (i == 0) {
bool trans;
int disposal;
getTransparencyAndDisposalMethod(cur, &trans, &disposal);
if (!trans && gif->SColorMap != NULL) {
paintingColor = bgColor;
} else {
paintingColor = SkColorSetARGB(0, 0, 0, 0);
}
bm->eraseColor(paintingColor);
fBackup.eraseColor(paintingColor);
} else {
// Dispose previous frame before move to next frame.
const SavedImage* prev = &fGIF->SavedImages[i-1];
disposeFrameIfNeeded(bm, prev, cur, &fBackup, paintingColor);
}
// Draw frame
// We can skip this process if this index is not last and disposal
// method == 2 or method == 3
if (i == lastIndex || !checkIfWillBeCleared(cur)) {
drawFrame(bm, cur, gif->SColorMap);
}
}
// save index
fLastDrawIndex = lastIndex;
return true;
}
///////////////////////////////////////////////////////////////////////////////
#include "SkTRegistry.h"
SkMovie* Factory(SkStream* stream) {
char buf[GIF_STAMP_LEN];
if (stream->read(buf, GIF_STAMP_LEN) == GIF_STAMP_LEN) {
if (memcmp(GIF_STAMP, buf, GIF_STAMP_LEN) == 0 ||
memcmp(GIF87_STAMP, buf, GIF_STAMP_LEN) == 0 ||
memcmp(GIF89_STAMP, buf, GIF_STAMP_LEN) == 0) {
// must rewind here, since our construct wants to re-read the data
stream->rewind();
return SkNEW_ARGS(SkGIFMovie, (stream));
}
}
return NULL;
}
static SkTRegistry<SkMovie*, SkStream*> gReg(Factory);
<commit_msg>fix warning (again) for SkMovie<commit_after>
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkMovie.h"
#include "SkColor.h"
#include "SkColorPriv.h"
#include "SkStream.h"
#include "SkTemplates.h"
#include "SkUtils.h"
#include "gif_lib.h"
class SkGIFMovie : public SkMovie {
public:
SkGIFMovie(SkStream* stream);
virtual ~SkGIFMovie();
protected:
virtual bool onGetInfo(Info*);
virtual bool onSetTime(SkMSec);
virtual bool onGetBitmap(SkBitmap*);
private:
GifFileType* fGIF;
int fCurrIndex;
int fLastDrawIndex;
SkBitmap fBackup;
};
static int Decode(GifFileType* fileType, GifByteType* out, int size) {
SkStream* stream = (SkStream*) fileType->UserData;
return (int) stream->read(out, size);
}
SkGIFMovie::SkGIFMovie(SkStream* stream)
{
#if GIFLIB_MAJOR < 5
fGIF = DGifOpen( stream, Decode );
#else
fGIF = DGifOpen( stream, Decode, NULL );
#endif
if (NULL == fGIF)
return;
if (DGifSlurp(fGIF) != GIF_OK)
{
DGifCloseFile(fGIF);
fGIF = NULL;
}
fCurrIndex = -1;
fLastDrawIndex = -1;
}
SkGIFMovie::~SkGIFMovie()
{
if (fGIF)
DGifCloseFile(fGIF);
}
static SkMSec savedimage_duration(const SavedImage* image)
{
for (int j = 0; j < image->ExtensionBlockCount; j++)
{
if (image->ExtensionBlocks[j].Function == GRAPHICS_EXT_FUNC_CODE)
{
SkASSERT(image->ExtensionBlocks[j].ByteCount >= 4);
const uint8_t* b = (const uint8_t*)image->ExtensionBlocks[j].Bytes;
return ((b[2] << 8) | b[1]) * 10;
}
}
return 0;
}
bool SkGIFMovie::onGetInfo(Info* info)
{
if (NULL == fGIF)
return false;
SkMSec dur = 0;
for (int i = 0; i < fGIF->ImageCount; i++)
dur += savedimage_duration(&fGIF->SavedImages[i]);
info->fDuration = dur;
info->fWidth = fGIF->SWidth;
info->fHeight = fGIF->SHeight;
info->fIsOpaque = false; // how to compute?
return true;
}
bool SkGIFMovie::onSetTime(SkMSec time)
{
if (NULL == fGIF)
return false;
SkMSec dur = 0;
for (int i = 0; i < fGIF->ImageCount; i++)
{
dur += savedimage_duration(&fGIF->SavedImages[i]);
if (dur >= time)
{
fCurrIndex = i;
return fLastDrawIndex != fCurrIndex;
}
}
fCurrIndex = fGIF->ImageCount - 1;
return true;
}
static void copyLine(uint32_t* dst, const unsigned char* src, const ColorMapObject* cmap,
int transparent, int width)
{
for (; width > 0; width--, src++, dst++) {
if (*src != transparent) {
const GifColorType& col = cmap->Colors[*src];
*dst = SkPackARGB32(0xFF, col.Red, col.Green, col.Blue);
}
}
}
static void copyInterlaceGroup(SkBitmap* bm, const unsigned char*& src,
const ColorMapObject* cmap, int transparent, int copyWidth,
int copyHeight, const GifImageDesc& imageDesc, int rowStep,
int startRow)
{
int row;
// every 'rowStep'th row, starting with row 'startRow'
for (row = startRow; row < copyHeight; row += rowStep) {
uint32_t* dst = bm->getAddr32(imageDesc.Left, imageDesc.Top + row);
copyLine(dst, src, cmap, transparent, copyWidth);
src += imageDesc.Width;
}
// pad for rest height
src += imageDesc.Width * ((imageDesc.Height - row + rowStep - 1) / rowStep);
}
static void blitInterlace(SkBitmap* bm, const SavedImage* frame, const ColorMapObject* cmap,
int transparent)
{
int width = bm->width();
int height = bm->height();
GifWord copyWidth = frame->ImageDesc.Width;
if (frame->ImageDesc.Left + copyWidth > width) {
copyWidth = width - frame->ImageDesc.Left;
}
GifWord copyHeight = frame->ImageDesc.Height;
if (frame->ImageDesc.Top + copyHeight > height) {
copyHeight = height - frame->ImageDesc.Top;
}
// deinterlace
const unsigned char* src = (unsigned char*)frame->RasterBits;
// group 1 - every 8th row, starting with row 0
copyInterlaceGroup(bm, src, cmap, transparent, copyWidth, copyHeight, frame->ImageDesc, 8, 0);
// group 2 - every 8th row, starting with row 4
copyInterlaceGroup(bm, src, cmap, transparent, copyWidth, copyHeight, frame->ImageDesc, 8, 4);
// group 3 - every 4th row, starting with row 2
copyInterlaceGroup(bm, src, cmap, transparent, copyWidth, copyHeight, frame->ImageDesc, 4, 2);
copyInterlaceGroup(bm, src, cmap, transparent, copyWidth, copyHeight, frame->ImageDesc, 2, 1);
}
static void blitNormal(SkBitmap* bm, const SavedImage* frame, const ColorMapObject* cmap,
int transparent)
{
int width = bm->width();
int height = bm->height();
const unsigned char* src = (unsigned char*)frame->RasterBits;
uint32_t* dst = bm->getAddr32(frame->ImageDesc.Left, frame->ImageDesc.Top);
GifWord copyWidth = frame->ImageDesc.Width;
if (frame->ImageDesc.Left + copyWidth > width) {
copyWidth = width - frame->ImageDesc.Left;
}
GifWord copyHeight = frame->ImageDesc.Height;
if (frame->ImageDesc.Top + copyHeight > height) {
copyHeight = height - frame->ImageDesc.Top;
}
for (; copyHeight > 0; copyHeight--) {
copyLine(dst, src, cmap, transparent, copyWidth);
src += frame->ImageDesc.Width;
dst += width;
}
}
static void fillRect(SkBitmap* bm, GifWord left, GifWord top, GifWord width, GifWord height,
uint32_t col)
{
int bmWidth = bm->width();
int bmHeight = bm->height();
uint32_t* dst = bm->getAddr32(left, top);
GifWord copyWidth = width;
if (left + copyWidth > bmWidth) {
copyWidth = bmWidth - left;
}
GifWord copyHeight = height;
if (top + copyHeight > bmHeight) {
copyHeight = bmHeight - top;
}
for (; copyHeight > 0; copyHeight--) {
sk_memset32(dst, col, copyWidth);
dst += bmWidth;
}
}
static void drawFrame(SkBitmap* bm, const SavedImage* frame, const ColorMapObject* cmap)
{
int transparent = -1;
for (int i = 0; i < frame->ExtensionBlockCount; ++i) {
ExtensionBlock* eb = frame->ExtensionBlocks + i;
if (eb->Function == GRAPHICS_EXT_FUNC_CODE &&
eb->ByteCount == 4) {
bool has_transparency = ((eb->Bytes[0] & 1) == 1);
if (has_transparency) {
transparent = (unsigned char)eb->Bytes[3];
}
}
}
if (frame->ImageDesc.ColorMap != NULL) {
// use local color table
cmap = frame->ImageDesc.ColorMap;
}
if (cmap == NULL || cmap->ColorCount != (1 << cmap->BitsPerPixel)) {
SkDEBUGFAIL("bad colortable setup");
return;
}
if (frame->ImageDesc.Interlace) {
blitInterlace(bm, frame, cmap, transparent);
} else {
blitNormal(bm, frame, cmap, transparent);
}
}
static bool checkIfWillBeCleared(const SavedImage* frame)
{
for (int i = 0; i < frame->ExtensionBlockCount; ++i) {
ExtensionBlock* eb = frame->ExtensionBlocks + i;
if (eb->Function == GRAPHICS_EXT_FUNC_CODE &&
eb->ByteCount == 4) {
// check disposal method
int disposal = ((eb->Bytes[0] >> 2) & 7);
if (disposal == 2 || disposal == 3) {
return true;
}
}
}
return false;
}
static void getTransparencyAndDisposalMethod(const SavedImage* frame, bool* trans, int* disposal)
{
*trans = false;
*disposal = 0;
for (int i = 0; i < frame->ExtensionBlockCount; ++i) {
ExtensionBlock* eb = frame->ExtensionBlocks + i;
if (eb->Function == GRAPHICS_EXT_FUNC_CODE &&
eb->ByteCount == 4) {
*trans = ((eb->Bytes[0] & 1) == 1);
*disposal = ((eb->Bytes[0] >> 2) & 7);
}
}
}
// return true if area of 'target' is completely covers area of 'covered'
static bool checkIfCover(const SavedImage* target, const SavedImage* covered)
{
if (target->ImageDesc.Left <= covered->ImageDesc.Left
&& covered->ImageDesc.Left + covered->ImageDesc.Width <=
target->ImageDesc.Left + target->ImageDesc.Width
&& target->ImageDesc.Top <= covered->ImageDesc.Top
&& covered->ImageDesc.Top + covered->ImageDesc.Height <=
target->ImageDesc.Top + target->ImageDesc.Height) {
return true;
}
return false;
}
static void disposeFrameIfNeeded(SkBitmap* bm, const SavedImage* cur, const SavedImage* next,
SkBitmap* backup, SkColor color)
{
// We can skip disposal process if next frame is not transparent
// and completely covers current area
bool curTrans;
int curDisposal;
getTransparencyAndDisposalMethod(cur, &curTrans, &curDisposal);
bool nextTrans;
int nextDisposal;
getTransparencyAndDisposalMethod(next, &nextTrans, &nextDisposal);
if ((curDisposal == 2 || curDisposal == 3)
&& (nextTrans || !checkIfCover(next, cur))) {
switch (curDisposal) {
// restore to background color
// -> 'background' means background under this image.
case 2:
fillRect(bm, cur->ImageDesc.Left, cur->ImageDesc.Top,
cur->ImageDesc.Width, cur->ImageDesc.Height,
color);
break;
// restore to previous
case 3:
bm->swap(*backup);
break;
}
}
// Save current image if next frame's disposal method == 3
if (nextDisposal == 3) {
const uint32_t* src = bm->getAddr32(0, 0);
uint32_t* dst = backup->getAddr32(0, 0);
int cnt = bm->width() * bm->height();
memcpy(dst, src, cnt*sizeof(uint32_t));
}
}
bool SkGIFMovie::onGetBitmap(SkBitmap* bm)
{
const GifFileType* gif = fGIF;
if (NULL == gif)
return false;
if (gif->ImageCount < 1) {
return false;
}
const int width = gif->SWidth;
const int height = gif->SHeight;
if (width <= 0 || height <= 0) {
return false;
}
// no need to draw
if (fLastDrawIndex >= 0 && fLastDrawIndex == fCurrIndex) {
return true;
}
int startIndex = fLastDrawIndex + 1;
if (fLastDrawIndex < 0 || !bm->readyToDraw()) {
// first time
startIndex = 0;
// create bitmap
bm->setConfig(SkBitmap::kARGB_8888_Config, width, height, 0);
if (!bm->allocPixels(NULL)) {
return false;
}
// create bitmap for backup
fBackup.setConfig(SkBitmap::kARGB_8888_Config, width, height, 0);
if (!fBackup.allocPixels(NULL)) {
return false;
}
} else if (startIndex > fCurrIndex) {
// rewind to 1st frame for repeat
startIndex = 0;
}
int lastIndex = fCurrIndex;
if (lastIndex < 0) {
// first time
lastIndex = 0;
} else if (lastIndex > fGIF->ImageCount - 1) {
// this block must not be reached.
lastIndex = fGIF->ImageCount - 1;
}
SkColor bgColor = SkPackARGB32(0, 0, 0, 0);
if (gif->SColorMap != NULL) {
const GifColorType& col = gif->SColorMap->Colors[fGIF->SBackGroundColor];
bgColor = SkColorSetARGB(0xFF, col.Red, col.Green, col.Blue);
}
static SkColor paintingColor = SkPackARGB32(0, 0, 0, 0);
// draw each frames - not intelligent way
for (int i = startIndex; i <= lastIndex; i++) {
const SavedImage* cur = &fGIF->SavedImages[i];
if (i == 0) {
bool trans;
int disposal;
getTransparencyAndDisposalMethod(cur, &trans, &disposal);
if (!trans && gif->SColorMap != NULL) {
paintingColor = bgColor;
} else {
paintingColor = SkColorSetARGB(0, 0, 0, 0);
}
bm->eraseColor(paintingColor);
fBackup.eraseColor(paintingColor);
} else {
// Dispose previous frame before move to next frame.
const SavedImage* prev = &fGIF->SavedImages[i-1];
disposeFrameIfNeeded(bm, prev, cur, &fBackup, paintingColor);
}
// Draw frame
// We can skip this process if this index is not last and disposal
// method == 2 or method == 3
if (i == lastIndex || !checkIfWillBeCleared(cur)) {
drawFrame(bm, cur, gif->SColorMap);
}
}
// save index
fLastDrawIndex = lastIndex;
return true;
}
///////////////////////////////////////////////////////////////////////////////
#include "SkTRegistry.h"
SkMovie* Factory(SkStream* stream) {
char buf[GIF_STAMP_LEN];
if (stream->read(buf, GIF_STAMP_LEN) == GIF_STAMP_LEN) {
if (memcmp(GIF_STAMP, buf, GIF_STAMP_LEN) == 0 ||
memcmp(GIF87_STAMP, buf, GIF_STAMP_LEN) == 0 ||
memcmp(GIF89_STAMP, buf, GIF_STAMP_LEN) == 0) {
// must rewind here, since our construct wants to re-read the data
stream->rewind();
return SkNEW_ARGS(SkGIFMovie, (stream));
}
}
return NULL;
}
static SkTRegistry<SkMovie*, SkStream*> gReg(Factory);
<|endoftext|> |
<commit_before>#ifndef H_ORDER
#define H_ORDER
#include <Wt/Dbo/Dbo>
namespace dbo = Wt::Dbo;
class Order;
#include "../user/User.hpp"
#include "Item.hpp"
enum OrderStatus
{
Ordered,
Sent,
Received
};
class Order
{
public:
dbo::ptr<User> user;
dbo::collection<dbo::ptr<Item> > items;
template<class Action>
void persist(Action& a)
{
dbo::belongsTo(a, user, "user");
dbo::hasMany(a, items, dbo::ManyToOne, "ordering");
}
};
typedef dbo::ptr<Order> POrder;
typedef dbo::collection<POrder> POrders;
#endif //defined H_ORDER
<commit_msg>Add time properties to order class<commit_after>#ifndef H_ORDER
#define H_ORDER
#include <Wt/Dbo/Dbo>
namespace dbo = Wt::Dbo;
class Order;
#include "../user/User.hpp"
#include "Item.hpp"
enum OrderStatus
{
Ordered,
Sent,
Received
};
class Order
{
public:
dbo::ptr<User> user;
dbo::collection<dbo::ptr<Item> > items;
Wt::WDateTime orderTime;
Wt::WDateTime receiveTime;
template<class Action>
void persist(Action& a)
{
dbo::field(a, orderTime, "orderTime");
dbo::field(a, receiveTime, "receiveTime");
dbo::belongsTo(a, user, "user");
dbo::hasMany(a, items, dbo::ManyToOne, "ordering");
}
};
typedef dbo::ptr<Order> POrder;
typedef dbo::collection<POrder> POrders;
#endif //defined H_ORDER
<|endoftext|> |
<commit_before>//===--- LoopUnrolling.cpp - Unroll loops -----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// This file contains functions which are used to decide if a loop worth to be
/// unrolled. Moreover contains function which mark the CFGBlocks which belongs
/// to the unrolled loop and store them in ProgramState.
///
//===----------------------------------------------------------------------===//
#include "clang/Analysis/CFGStmtMap.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/AST/ParentMap.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h"
#include "llvm/ADT/Statistic.h"
using namespace clang;
using namespace ento;
using namespace clang::ast_matchers;
#define DEBUG_TYPE "LoopUnrolling"
STATISTIC(NumTimesLoopUnrolled,
"The # of times a loop has got completely unrolled");
REGISTER_MAP_WITH_PROGRAMSTATE(UnrolledLoops, const Stmt *,
const FunctionDecl *)
namespace clang {
namespace ento {
static bool isLoopStmt(const Stmt *S) {
return S && (isa<ForStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S));
}
static internal::Matcher<Stmt> simpleCondition(StringRef BindName) {
return binaryOperator(
anyOf(hasOperatorName("<"), hasOperatorName(">"), hasOperatorName("<="),
hasOperatorName(">="), hasOperatorName("!=")),
hasEitherOperand(ignoringParenImpCasts(
declRefExpr(to(varDecl(hasType(isInteger())).bind(BindName))))),
hasEitherOperand(ignoringParenImpCasts(integerLiteral())));
}
static internal::Matcher<Stmt> changeIntBoundNode(StringRef NodeName) {
return anyOf(hasDescendant(unaryOperator(
anyOf(hasOperatorName("--"), hasOperatorName("++")),
hasUnaryOperand(ignoringParenImpCasts(
declRefExpr(to(varDecl(equalsBoundNode(NodeName)))))))),
hasDescendant(binaryOperator(
anyOf(hasOperatorName("="), hasOperatorName("+="),
hasOperatorName("/="), hasOperatorName("*="),
hasOperatorName("-=")),
hasLHS(ignoringParenImpCasts(
declRefExpr(to(varDecl(equalsBoundNode(NodeName)))))))));
}
static internal::Matcher<Stmt> callByRef(StringRef NodeName) {
return hasDescendant(callExpr(forEachArgumentWithParam(
declRefExpr(to(varDecl(equalsBoundNode(NodeName)))),
parmVarDecl(hasType(references(qualType(unless(isConstQualified()))))))));
}
static internal::Matcher<Stmt> assignedToRef(StringRef NodeName) {
return hasDescendant(varDecl(
allOf(hasType(referenceType()),
hasInitializer(
anyOf(initListExpr(has(
declRefExpr(to(varDecl(equalsBoundNode(NodeName)))))),
declRefExpr(to(varDecl(equalsBoundNode(NodeName)))))))));
}
static internal::Matcher<Stmt> getAddrTo(StringRef NodeName) {
return hasDescendant(unaryOperator(
hasOperatorName("&"),
hasUnaryOperand(declRefExpr(hasDeclaration(equalsBoundNode(NodeName))))));
}
static internal::Matcher<Stmt> hasSuspiciousStmt(StringRef NodeName) {
return anyOf(hasDescendant(gotoStmt()), hasDescendant(switchStmt()),
// Escaping and not known mutation of the loop counter is handled
// by exclusion of assigning and address-of operators and
// pass-by-ref function calls on the loop counter from the body.
changeIntBoundNode(NodeName), callByRef(NodeName),
getAddrTo(NodeName), assignedToRef(NodeName));
}
static internal::Matcher<Stmt> forLoopMatcher() {
return forStmt(
hasCondition(simpleCondition("initVarName")),
// Initialization should match the form: 'int i = 6' or 'i = 42'.
hasLoopInit(
anyOf(declStmt(hasSingleDecl(
varDecl(allOf(hasInitializer(integerLiteral()),
equalsBoundNode("initVarName"))))),
binaryOperator(hasLHS(declRefExpr(to(varDecl(
equalsBoundNode("initVarName"))))),
hasRHS(integerLiteral())))),
// Incrementation should be a simple increment or decrement
// operator call.
hasIncrement(unaryOperator(
anyOf(hasOperatorName("++"), hasOperatorName("--")),
hasUnaryOperand(declRefExpr(
to(varDecl(allOf(equalsBoundNode("initVarName"),
hasType(isInteger())))))))),
unless(hasBody(hasSuspiciousStmt("initVarName")))).bind("forLoop");
}
bool shouldCompletelyUnroll(const Stmt *LoopStmt, ASTContext &ASTCtx) {
if (!isLoopStmt(LoopStmt))
return false;
// TODO: Match the cases where the bound is not a concrete literal but an
// integer with known value
auto Matches = match(forLoopMatcher(), *LoopStmt, ASTCtx);
return !Matches.empty();
}
namespace {
class LoopBlockVisitor : public ConstStmtVisitor<LoopBlockVisitor> {
public:
LoopBlockVisitor(llvm::SmallPtrSet<const CFGBlock *, 8> &BS) : BlockSet(BS) {}
void VisitChildren(const Stmt *S) {
for (const Stmt *Child : S->children())
if (Child)
Visit(Child);
}
void VisitStmt(const Stmt *S) {
// In case of nested loops we only unroll the inner loop if it's marked too.
if (!S || (isLoopStmt(S) && S != LoopStmt))
return;
BlockSet.insert(StmtToBlockMap->getBlock(S));
VisitChildren(S);
}
void setBlocksOfLoop(const Stmt *Loop, const CFGStmtMap *M) {
BlockSet.clear();
StmtToBlockMap = M;
LoopStmt = Loop;
Visit(LoopStmt);
}
private:
llvm::SmallPtrSet<const CFGBlock *, 8> &BlockSet;
const CFGStmtMap *StmtToBlockMap;
const Stmt *LoopStmt;
};
}
// TODO: refactor this function using LoopExit CFG element - once we have the
// information when the simulation reaches the end of the loop we can cleanup
// the state
bool isUnrolledLoopBlock(const CFGBlock *Block, ExplodedNode *Pred,
AnalysisManager &AMgr) {
const Stmt *Term = Block->getTerminator();
auto State = Pred->getState();
// In case of nested loops in an inlined function should not be unrolled only
// if the inner loop is marked.
if (Term && isLoopStmt(Term) && !State->contains<UnrolledLoops>(Term))
return false;
const CFGBlock *SearchedBlock;
llvm::SmallPtrSet<const CFGBlock *, 8> BlockSet;
LoopBlockVisitor LBV(BlockSet);
// Check the CFGBlocks of every marked loop.
for (auto &E : State->get<UnrolledLoops>()) {
SearchedBlock = Block;
const StackFrameContext *StackFrame = Pred->getStackFrame();
ParentMap PM(E.second->getBody());
CFGStmtMap *M = CFGStmtMap::Build(AMgr.getCFG(E.second), &PM);
LBV.setBlocksOfLoop(E.first, M);
// In case of an inlined function call check if any of its callSiteBlock is
// marked.
while (SearchedBlock && BlockSet.find(SearchedBlock) == BlockSet.end()) {
SearchedBlock = StackFrame->getCallSiteBlock();
StackFrame = StackFrame->getParent()->getCurrentStackFrame();
}
delete M;
if (SearchedBlock)
return true;
}
return false;
}
ProgramStateRef markLoopAsUnrolled(const Stmt *Term, ProgramStateRef State,
const FunctionDecl *FD) {
if (State->contains<UnrolledLoops>(Term))
return State;
State = State->set<UnrolledLoops>(Term, FD);
++NumTimesLoopUnrolled;
return State;
}
}
}
<commit_msg>[StaticAnalyzer] LoopUnrolling - Attempt to fix a crash in r309006.<commit_after>//===--- LoopUnrolling.cpp - Unroll loops -----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// This file contains functions which are used to decide if a loop worth to be
/// unrolled. Moreover contains function which mark the CFGBlocks which belongs
/// to the unrolled loop and store them in ProgramState.
///
//===----------------------------------------------------------------------===//
#include "clang/Analysis/CFGStmtMap.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/AST/ParentMap.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h"
#include "llvm/ADT/Statistic.h"
using namespace clang;
using namespace ento;
using namespace clang::ast_matchers;
#define DEBUG_TYPE "LoopUnrolling"
STATISTIC(NumTimesLoopUnrolled,
"The # of times a loop has got completely unrolled");
REGISTER_MAP_WITH_PROGRAMSTATE(UnrolledLoops, const Stmt *,
const FunctionDecl *)
namespace clang {
namespace ento {
static bool isLoopStmt(const Stmt *S) {
return S && (isa<ForStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S));
}
static internal::Matcher<Stmt> simpleCondition(StringRef BindName) {
return binaryOperator(
anyOf(hasOperatorName("<"), hasOperatorName(">"), hasOperatorName("<="),
hasOperatorName(">="), hasOperatorName("!=")),
hasEitherOperand(ignoringParenImpCasts(
declRefExpr(to(varDecl(hasType(isInteger())).bind(BindName))))),
hasEitherOperand(ignoringParenImpCasts(integerLiteral())));
}
static internal::Matcher<Stmt> changeIntBoundNode(StringRef NodeName) {
return anyOf(hasDescendant(unaryOperator(
anyOf(hasOperatorName("--"), hasOperatorName("++")),
hasUnaryOperand(ignoringParenImpCasts(
declRefExpr(to(varDecl(equalsBoundNode(NodeName)))))))),
hasDescendant(binaryOperator(
anyOf(hasOperatorName("="), hasOperatorName("+="),
hasOperatorName("/="), hasOperatorName("*="),
hasOperatorName("-=")),
hasLHS(ignoringParenImpCasts(
declRefExpr(to(varDecl(equalsBoundNode(NodeName)))))))));
}
static internal::Matcher<Stmt> callByRef(StringRef NodeName) {
return hasDescendant(callExpr(forEachArgumentWithParam(
declRefExpr(to(varDecl(equalsBoundNode(NodeName)))),
parmVarDecl(hasType(references(qualType(unless(isConstQualified()))))))));
}
static internal::Matcher<Stmt> assignedToRef(StringRef NodeName) {
return hasDescendant(varDecl(
allOf(hasType(referenceType()),
hasInitializer(
anyOf(initListExpr(has(
declRefExpr(to(varDecl(equalsBoundNode(NodeName)))))),
declRefExpr(to(varDecl(equalsBoundNode(NodeName)))))))));
}
static internal::Matcher<Stmt> getAddrTo(StringRef NodeName) {
return hasDescendant(unaryOperator(
hasOperatorName("&"),
hasUnaryOperand(declRefExpr(hasDeclaration(equalsBoundNode(NodeName))))));
}
static internal::Matcher<Stmt> hasSuspiciousStmt(StringRef NodeName) {
return anyOf(hasDescendant(gotoStmt()), hasDescendant(switchStmt()),
// Escaping and not known mutation of the loop counter is handled
// by exclusion of assigning and address-of operators and
// pass-by-ref function calls on the loop counter from the body.
changeIntBoundNode(NodeName), callByRef(NodeName),
getAddrTo(NodeName), assignedToRef(NodeName));
}
static internal::Matcher<Stmt> forLoopMatcher() {
return forStmt(
hasCondition(simpleCondition("initVarName")),
// Initialization should match the form: 'int i = 6' or 'i = 42'.
hasLoopInit(
anyOf(declStmt(hasSingleDecl(
varDecl(allOf(hasInitializer(integerLiteral()),
equalsBoundNode("initVarName"))))),
binaryOperator(hasLHS(declRefExpr(to(varDecl(
equalsBoundNode("initVarName"))))),
hasRHS(integerLiteral())))),
// Incrementation should be a simple increment or decrement
// operator call.
hasIncrement(unaryOperator(
anyOf(hasOperatorName("++"), hasOperatorName("--")),
hasUnaryOperand(declRefExpr(
to(varDecl(allOf(equalsBoundNode("initVarName"),
hasType(isInteger())))))))),
unless(hasBody(hasSuspiciousStmt("initVarName")))).bind("forLoop");
}
bool shouldCompletelyUnroll(const Stmt *LoopStmt, ASTContext &ASTCtx) {
if (!isLoopStmt(LoopStmt))
return false;
// TODO: Match the cases where the bound is not a concrete literal but an
// integer with known value
auto Matches = match(forLoopMatcher(), *LoopStmt, ASTCtx);
return !Matches.empty();
}
namespace {
class LoopBlockVisitor : public ConstStmtVisitor<LoopBlockVisitor> {
public:
LoopBlockVisitor(llvm::SmallPtrSet<const CFGBlock *, 8> &BS) : BlockSet(BS) {}
void VisitChildren(const Stmt *S) {
for (const Stmt *Child : S->children())
if (Child)
Visit(Child);
}
void VisitStmt(const Stmt *S) {
// In case of nested loops we only unroll the inner loop if it's marked too.
if (!S || (isLoopStmt(S) && S != LoopStmt))
return;
BlockSet.insert(StmtToBlockMap->getBlock(S));
VisitChildren(S);
}
void setBlocksOfLoop(const Stmt *Loop, const CFGStmtMap *M) {
BlockSet.clear();
StmtToBlockMap = M;
LoopStmt = Loop;
Visit(LoopStmt);
}
private:
llvm::SmallPtrSet<const CFGBlock *, 8> &BlockSet;
const CFGStmtMap *StmtToBlockMap;
const Stmt *LoopStmt;
};
}
// TODO: refactor this function using LoopExit CFG element - once we have the
// information when the simulation reaches the end of the loop we can cleanup
// the state
bool isUnrolledLoopBlock(const CFGBlock *Block, ExplodedNode *Pred,
AnalysisManager &AMgr) {
const Stmt *Term = Block->getTerminator();
auto State = Pred->getState();
// In case of nested loops in an inlined function should not be unrolled only
// if the inner loop is marked.
if (Term && isLoopStmt(Term) && !State->contains<UnrolledLoops>(Term))
return false;
const CFGBlock *SearchedBlock;
llvm::SmallPtrSet<const CFGBlock *, 8> BlockSet;
LoopBlockVisitor LBV(BlockSet);
// Check the CFGBlocks of every marked loop.
for (auto &E : State->get<UnrolledLoops>()) {
SearchedBlock = Block;
const StackFrameContext *StackFrame = Pred->getStackFrame();
ParentMap PM(E.second->getBody());
CFGStmtMap *M = CFGStmtMap::Build(AMgr.getCFG(E.second), &PM);
LBV.setBlocksOfLoop(E.first, M);
// In case of an inlined function call check if any of its callSiteBlock is
// marked.
while (BlockSet.find(SearchedBlock) == BlockSet.end() && !StackFrame->inTopFrame()) {
SearchedBlock = StackFrame->getCallSiteBlock();
if(!SearchedBlock)
break;
StackFrame = StackFrame->getParent()->getCurrentStackFrame();
}
delete M;
if (SearchedBlock)
return true;
}
return false;
}
ProgramStateRef markLoopAsUnrolled(const Stmt *Term, ProgramStateRef State,
const FunctionDecl *FD) {
if (State->contains<UnrolledLoops>(Term))
return State;
State = State->set<UnrolledLoops>(Term, FD);
++NumTimesLoopUnrolled;
return State;
}
}
}
<|endoftext|> |
<commit_before>#include "askpassphrasepage.h"
#include "ui_askpassphrasepage.h"
#include "init.h"
#include "util.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include "bitcoingui.h"
#include <QPushButton>
#include <QKeyEvent>
using namespace GUIUtil;
AskPassphrasePage::AskPassphrasePage(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphrasePage),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
this->layout()->setContentsMargins(0, 0, 0, 0);
this->setStyleSheet(GUIUtil::veriAskPassphrasePageStyleSheet);
ui->formLayout->setContentsMargins(250, 200 + HEADER_HEIGHT, 250, 250);
ui->messageLabel->setFont(qFontBold);
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
QWidget::setTabOrder(ui->passEdit1, ui->passEdit2);
QWidget::setTabOrder(ui->passEdit2, ui->passEdit3);
QWidget::setTabOrder(ui->passEdit3, ui->buttonBox->button(QDialogButtonBox::Ok));
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->passEdit1->hide();
ui->passEdit2->show();
ui->passEdit3->show();
ui->passEdit2->setFocus();
ui->passEdit2->setPlaceholderText(tr("New passphrase..."));
ui->passEdit3->setPlaceholderText(tr("Repeat new passphrase..."));
ui->messageLabel->setText(tr("Welcome! Please enter a passphrase of 10 or more characters, or 8 or more words."));
ui->warningLabel->setText(tr("WARNING: IF YOU LOSE YOUR PASSPHRASE, YOU WILL LOSE ALL OF YOUR COINS!"));
break;
case Lock: // Ask passphrase
ui->passEdit1->hide();
ui->passEdit2->hide();
ui->passEdit3->hide();
ui->messageLabel->setText(tr("Click OK to lock the wallet."));
break;
case Unlock: // Ask passphrase
ui->passEdit1->show();
ui->passEdit2->hide();
ui->passEdit3->hide();
ui->passEdit1->setFocus();
ui->passEdit1->setPlaceholderText(tr("Enter passphrase..."));
ui->messageLabel->setText(tr("Please enter your passphrase to unlock the wallet."));
break;
}
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit1, SIGNAL(returnPressed()), this, SLOT(accept()));
connect(ui->passEdit2, SIGNAL(returnPressed()), this, SLOT(accept()));
connect(ui->passEdit3, SIGNAL(returnPressed()), this, SLOT(accept()));
connect(ui->buttonBox->button(QDialogButtonBox::Ok), SIGNAL(clicked()), this, SLOT(accept()));
}
AskPassphrasePage::~AskPassphrasePage()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
delete ui;
}
void AskPassphrasePage::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphrasePage::accept()
{
if(!model)
return;
SecureString oldpass, newpass1, newpass2;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
switch(mode)
{
case Encrypt: // Encrypt wallet and set password
if(newpass1.empty() || newpass2.empty())
{
ui->messageLabel->setText(tr("The new passphrase cannot be blank."));
break;
}
if(newpass1.length() < 10)
{
ui->messageLabel->setText(tr("The new passphrase must be 10 or more characters."));
break;
}
if(newpass1 != newpass2)
{
ui->messageLabel->setText(tr("The passphrases do not match."));
break;
}
else
{
if(model->setWalletEncrypted(true, newpass1))
{
ui->messageLabel->setText(tr("SolarCoin will now restart to finish the encryption process."));
ui->warningLabel->setText(tr("IMPORTANT: Previous backups of your wallet should be replaced with the new one."));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit2->setText(QString(""));
ui->passEdit2->setEnabled(false);
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
ui->passEdit3->setText(QString(""));
ui->passEdit3->setEnabled(false);
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
this->repaint();
fRestart = true;
MilliSleep(7 * 1000);
StartShutdown();
}
else
{
ui->messageLabel->setText(tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
}
break;
case Lock: // Turn off staking
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
emit lockWalletFeatures(true);
break;
case Unlock: // Turn on staking
if(!model->setWalletLocked(false, oldpass))
{
ui->messageLabel->setText(tr("The passphrase entered for the wallet is incorrect."));
}
else
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
ui->passEdit1->setText(QString(""));
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
emit lockWalletFeatures(false);
}
break;
}
}
void AskPassphrasePage::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = true;
switch(mode)
{
case Lock: // Old passphrase x1
break;
case Unlock: // Old passphrase x1
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphrasePage::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->warningLabel->setText(tr("WARNING: The Caps Lock key is on!"));
} else {
ui->warningLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphrasePage::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) {
fCapsLock = true;
ui->warningLabel->setText(tr("WARNING: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->warningLabel->clear();
}
}
}
return QWidget::eventFilter(object, event);
}
<commit_msg>tweak<commit_after>#include "askpassphrasepage.h"
#include "ui_askpassphrasepage.h"
#include "init.h"
#include "util.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include "bitcoingui.h"
#include <QPushButton>
#include <QKeyEvent>
using namespace GUIUtil;
AskPassphrasePage::AskPassphrasePage(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphrasePage),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
this->layout()->setContentsMargins(0, 0, 0, 0);
this->setStyleSheet(GUIUtil::veriAskPassphrasePageStyleSheet);
ui->formLayout->setContentsMargins(250, 250 + HEADER_HEIGHT, 250, 250);
ui->messageLabel->setFont(qFontBold);
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
QWidget::setTabOrder(ui->passEdit1, ui->passEdit2);
QWidget::setTabOrder(ui->passEdit2, ui->passEdit3);
QWidget::setTabOrder(ui->passEdit3, ui->buttonBox->button(QDialogButtonBox::Ok));
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->passEdit1->hide();
ui->passEdit2->show();
ui->passEdit3->show();
ui->passEdit2->setFocus();
ui->passEdit2->setPlaceholderText(tr("New passphrase..."));
ui->passEdit3->setPlaceholderText(tr("Repeat new passphrase..."));
ui->messageLabel->setText(tr("Welcome! Please enter a passphrase of 10 or more characters, or 8 or more words."));
ui->warningLabel->setText(tr("WARNING: IF YOU LOSE YOUR PASSPHRASE, YOU WILL LOSE ALL OF YOUR COINS!"));
break;
case Lock: // Ask passphrase
ui->passEdit1->hide();
ui->passEdit2->hide();
ui->passEdit3->hide();
ui->messageLabel->setText(tr("Click OK to lock the wallet."));
break;
case Unlock: // Ask passphrase
ui->passEdit1->show();
ui->passEdit2->hide();
ui->passEdit3->hide();
ui->passEdit1->setFocus();
ui->passEdit1->setPlaceholderText(tr("Enter passphrase..."));
ui->messageLabel->setText(tr("Please enter your passphrase to unlock the wallet."));
break;
}
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit1, SIGNAL(returnPressed()), this, SLOT(accept()));
connect(ui->passEdit2, SIGNAL(returnPressed()), this, SLOT(accept()));
connect(ui->passEdit3, SIGNAL(returnPressed()), this, SLOT(accept()));
connect(ui->buttonBox->button(QDialogButtonBox::Ok), SIGNAL(clicked()), this, SLOT(accept()));
}
AskPassphrasePage::~AskPassphrasePage()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
delete ui;
}
void AskPassphrasePage::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphrasePage::accept()
{
if(!model)
return;
SecureString oldpass, newpass1, newpass2;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
switch(mode)
{
case Encrypt: // Encrypt wallet and set password
if(newpass1.empty() || newpass2.empty())
{
ui->messageLabel->setText(tr("The new passphrase cannot be blank."));
break;
}
if(newpass1.length() < 10)
{
ui->messageLabel->setText(tr("The new passphrase must be 10 or more characters."));
break;
}
if(newpass1 != newpass2)
{
ui->messageLabel->setText(tr("The passphrases do not match."));
break;
}
else
{
if(model->setWalletEncrypted(true, newpass1))
{
ui->messageLabel->setText(tr("SolarCoin will now restart to finish the encryption process."));
ui->warningLabel->setText(tr("IMPORTANT: Previous backups of your wallet should be replaced with the new one."));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit2->setText(QString(""));
ui->passEdit2->setEnabled(false);
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
ui->passEdit3->setText(QString(""));
ui->passEdit3->setEnabled(false);
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
this->repaint();
fRestart = true;
MilliSleep(7 * 1000);
StartShutdown();
}
else
{
ui->messageLabel->setText(tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
}
break;
case Lock: // Turn off staking
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
emit lockWalletFeatures(true);
break;
case Unlock: // Turn on staking
if(!model->setWalletLocked(false, oldpass))
{
ui->messageLabel->setText(tr("The passphrase entered for the wallet is incorrect."));
}
else
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
ui->passEdit1->setText(QString(""));
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
emit lockWalletFeatures(false);
}
break;
}
}
void AskPassphrasePage::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = true;
switch(mode)
{
case Lock: // Old passphrase x1
break;
case Unlock: // Old passphrase x1
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphrasePage::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->warningLabel->setText(tr("WARNING: The Caps Lock key is on!"));
} else {
ui->warningLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphrasePage::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) {
fCapsLock = true;
ui->warningLabel->setText(tr("WARNING: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->warningLabel->clear();
}
}
}
return QWidget::eventFilter(object, event);
}
<|endoftext|> |
<commit_before>
#include "loop.h"
#include <glib.h>
#include <uv.h>
/* Integration for the GLib main loop and UV's main loop */
namespace GNodeJS {
struct uv_loop_source {
GSource source;
uv_loop_t *loop;
};
static gboolean uv_loop_source_prepare (GSource *base, int *timeout) {
struct uv_loop_source *source = (struct uv_loop_source *) base;
uv_update_time (source->loop);
bool loop_alive = uv_loop_alive (source->loop);
/* If the loop is dead, we can simply sleep forever until a GTK+ source
* (presumably) wakes us back up again. */
if (!loop_alive)
return FALSE;
/* Otherwise, check the timeout. If the timeout is 0, that means we're
* ready to go. Otherwise, keep sleeping until the timeout happens again. */
int t = uv_backend_timeout (source->loop);
*timeout = t;
if (t == 0)
return TRUE;
else
return FALSE;
}
static gboolean uv_loop_source_dispatch (GSource *base, GSourceFunc callback, gpointer user_data) {
struct uv_loop_source *source = (struct uv_loop_source *) base;
uv_run (source->loop, UV_RUN_NOWAIT);
return G_SOURCE_CONTINUE;
}
static GSourceFuncs uv_loop_source_funcs = {
uv_loop_source_prepare,
NULL,
uv_loop_source_dispatch,
NULL,
NULL, NULL,
};
static GSource *uv_loop_source_new (uv_loop_t *loop) {
struct uv_loop_source *source = (struct uv_loop_source *) g_source_new (&uv_loop_source_funcs, sizeof (*source));
source->loop = loop;
g_source_add_unix_fd (&source->source,
uv_backend_fd (loop),
(GIOCondition) (G_IO_IN | G_IO_OUT | G_IO_ERR));
return &source->source;
}
void StartLoop() {
GSource *source = uv_loop_source_new (uv_default_loop ());
g_source_attach (source, NULL);
}
};
<commit_msg>loop: Add explanatory comments<commit_after>
#include "loop.h"
#include <glib.h>
#include <uv.h>
/* Integration for the GLib main loop and uv's main loop */
/* The way that this works is that we take uv's loop and nest it inside GLib's
* mainloop, since nesting GLib inside uv seems to be fairly impossible until
* either uv allows external sources to drive prepare/checl, or until GLib
* exposes an epoll fd to wait on... */
namespace GNodeJS {
struct uv_loop_source {
GSource source;
uv_loop_t *loop;
};
static gboolean uv_loop_source_prepare (GSource *base, int *timeout) {
struct uv_loop_source *source = (struct uv_loop_source *) base;
uv_update_time (source->loop);
bool loop_alive = uv_loop_alive (source->loop);
/* If the loop is dead, we can simply sleep forever until a GTK+ source
* (presumably) wakes us back up again. */
if (!loop_alive)
return FALSE;
/* Otherwise, check the timeout. If the timeout is 0, that means we're
* ready to go. Otherwise, keep sleeping until the timeout happens again. */
int t = uv_backend_timeout (source->loop);
*timeout = t;
if (t == 0)
return TRUE;
else
return FALSE;
}
static gboolean uv_loop_source_dispatch (GSource *base, GSourceFunc callback, gpointer user_data) {
struct uv_loop_source *source = (struct uv_loop_source *) base;
uv_run (source->loop, UV_RUN_NOWAIT);
return G_SOURCE_CONTINUE;
}
static GSourceFuncs uv_loop_source_funcs = {
uv_loop_source_prepare,
NULL,
uv_loop_source_dispatch,
NULL,
NULL, NULL,
};
static GSource *uv_loop_source_new (uv_loop_t *loop) {
struct uv_loop_source *source = (struct uv_loop_source *) g_source_new (&uv_loop_source_funcs, sizeof (*source));
source->loop = loop;
g_source_add_unix_fd (&source->source,
uv_backend_fd (loop),
(GIOCondition) (G_IO_IN | G_IO_OUT | G_IO_ERR));
return &source->source;
}
void StartLoop() {
GSource *source = uv_loop_source_new (uv_default_loop ());
g_source_attach (source, NULL);
}
};
<|endoftext|> |
<commit_before>
/* We would like to have a tool that extracts translations for given
authority data
The german term is found in Field 150
Currently there are two different kinds of translations:
TxTheo-Translations with the following definitions:
710: Körperschaft - fremdsprachige Äquivalenz
711: Konferenz - fremdsprachige Äquivalenz
700: Person - fremdsprachige Äquivalenz
730: Titel - fremdsprachige Äquivalenz
750: Sachbegriff - fremdsprachige Äquivalenz
751: Geografikum - fremdsprachige Äquivalenz
LoC/Rameau Translations:
700: Person - Bevorzugter Name in einem anderen Datenbestand
710: Körperschaft - Bevorzugter Name in einem anderen Datenbestand
711: Konferenz - Bevorzugte Benennung in einem anderen Datenbestand
730: Einheitstitel - Bevorzugter Name in einem anderen Datenbestand
750: Sachbegriff - Bevorzugte Benennung in einem anderen Datenbestand
751: Geografikum - Bevorzugter Name in einem anderen Datenbestand
*/
#include <iostream>
#include <vector>
#include <cstdlib>
#include "Compiler.h"
#include "MarcUtil.h"
#include "MediaTypeUtil.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "util.h"
// Languages to handle
//enum languages { "en","fr" };
const unsigned int NUMBER_OF_LANGUAGES = 2;
const std::string languages_to_create_str = "en, fr";
enum languages { en, fr };
void Usage() {
std::cerr << "Usage: " << ::progname << " norm_data_marc_input extracted_translations\n";
std::exit(EXIT_FAILURE);
}
void augment_ixtheo_tag_with_language(const MarcUtil::Record &record, const std::string tag, std::vector<std::string> &translations) {
auto ixtheo_pos = std::find(translations.begin(), translations.end(), "IxTheo");
if (ixtheo_pos != translations.end()) {
std::vector<std::string> ixtheo_lang_code;
record.extractSubfields(tag, "9" , &ixtheo_lang_code);
for (auto lang_code : ixtheo_lang_code) {
if (lang_code.find("eng") != std::string::npos && *ixtheo_pos != "IxTheo_eng")
*ixtheo_pos = *ixtheo_pos + "_eng";
// FIXME: There are currently no french translations...
else if (lang_code.find("fra") != std::string::npos && *ixtheo_pos != "IxTheo_fra")
*ixtheo_pos = *ixtheo_pos + "_fra";
}
}
}
void ExtractTranslations(File* const marc_norm_input,
const std::string german_term_field_spec,
const std::string translation_field_spec,
std::map<std::string,std::string> term_to_translation_map[]) {
std::set<std::string> german_tags_and_subfield_codes;
if (unlikely(StringUtil::Split(german_term_field_spec, ':', &german_tags_and_subfield_codes) < 1))
Error("ExtractTranslations: Need at least one translation field");
std::set<std::string> translation_tags_and_subfield_codes;
if (unlikely(StringUtil::Split(translation_field_spec, ':', &translation_tags_and_subfield_codes) < 1))
Error("ExtractTranslations: Need at least one translation field");
unsigned count(0);
while (const MarcUtil::Record record = MarcUtil::Record::XmlFactory(marc_norm_input)) {
std::vector<std::string> german_term;
// Determine the german term we will have translations for
for (auto tag_and_subfields : german_tags_and_subfield_codes) {
const std::string tag(tag_and_subfields.substr(0, 3));
const std::string subfields(tag_and_subfields.substr(3));
std::vector<std::string> german_term_for_one_field;
record.extractSubfields(tag, subfields, &german_term_for_one_field);
// We may get the german term from only one field
if (german_term.size() > 1)
Warning("We have german terms in more than one field for PPN: " + record.getFields()[0]);
if (not german_term_for_one_field.empty())
german_term = german_term_for_one_field;
}
std::vector<std::string> all_translations;
// Extract all additional translations
for (auto tag_and_subfields : translation_tags_and_subfield_codes) {
const std::string tag(tag_and_subfields.substr(0, 3));
const std::string subfields(tag_and_subfields.substr(3));
std::vector<std::string> translations;
record.extractSubfields(tag, subfields, &translations);
// For IxTheo-Translations add the language code in the same field
augment_ixtheo_tag_with_language(record, tag, translations);
all_translations.insert(std::end(all_translations), std::begin(translations), std::end(translations));
}
for (auto it = all_translations.begin(); it != all_translations.end(); it++) {
if (*it == "IxTheo_eng") {
term_to_translation_map[en].emplace(StringUtil::Join(german_term, ' '), *(it+1));
++it;
}
else if (*it == "IxTheo_fra") {
term_to_translation_map[fr].emplace(StringUtil::Join(german_term, ' '), *(it+1));
++it;
}
else if (*it == "lcsh") {
term_to_translation_map[en].emplace(StringUtil::Join(german_term, ' '), *(it+1));
++it;
}
else if (*it == "ram") {
term_to_translation_map[fr].emplace(StringUtil::Join(german_term, ' '), *(it+1));
++it;
}
}
}
count++;
}
std::unique_ptr<File> OpenInputFile(const std::string &filename) {
std::string mode("r");
mode += MediaTypeUtil::GetFileMediaType(filename) == "application/lz4" ? "u" : "m";
std::unique_ptr<File> file(new File(filename, mode));
if (file == nullptr)
Error("can't open \"" + filename + "\" for reading!");
return file;
}
int main(int argc, char **argv) {
progname = argv[0];
if (argc != 3)
Usage();
const std::string norm_data_marc_input_filename(argv[1]);
std::unique_ptr<File> norm_data_marc_input(OpenInputFile(norm_data_marc_input_filename));
const std::string extracted_translations_filename(argv[2]);
if (unlikely(norm_data_marc_input_filename == extracted_translations_filename))
Error("Norm data input file name equals output file name!");
std::string output_mode("w");
if (norm_data_marc_input->isCompressingOrUncompressing())
output_mode += 'c';
// Create a file for each language
std::vector<std::string> output_file_components;
if (unlikely(StringUtil::Split(extracted_translations_filename, ".", &output_file_components) < 1))
Error("extracted_translations_filename " + extracted_translations_filename + " is not valid");
std::vector<std::string> languages_to_create;
if (unlikely(StringUtil::Split(languages_to_create_str, ',', &languages_to_create) < 1))
Error("String " + languages_to_create_str + " is not valid");
File* lang_file[NUMBER_OF_LANGUAGES];
unsigned i(0);
// Derive output components from given input filename
std::string extension = (output_file_components.size() > 1) ? output_file_components.back() : "";
std::string basename;
if (extension != "")
output_file_components.pop_back();
basename = StringUtil::Join(output_file_components, ".");
// Assemble output filename
for (auto lang : languages_to_create) {
lang = StringUtil::Trim(lang);
std::string lang_file_name_str =
(extension != "") ? basename + "_" + lang + "." + extension : basename + "_" + lang;
lang_file[i++] = new File(lang_file_name_str, output_mode);
if (lang_file[i] == NULL)
Error("can't open \"" + lang_file_name_str + "\" for writing!");
}
try {
std::map<std::string, std::string> term_to_translation_map[NUMBER_OF_LANGUAGES];
ExtractTranslations(norm_data_marc_input.get(), "100a:150a", "750a2", term_to_translation_map);
for (auto line : term_to_translation_map[en]) {
*(lang_file[en]) << line.first << "|" << line.second << "\n";
}
for (auto line : term_to_translation_map[fr]) {
*(lang_file[fr]) << line.first << "|" << line.second << "\n";
}
} catch (const std::exception &x) {
Error("caught exception: " + std::string(x.what()));
}
}
<commit_msg>Changes as desired<commit_after>/** \file extract_normdata_translations.cc
* \brief Extract IxTheo and MACS translations from the normdata file and write it to
* language specific text files
* \author Johannes Riedl
*/
/*
Copyright (C) 2016, Library of the University of Tübingen
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/>.
*/
/* The German term is found in Field 150
Currently there are two different kinds of translations:
IxTheo-Translations with the following definitions:
710: Körperschaft - fremdsprachige Äquivalenz
711: Konferenz - fremdsprachige Äquivalenz
700: Person - fremdsprachige Äquivalenz
730: Titel - fremdsprachige Äquivalenz
750: Sachbegriff - fremdsprachige Äquivalenz
751: Geografikum - fremdsprachige Äquivalenz
LoC/Rameau Translations:
700: Person - Bevorzugter Name in einem anderen Datenbestand
710: Körperschaft - Bevorzugter Name in einem anderen Datenbestand
711: Konferenz - Bevorzugte Benennung in einem anderen Datenbestand
730: Einheitstitel - Bevorzugter Name in einem anderen Datenbestand
750: Sachbegriff - Bevorzugte Benennung in einem anderen Datenbestand
751: Geografikum - Bevorzugter Name in einem anderen Datenbestand
*/
#include <iostream>
#include <vector>
#include <cstdlib>
#include "Compiler.h"
#include "MarcUtil.h"
#include "MediaTypeUtil.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "util.h"
// Languages to handle
const unsigned int NUMBER_OF_LANGUAGES = 2;
const std::vector<std::string> languages_to_create{ "en", "fr" };
enum languages { en, fr };
void Usage() {
std::cerr << "Usage: " << ::progname << " norm_data_marc_input extracted_translations\n";
std::exit(EXIT_FAILURE);
}
void augmentIxTheoTagWithLanguage(const MarcUtil::Record &record, const std::string &tag, std::vector<std::string> * const translations) {
auto ixtheo_pos = std::find(translations->begin(), translations->end(), "IxTheo");
if (ixtheo_pos != translations->end()) {
std::vector<std::string> ixtheo_lang_code;
record.extractSubfields(tag, "9" , &ixtheo_lang_code);
for (auto lang_code : ixtheo_lang_code) {
if (lang_code.find("eng") != std::string::npos and *ixtheo_pos != "IxTheo_eng")
*ixtheo_pos += "_eng";
else if (lang_code.find("fra") != std::string::npos and *ixtheo_pos != "IxTheo_fra")
*ixtheo_pos += "_fra";
else
Warning("Unsupported language code " + lang_code);
}
}
}
void ExtractTranslations(File* const marc_norm_input,
const std::string german_term_field_spec,
const std::string translation_field_spec,
std::map<std::string,std::string> term_to_translation_map[])
{
std::set<std::string> german_tags_and_subfield_codes;
if (unlikely(StringUtil::Split(german_term_field_spec, ':', &german_tags_and_subfield_codes) < 1))
Error("ExtractTranslations: Need at least one translation field");
std::set<std::string> translation_tags_and_subfield_codes;
if (unlikely(StringUtil::Split(translation_field_spec, ':', &translation_tags_and_subfield_codes) < 1))
Error("ExtractTranslations: Need at least one translation field");
unsigned count(0);
while (const MarcUtil::Record record = MarcUtil::Record::XmlFactory(marc_norm_input)) {
std::vector<std::string> german_term;
// Determine the German term we will have translations for
for (const auto tag_and_subfields : german_tags_and_subfield_codes) {
const std::string tag(tag_and_subfields.substr(0, 3));
const std::string subfields(tag_and_subfields.substr(3));
std::vector<std::string> german_term_for_one_field;
record.extractSubfields(tag, subfields, &german_term_for_one_field);
// We may get the german term from only one field
if (german_term.size() > 1)
Warning("We have german terms in more than one field for PPN: " + record.getFields()[0]);
if (not german_term_for_one_field.empty())
german_term = german_term_for_one_field;
}
std::vector<std::string> all_translations;
// Extract all additional translations
for (auto tag_and_subfields : translation_tags_and_subfield_codes) {
const std::string tag(tag_and_subfields.substr(0, 3));
const std::string subfields(tag_and_subfields.substr(3));
std::vector<std::string> translations;
record.extractSubfields(tag, subfields, &translations);
// For IxTheo-Translations add the language code in the same field
augmentIxTheoTagWithLanguage(record, tag, &translations);
all_translations.insert(all_translations.end(), translations.begin(), translations.end());
}
for (auto it = all_translations.begin(); it != all_translations.end(); ++it) {
if (*it == "IxTheo_eng") {
term_to_translation_map[en].emplace(StringUtil::Join(german_term, ' '), *(it + 1));
++it;
} else if (*it == "IxTheo_fra") {
term_to_translation_map[fr].emplace(StringUtil::Join(german_term, ' '), *(it + 1));
++it;
} else if (*it == "lcsh") {
term_to_translation_map[en].emplace(StringUtil::Join(german_term, ' '), *(it + 1));
++it;
} else if (*it == "ram") {
term_to_translation_map[fr].emplace(StringUtil::Join(german_term, ' '), *(it + 1));
++it;
}
}
}
++count;
}
std::unique_ptr<File> OpenInputFile(const std::string &filename) {
std::string mode("r");
if (MediaTypeUtil::GetFileMediaType(filename) == "application/lz4")
mode += "u";
std::unique_ptr<File> file(new File(filename, mode));
if (file->fail())
Error("can't open \"" + filename + "\" for reading!");
return file;
}
int main(int argc, char **argv) {
::progname = argv[0];
if (argc != 3)
Usage();
const std::string norm_data_marc_input_filename(argv[1]);
std::unique_ptr<File> norm_data_marc_input(OpenInputFile(norm_data_marc_input_filename));
const std::string extracted_translations_filename(argv[2]);
if (unlikely(norm_data_marc_input_filename == extracted_translations_filename))
Error("Norm data input file name equals output file name!");
std::string output_mode("w");
if (norm_data_marc_input->isCompressingOrUncompressing())
output_mode += 'c';
// Create a file for each language
std::vector<std::string> output_file_components;
if (unlikely(StringUtil::Split(extracted_translations_filename, ".", &output_file_components) < 1))
Error("extracted_translations_filename " + extracted_translations_filename + " is not valid");
File *lang_files[NUMBER_OF_LANGUAGES];
unsigned i(0);
// Derive output components from given input filename
std::string extension = (output_file_components.size() > 1) ? output_file_components.back() : "";
std::string basename;
if (not extension.empty())
output_file_components.pop_back();
basename = StringUtil::Join(output_file_components, ".");
// Assemble output filename
for (auto lang : languages_to_create) {
lang = StringUtil::Trim(lang);
std::string lang_file_name_str =
(extension != "") ? basename + "_" + lang + "." + extension : basename + "_" + lang;
lang_files[i++] = new File(lang_file_name_str, output_mode);
if (lang_files[i]->fail())
Error("can't open \"" + lang_file_name_str + "\" for writing!");
}
try {
std::map<std::string, std::string> term_to_translation_map[NUMBER_OF_LANGUAGES];
ExtractTranslations(norm_data_marc_input.get(), "100a:150a", "750a2", term_to_translation_map);
for (auto line : term_to_translation_map[en]) {
*(lang_files[en]) << line.first << "|" << line.second << "\n";
}
for (auto line : term_to_translation_map[fr]) {
*(lang_files[fr]) << line.first << "|" << line.second << "\n";
}
} catch (const std::exception &x) {
Error("caught exception: " + std::string(x.what()));
}
}
<|endoftext|> |
<commit_before>//===- AArch64MacroFusion.cpp - AArch64 Macro Fusion ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file This file contains the AArch64 implementation of the DAG scheduling
/// mutation to pair instructions back to back.
//
//===----------------------------------------------------------------------===//
#include "AArch64Subtarget.h"
#include "llvm/CodeGen/MacroFusion.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
using namespace llvm;
namespace {
/// CMN, CMP, TST followed by Bcc
static bool isArithmeticBccPair(unsigned FirstOpcode, unsigned SecondOpcode,
const MachineInstr *FirstMI) {
if (SecondOpcode != AArch64::Bcc)
return false;
switch (FirstOpcode) {
case AArch64::INSTRUCTION_LIST_END:
return true;
case AArch64::ADDSWri:
case AArch64::ADDSWrr:
case AArch64::ADDSXri:
case AArch64::ADDSXrr:
case AArch64::ANDSWri:
case AArch64::ANDSWrr:
case AArch64::ANDSXri:
case AArch64::ANDSXrr:
case AArch64::SUBSWri:
case AArch64::SUBSWrr:
case AArch64::SUBSXri:
case AArch64::SUBSXrr:
case AArch64::BICSWrr:
case AArch64::BICSXrr:
return true;
case AArch64::ADDSWrs:
case AArch64::ADDSXrs:
case AArch64::ANDSWrs:
case AArch64::ANDSXrs:
case AArch64::SUBSWrs:
case AArch64::SUBSXrs:
case AArch64::BICSWrs:
case AArch64::BICSXrs:
// Shift value can be 0 making these behave like the "rr" variant...
return !AArch64InstrInfo::hasShiftedReg(*FirstMI);
}
return false;
}
/// ALU operations followed by CBZ/CBNZ.
static bool isArithmeticCbzPair(unsigned FirstOpcode, unsigned SecondOpcode,
const MachineInstr *FirstMI) {
if (SecondOpcode != AArch64::CBNZW &&
SecondOpcode != AArch64::CBNZX &&
SecondOpcode != AArch64::CBZW &&
SecondOpcode != AArch64::CBZX)
return false;
switch (FirstOpcode) {
case AArch64::INSTRUCTION_LIST_END:
return true;
case AArch64::ADDWri:
case AArch64::ADDWrr:
case AArch64::ADDXri:
case AArch64::ADDXrr:
case AArch64::ANDWri:
case AArch64::ANDWrr:
case AArch64::ANDXri:
case AArch64::ANDXrr:
case AArch64::EORWri:
case AArch64::EORWrr:
case AArch64::EORXri:
case AArch64::EORXrr:
case AArch64::ORRWri:
case AArch64::ORRWrr:
case AArch64::ORRXri:
case AArch64::ORRXrr:
case AArch64::SUBWri:
case AArch64::SUBWrr:
case AArch64::SUBXri:
case AArch64::SUBXrr:
return true;
case AArch64::ADDWrs:
case AArch64::ADDXrs:
case AArch64::ANDWrs:
case AArch64::ANDXrs:
case AArch64::SUBWrs:
case AArch64::SUBXrs:
case AArch64::BICWrs:
case AArch64::BICXrs:
// Shift value can be 0 making these behave like the "rr" variant...
return !AArch64InstrInfo::hasShiftedReg(*FirstMI);
}
return false;
}
/// AES crypto encoding or decoding.
static bool isAESPair(unsigned FirstOpcode, unsigned SecondOpcode) {
// AES encode.
if ((FirstOpcode == AArch64::INSTRUCTION_LIST_END ||
FirstOpcode == AArch64::AESErr) &&
(SecondOpcode == AArch64::AESMCrr ||
SecondOpcode == AArch64::AESMCrrTied))
return true;
// AES decode.
else if ((FirstOpcode == AArch64::INSTRUCTION_LIST_END ||
FirstOpcode == AArch64::AESDrr) &&
(SecondOpcode == AArch64::AESIMCrr ||
SecondOpcode == AArch64::AESIMCrrTied))
return true;
return false;
}
/// AESE/AESD/PMULL + EOR.
static bool isCryptoEORPair(unsigned FirstOpcode, unsigned SecondOpcode) {
if (SecondOpcode != AArch64::EORv16i8)
return false;
switch (FirstOpcode) {
case AArch64::INSTRUCTION_LIST_END:
case AArch64::AESErr:
case AArch64::AESDrr:
case AArch64::PMULLv16i8:
case AArch64::PMULLv8i8:
case AArch64::PMULLv1i64:
case AArch64::PMULLv2i64:
return true;
}
return false;
}
/// Literal generation.
static bool isLiteralsPair(unsigned FirstOpcode, unsigned SecondOpcode,
const MachineInstr *FirstMI,
const MachineInstr &SecondMI) {
// PC relative address.
if ((FirstOpcode == AArch64::INSTRUCTION_LIST_END ||
FirstOpcode == AArch64::ADRP) &&
SecondOpcode == AArch64::ADDXri)
return true;
// 32 bit immediate.
else if ((FirstOpcode == AArch64::INSTRUCTION_LIST_END ||
FirstOpcode == AArch64::MOVZWi) &&
(SecondOpcode == AArch64::MOVKWi &&
SecondMI.getOperand(3).getImm() == 16))
return true;
// Lower half of 64 bit immediate.
else if((FirstOpcode == AArch64::INSTRUCTION_LIST_END ||
FirstOpcode == AArch64::MOVZXi) &&
(SecondOpcode == AArch64::MOVKXi &&
SecondMI.getOperand(3).getImm() == 16))
return true;
// Upper half of 64 bit immediate.
else if ((FirstOpcode == AArch64::INSTRUCTION_LIST_END ||
(FirstOpcode == AArch64::MOVKXi &&
FirstMI->getOperand(3).getImm() == 32)) &&
(SecondOpcode == AArch64::MOVKXi &&
SecondMI.getOperand(3).getImm() == 48))
return true;
return false;
}
// Fuse address generation and loads or stores.
static bool isAddressLdStPair(unsigned FirstOpcode, unsigned SecondOpcode,
const MachineInstr &SecondMI) {
switch (SecondOpcode) {
case AArch64::STRBBui:
case AArch64::STRBui:
case AArch64::STRDui:
case AArch64::STRHHui:
case AArch64::STRHui:
case AArch64::STRQui:
case AArch64::STRSui:
case AArch64::STRWui:
case AArch64::STRXui:
case AArch64::LDRBBui:
case AArch64::LDRBui:
case AArch64::LDRDui:
case AArch64::LDRHHui:
case AArch64::LDRHui:
case AArch64::LDRQui:
case AArch64::LDRSui:
case AArch64::LDRWui:
case AArch64::LDRXui:
case AArch64::LDRSBWui:
case AArch64::LDRSBXui:
case AArch64::LDRSHWui:
case AArch64::LDRSHXui:
case AArch64::LDRSWui:
switch (FirstOpcode) {
case AArch64::INSTRUCTION_LIST_END:
return true;
case AArch64::ADR:
return SecondMI.getOperand(2).getImm() == 0;
case AArch64::ADRP:
return true;
}
}
return false;
}
// Compare and conditional select.
static bool isCCSelectPair(unsigned FirstOpcode, unsigned SecondOpcode,
const MachineInstr *FirstMI) {
// 32 bits
if (SecondOpcode == AArch64::CSELWr) {
// Assume the 1st instr to be a wildcard if it is unspecified.
if (FirstOpcode == AArch64::INSTRUCTION_LIST_END)
return true;
if (FirstMI->definesRegister(AArch64::WZR))
switch (FirstOpcode) {
case AArch64::SUBSWrs:
return !AArch64InstrInfo::hasShiftedReg(*FirstMI);
case AArch64::SUBSWrx:
return !AArch64InstrInfo::hasExtendedReg(*FirstMI);
case AArch64::SUBSWrr:
case AArch64::SUBSWri:
return true;
}
}
// 64 bits
else if (SecondOpcode == AArch64::CSELXr) {
// Assume the 1st instr to be a wildcard if it is unspecified.
if (FirstOpcode == AArch64::INSTRUCTION_LIST_END)
return true;
if (FirstMI->definesRegister(AArch64::XZR))
switch (FirstOpcode) {
case AArch64::SUBSXrs:
return !AArch64InstrInfo::hasShiftedReg(*FirstMI);
case AArch64::SUBSXrx:
case AArch64::SUBSXrx64:
return !AArch64InstrInfo::hasExtendedReg(*FirstMI);
case AArch64::SUBSXrr:
case AArch64::SUBSXri:
return true;
}
}
return false;
}
/// Check if the instr pair, FirstMI and SecondMI, should be fused
/// together. Given SecondMI, when FirstMI is unspecified, then check if
/// SecondMI may be part of a fused pair at all.
static bool shouldScheduleAdjacent(const TargetInstrInfo &TII,
const TargetSubtargetInfo &TSI,
const MachineInstr *FirstMI,
const MachineInstr &SecondMI) {
const AArch64Subtarget &ST = static_cast<const AArch64Subtarget&>(TSI);
// Assume the 1st instr to be a wildcard if it is unspecified.
unsigned FirstOpc =
FirstMI ? FirstMI->getOpcode()
: static_cast<unsigned>(AArch64::INSTRUCTION_LIST_END);
unsigned SecondOpc = SecondMI.getOpcode();
if (ST.hasArithmeticBccFusion() &&
isArithmeticBccPair(FirstOpc, SecondOpc, FirstMI))
return true;
if (ST.hasArithmeticCbzFusion() &&
isArithmeticCbzPair(FirstOpc, SecondOpc, FirstMI))
return true;
if (ST.hasFuseAES() && isAESPair(FirstOpc, SecondOpc))
return true;
if (ST.hasFuseCryptoEOR() && isCryptoEORPair(FirstOpc, SecondOpc))
return true;
if (ST.hasFuseLiterals() &&
isLiteralsPair(FirstOpc, SecondOpc, FirstMI, SecondMI))
return true;
if (ST.hasFuseAddress() && isAddressLdStPair(FirstOpc, SecondOpc, SecondMI))
return true;
if (ST.hasFuseCCSelect() && isCCSelectPair(FirstOpc, SecondOpc, FirstMI))
return true;
return false;
}
} // end namespace
namespace llvm {
std::unique_ptr<ScheduleDAGMutation> createAArch64MacroFusionDAGMutation () {
return createMacroFusionDAGMutation(shouldScheduleAdjacent);
}
} // end namespace llvm
<commit_msg>[NFC][AArch64] Refactor macro fusion<commit_after>//===- AArch64MacroFusion.cpp - AArch64 Macro Fusion ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file This file contains the AArch64 implementation of the DAG scheduling
/// mutation to pair instructions back to back.
//
//===----------------------------------------------------------------------===//
#include "AArch64Subtarget.h"
#include "llvm/CodeGen/MacroFusion.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
using namespace llvm;
namespace {
/// CMN, CMP, TST followed by Bcc
static bool isArithmeticBccPair(const MachineInstr *FirstMI,
const MachineInstr &SecondMI) {
if (SecondMI.getOpcode() != AArch64::Bcc)
return false;
// Assume the 1st instr to be a wildcard if it is unspecified.
if (FirstMI == nullptr)
return true;
switch (FirstMI->getOpcode()) {
case AArch64::ADDSWri:
case AArch64::ADDSWrr:
case AArch64::ADDSXri:
case AArch64::ADDSXrr:
case AArch64::ANDSWri:
case AArch64::ANDSWrr:
case AArch64::ANDSXri:
case AArch64::ANDSXrr:
case AArch64::SUBSWri:
case AArch64::SUBSWrr:
case AArch64::SUBSXri:
case AArch64::SUBSXrr:
case AArch64::BICSWrr:
case AArch64::BICSXrr:
return true;
case AArch64::ADDSWrs:
case AArch64::ADDSXrs:
case AArch64::ANDSWrs:
case AArch64::ANDSXrs:
case AArch64::SUBSWrs:
case AArch64::SUBSXrs:
case AArch64::BICSWrs:
case AArch64::BICSXrs:
// Shift value can be 0 making these behave like the "rr" variant...
return !AArch64InstrInfo::hasShiftedReg(*FirstMI);
}
return false;
}
/// ALU operations followed by CBZ/CBNZ.
static bool isArithmeticCbzPair(const MachineInstr *FirstMI,
const MachineInstr &SecondMI) {
switch (SecondMI.getOpcode()) {
default:
return false;
case AArch64::CBNZW:
case AArch64::CBNZX:
case AArch64::CBZW:
case AArch64::CBZX:
LLVM_FALLTHROUGH;
}
// Assume the 1st instr to be a wildcard if it is unspecified.
if (FirstMI == nullptr)
return true;
switch (FirstMI->getOpcode()) {
case AArch64::ADDWri:
case AArch64::ADDWrr:
case AArch64::ADDXri:
case AArch64::ADDXrr:
case AArch64::ANDWri:
case AArch64::ANDWrr:
case AArch64::ANDXri:
case AArch64::ANDXrr:
case AArch64::EORWri:
case AArch64::EORWrr:
case AArch64::EORXri:
case AArch64::EORXrr:
case AArch64::ORRWri:
case AArch64::ORRWrr:
case AArch64::ORRXri:
case AArch64::ORRXrr:
case AArch64::SUBWri:
case AArch64::SUBWrr:
case AArch64::SUBXri:
case AArch64::SUBXrr:
return true;
case AArch64::ADDWrs:
case AArch64::ADDXrs:
case AArch64::ANDWrs:
case AArch64::ANDXrs:
case AArch64::SUBWrs:
case AArch64::SUBXrs:
case AArch64::BICWrs:
case AArch64::BICXrs:
// Shift value can be 0 making these behave like the "rr" variant...
return !AArch64InstrInfo::hasShiftedReg(*FirstMI);
}
return false;
}
/// AES crypto encoding or decoding.
static bool isAESPair(const MachineInstr *FirstMI,
const MachineInstr &SecondMI) {
// Assume the 1st instr to be a wildcard if it is unspecified.
switch (SecondMI.getOpcode()) {
// AES encode.
case AArch64::AESMCrr:
case AArch64::AESMCrrTied:
return FirstMI == nullptr || FirstMI->getOpcode() == AArch64::AESErr;
// AES decode.
case AArch64::AESIMCrr:
case AArch64::AESIMCrrTied:
return FirstMI == nullptr || FirstMI->getOpcode() == AArch64::AESDrr;
}
return false;
}
/// AESE/AESD/PMULL + EOR.
static bool isCryptoEORPair(const MachineInstr *FirstMI,
const MachineInstr &SecondMI) {
if (SecondMI.getOpcode() != AArch64::EORv16i8)
return false;
// Assume the 1st instr to be a wildcard if it is unspecified.
if (FirstMI == nullptr)
return true;
switch (FirstMI->getOpcode()) {
case AArch64::AESErr:
case AArch64::AESDrr:
case AArch64::PMULLv16i8:
case AArch64::PMULLv8i8:
case AArch64::PMULLv1i64:
case AArch64::PMULLv2i64:
return true;
}
return false;
}
/// Literal generation.
static bool isLiteralsPair(const MachineInstr *FirstMI,
const MachineInstr &SecondMI) {
// Assume the 1st instr to be a wildcard if it is unspecified.
// PC relative address.
if ((FirstMI == nullptr || FirstMI->getOpcode() == AArch64::ADRP) &&
SecondMI.getOpcode() == AArch64::ADDXri)
return true;
// 32 bit immediate.
if ((FirstMI == nullptr || FirstMI->getOpcode() == AArch64::MOVZWi) &&
(SecondMI.getOpcode() == AArch64::MOVKWi &&
SecondMI.getOperand(3).getImm() == 16))
return true;
// Lower half of 64 bit immediate.
if((FirstMI == nullptr || FirstMI->getOpcode() == AArch64::MOVZXi) &&
(SecondMI.getOpcode() == AArch64::MOVKXi &&
SecondMI.getOperand(3).getImm() == 16))
return true;
// Upper half of 64 bit immediate.
if ((FirstMI == nullptr ||
(FirstMI->getOpcode() == AArch64::MOVKXi &&
FirstMI->getOperand(3).getImm() == 32)) &&
(SecondMI.getOpcode() == AArch64::MOVKXi &&
SecondMI.getOperand(3).getImm() == 48))
return true;
return false;
}
/// Fuse address generation and loads or stores.
static bool isAddressLdStPair(const MachineInstr *FirstMI,
const MachineInstr &SecondMI) {
switch (SecondMI.getOpcode()) {
case AArch64::STRBBui:
case AArch64::STRBui:
case AArch64::STRDui:
case AArch64::STRHHui:
case AArch64::STRHui:
case AArch64::STRQui:
case AArch64::STRSui:
case AArch64::STRWui:
case AArch64::STRXui:
case AArch64::LDRBBui:
case AArch64::LDRBui:
case AArch64::LDRDui:
case AArch64::LDRHHui:
case AArch64::LDRHui:
case AArch64::LDRQui:
case AArch64::LDRSui:
case AArch64::LDRWui:
case AArch64::LDRXui:
case AArch64::LDRSBWui:
case AArch64::LDRSBXui:
case AArch64::LDRSHWui:
case AArch64::LDRSHXui:
case AArch64::LDRSWui:
// Assume the 1st instr to be a wildcard if it is unspecified.
if (FirstMI == nullptr)
return true;
switch (FirstMI->getOpcode()) {
case AArch64::ADR:
return SecondMI.getOperand(2).getImm() == 0;
case AArch64::ADRP:
return true;
}
}
return false;
}
/// Compare and conditional select.
static bool isCCSelectPair(const MachineInstr *FirstMI,
const MachineInstr &SecondMI) {
// 32 bits
if (SecondMI.getOpcode() == AArch64::CSELWr) {
// Assume the 1st instr to be a wildcard if it is unspecified.
if (FirstMI == nullptr)
return true;
if (FirstMI->definesRegister(AArch64::WZR))
switch (FirstMI->getOpcode()) {
case AArch64::SUBSWrs:
return !AArch64InstrInfo::hasShiftedReg(*FirstMI);
case AArch64::SUBSWrx:
return !AArch64InstrInfo::hasExtendedReg(*FirstMI);
case AArch64::SUBSWrr:
case AArch64::SUBSWri:
return true;
}
}
// 64 bits
if (SecondMI.getOpcode() == AArch64::CSELXr) {
// Assume the 1st instr to be a wildcard if it is unspecified.
if (FirstMI == nullptr)
return true;
if (FirstMI->definesRegister(AArch64::XZR))
switch (FirstMI->getOpcode()) {
case AArch64::SUBSXrs:
return !AArch64InstrInfo::hasShiftedReg(*FirstMI);
case AArch64::SUBSXrx:
case AArch64::SUBSXrx64:
return !AArch64InstrInfo::hasExtendedReg(*FirstMI);
case AArch64::SUBSXrr:
case AArch64::SUBSXri:
return true;
}
}
return false;
}
/// Check if the instr pair, FirstMI and SecondMI, should be fused
/// together. Given SecondMI, when FirstMI is unspecified, then check if
/// SecondMI may be part of a fused pair at all.
static bool shouldScheduleAdjacent(const TargetInstrInfo &TII,
const TargetSubtargetInfo &TSI,
const MachineInstr *FirstMI,
const MachineInstr &SecondMI) {
const AArch64Subtarget &ST = static_cast<const AArch64Subtarget&>(TSI);
// All checking functions assume that the 1st instr is a wildcard if it is
// unspecified.
if (ST.hasArithmeticBccFusion() && isArithmeticBccPair(FirstMI, SecondMI))
return true;
if (ST.hasArithmeticCbzFusion() && isArithmeticCbzPair(FirstMI, SecondMI))
return true;
if (ST.hasFuseAES() && isAESPair(FirstMI, SecondMI))
return true;
if (ST.hasFuseCryptoEOR() && isCryptoEORPair(FirstMI, SecondMI))
return true;
if (ST.hasFuseLiterals() && isLiteralsPair(FirstMI, SecondMI))
return true;
if (ST.hasFuseAddress() && isAddressLdStPair(FirstMI, SecondMI))
return true;
if (ST.hasFuseCCSelect() && isCCSelectPair(FirstMI, SecondMI))
return true;
return false;
}
} // end namespace
namespace llvm {
std::unique_ptr<ScheduleDAGMutation> createAArch64MacroFusionDAGMutation () {
return createMacroFusionDAGMutation(shouldScheduleAdjacent);
}
} // end namespace llvm
<|endoftext|> |
<commit_before>#include <iostream>
#include <boost/program_options/errors.hpp>
#include <sdd/order/order_error.hh>
#include "conf/fill_configuration.hh"
#include "mc/mc.hh"
#include "parsers/parse.hh"
#include "parsers/parse_error.hh"
#include "pn/tina.hh"
#include "util/export_to_tina.hh"
#include "util/select_input.hh"
/*------------------------------------------------------------------------------------------------*/
int
main(int argc, char** argv)
{
using namespace pnmc;
try
{
boost::optional<conf::configuration> conf_opt;
conf_opt = conf::fill_configuration(argc, argv);
if (not conf_opt) // --help or --version
{
return 0;
}
const auto& conf = *conf_opt;
auto in = util::select_input(conf);
const auto net_ptr = parsers::parse(conf, *in);
util::export_to_tina(conf, *net_ptr);
mc::mc worker(conf);
worker(*net_ptr);
return 0;
}
catch (const boost::program_options::error& e)
{
std::cerr << e.what() << std::endl;
std::cerr << "Exiting." << std::endl;
return 1;
}
catch (const parsers::parse_error& e)
{
std::cerr << "Error when parsing input:" << std::endl;
std::cerr << e.what() << std::endl;
std::cerr << "Exiting." << std::endl;
return 2;
}
// catch (const sdd::order_error& e)
// {
// std::cerr << "Order error:" << std::endl;
// std::cerr << e.what() << std::endl;
// std::cerr << "Exiting." << std::endl;
// return 3;
// }
// catch (const std::runtime_error& e)
// {
// std::cerr << "Error:" << std::endl;
// std::cerr << e.what() << std::endl;
// std::cerr << "Exiting." << std::endl;
// return 4;
// }
// catch (std::exception& e)
// {
// std::cerr << "Error unknown. Please report the following to [email protected]." << std::endl;
// std::cerr << e.what() << std::endl;
// std::cerr << "Exiting." << std::endl;
// return -1;
// }
}
/*------------------------------------------------------------------------------------------------*/
<commit_msg>Reinstate handling of exceptions in main.<commit_after>#include <iostream>
#include <boost/program_options/errors.hpp>
#include <sdd/order/order_error.hh>
#include "conf/fill_configuration.hh"
#include "mc/mc.hh"
#include "parsers/parse.hh"
#include "parsers/parse_error.hh"
#include "pn/tina.hh"
#include "util/export_to_tina.hh"
#include "util/select_input.hh"
/*------------------------------------------------------------------------------------------------*/
int
main(int argc, char** argv)
{
using namespace pnmc;
try
{
boost::optional<conf::configuration> conf_opt;
conf_opt = conf::fill_configuration(argc, argv);
if (not conf_opt) // --help or --version
{
return 0;
}
const auto& conf = *conf_opt;
auto in = util::select_input(conf);
const auto net_ptr = parsers::parse(conf, *in);
util::export_to_tina(conf, *net_ptr);
mc::mc worker(conf);
worker(*net_ptr);
return 0;
}
catch (const boost::program_options::error& e)
{
std::cerr << e.what() << std::endl;
std::cerr << "Exiting." << std::endl;
return 1;
}
catch (const parsers::parse_error& e)
{
std::cerr << "Error when parsing input:" << std::endl;
std::cerr << e.what() << std::endl;
std::cerr << "Exiting." << std::endl;
return 2;
}
catch (const sdd::order_error& e)
{
std::cerr << "Order error:" << std::endl;
std::cerr << e.what() << std::endl;
std::cerr << "Exiting." << std::endl;
return 3;
}
catch (const std::runtime_error& e)
{
std::cerr << "Error:" << std::endl;
std::cerr << e.what() << std::endl;
std::cerr << "Exiting." << std::endl;
return 4;
}
catch (std::exception& e)
{
std::cerr << "Error unknown. Please report the following to [email protected]." << std::endl;
std::cerr << e.what() << std::endl;
std::cerr << "Exiting." << std::endl;
return -1;
}
}
/*------------------------------------------------------------------------------------------------*/
<|endoftext|> |
<commit_before>/* ------------------------------------------------------------------------ */
/* Copyright 2002-2020, OpenNebula Project, OpenNebula Systems */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------*/
// -----------------------------------------------------------------------------
// This file includes the SQL schema defintion for OpenNebula objects
// -----------------------------------------------------------------------------
namespace one_db
{
/* ---------------------------------------------------------------------- */
/* HOST TABLES */
/* ---------------------------------------------------------------------- */
const char * host_table = "host_pool";
const char * host_db_names = "oid, name, body, state, uid, gid, owner_u, "
"group_u, other_u, cid";
const char * host_db_bootstrap =
"CREATE TABLE IF NOT EXISTS host_pool ("
" oid INTEGER PRIMARY KEY, "
" name VARCHAR(128),"
" body MEDIUMTEXT,"
" state INTEGER,"
" uid INTEGER,"
" gid INTEGER,"
" owner_u INTEGER,"
" group_u INTEGER,"
" other_u INTEGER,"
" cid INTEGER)";
const char * host_monitor_table = "host_monitoring";
const char * host_monitor_db_names = "hid, last_mon_time, body";
const char * host_monitor_db_bootstrap =
"CREATE TABLE IF NOT EXISTS host_monitoring ("
" hid INTEGER,"
" last_mon_time INTEGER,"
" body MEDIUMTEXT,"
" PRIMARY KEY(hid, last_mon_time))";
/* ---------------------------------------------------------------------- */
/* VM TABLES */
/* ---------------------------------------------------------------------- */
const char * vm_table = "vm_pool";
const char * vm_db_names =
"oid, name, body, uid, gid, state, lcm_state, "
"owner_u, group_u, other_u, short_body, search_token";
const char * vm_db_bootstrap = "CREATE TABLE IF NOT EXISTS "
"vm_pool (oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, "
"uid INTEGER, gid INTEGER, state INTEGER, "
"lcm_state INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
"short_body MEDIUMTEXT, search_token MEDIUMTEXT";
const char * vm_monitor_table = "vm_monitoring";
const char * vm_monitor_db_names = "vmid, last_poll, body";
const char * vm_monitor_db_bootstrap = "CREATE TABLE IF NOT EXISTS "
"vm_monitoring (vmid INTEGER, last_poll INTEGER, body MEDIUMTEXT, "
"PRIMARY KEY(vmid, last_poll))";
const char * vm_showback_table = "vm_showback";
const char * vm_showback_db_names = "vmid, year, month, body";
const char * vm_showback_db_bootstrap =
"CREATE TABLE IF NOT EXISTS vm_showback "
"(vmid INTEGER, year INTEGER, month INTEGER, body MEDIUMTEXT, "
"PRIMARY KEY(vmid, year, month))";
const char * vm_import_table = "vm_import";
const char * vm_import_db_names = "deploy_id, vmid";
const char * vm_import_db_bootstrap =
"CREATE TABLE IF NOT EXISTS vm_import "
"(deploy_id VARCHAR(128), vmid INTEGER, PRIMARY KEY(deploy_id))";
const char * vm_group_table = "vmgroup_pool";
const char * vm_group_db_names = "oid, name, body, uid, gid, owner_u, group_u, "
"other_u";
const char * vm_group_db_bootstrap = "CREATE TABLE IF NOT EXISTS vmgroup_pool "
"(oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, "
"uid INTEGER, gid INTEGER, owner_u INTEGER, group_u INTEGER, "
"other_u INTEGER, UNIQUE(name,uid))";
const char * vm_template_table = "template_pool";
const char * vm_template_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * vm_template_db_bootstrap =
"CREATE TABLE IF NOT EXISTS template_pool (oid INTEGER PRIMARY KEY, "
"name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, "
"owner_u INTEGER, group_u INTEGER, other_u INTEGER)";
/* ---------------------------------------------------------------------- */
/* Cluster tables */
/* ---------------------------------------------------------------------- */
const char * cluster_table = "cluster_pool";
const char * cluster_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * cluster_db_bootstrap = "CREATE TABLE IF NOT EXISTS cluster_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
"UNIQUE(name))";
const char * cluster_datastore_table = "cluster_datastore_relation";
const char * cluster_datastore_db_names = "cid, oid";
const char * cluster_datastore_db_bootstrap =
"CREATE TABLE IF NOT EXISTS cluster_datastore_relation ("
"cid INTEGER, oid INTEGER, PRIMARY KEY(cid, oid))";
const char * cluster_network_table = "cluster_network_relation";
const char * cluster_network_db_names = "cid, oid";
const char * cluster_network_db_bootstrap =
"CREATE TABLE IF NOT EXISTS cluster_network_relation ("
"cid INTEGER, oid INTEGER, PRIMARY KEY(cid, oid))";
const char * cluster_bitmap_table = "cluster_vnc_bitmap";
/* ---------------------------------------------------------------------- */
/* ACL tables */
/* ---------------------------------------------------------------------- */
const char * acl_table = "acl";
const char * acl_db_names = "oid, user_oid, resource, rights, zone";
const char * acl_db_bootstrap = "CREATE TABLE IF NOT EXISTS "
"acl (oid INT PRIMARY KEY, user_oid BIGINT, resource BIGINT, "
"rights BIGINT, zone BIGINT, UNIQUE(user_oid, resource, rights, zone))";
/* ---------------------------------------------------------------------- */
/* Datastore tables */
/* ---------------------------------------------------------------------- */
const char * ds_table = "datastore_pool";
const char * ds_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * ds_db_bootstrap =
"CREATE TABLE IF NOT EXISTS datastore_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER)";
/* ---------------------------------------------------------------------- */
/* Document tables */
/* ---------------------------------------------------------------------- */
const char * doc_table = "document_pool";
const char * doc_db_names =
"oid, name, body, type, uid, gid, owner_u, group_u, other_u";
const char * doc_db_bootstrap =
"CREATE TABLE IF NOT EXISTS document_pool (oid INTEGER PRIMARY KEY, "
"name VARCHAR(128), body MEDIUMTEXT, type INTEGER, uid INTEGER, gid INTEGER, "
"owner_u INTEGER, group_u INTEGER, other_u INTEGER)";
/* ---------------------------------------------------------------------- */
/* Group tables */
/* ---------------------------------------------------------------------- */
const char * group_table = "group_pool";
const char * group_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * group_db_bootstrap = "CREATE TABLE IF NOT EXISTS group_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
"UNIQUE(name))";
/* ---------------------------------------------------------------------- */
/* History tables */
/* ---------------------------------------------------------------------- */
const char * history_table = "history";
const char * history_db_names = "vid, seq, body, stime, etime";
const char * history_db_bootstrap = "CREATE TABLE IF NOT EXISTS "
"history (vid INTEGER, seq INTEGER, body MEDIUMTEXT, "
"stime INTEGER, etime INTEGER,PRIMARY KEY(vid,seq))";
/* ---------------------------------------------------------------------- */
/* Hook tables */
/* ---------------------------------------------------------------------- */
const char * hook_table = "hook_pool";
const char * hook_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u, type";
const char * hook_db_bootstrap = "CREATE TABLE IF NOT EXISTS hook_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER,"
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, type INTEGER)";
const char * hook_log_table = "hook_log";
const char * hook_log_db_names = "hkid, exeid, timestamp, rc, body";
const char * hook_log_db_bootstrap = "CREATE TABLE IF NOT EXISTS hook_log"
" (hkid INTEGER, exeid INTEGER, timestamp INTEGER, rc INTEGER,"
" body MEDIUMTEXT,PRIMARY KEY(hkid, exeid))";
/* ---------------------------------------------------------------------- */
/* Image tables */
/* ---------------------------------------------------------------------- */
const char * image_table = "image_pool";
const char * image_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * image_db_bootstrap = "CREATE TABLE IF NOT EXISTS image_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
"UNIQUE(name,uid) )";
/* ---------------------------------------------------------------------- */
/* Log tables */
/* ---------------------------------------------------------------------- */
const char * log_table = "logdb";
const char * log_db_names = "log_index, term, sqlcmd, timestamp, fed_index, applied";
const char * log_db_bootstrap = "CREATE TABLE IF NOT EXISTS "
"logdb (log_index BIGINT UNSIGNED PRIMARY KEY, term INTEGER, sqlcmd MEDIUMTEXT, "
"timestamp INTEGER, fed_index BIGINT UNSIGNED, applied BOOLEAN)";
/* ---------------------------------------------------------------------- */
/* Marketplace tables */
/* ---------------------------------------------------------------------- */
const char * mp_table = "marketplace_pool";
const char * mp_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * mp_db_bootstrap =
"CREATE TABLE IF NOT EXISTS marketplace_pool (oid INTEGER PRIMARY KEY, "
"name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, "
"owner_u INTEGER, group_u INTEGER, other_u INTEGER)";
const char * mp_app_table = "marketplaceapp_pool";
const char * mp_app_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * mp_app_db_bootstrap =
"CREATE TABLE IF NOT EXISTS marketplaceapp_pool (oid INTEGER PRIMARY KEY, "
"name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, "
"owner_u INTEGER, group_u INTEGER, other_u INTEGER, UNIQUE(name,uid))";
/* ---------------------------------------------------------------------- */
/* Quotas tables */
/* ---------------------------------------------------------------------- */
const char * group_quotas_db_table = "group_quotas";
const char * group_quotas_db_names = "group_oid, body";
const char * group_quotas_db_oid_column = "group_oid";
const char * group_quotas_db_bootstrap =
"CREATE TABLE IF NOT EXISTS group_quotas ("
"group_oid INTEGER PRIMARY KEY, body MEDIUMTEXT)";
const char * user_quotas_db_table = "user_quotas";
const char * user_quotas_db_names = "user_oid, body";
const char * user_quotas_db_oid_column = "user_oid";
const char * user_quotas_db_bootstrap =
"CREATE TABLE IF NOT EXISTS user_quotas ("
"user_oid INTEGER PRIMARY KEY, body MEDIUMTEXT)";
/* ---------------------------------------------------------------------- */
/* Security Group tables */
/* ---------------------------------------------------------------------- */
const char * sg_table = "secgroup_pool";
const char * sg_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * sg_db_bootstrap = "CREATE TABLE IF NOT EXISTS secgroup_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
"UNIQUE(name,uid))";
/* ---------------------------------------------------------------------- */
/* User tables */
/* ---------------------------------------------------------------------- */
const char * user_table = "user_pool";
const char * user_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * user_db_bootstrap = "CREATE TABLE IF NOT EXISTS user_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
"UNIQUE(name))";
/* ---------------------------------------------------------------------- */
/* VDC tables */
/* ---------------------------------------------------------------------- */
const char * vdc_table = "vdc_pool";
const char * vdc_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * vdc_db_bootstrap = "CREATE TABLE IF NOT EXISTS vdc_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
"UNIQUE(name))";
/* ---------------------------------------------------------------------- */
/* Virtual Network tables */
/* ---------------------------------------------------------------------- */
const char * vn_table = "network_pool";
const char * vn_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u, pid";
const char * vn_db_bootstrap = "CREATE TABLE IF NOT EXISTS"
" network_pool (oid INTEGER PRIMARY KEY, name VARCHAR(128),"
" body MEDIUMTEXT, uid INTEGER, gid INTEGER,"
" owner_u INTEGER, group_u INTEGER, other_u INTEGER,"
" pid INTEGER, UNIQUE(name,uid))";
const char * vn_template_table = "vn_template_pool";
const char * vn_template_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * vn_template_db_bootstrap =
"CREATE TABLE IF NOT EXISTS vn_template_pool (oid INTEGER PRIMARY KEY, "
"name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, "
"owner_u INTEGER, group_u INTEGER, other_u INTEGER)";
/* ---------------------------------------------------------------------- */
/* Virtual Router tables */
/* ---------------------------------------------------------------------- */
const char * vr_table = "vrouter_pool";
const char * vr_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * vr_db_bootstrap =
"CREATE TABLE IF NOT EXISTS vrouter_pool (oid INTEGER PRIMARY KEY, "
"name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, "
"owner_u INTEGER, group_u INTEGER, other_u INTEGER)";
/* ---------------------------------------------------------------------- */
/* Zone tables */
/* ---------------------------------------------------------------------- */
const char * zone_table = "zone_pool";
const char * zone_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * zone_db_bootstrap = "CREATE TABLE IF NOT EXISTS zone_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
"UNIQUE(name))";
}
<commit_msg>B #5025: Use userset collumn name (#151)<commit_after>/* ------------------------------------------------------------------------ */
/* Copyright 2002-2020, OpenNebula Project, OpenNebula Systems */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------*/
// -----------------------------------------------------------------------------
// This file includes the SQL schema defintion for OpenNebula objects
// -----------------------------------------------------------------------------
namespace one_db
{
/* ---------------------------------------------------------------------- */
/* HOST TABLES */
/* ---------------------------------------------------------------------- */
const char * host_table = "host_pool";
const char * host_db_names = "oid, name, body, state, uid, gid, owner_u, "
"group_u, other_u, cid";
const char * host_db_bootstrap =
"CREATE TABLE IF NOT EXISTS host_pool ("
" oid INTEGER PRIMARY KEY, "
" name VARCHAR(128),"
" body MEDIUMTEXT,"
" state INTEGER,"
" uid INTEGER,"
" gid INTEGER,"
" owner_u INTEGER,"
" group_u INTEGER,"
" other_u INTEGER,"
" cid INTEGER)";
const char * host_monitor_table = "host_monitoring";
const char * host_monitor_db_names = "hid, last_mon_time, body";
const char * host_monitor_db_bootstrap =
"CREATE TABLE IF NOT EXISTS host_monitoring ("
" hid INTEGER,"
" last_mon_time INTEGER,"
" body MEDIUMTEXT,"
" PRIMARY KEY(hid, last_mon_time))";
/* ---------------------------------------------------------------------- */
/* VM TABLES */
/* ---------------------------------------------------------------------- */
const char * vm_table = "vm_pool";
const char * vm_db_names =
"oid, name, body, uid, gid, state, lcm_state, "
"owner_u, group_u, other_u, short_body, search_token";
const char * vm_db_bootstrap = "CREATE TABLE IF NOT EXISTS "
"vm_pool (oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, "
"uid INTEGER, gid INTEGER, state INTEGER, "
"lcm_state INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
"short_body MEDIUMTEXT, search_token MEDIUMTEXT";
const char * vm_monitor_table = "vm_monitoring";
const char * vm_monitor_db_names = "vmid, last_poll, body";
const char * vm_monitor_db_bootstrap = "CREATE TABLE IF NOT EXISTS "
"vm_monitoring (vmid INTEGER, last_poll INTEGER, body MEDIUMTEXT, "
"PRIMARY KEY(vmid, last_poll))";
const char * vm_showback_table = "vm_showback";
const char * vm_showback_db_names = "vmid, year, month, body";
const char * vm_showback_db_bootstrap =
"CREATE TABLE IF NOT EXISTS vm_showback "
"(vmid INTEGER, year INTEGER, month INTEGER, body MEDIUMTEXT, "
"PRIMARY KEY(vmid, year, month))";
const char * vm_import_table = "vm_import";
const char * vm_import_db_names = "deploy_id, vmid";
const char * vm_import_db_bootstrap =
"CREATE TABLE IF NOT EXISTS vm_import "
"(deploy_id VARCHAR(128), vmid INTEGER, PRIMARY KEY(deploy_id))";
const char * vm_group_table = "vmgroup_pool";
const char * vm_group_db_names = "oid, name, body, uid, gid, owner_u, group_u, "
"other_u";
const char * vm_group_db_bootstrap = "CREATE TABLE IF NOT EXISTS vmgroup_pool "
"(oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, "
"uid INTEGER, gid INTEGER, owner_u INTEGER, group_u INTEGER, "
"other_u INTEGER, UNIQUE(name,uid))";
const char * vm_template_table = "template_pool";
const char * vm_template_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * vm_template_db_bootstrap =
"CREATE TABLE IF NOT EXISTS template_pool (oid INTEGER PRIMARY KEY, "
"name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, "
"owner_u INTEGER, group_u INTEGER, other_u INTEGER)";
/* ---------------------------------------------------------------------- */
/* Cluster tables */
/* ---------------------------------------------------------------------- */
const char * cluster_table = "cluster_pool";
const char * cluster_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * cluster_db_bootstrap = "CREATE TABLE IF NOT EXISTS cluster_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
"UNIQUE(name))";
const char * cluster_datastore_table = "cluster_datastore_relation";
const char * cluster_datastore_db_names = "cid, oid";
const char * cluster_datastore_db_bootstrap =
"CREATE TABLE IF NOT EXISTS cluster_datastore_relation ("
"cid INTEGER, oid INTEGER, PRIMARY KEY(cid, oid))";
const char * cluster_network_table = "cluster_network_relation";
const char * cluster_network_db_names = "cid, oid";
const char * cluster_network_db_bootstrap =
"CREATE TABLE IF NOT EXISTS cluster_network_relation ("
"cid INTEGER, oid INTEGER, PRIMARY KEY(cid, oid))";
const char * cluster_bitmap_table = "cluster_vnc_bitmap";
/* ---------------------------------------------------------------------- */
/* ACL tables */
/* ---------------------------------------------------------------------- */
const char * acl_table = "acl";
const char * acl_db_names = "oid, userset, resource, rights, zone";
const char * acl_db_bootstrap = "CREATE TABLE IF NOT EXISTS "
"acl (oid INT PRIMARY KEY, userset BIGINT, resource BIGINT, "
"rights BIGINT, zone BIGINT, UNIQUE(userset, resource, rights, zone))";
/* ---------------------------------------------------------------------- */
/* Datastore tables */
/* ---------------------------------------------------------------------- */
const char * ds_table = "datastore_pool";
const char * ds_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * ds_db_bootstrap =
"CREATE TABLE IF NOT EXISTS datastore_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER)";
/* ---------------------------------------------------------------------- */
/* Document tables */
/* ---------------------------------------------------------------------- */
const char * doc_table = "document_pool";
const char * doc_db_names =
"oid, name, body, type, uid, gid, owner_u, group_u, other_u";
const char * doc_db_bootstrap =
"CREATE TABLE IF NOT EXISTS document_pool (oid INTEGER PRIMARY KEY, "
"name VARCHAR(128), body MEDIUMTEXT, type INTEGER, uid INTEGER, gid INTEGER, "
"owner_u INTEGER, group_u INTEGER, other_u INTEGER)";
/* ---------------------------------------------------------------------- */
/* Group tables */
/* ---------------------------------------------------------------------- */
const char * group_table = "group_pool";
const char * group_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * group_db_bootstrap = "CREATE TABLE IF NOT EXISTS group_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
"UNIQUE(name))";
/* ---------------------------------------------------------------------- */
/* History tables */
/* ---------------------------------------------------------------------- */
const char * history_table = "history";
const char * history_db_names = "vid, seq, body, stime, etime";
const char * history_db_bootstrap = "CREATE TABLE IF NOT EXISTS "
"history (vid INTEGER, seq INTEGER, body MEDIUMTEXT, "
"stime INTEGER, etime INTEGER,PRIMARY KEY(vid,seq))";
/* ---------------------------------------------------------------------- */
/* Hook tables */
/* ---------------------------------------------------------------------- */
const char * hook_table = "hook_pool";
const char * hook_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u, type";
const char * hook_db_bootstrap = "CREATE TABLE IF NOT EXISTS hook_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER,"
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, type INTEGER)";
const char * hook_log_table = "hook_log";
const char * hook_log_db_names = "hkid, exeid, timestamp, rc, body";
const char * hook_log_db_bootstrap = "CREATE TABLE IF NOT EXISTS hook_log"
" (hkid INTEGER, exeid INTEGER, timestamp INTEGER, rc INTEGER,"
" body MEDIUMTEXT,PRIMARY KEY(hkid, exeid))";
/* ---------------------------------------------------------------------- */
/* Image tables */
/* ---------------------------------------------------------------------- */
const char * image_table = "image_pool";
const char * image_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * image_db_bootstrap = "CREATE TABLE IF NOT EXISTS image_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
"UNIQUE(name,uid) )";
/* ---------------------------------------------------------------------- */
/* Log tables */
/* ---------------------------------------------------------------------- */
const char * log_table = "logdb";
const char * log_db_names = "log_index, term, sqlcmd, timestamp, fed_index, applied";
const char * log_db_bootstrap = "CREATE TABLE IF NOT EXISTS "
"logdb (log_index BIGINT UNSIGNED PRIMARY KEY, term INTEGER, sqlcmd MEDIUMTEXT, "
"timestamp INTEGER, fed_index BIGINT UNSIGNED, applied BOOLEAN)";
/* ---------------------------------------------------------------------- */
/* Marketplace tables */
/* ---------------------------------------------------------------------- */
const char * mp_table = "marketplace_pool";
const char * mp_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * mp_db_bootstrap =
"CREATE TABLE IF NOT EXISTS marketplace_pool (oid INTEGER PRIMARY KEY, "
"name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, "
"owner_u INTEGER, group_u INTEGER, other_u INTEGER)";
const char * mp_app_table = "marketplaceapp_pool";
const char * mp_app_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * mp_app_db_bootstrap =
"CREATE TABLE IF NOT EXISTS marketplaceapp_pool (oid INTEGER PRIMARY KEY, "
"name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, "
"owner_u INTEGER, group_u INTEGER, other_u INTEGER, UNIQUE(name,uid))";
/* ---------------------------------------------------------------------- */
/* Quotas tables */
/* ---------------------------------------------------------------------- */
const char * group_quotas_db_table = "group_quotas";
const char * group_quotas_db_names = "group_oid, body";
const char * group_quotas_db_oid_column = "group_oid";
const char * group_quotas_db_bootstrap =
"CREATE TABLE IF NOT EXISTS group_quotas ("
"group_oid INTEGER PRIMARY KEY, body MEDIUMTEXT)";
const char * user_quotas_db_table = "user_quotas";
const char * user_quotas_db_names = "user_oid, body";
const char * user_quotas_db_oid_column = "user_oid";
const char * user_quotas_db_bootstrap =
"CREATE TABLE IF NOT EXISTS user_quotas ("
"user_oid INTEGER PRIMARY KEY, body MEDIUMTEXT)";
/* ---------------------------------------------------------------------- */
/* Security Group tables */
/* ---------------------------------------------------------------------- */
const char * sg_table = "secgroup_pool";
const char * sg_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * sg_db_bootstrap = "CREATE TABLE IF NOT EXISTS secgroup_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
"UNIQUE(name,uid))";
/* ---------------------------------------------------------------------- */
/* User tables */
/* ---------------------------------------------------------------------- */
const char * user_table = "user_pool";
const char * user_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * user_db_bootstrap = "CREATE TABLE IF NOT EXISTS user_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
"UNIQUE(name))";
/* ---------------------------------------------------------------------- */
/* VDC tables */
/* ---------------------------------------------------------------------- */
const char * vdc_table = "vdc_pool";
const char * vdc_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * vdc_db_bootstrap = "CREATE TABLE IF NOT EXISTS vdc_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
"UNIQUE(name))";
/* ---------------------------------------------------------------------- */
/* Virtual Network tables */
/* ---------------------------------------------------------------------- */
const char * vn_table = "network_pool";
const char * vn_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u, pid";
const char * vn_db_bootstrap = "CREATE TABLE IF NOT EXISTS"
" network_pool (oid INTEGER PRIMARY KEY, name VARCHAR(128),"
" body MEDIUMTEXT, uid INTEGER, gid INTEGER,"
" owner_u INTEGER, group_u INTEGER, other_u INTEGER,"
" pid INTEGER, UNIQUE(name,uid))";
const char * vn_template_table = "vn_template_pool";
const char * vn_template_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * vn_template_db_bootstrap =
"CREATE TABLE IF NOT EXISTS vn_template_pool (oid INTEGER PRIMARY KEY, "
"name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, "
"owner_u INTEGER, group_u INTEGER, other_u INTEGER)";
/* ---------------------------------------------------------------------- */
/* Virtual Router tables */
/* ---------------------------------------------------------------------- */
const char * vr_table = "vrouter_pool";
const char * vr_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * vr_db_bootstrap =
"CREATE TABLE IF NOT EXISTS vrouter_pool (oid INTEGER PRIMARY KEY, "
"name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, "
"owner_u INTEGER, group_u INTEGER, other_u INTEGER)";
/* ---------------------------------------------------------------------- */
/* Zone tables */
/* ---------------------------------------------------------------------- */
const char * zone_table = "zone_pool";
const char * zone_db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * zone_db_bootstrap = "CREATE TABLE IF NOT EXISTS zone_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
"UNIQUE(name))";
}
<|endoftext|> |
<commit_before>
/*
* @(#)$Id$
*
* Copyright (c) 2004 Intel Corporation. All rights reserved.
*
* This file is distributed under the terms in the attached INTEL-LICENSE file.
* If you do not find these files, copies can be found by writing to:
* Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,
* Berkeley, CA, 94704. Attention: Intel License Inquiry.
*
*
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif /* HAVE_CONFIG_H */
#include <async.h>
#include <arpc.h>
#include <iostream>
#include <vector>
#include "tuple.h"
#include "groupby.h"
#include "print.h"
#include "timedPushSource.h"
#include "randomPushSource.h"
#include "pelTransform.h"
#include "timedPullSink.h"
#include "router.h"
#include "queue.h"
/** Test queue */
void agg()
{
std::cout << "\n[Agg]\n";
Router::ConfigurationRef conf = New refcounted< Router::Configuration >();
ElementSpecRef randomPushSourceSpec = conf->addElement(new refcounted<RandomPushSource>("randSource", 1, 0, 5));
ElementSpecRef sourcePrintS = conf->addElement(New refcounted< Print >("AfterSource"));
std::vector<int> primaryFields; primaryFields.push_back(1); primaryFields.push_back(2);
std::vector<int> groupByFields; groupByFields.push_back(1);
std::vector<int> aggFields; aggFields.push_back(3);
std::vector<int> aggTypes; aggTypes.push_back(GroupBy::MIN_AGG);
ElementSpecRef groupBySpec = conf->addElement(New refcounted<GroupBy>("groupBy", "testAgg", primaryFields,
groupByFields, aggFields, aggTypes,
5, true));
ElementSpecRef queueSpec = conf->addElement(New refcounted<Queue>("queue", 10));
ElementSpecRef sinkPrintS = conf->addElement(New refcounted< Print >("BeforeSink"));
ElementSpecRef sinkS = conf->addElement(New refcounted< TimedPullSink >("sink", 1));
conf->hookUp(randomPushSourceSpec, 0, sourcePrintS ,0);
conf->hookUp(sourcePrintS, 0, groupBySpec, 0);
conf->hookUp(groupBySpec, 0, queueSpec, 0);
conf->hookUp(queueSpec, 0, sinkPrintS, 0);
conf->hookUp(sinkPrintS, 0, sinkS, 0);
RouterRef router = New refcounted< Router >(conf);
if (router->initialize(router) == 0) {
std::cout << "Correctly initialized configuration.\n";
} else {
std::cout << "** Failed to initialize correct spec\n";
}
// Activate the router
router->activate();
}
int main(int argc, char **argv)
{
std::cout << "\nTest Agg Start\n";
agg();
amain();
std::cout << "\nTest Agg End\n";
return 0;
}
<commit_msg>aggregate selections<commit_after>
/*
* @(#)$Id$
*
* Copyright (c) 2004 Intel Corporation. All rights reserved.
*
* This file is distributed under the terms in the attached INTEL-LICENSE file.
* If you do not find these files, copies can be found by writing to:
* Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,
* Berkeley, CA, 94704. Attention: Intel License Inquiry.
*
*
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif /* HAVE_CONFIG_H */
#include <async.h>
#include <arpc.h>
#include <iostream>
#include <vector>
#include "tuple.h"
#include "groupby.h"
#include "print.h"
#include "timedPushSource.h"
#include "randomPushSource.h"
#include "pelTransform.h"
#include "timedPullSink.h"
#include "router.h"
#include "queue.h"
/** Test queue */
void agg()
{
std::cout << "\n[Agg]\n";
Router::ConfigurationRef conf = New refcounted< Router::Configuration >();
ElementSpecRef randomPushSourceSpec = conf->addElement(new refcounted<RandomPushSource>("randSource", 1, 0, 5));
ElementSpecRef sourcePrintS = conf->addElement(New refcounted< Print >("AfterSource"));
std::vector<int> primaryFields; primaryFields.push_back(1); primaryFields.push_back(2);
std::vector<int> groupByFields; groupByFields.push_back(1);
std::vector<int> aggFields; aggFields.push_back(3);
std::vector<int> aggTypes; aggTypes.push_back(GroupBy::MIN_AGG);
ElementSpecRef groupBySpec = conf->addElement(New refcounted<GroupBy>("groupBy", "testAgg", primaryFields,
groupByFields, aggFields, aggTypes,
5, false));
ElementSpecRef queueSpec = conf->addElement(New refcounted<Queue>("queue", 10));
ElementSpecRef sinkPrintS = conf->addElement(New refcounted< Print >("BeforeSink"));
ElementSpecRef sinkS = conf->addElement(New refcounted< TimedPullSink >("sink", 1));
conf->hookUp(randomPushSourceSpec, 0, sourcePrintS ,0);
conf->hookUp(sourcePrintS, 0, groupBySpec, 0);
conf->hookUp(groupBySpec, 0, queueSpec, 0);
conf->hookUp(queueSpec, 0, sinkPrintS, 0);
conf->hookUp(sinkPrintS, 0, sinkS, 0);
RouterRef router = New refcounted< Router >(conf);
if (router->initialize(router) == 0) {
std::cout << "Correctly initialized configuration.\n";
} else {
std::cout << "** Failed to initialize correct spec\n";
}
// Activate the router
router->activate();
}
int main(int argc, char **argv)
{
std::cout << "\nTest Agg Start\n";
agg();
amain();
std::cout << "\nTest Agg End\n";
return 0;
}
<|endoftext|> |
<commit_before>// =-=-=-=-=-=-=-
#include "irods_error.hpp"
// =-=-=-=-=-=-=-
// irods includes
#include "rodsLog.hpp"
// =-=-=-=-=-=-=-
// boost includes
#include <boost/lexical_cast.hpp>
// =-=-=-=-=-=-=-
// stl includes
#include <iostream>
namespace irods {
// =-=-=-=-=-=-=-
// private - helper fcn to build the result string
std::string error::build_result_string(
std::string _file,
int _line,
std::string _fcn ) {
// =-=-=-=-=-=-=-
// decorate message based on status
std::string result;
if ( status_ ) {
result = "[+]\t";
}
else {
result = "[-]\t";
}
// =-=-=-=-=-=-=-
// only keep the file name the path back to iRODS
std::string line_info = _file + ":" + boost::lexical_cast<std::string>( _line ) + ":" + _fcn;
size_t pos = line_info.find( "iRODS" );
if ( std::string::npos != pos ) {
line_info = line_info.substr( pos );
}
// =-=-=-=-=-=-=-
// get the rods error and errno string
char* errno_str = 0;
char* irods_err = rodsErrorName( code_, &errno_str );
// =-=-=-=-=-=-=-
// compose resulting message given all components
result += line_info + " : " +
+ " status [" + irods_err + "] errno [" + errno_str + "]"
+ " -- message [" + message_ + "]";
return result;
} // build_result_string
// =-=-=-=-=-=-=-
// public - default constructor
error::error( ) : status_( false ), code_( 0 ), message_( "" ) {
} // ctor
// =-=-=-=-=-=-=-
// public - useful constructor
error::error(
bool _status,
long long _code,
std::string _msg,
std::string _file,
int _line,
std::string _fcn ) :
status_( _status ),
code_( _code ),
message_( _msg ) {
// =-=-=-=-=-=-=-
// cache message on message stack
if ( !_msg.empty() ) {
result_stack_.push_back( build_result_string( _file, _line, _fcn ) );
}
} // ctor
// =-=-=-=-=-=-=-
// public - deprecated constructor - since 4.0.3
error::error(
bool ,
long long ,
std::string _msg,
std::string _file,
int _line,
std::string _fcn,
const error& _rhs ) :
status_( _rhs.status() ),
code_( _rhs.code() ),
message_( _msg ) {
// =-=-=-=-=-=-=-
// cache RHS vector into our vector first
result_stack_ = _rhs.result_stack_;
// =-=-=-=-=-=-=-
// cache message on message stack
result_stack_.push_back( build_result_string( _file, _line, _fcn ) );
} // ctor
// =-=-=-=-=-=-=-
// public - useful constructor
error::error(
std::string _msg,
std::string _file,
int _line,
std::string _fcn,
const error& _rhs ) :
status_( _rhs.status() ),
code_( _rhs.code() ),
message_( _msg ) {
// =-=-=-=-=-=-=-
// cache RHS vector into our vector first
result_stack_ = _rhs.result_stack_;
// =-=-=-=-=-=-=-
// cache message on message stack
result_stack_.push_back( build_result_string( _file, _line, _fcn ) );
} // ctor
// =-=-=-=-=-=-=-
// public - copy constructor
error::error( const error& _rhs ) {
status_ = _rhs.status_;
code_ = _rhs.code_;
message_ = _rhs.message_;
result_stack_ = _rhs.result_stack_;
} // cctor
// =-=-=-=-=-=-=-
// public - Destructor
error::~error() {
} // dtor
// =-=-=-=-=-=-=-
// public - Assignment Operator
error& error::operator=( const error& _rhs ) {
status_ = _rhs.status_;
code_ = _rhs.code_;
message_ = _rhs.message_;
result_stack_ = _rhs.result_stack_;
return *this;
} // assignment operator
// =-=-=-=-=-=-=-
// public - return the status of this error object
bool error::status( ) const {
return status_;
} // status
// =-=-=-=-=-=-=-
// public - return the code of this error object
long long error::code( ) const {
return code_;
} // code
// =-=-=-=-=-=-=-
// public - return the composite result for logging, etc.
std::string error::result() const {
// compose single string of the result stack for print out
std::string result;
std::string tabs = "";
for ( size_t i = 0; i < result_stack_.size(); ++i ) {
if ( i != 0 ) {
result += "\n";
}
result += tabs;
result += result_stack_[ result_stack_.size() - 1 - i ];
tabs += "\t";
} // for i
// add extra newline for formatting
result += "\n\n";
return result;
} // result
// =-=-=-=-=-=-=-
// public - return the status_ - deprecated in 4.0.3
bool error::ok() {
return status_;
} // ok
// =-=-=-=-=-=-=-
// public - return the status_
bool error::ok() const {
return status_;
} // ok
error assert_error(
bool expr_,
long long code_,
const std::string& file_,
const std::string& function_,
const std::string& format_,
int line_,
... ) {
error result = SUCCESS();
if ( !expr_ ) {
va_list ap;
va_start( ap, line_ );
const int buffer_size = 4096;
char buffer[buffer_size];
vsnprintf( buffer, buffer_size, format_.c_str(), ap );
va_end( ap );
std::stringstream msg;
msg << buffer;
result = error( false, code_, msg.str(), file_, line_, function_ );
}
return result;
}
error assert_pass(
const error& _prev_error,
const std::string& _file,
const std::string& _function,
const std::string& _format,
int _line,
... ) {
std::stringstream msg;
if ( !_prev_error.ok() ) {
va_list ap;
va_start( ap, _line );
const int buffer_size = 4096;
char buffer[buffer_size];
vsnprintf( buffer, buffer_size, _format.c_str(), ap );
va_end( ap );
msg << buffer;
}
return error( msg.str(), _file, _line, _function, _prev_error );
}
}; // namespace irods
<commit_msg>[#2212] CID76125, CID76124, and CID76123:<commit_after>// =-=-=-=-=-=-=-
#include "irods_error.hpp"
// =-=-=-=-=-=-=-
// irods includes
#include "rodsLog.hpp"
// =-=-=-=-=-=-=-
// boost includes
#include <boost/lexical_cast.hpp>
// =-=-=-=-=-=-=-
// stl includes
#include <iostream>
namespace irods {
// =-=-=-=-=-=-=-
// private - helper fcn to build the result string
std::string error::build_result_string(
std::string _file,
int _line,
std::string _fcn ) {
// =-=-=-=-=-=-=-
// decorate message based on status
std::string result;
if ( status_ ) {
result = "[+]\t";
}
else {
result = "[-]\t";
}
// =-=-=-=-=-=-=-
// only keep the file name the path back to iRODS
std::string line_info;
try { //replace with std::to_string when we have c++14
line_info = _file + ":" + boost::lexical_cast<std::string>( _line ) + ":" + _fcn;
} catch ( boost::bad_lexical_cast e ) {
line_info = _file + ":<unknown line number>:" + _fcn;
}
size_t pos = line_info.find( "iRODS" );
if ( std::string::npos != pos ) {
line_info = line_info.substr( pos );
}
// =-=-=-=-=-=-=-
// get the rods error and errno string
char* errno_str = 0;
char* irods_err = rodsErrorName( code_, &errno_str );
// =-=-=-=-=-=-=-
// compose resulting message given all components
result += line_info + " : " +
+ " status [" + irods_err + "] errno [" + errno_str + "]"
+ " -- message [" + message_ + "]";
return result;
} // build_result_string
// =-=-=-=-=-=-=-
// public - default constructor
error::error( ) : status_( false ), code_( 0 ), message_( "" ) {
} // ctor
// =-=-=-=-=-=-=-
// public - useful constructor
error::error(
bool _status,
long long _code,
std::string _msg,
std::string _file,
int _line,
std::string _fcn ) :
status_( _status ),
code_( _code ),
message_( _msg ) {
// =-=-=-=-=-=-=-
// cache message on message stack
if ( !_msg.empty() ) {
result_stack_.push_back( build_result_string( _file, _line, _fcn ) );
}
} // ctor
// =-=-=-=-=-=-=-
// public - deprecated constructor - since 4.0.3
error::error(
bool ,
long long ,
std::string _msg,
std::string _file,
int _line,
std::string _fcn,
const error& _rhs ) :
status_( _rhs.status() ),
code_( _rhs.code() ),
message_( _msg ) {
// =-=-=-=-=-=-=-
// cache RHS vector into our vector first
result_stack_ = _rhs.result_stack_;
// =-=-=-=-=-=-=-
// cache message on message stack
result_stack_.push_back( build_result_string( _file, _line, _fcn ) );
} // ctor
// =-=-=-=-=-=-=-
// public - useful constructor
error::error(
std::string _msg,
std::string _file,
int _line,
std::string _fcn,
const error& _rhs ) :
status_( _rhs.status() ),
code_( _rhs.code() ),
message_( _msg ) {
// =-=-=-=-=-=-=-
// cache RHS vector into our vector first
result_stack_ = _rhs.result_stack_;
// =-=-=-=-=-=-=-
// cache message on message stack
result_stack_.push_back( build_result_string( _file, _line, _fcn ) );
} // ctor
// =-=-=-=-=-=-=-
// public - copy constructor
error::error( const error& _rhs ) {
status_ = _rhs.status_;
code_ = _rhs.code_;
message_ = _rhs.message_;
result_stack_ = _rhs.result_stack_;
} // cctor
// =-=-=-=-=-=-=-
// public - Destructor
error::~error() {
} // dtor
// =-=-=-=-=-=-=-
// public - Assignment Operator
error& error::operator=( const error& _rhs ) {
status_ = _rhs.status_;
code_ = _rhs.code_;
message_ = _rhs.message_;
result_stack_ = _rhs.result_stack_;
return *this;
} // assignment operator
// =-=-=-=-=-=-=-
// public - return the status of this error object
bool error::status( ) const {
return status_;
} // status
// =-=-=-=-=-=-=-
// public - return the code of this error object
long long error::code( ) const {
return code_;
} // code
// =-=-=-=-=-=-=-
// public - return the composite result for logging, etc.
std::string error::result() const {
// compose single string of the result stack for print out
std::string result;
std::string tabs = "";
for ( size_t i = 0; i < result_stack_.size(); ++i ) {
if ( i != 0 ) {
result += "\n";
}
result += tabs;
result += result_stack_[ result_stack_.size() - 1 - i ];
tabs += "\t";
} // for i
// add extra newline for formatting
result += "\n\n";
return result;
} // result
// =-=-=-=-=-=-=-
// public - return the status_ - deprecated in 4.0.3
bool error::ok() {
return status_;
} // ok
// =-=-=-=-=-=-=-
// public - return the status_
bool error::ok() const {
return status_;
} // ok
error assert_error(
bool expr_,
long long code_,
const std::string& file_,
const std::string& function_,
const std::string& format_,
int line_,
... ) {
error result = SUCCESS();
if ( !expr_ ) {
va_list ap;
va_start( ap, line_ );
const int buffer_size = 4096;
char buffer[buffer_size];
vsnprintf( buffer, buffer_size, format_.c_str(), ap );
va_end( ap );
std::stringstream msg;
msg << buffer;
result = error( false, code_, msg.str(), file_, line_, function_ );
}
return result;
}
error assert_pass(
const error& _prev_error,
const std::string& _file,
const std::string& _function,
const std::string& _format,
int _line,
... ) {
std::stringstream msg;
if ( !_prev_error.ok() ) {
va_list ap;
va_start( ap, _line );
const int buffer_size = 4096;
char buffer[buffer_size];
vsnprintf( buffer, buffer_size, _format.c_str(), ap );
va_end( ap );
msg << buffer;
}
return error( msg.str(), _file, _line, _function, _prev_error );
}
}; // namespace irods
<|endoftext|> |
<commit_before>#define BOOST_TEST_MODULE Bitcoin Test Suite
#include <boost/test/unit_test.hpp>
#include "main.h"
#include "wallet.h"
CWallet* pwalletMain;
CClientUIInterface uiInterface;
extern bool fPrintToConsole;
extern void noui_connect();
struct TestingSetup {
TestingSetup() {
fPrintToConsole = true; // don't want to write to debug.log file
noui_connect();
pwalletMain = new CWallet();
RegisterWallet(pwalletMain);
}
~TestingSetup()
{
delete pwalletMain;
pwalletMain = NULL;
}
};
BOOST_GLOBAL_FIXTURE(TestingSetup);
void Shutdown(void* parg)
{
exit(0);
}
void StartShutdown()
{
exit(0);
}
<commit_msg>Delete test_bitcoin.cpp<commit_after><|endoftext|> |
<commit_before>#include "assert.hh"
#include "buffer.hh"
#include "buffer_manager.hh"
#include "client_manager.hh"
#include "color_registry.hh"
#include "command_manager.hh"
#include "commands.hh"
#include "context.hh"
#include "debug.hh"
#include "event_manager.hh"
#include "file.hh"
#include "highlighters.hh"
#include "hook_manager.hh"
#include "ncurses.hh"
#include "option_manager.hh"
#include "keymap_manager.hh"
#include "parameters_parser.hh"
#include "register_manager.hh"
#include "remote.hh"
#include "shell_manager.hh"
#include "string.hh"
#include "window.hh"
#if defined(__APPLE__)
#include <mach-o/dyld.h>
#endif
#include <unordered_map>
#include <locale>
#include <signal.h>
using namespace Kakoune;
void run_unit_tests();
String runtime_directory()
{
char buffer[2048];
#if defined(__linux__) || defined(__CYGWIN__)
ssize_t res = readlink("/proc/self/exe", buffer, 2048);
kak_assert(res != -1);
buffer[res] = '\0';
#elif defined(__APPLE__)
uint32_t bufsize = 2048;
_NSGetExecutablePath(buffer, &bufsize);
char* canonical_path = realpath(buffer, nullptr);
strncpy(buffer, canonical_path, 2048);
free(canonical_path);
#else
# error "finding executable path is not implemented on this platform"
#endif
char* ptr = strrchr(buffer, '/');
if (not ptr)
throw runtime_error("unable to determine runtime directory");
return String(buffer, ptr);
}
void register_env_vars()
{
struct EnvVarDesc { const char* name; String (*func)(const String&, const Context&); };
static const EnvVarDesc env_vars[] = { {
"bufname",
[](const String& name, const Context& context)
{ return context.buffer().display_name(); }
}, {
"timestamp",
[](const String& name, const Context& context)
{ return to_string(context.buffer().timestamp()); }
}, {
"selection",
[](const String& name, const Context& context)
{ const Range& sel = context.editor().main_selection();
return content(context.buffer(), sel); }
}, {
"selections",
[](const String& name, const Context& context)
{ auto sels = context.editor().selections_content();
String res;
for (size_t i = 0; i < sels.size(); ++i)
{
res += escape(sels[i], ':', '\\');
if (i != sels.size() - 1)
res += ':';
}
return res; }
}, {
"runtime",
[](const String& name, const Context& context)
{ return runtime_directory(); }
}, {
"opt_.+",
[](const String& name, const Context& context)
{ return context.options()[name.substr(4_byte)].get_as_string(); }
}, {
"reg_.+",
[](const String& name, const Context& context)
{ return RegisterManager::instance()[name[4]].values(context)[0]; }
}, {
"session",
[](const String& name, const Context& context)
{ return Server::instance().session(); }
}, {
"client",
[](const String& name, const Context& context)
{ return context.name(); }
}, {
"cursor_line",
[](const String& name, const Context& context)
{ return to_string(context.editor().main_selection().last().line + 1); }
}, {
"cursor_column",
[](const String& name, const Context& context)
{ return to_string(context.editor().main_selection().last().column + 1); }
}, {
"selection_desc",
[](const String& name, const Context& context)
{ auto& sel = context.editor().main_selection();
auto beg = sel.min();
return to_string(beg.line + 1) + ':' + to_string(beg.column + 1) + '+' +
to_string((int)context.buffer().distance(beg, sel.max())+1); }
}, {
"window_width",
[](const String& name, const Context& context)
{ return to_string(context.window().dimensions().column); }
}, {
"window_height",
[](const String& name, const Context& context)
{ return to_string(context.window().dimensions().line); }
} };
ShellManager& shell_manager = ShellManager::instance();
for (auto& env_var : env_vars)
shell_manager.register_env_var(env_var.name, env_var.func);
}
void register_registers()
{
using StringList = std::vector<String>;
struct DynRegDesc { char name; StringList (*func)(const Context&); };
static const DynRegDesc dyn_regs[] = {
{ '%', [](const Context& context) { return StringList{{context.buffer().display_name()}}; } },
{ '.', [](const Context& context) { return context.editor().selections_content(); } },
{ '#', [](const Context& context) { return StringList{{to_string((int)context.editor().selections().size())}}; } },
};
RegisterManager& register_manager = RegisterManager::instance();
for (auto& dyn_reg : dyn_regs)
register_manager.register_dynamic_register(dyn_reg.name, dyn_reg.func);
for (size_t i = 0; i < 10; ++i)
{
register_manager.register_dynamic_register('0'+i,
[i](const Context& context) {
std::vector<String> result;
for (auto& sel : context.editor().selections())
result.emplace_back(i < sel.captures().size() ? sel.captures()[i] : "");
return result;
});
}
}
void create_local_client(const String& init_command)
{
class LocalNCursesUI : public NCursesUI
{
~LocalNCursesUI()
{
if (not ClientManager::instance().empty() and fork())
{
this->NCursesUI::~NCursesUI();
puts("detached from terminal\n");
exit(0);
}
}
};
UserInterface* ui = new LocalNCursesUI{};
static Client* client = ClientManager::instance().create_client(
std::unique_ptr<UserInterface>{ui}, init_command);
signal(SIGHUP, [](int) {
if (client)
ClientManager::instance().remove_client(*client);
client = nullptr;
});
}
void signal_handler(int signal)
{
NCursesUI::abort();
const char* text = nullptr;
switch (signal)
{
case SIGSEGV: text = "SIGSEGV"; break;
case SIGFPE: text = "SIGFPE"; break;
case SIGQUIT: text = "SIGQUIT"; break;
case SIGTERM: text = "SIGTERM"; break;
}
on_assert_failed(text);
abort();
}
int run_client(const String& session, const String& init_command)
{
try
{
EventManager event_manager;
auto client = connect_to(session,
std::unique_ptr<UserInterface>{new NCursesUI{}},
init_command);
while (true)
event_manager.handle_next_events();
}
catch (peer_disconnected&)
{
fputs("disconnected from server\n", stderr);
return -1;
}
return 0;
}
int kakoune(memoryview<String> params)
{
ParametersParser parser(params, { { "c", true },
{ "e", true },
{ "n", false },
{ "s", true },
{ "d", false } });
String init_command;
if (parser.has_option("e"))
init_command = parser.option_value("e");
if (parser.has_option("c"))
{
for (auto opt : { "n", "s", "d" })
{
if (parser.has_option(opt))
{
fprintf(stderr, "error: -%s makes not sense with -c\n", opt);
return -1;
}
}
return run_client(parser.option_value("c"), init_command);
}
const bool daemon = parser.has_option("d");
static bool terminate = false;
if (daemon)
{
if (not parser.has_option("s"))
{
fputs("-d needs a session name to be specified with -s\n", stderr);
return -1;
}
if (pid_t child = fork())
{
printf("Kakoune forked to background, for session '%s'\n"
"send SIGTERM to process %d for closing the session\n",
parser.option_value("s").c_str(), child);
exit(0);
}
signal(SIGTERM, [](int) { terminate = true; });
}
EventManager event_manager;
GlobalOptions global_options;
GlobalHooks global_hooks;
GlobalKeymaps global_keymaps;
ShellManager shell_manager;
CommandManager command_manager;
BufferManager buffer_manager;
RegisterManager register_manager;
HighlighterRegistry highlighter_registry;
ColorRegistry color_registry;
ClientManager client_manager;
run_unit_tests();
register_env_vars();
register_registers();
register_commands();
register_highlighters();
write_debug("*** This is the debug buffer, where debug info will be written ***");
write_debug("pid: " + to_string(getpid()));
write_debug("utf-8 test: é á ï");
Server server(parser.has_option("s") ? parser.option_value("s") : to_string(getpid()));
if (not parser.has_option("n")) try
{
Context initialisation_context;
command_manager.execute("source " + runtime_directory() + "/kakrc",
initialisation_context);
}
catch (Kakoune::runtime_error& error)
{
write_debug("error while parsing kakrc: "_str + error.what());
}
catch (Kakoune::client_removed&)
{
write_debug("error while parsing kakrc: asked to quit");
}
{
Context empty_context;
global_hooks.run_hook("KakBegin", "", empty_context);
}
if (parser.positional_count() != 0) try
{
// create buffers in reverse order so that the first given buffer
// is the most recently created one.
for (int i = parser.positional_count() - 1; i >= 0; --i)
{
const String& file = parser[i];
if (not create_buffer_from_file(file))
new Buffer(file, Buffer::Flags::New | Buffer::Flags::File);
}
}
catch (Kakoune::runtime_error& error)
{
write_debug("error while opening command line files: "_str + error.what());
}
else
new Buffer("*scratch*", Buffer::Flags::None);
if (not daemon)
create_local_client(init_command);
while (not terminate and (not client_manager.empty() or daemon))
event_manager.handle_next_events();
{
Context empty_context;
global_hooks.run_hook("KakEnd", "", empty_context);
}
return 0;
}
int main(int argc, char* argv[])
{
try
{
setlocale(LC_ALL, "");
signal(SIGSEGV, signal_handler);
signal(SIGFPE, signal_handler);
signal(SIGQUIT, signal_handler);
signal(SIGTERM, signal_handler);
std::vector<String> params;
for (size_t i = 1; i < argc; ++i)
params.push_back(argv[i]);
kakoune(params);
}
catch (Kakoune::exception& error)
{
on_assert_failed(("uncaught exception:\n"_str + error.what()).c_str());
return -1;
}
catch (std::exception& error)
{
on_assert_failed(("uncaught exception:\n"_str + error.what()).c_str());
return -1;
}
catch (...)
{
on_assert_failed("uncaught exception");
return -1;
}
return 0;
}
<commit_msg>tweak initial debug infos<commit_after>#include "assert.hh"
#include "buffer.hh"
#include "buffer_manager.hh"
#include "client_manager.hh"
#include "color_registry.hh"
#include "command_manager.hh"
#include "commands.hh"
#include "context.hh"
#include "debug.hh"
#include "event_manager.hh"
#include "file.hh"
#include "highlighters.hh"
#include "hook_manager.hh"
#include "ncurses.hh"
#include "option_manager.hh"
#include "keymap_manager.hh"
#include "parameters_parser.hh"
#include "register_manager.hh"
#include "remote.hh"
#include "shell_manager.hh"
#include "string.hh"
#include "window.hh"
#if defined(__APPLE__)
#include <mach-o/dyld.h>
#endif
#include <unordered_map>
#include <locale>
#include <signal.h>
using namespace Kakoune;
void run_unit_tests();
String runtime_directory()
{
char buffer[2048];
#if defined(__linux__) || defined(__CYGWIN__)
ssize_t res = readlink("/proc/self/exe", buffer, 2048);
kak_assert(res != -1);
buffer[res] = '\0';
#elif defined(__APPLE__)
uint32_t bufsize = 2048;
_NSGetExecutablePath(buffer, &bufsize);
char* canonical_path = realpath(buffer, nullptr);
strncpy(buffer, canonical_path, 2048);
free(canonical_path);
#else
# error "finding executable path is not implemented on this platform"
#endif
char* ptr = strrchr(buffer, '/');
if (not ptr)
throw runtime_error("unable to determine runtime directory");
return String(buffer, ptr);
}
void register_env_vars()
{
struct EnvVarDesc { const char* name; String (*func)(const String&, const Context&); };
static const EnvVarDesc env_vars[] = { {
"bufname",
[](const String& name, const Context& context)
{ return context.buffer().display_name(); }
}, {
"timestamp",
[](const String& name, const Context& context)
{ return to_string(context.buffer().timestamp()); }
}, {
"selection",
[](const String& name, const Context& context)
{ const Range& sel = context.editor().main_selection();
return content(context.buffer(), sel); }
}, {
"selections",
[](const String& name, const Context& context)
{ auto sels = context.editor().selections_content();
String res;
for (size_t i = 0; i < sels.size(); ++i)
{
res += escape(sels[i], ':', '\\');
if (i != sels.size() - 1)
res += ':';
}
return res; }
}, {
"runtime",
[](const String& name, const Context& context)
{ return runtime_directory(); }
}, {
"opt_.+",
[](const String& name, const Context& context)
{ return context.options()[name.substr(4_byte)].get_as_string(); }
}, {
"reg_.+",
[](const String& name, const Context& context)
{ return RegisterManager::instance()[name[4]].values(context)[0]; }
}, {
"session",
[](const String& name, const Context& context)
{ return Server::instance().session(); }
}, {
"client",
[](const String& name, const Context& context)
{ return context.name(); }
}, {
"cursor_line",
[](const String& name, const Context& context)
{ return to_string(context.editor().main_selection().last().line + 1); }
}, {
"cursor_column",
[](const String& name, const Context& context)
{ return to_string(context.editor().main_selection().last().column + 1); }
}, {
"selection_desc",
[](const String& name, const Context& context)
{ auto& sel = context.editor().main_selection();
auto beg = sel.min();
return to_string(beg.line + 1) + ':' + to_string(beg.column + 1) + '+' +
to_string((int)context.buffer().distance(beg, sel.max())+1); }
}, {
"window_width",
[](const String& name, const Context& context)
{ return to_string(context.window().dimensions().column); }
}, {
"window_height",
[](const String& name, const Context& context)
{ return to_string(context.window().dimensions().line); }
} };
ShellManager& shell_manager = ShellManager::instance();
for (auto& env_var : env_vars)
shell_manager.register_env_var(env_var.name, env_var.func);
}
void register_registers()
{
using StringList = std::vector<String>;
struct DynRegDesc { char name; StringList (*func)(const Context&); };
static const DynRegDesc dyn_regs[] = {
{ '%', [](const Context& context) { return StringList{{context.buffer().display_name()}}; } },
{ '.', [](const Context& context) { return context.editor().selections_content(); } },
{ '#', [](const Context& context) { return StringList{{to_string((int)context.editor().selections().size())}}; } },
};
RegisterManager& register_manager = RegisterManager::instance();
for (auto& dyn_reg : dyn_regs)
register_manager.register_dynamic_register(dyn_reg.name, dyn_reg.func);
for (size_t i = 0; i < 10; ++i)
{
register_manager.register_dynamic_register('0'+i,
[i](const Context& context) {
std::vector<String> result;
for (auto& sel : context.editor().selections())
result.emplace_back(i < sel.captures().size() ? sel.captures()[i] : "");
return result;
});
}
}
void create_local_client(const String& init_command)
{
class LocalNCursesUI : public NCursesUI
{
~LocalNCursesUI()
{
if (not ClientManager::instance().empty() and fork())
{
this->NCursesUI::~NCursesUI();
puts("detached from terminal\n");
exit(0);
}
}
};
UserInterface* ui = new LocalNCursesUI{};
static Client* client = ClientManager::instance().create_client(
std::unique_ptr<UserInterface>{ui}, init_command);
signal(SIGHUP, [](int) {
if (client)
ClientManager::instance().remove_client(*client);
client = nullptr;
});
}
void signal_handler(int signal)
{
NCursesUI::abort();
const char* text = nullptr;
switch (signal)
{
case SIGSEGV: text = "SIGSEGV"; break;
case SIGFPE: text = "SIGFPE"; break;
case SIGQUIT: text = "SIGQUIT"; break;
case SIGTERM: text = "SIGTERM"; break;
}
on_assert_failed(text);
abort();
}
int run_client(const String& session, const String& init_command)
{
try
{
EventManager event_manager;
auto client = connect_to(session,
std::unique_ptr<UserInterface>{new NCursesUI{}},
init_command);
while (true)
event_manager.handle_next_events();
}
catch (peer_disconnected&)
{
fputs("disconnected from server\n", stderr);
return -1;
}
return 0;
}
int kakoune(memoryview<String> params)
{
ParametersParser parser(params, { { "c", true },
{ "e", true },
{ "n", false },
{ "s", true },
{ "d", false } });
String init_command;
if (parser.has_option("e"))
init_command = parser.option_value("e");
if (parser.has_option("c"))
{
for (auto opt : { "n", "s", "d" })
{
if (parser.has_option(opt))
{
fprintf(stderr, "error: -%s makes not sense with -c\n", opt);
return -1;
}
}
return run_client(parser.option_value("c"), init_command);
}
const bool daemon = parser.has_option("d");
static bool terminate = false;
if (daemon)
{
if (not parser.has_option("s"))
{
fputs("-d needs a session name to be specified with -s\n", stderr);
return -1;
}
if (pid_t child = fork())
{
printf("Kakoune forked to background, for session '%s'\n"
"send SIGTERM to process %d for closing the session\n",
parser.option_value("s").c_str(), child);
exit(0);
}
signal(SIGTERM, [](int) { terminate = true; });
}
EventManager event_manager;
GlobalOptions global_options;
GlobalHooks global_hooks;
GlobalKeymaps global_keymaps;
ShellManager shell_manager;
CommandManager command_manager;
BufferManager buffer_manager;
RegisterManager register_manager;
HighlighterRegistry highlighter_registry;
ColorRegistry color_registry;
ClientManager client_manager;
run_unit_tests();
register_env_vars();
register_registers();
register_commands();
register_highlighters();
write_debug("*** This is the debug buffer, where debug info will be written ***");
write_debug("pid: " + to_string(getpid()));
Server server(parser.has_option("s") ? parser.option_value("s") : to_string(getpid()));
write_debug("session: " + server.session());
if (not parser.has_option("n")) try
{
Context initialisation_context;
command_manager.execute("source " + runtime_directory() + "/kakrc",
initialisation_context);
}
catch (Kakoune::runtime_error& error)
{
write_debug("error while parsing kakrc: "_str + error.what());
}
catch (Kakoune::client_removed&)
{
write_debug("error while parsing kakrc: asked to quit");
}
{
Context empty_context;
global_hooks.run_hook("KakBegin", "", empty_context);
}
if (parser.positional_count() != 0) try
{
// create buffers in reverse order so that the first given buffer
// is the most recently created one.
for (int i = parser.positional_count() - 1; i >= 0; --i)
{
const String& file = parser[i];
if (not create_buffer_from_file(file))
new Buffer(file, Buffer::Flags::New | Buffer::Flags::File);
}
}
catch (Kakoune::runtime_error& error)
{
write_debug("error while opening command line files: "_str + error.what());
}
else
new Buffer("*scratch*", Buffer::Flags::None);
if (not daemon)
create_local_client(init_command);
while (not terminate and (not client_manager.empty() or daemon))
event_manager.handle_next_events();
{
Context empty_context;
global_hooks.run_hook("KakEnd", "", empty_context);
}
return 0;
}
int main(int argc, char* argv[])
{
try
{
setlocale(LC_ALL, "");
signal(SIGSEGV, signal_handler);
signal(SIGFPE, signal_handler);
signal(SIGQUIT, signal_handler);
signal(SIGTERM, signal_handler);
std::vector<String> params;
for (size_t i = 1; i < argc; ++i)
params.push_back(argv[i]);
kakoune(params);
}
catch (Kakoune::exception& error)
{
on_assert_failed(("uncaught exception:\n"_str + error.what()).c_str());
return -1;
}
catch (std::exception& error)
{
on_assert_failed(("uncaught exception:\n"_str + error.what()).c_str());
return -1;
}
catch (...)
{
on_assert_failed("uncaught exception");
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "openmc/distribution.h"
#include <algorithm> // for copy
#include <cmath> // for sqrt, floor, max
#include <iterator> // for back_inserter
#include <numeric> // for accumulate
#include <stdexcept> // for runtime_error
#include <string> // for string, stod
#include "openmc/error.h"
#include "openmc/math_functions.h"
#include "openmc/random_dist.h"
#include "openmc/random_lcg.h"
#include "openmc/xml_interface.h"
namespace openmc {
//==============================================================================
// Discrete implementation
//==============================================================================
Discrete::Discrete(pugi::xml_node node)
{
auto params = get_node_array<double>(node, "parameters");
std::size_t n = params.size();
std::copy(params.begin(), params.begin() + n / 2, std::back_inserter(x_));
std::copy(params.begin() + n / 2, params.end(), std::back_inserter(p_));
normalize();
}
Discrete::Discrete(const double* x, const double* p, int n)
: x_ {x, x + n}, p_ {p, p + n}
{
normalize();
}
double Discrete::sample(uint64_t* seed) const
{
int n = x_.size();
if (n > 1) {
double xi = prn(seed);
double c = 0.0;
for (int i = 0; i < n; ++i) {
c += p_[i];
if (xi < c)
return x_[i];
}
throw std::runtime_error {"Error when sampling probability mass function."};
} else {
return x_[0];
}
}
void Discrete::normalize()
{
// Renormalize density function so that it sums to unity
double norm = std::accumulate(p_.begin(), p_.end(), 0.0);
for (auto& p_i : p_) {
p_i /= norm;
}
}
//==============================================================================
// Uniform implementation
//==============================================================================
Uniform::Uniform(pugi::xml_node node)
{
auto params = get_node_array<double>(node, "parameters");
if (params.size() != 2) {
openmc::fatal_error("Uniform distribution must have two "
"parameters specified.");
}
a_ = params.at(0);
b_ = params.at(1);
}
double Uniform::sample(uint64_t* seed) const
{
return a_ + prn(seed) * (b_ - a_);
}
//==============================================================================
// Maxwell implementation
//==============================================================================
Maxwell::Maxwell(pugi::xml_node node)
{
theta_ = std::stod(get_node_value(node, "parameters"));
}
double Maxwell::sample(uint64_t* seed) const
{
return maxwell_spectrum(theta_, seed);
}
//==============================================================================
// Watt implementation
//==============================================================================
Watt::Watt(pugi::xml_node node)
{
auto params = get_node_array<double>(node, "parameters");
if (params.size() != 2)
openmc::fatal_error("Watt energy distribution must have two "
"parameters specified.");
a_ = params.at(0);
b_ = params.at(1);
}
double Watt::sample(uint64_t* seed) const
{
return watt_spectrum(a_, b_, seed);
}
//==============================================================================
// Normal implementation
//==============================================================================
Normal::Normal(pugi::xml_node node)
{
auto params = get_node_array<double>(node, "parameters");
if (params.size() != 2) {
openmc::fatal_error("Normal energy distribution must have two "
"parameters specified.");
}
mean_value_ = params.at(0);
std_dev_ = params.at(1);
}
double Normal::sample(uint64_t* seed) const
{
return normal_variate(mean_value_, std_dev_, seed);
}
//==============================================================================
// Muir implementation
//==============================================================================
Muir::Muir(pugi::xml_node node)
{
auto params = get_node_array<double>(node, "parameters");
if (params.size() != 3) {
openmc::fatal_error("Muir energy distribution must have three "
"parameters specified.");
}
e0_ = params.at(0);
m_rat_ = params.at(1);
kt_ = params.at(2);
}
double Muir::sample(uint64_t* seed) const
{
return muir_spectrum(e0_, m_rat_, kt_, seed);
}
//==============================================================================
// Tabular implementation
//==============================================================================
Tabular::Tabular(pugi::xml_node node)
{
if (check_for_node(node, "interpolation")) {
std::string temp = get_node_value(node, "interpolation");
if (temp == "histogram") {
interp_ = Interpolation::histogram;
} else if (temp == "linear-linear") {
interp_ = Interpolation::lin_lin;
} else {
openmc::fatal_error(
"Unknown interpolation type for distribution: " + temp);
}
} else {
interp_ = Interpolation::histogram;
}
// Read and initialize tabular distribution
auto params = get_node_array<double>(node, "parameters");
std::size_t n = params.size() / 2;
const double* x = params.data();
const double* p = x + n;
init(x, p, n);
}
Tabular::Tabular(const double* x, const double* p, int n, Interpolation interp,
const double* c)
: interp_ {interp}
{
init(x, p, n, c);
}
void Tabular::init(
const double* x, const double* p, std::size_t n, const double* c)
{
// Copy x/p arrays into vectors
std::copy(x, x + n, std::back_inserter(x_));
std::copy(p, p + n, std::back_inserter(p_));
// Check interpolation parameter
if (interp_ != Interpolation::histogram &&
interp_ != Interpolation::lin_lin) {
openmc::fatal_error("Only histogram and linear-linear interpolation "
"for tabular distribution is supported.");
}
// Calculate cumulative distribution function
if (c) {
std::copy(c, c + n, std::back_inserter(c_));
} else {
c_.resize(n);
c_[0] = 0.0;
for (int i = 1; i < n; ++i) {
if (interp_ == Interpolation::histogram) {
c_[i] = c_[i - 1] + p_[i - 1] * (x_[i] - x_[i - 1]);
} else if (interp_ == Interpolation::lin_lin) {
c_[i] = c_[i - 1] + 0.5 * (p_[i - 1] + p_[i]) * (x_[i] - x_[i - 1]);
}
}
}
// Normalize density and distribution functions
for (int i = 0; i < n; ++i) {
p_[i] = p_[i] / c_[n - 1];
c_[i] = c_[i] / c_[n - 1];
}
}
double Tabular::sample(uint64_t* seed) const
{
// Sample value of CDF
double c = prn(seed);
// Find first CDF bin which is above the sampled value
double c_i = c_[0];
int i;
std::size_t n = c_.size();
for (i = 0; i < n - 1; ++i) {
if (c <= c_[i + 1])
break;
c_i = c_[i + 1];
}
// Determine bounding PDF values
double x_i = x_[i];
double p_i = p_[i];
if (interp_ == Interpolation::histogram) {
// Histogram interpolation
if (p_i > 0.0) {
return x_i + (c - c_i) / p_i;
} else {
return x_i;
}
} else {
// Linear-linear interpolation
double x_i1 = x_[i + 1];
double p_i1 = p_[i + 1];
double m = (p_i1 - p_i) / (x_i1 - x_i);
if (m == 0.0) {
return x_i + (c - c_i) / p_i;
} else {
return x_i +
(std::sqrt(std::max(0.0, p_i * p_i + 2 * m * (c - c_i))) - p_i) /
m;
}
}
}
//==============================================================================
// Equiprobable implementation
//==============================================================================
double Equiprobable::sample(uint64_t* seed) const
{
std::size_t n = x_.size();
double r = prn(seed);
int i = std::floor((n - 1) * r);
double xl = x_[i];
double xr = x_[i + i];
return xl + ((n - 1) * r - i) * (xr - xl);
}
//==============================================================================
// Mixture implementation
//==============================================================================
Mixture::Mixture(pugi::xml_node node)
{
double cumsum = 0.0;
for (pugi::xml_node pair : node.children("pair")) {
// Check that required data exists
if (!pair.attribute("probability")) fatal_error("Mixture pair element does not have probability.");
if (!pair.child("dist")) fatal_error("Mixture pair element does not have a distribution.");
// cummulative sum of probybilities
cumsum += std::stod(pair.attribute("probability").value());
// Save cummulative probybility and distrubution
distribution_.push_back(
std::make_pair(cumsum, distribution_from_xml(pair.child("dist"))));
}
// Normalize cummulative probabilities to 1
for (auto& pair : distribution_) {
pair.first /= cumsum;
}
}
double Mixture::sample(uint64_t* seed) const
{
// Sample value of CDF
const double p = prn(seed);
// find matching distribution
const auto it = std::lower_bound(distribution_.cbegin(), distribution_.cend(),
p, [](const DistPair& pair, double p) { return pair.first < p; });
// This should not happen. Catch it
Ensures(it != distribution_.cend());
// Sample the choosen distribution
return it->second->sample(seed);
}
//==============================================================================
// Helper function
//==============================================================================
UPtrDist distribution_from_xml(pugi::xml_node node)
{
if (!check_for_node(node, "type"))
openmc::fatal_error("Distribution type must be specified.");
// Determine type of distribution
std::string type = get_node_value(node, "type", true, true);
// Allocate extension of Distribution
UPtrDist dist;
if (type == "uniform") {
dist = UPtrDist {new Uniform(node)};
} else if (type == "maxwell") {
dist = UPtrDist {new Maxwell(node)};
} else if (type == "watt") {
dist = UPtrDist {new Watt(node)};
} else if (type == "normal") {
dist = UPtrDist {new Normal(node)};
} else if (type == "muir") {
dist = UPtrDist {new Muir(node)};
} else if (type == "discrete") {
dist = UPtrDist {new Discrete(node)};
} else if (type == "tabular") {
dist = UPtrDist {new Tabular(node)};
} else if (type == "mixture") {
dist = UPtrDist{new Mixture(node)};
} else {
openmc::fatal_error("Invalid distribution type: " + type);
}
return dist;
}
} // namespace openmc
<commit_msg>Update src/distribution.cpp<commit_after>#include "openmc/distribution.h"
#include <algorithm> // for copy
#include <cmath> // for sqrt, floor, max
#include <iterator> // for back_inserter
#include <numeric> // for accumulate
#include <stdexcept> // for runtime_error
#include <string> // for string, stod
#include "openmc/error.h"
#include "openmc/math_functions.h"
#include "openmc/random_dist.h"
#include "openmc/random_lcg.h"
#include "openmc/xml_interface.h"
namespace openmc {
//==============================================================================
// Discrete implementation
//==============================================================================
Discrete::Discrete(pugi::xml_node node)
{
auto params = get_node_array<double>(node, "parameters");
std::size_t n = params.size();
std::copy(params.begin(), params.begin() + n / 2, std::back_inserter(x_));
std::copy(params.begin() + n / 2, params.end(), std::back_inserter(p_));
normalize();
}
Discrete::Discrete(const double* x, const double* p, int n)
: x_ {x, x + n}, p_ {p, p + n}
{
normalize();
}
double Discrete::sample(uint64_t* seed) const
{
int n = x_.size();
if (n > 1) {
double xi = prn(seed);
double c = 0.0;
for (int i = 0; i < n; ++i) {
c += p_[i];
if (xi < c)
return x_[i];
}
throw std::runtime_error {"Error when sampling probability mass function."};
} else {
return x_[0];
}
}
void Discrete::normalize()
{
// Renormalize density function so that it sums to unity
double norm = std::accumulate(p_.begin(), p_.end(), 0.0);
for (auto& p_i : p_) {
p_i /= norm;
}
}
//==============================================================================
// Uniform implementation
//==============================================================================
Uniform::Uniform(pugi::xml_node node)
{
auto params = get_node_array<double>(node, "parameters");
if (params.size() != 2) {
openmc::fatal_error("Uniform distribution must have two "
"parameters specified.");
}
a_ = params.at(0);
b_ = params.at(1);
}
double Uniform::sample(uint64_t* seed) const
{
return a_ + prn(seed) * (b_ - a_);
}
//==============================================================================
// Maxwell implementation
//==============================================================================
Maxwell::Maxwell(pugi::xml_node node)
{
theta_ = std::stod(get_node_value(node, "parameters"));
}
double Maxwell::sample(uint64_t* seed) const
{
return maxwell_spectrum(theta_, seed);
}
//==============================================================================
// Watt implementation
//==============================================================================
Watt::Watt(pugi::xml_node node)
{
auto params = get_node_array<double>(node, "parameters");
if (params.size() != 2)
openmc::fatal_error("Watt energy distribution must have two "
"parameters specified.");
a_ = params.at(0);
b_ = params.at(1);
}
double Watt::sample(uint64_t* seed) const
{
return watt_spectrum(a_, b_, seed);
}
//==============================================================================
// Normal implementation
//==============================================================================
Normal::Normal(pugi::xml_node node)
{
auto params = get_node_array<double>(node, "parameters");
if (params.size() != 2) {
openmc::fatal_error("Normal energy distribution must have two "
"parameters specified.");
}
mean_value_ = params.at(0);
std_dev_ = params.at(1);
}
double Normal::sample(uint64_t* seed) const
{
return normal_variate(mean_value_, std_dev_, seed);
}
//==============================================================================
// Muir implementation
//==============================================================================
Muir::Muir(pugi::xml_node node)
{
auto params = get_node_array<double>(node, "parameters");
if (params.size() != 3) {
openmc::fatal_error("Muir energy distribution must have three "
"parameters specified.");
}
e0_ = params.at(0);
m_rat_ = params.at(1);
kt_ = params.at(2);
}
double Muir::sample(uint64_t* seed) const
{
return muir_spectrum(e0_, m_rat_, kt_, seed);
}
//==============================================================================
// Tabular implementation
//==============================================================================
Tabular::Tabular(pugi::xml_node node)
{
if (check_for_node(node, "interpolation")) {
std::string temp = get_node_value(node, "interpolation");
if (temp == "histogram") {
interp_ = Interpolation::histogram;
} else if (temp == "linear-linear") {
interp_ = Interpolation::lin_lin;
} else {
openmc::fatal_error(
"Unknown interpolation type for distribution: " + temp);
}
} else {
interp_ = Interpolation::histogram;
}
// Read and initialize tabular distribution
auto params = get_node_array<double>(node, "parameters");
std::size_t n = params.size() / 2;
const double* x = params.data();
const double* p = x + n;
init(x, p, n);
}
Tabular::Tabular(const double* x, const double* p, int n, Interpolation interp,
const double* c)
: interp_ {interp}
{
init(x, p, n, c);
}
void Tabular::init(
const double* x, const double* p, std::size_t n, const double* c)
{
// Copy x/p arrays into vectors
std::copy(x, x + n, std::back_inserter(x_));
std::copy(p, p + n, std::back_inserter(p_));
// Check interpolation parameter
if (interp_ != Interpolation::histogram &&
interp_ != Interpolation::lin_lin) {
openmc::fatal_error("Only histogram and linear-linear interpolation "
"for tabular distribution is supported.");
}
// Calculate cumulative distribution function
if (c) {
std::copy(c, c + n, std::back_inserter(c_));
} else {
c_.resize(n);
c_[0] = 0.0;
for (int i = 1; i < n; ++i) {
if (interp_ == Interpolation::histogram) {
c_[i] = c_[i - 1] + p_[i - 1] * (x_[i] - x_[i - 1]);
} else if (interp_ == Interpolation::lin_lin) {
c_[i] = c_[i - 1] + 0.5 * (p_[i - 1] + p_[i]) * (x_[i] - x_[i - 1]);
}
}
}
// Normalize density and distribution functions
for (int i = 0; i < n; ++i) {
p_[i] = p_[i] / c_[n - 1];
c_[i] = c_[i] / c_[n - 1];
}
}
double Tabular::sample(uint64_t* seed) const
{
// Sample value of CDF
double c = prn(seed);
// Find first CDF bin which is above the sampled value
double c_i = c_[0];
int i;
std::size_t n = c_.size();
for (i = 0; i < n - 1; ++i) {
if (c <= c_[i + 1])
break;
c_i = c_[i + 1];
}
// Determine bounding PDF values
double x_i = x_[i];
double p_i = p_[i];
if (interp_ == Interpolation::histogram) {
// Histogram interpolation
if (p_i > 0.0) {
return x_i + (c - c_i) / p_i;
} else {
return x_i;
}
} else {
// Linear-linear interpolation
double x_i1 = x_[i + 1];
double p_i1 = p_[i + 1];
double m = (p_i1 - p_i) / (x_i1 - x_i);
if (m == 0.0) {
return x_i + (c - c_i) / p_i;
} else {
return x_i +
(std::sqrt(std::max(0.0, p_i * p_i + 2 * m * (c - c_i))) - p_i) /
m;
}
}
}
//==============================================================================
// Equiprobable implementation
//==============================================================================
double Equiprobable::sample(uint64_t* seed) const
{
std::size_t n = x_.size();
double r = prn(seed);
int i = std::floor((n - 1) * r);
double xl = x_[i];
double xr = x_[i + i];
return xl + ((n - 1) * r - i) * (xr - xl);
}
//==============================================================================
// Mixture implementation
//==============================================================================
Mixture::Mixture(pugi::xml_node node)
{
double cumsum = 0.0;
for (pugi::xml_node pair : node.children("pair")) {
// Check that required data exists
if (!pair.attribute("probability")) fatal_error("Mixture pair element does not have probability.");
if (!pair.child("dist")) fatal_error("Mixture pair element does not have a distribution.");
// cummulative sum of probybilities
cumsum += std::stod(pair.attribute("probability").value());
// Save cummulative probybility and distrubution
distribution_.push_back(
std::make_pair(cumsum, distribution_from_xml(pair.child("dist"))));
}
// Normalize cummulative probabilities to 1
for (auto& pair : distribution_) {
pair.first /= cumsum;
}
}
double Mixture::sample(uint64_t* seed) const
{
// Sample value of CDF
const double p = prn(seed);
// find matching distribution
const auto it = std::lower_bound(distribution_.cbegin(), distribution_.cend(),
p, [](const DistPair& pair, double p) { return pair.first < p; });
// This should not happen. Catch it
Ensures(it != distribution_.cend());
// Sample the chosen distribution
return it->second->sample(seed);
}
//==============================================================================
// Helper function
//==============================================================================
UPtrDist distribution_from_xml(pugi::xml_node node)
{
if (!check_for_node(node, "type"))
openmc::fatal_error("Distribution type must be specified.");
// Determine type of distribution
std::string type = get_node_value(node, "type", true, true);
// Allocate extension of Distribution
UPtrDist dist;
if (type == "uniform") {
dist = UPtrDist {new Uniform(node)};
} else if (type == "maxwell") {
dist = UPtrDist {new Maxwell(node)};
} else if (type == "watt") {
dist = UPtrDist {new Watt(node)};
} else if (type == "normal") {
dist = UPtrDist {new Normal(node)};
} else if (type == "muir") {
dist = UPtrDist {new Muir(node)};
} else if (type == "discrete") {
dist = UPtrDist {new Discrete(node)};
} else if (type == "tabular") {
dist = UPtrDist {new Tabular(node)};
} else if (type == "mixture") {
dist = UPtrDist{new Mixture(node)};
} else {
openmc::fatal_error("Invalid distribution type: " + type);
}
return dist;
}
} // namespace openmc
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.11 2000/07/08 00:17:13 andyh
* Cleanup of yesterday's speedup changes. Merged new bit into the
* scanner character properties table.
*
* Revision 1.10 2000/07/07 01:08:44 andyh
* Parser speed up in scan of XML content.
*
* Revision 1.9 2000/03/02 19:54:29 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.8 2000/02/24 20:18:07 abagchi
* Swat for removing Log from API docs
*
* Revision 1.7 2000/02/24 02:12:53 aruna1
* ReaderMgr:;getReaderDepth() added
*
* Revision 1.6 2000/02/06 07:47:53 rahulj
* Year 2K copyright swat.
*
* Revision 1.5 2000/01/25 01:04:21 roddey
* Fixes a bogus error about ]]> in char data.
*
* Revision 1.4 2000/01/24 20:40:43 roddey
* Exposed the APIs to get to the byte offset in the source XML buffer. This stuff
* is not tested yet, but I wanted to get the API changes in now so that the API
* can be stablized.
*
* Revision 1.3 2000/01/12 00:15:04 roddey
* Changes to deal with multiply nested, relative pathed, entities and to deal
* with the new URL class changes.
*
* Revision 1.2 1999/12/15 19:48:03 roddey
* Changed to use new split of transcoder interfaces into XML transcoders and
* LCP transcoders, and implementation of intrinsic transcoders as pluggable
* transcoders, and addition of Latin1 intrinsic support.
*
* Revision 1.1.1.1 1999/11/09 01:08:13 twl
* Initial checkin
*
* Revision 1.4 1999/11/08 20:56:54 droddey
* If the main xml entity does not exist, we need to get the error handling for that
* inside the main XMLScanner::scanDocument() try block so that it gets reported
* in the normal way. We have to add a little extra safety code because, when this
* happens, there is no reader on the reader stack to get position ino from.
*
* Revision 1.3 1999/11/08 20:44:43 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
#if !defined(READERMGR_HPP)
#define READERMGR_HPP
#include <util/RefStackOf.hpp>
#include <util/XMLString.hpp>
#include <sax/Locator.hpp>
#include <framework/XMLBuffer.hpp>
#include <internal/XMLReader.hpp>
class XMLBuffer;
class XMLEntityDecl;
class XMLEntityHandler;
class XMLDocumentHandler;
class XMLScanner;
// ---------------------------------------------------------------------------
// This class is used by the scanner. The scanner must deal with expansion
// of entities, some of which are totally different files (external parsed
// entities.) It does so by pushing readers onto a stack. The top reader is
// the one it wants to read out of, but that one must be popped when it is
// empty. To keep that logic from being all over the place, the scanner
// talks to the reader manager, which handles the stack and popping off
// used up readers.
// ---------------------------------------------------------------------------
class XMLPARSER_EXPORT ReaderMgr : public Locator
{
public :
// -----------------------------------------------------------------------
// Class specific types
// -----------------------------------------------------------------------
struct LastExtEntityInfo
{
const XMLCh* systemId;
const XMLCh* publicId;
unsigned int lineNumber;
unsigned int colNumber;
};
// -----------------------------------------------------------------------
// Constructors and Destructor
// -----------------------------------------------------------------------
ReaderMgr();
~ReaderMgr();
// -----------------------------------------------------------------------
// Convenience scanning methods
//
// This are all convenience methods that work in terms of the core
// character spooling methods.
// -----------------------------------------------------------------------
bool atEOF() const;
bool getName(XMLBuffer& toFill);
bool getNameToken(XMLBuffer& toFill);
XMLCh getNextChar();
bool getNextCharIfNot(const XMLCh chNotToGet, XMLCh& chGotten);
void movePlainContentChars(XMLBuffer &dest);
void getSpaces(XMLBuffer& toFill);
void getUpToCharOrWS(XMLBuffer& toFill, const XMLCh toCheck);
bool isEmpty() const;
bool lookingAtChar(const XMLCh toCheck);
bool lookingAtSpace();
XMLCh peekNextChar();
bool skipIfQuote(XMLCh& chGotten);
void skipPastChar(const XMLCh toSkip);
bool skipPastSpaces();
void skipToChar(const XMLCh toSkipTo);
bool skippedChar(const XMLCh toSkip);
bool skippedSpace();
bool skippedString(const XMLCh* const toSkip);
void skipQuotedString(const XMLCh quoteCh);
XMLCh skipUntilIn(const XMLCh* const listToSkip);
XMLCh skipUntilInOrWS(const XMLCh* const listToSkip);
// -----------------------------------------------------------------------
// Control methods
// -----------------------------------------------------------------------
void cleanStackBackTo(const unsigned int readerNum);
XMLReader* createReader
(
const InputSource& src
, const bool xmlDecl
, const XMLReader::RefFrom refFrom
, const XMLReader::Types type
, const XMLReader::Sources source
);
XMLReader* createReader
(
const XMLCh* const sysId
, const XMLCh* const pubId
, const bool xmlDecl
, const XMLReader::RefFrom refFrom
, const XMLReader::Types type
, const XMLReader::Sources source
, InputSource*& srcToFill
);
XMLReader* createIntEntReader
(
const XMLCh* const sysId
, const XMLReader::RefFrom refFrom
, const XMLReader::Types type
, const XMLCh* const dataBuf
, const unsigned int dataLen
, const bool copyBuf
);
bool isScanningPERefOutOfLiteral() const;
bool pushReader
(
XMLReader* const reader
, XMLEntityDecl* const entity
);
void reset();
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
const XMLCh* getCurrentEncodingStr() const;
const XMLEntityDecl* getCurrentEntity() const;
XMLEntityDecl* getCurrentEntity();
const XMLReader* getCurrentReader() const;
XMLReader* getCurrentReader();
unsigned int getCurrentReaderNum() const;
unsigned int getReaderDepth() const;
void getLastExtEntityInfo(LastExtEntityInfo& lastInfo) const;
unsigned int getSrcOffset() const;
bool getThrowEOE() const;
// -----------------------------------------------------------------------
// Setter methods
// -----------------------------------------------------------------------
void setEntityHandler(XMLEntityHandler* const newHandler);
void setThrowEOE(const bool newValue);
// -----------------------------------------------------------------------
// Implement the SAX Locator interface
// -----------------------------------------------------------------------
virtual const XMLCh* getPublicId() const;
virtual const XMLCh* getSystemId() const;
virtual int getLineNumber() const;
virtual int getColumnNumber() const;
private :
// -----------------------------------------------------------------------
// Private helper methods
// -----------------------------------------------------------------------
const XMLReader* getLastExtEntity(const XMLEntityDecl*& itsEntity) const;
bool popReader();
// -----------------------------------------------------------------------
// Private data members
//
// fCurEntity
// This is the current top of stack entity. We pull it off the stack
// and store it here for efficiency.
//
// fCurReader
// This is the current top of stack reader. We pull it off the
// stack and store it here for efficiency.
//
// fEntityHandler
// This is the installed entity handler. Its installed via the
// scanner but he passes it on to us since we need it the most, in
// process of creating external entity readers.
//
// fEntityStack
// We need to keep up with which of the pushed readers are pushed
// entity values that are being spooled. This is done to avoid the
// problem of recursive definitions. This stack consists of refs to
// EntityDecl objects for the pushed entities.
//
// fNextReaderNum
// This is the reader serial number value. Each new reader that is
// created from this reader is given a successive number. This lets
// us catch things like partial markup errors and such.
//
// fReaderStack
// This is the stack of reader references. We own all the readers
// and destroy them when they are used up.
//
// fThrowEOE
// This flag controls whether we throw an exception when we hit an
// end of entity. The scanner doesn't really need to know about ends
// of entities in the int/ext subsets, so it will turn this flag off
// until it gets into the content usually.
// -----------------------------------------------------------------------
XMLEntityDecl* fCurEntity;
XMLReader* fCurReader;
XMLEntityHandler* fEntityHandler;
RefStackOf<XMLEntityDecl>* fEntityStack;
unsigned int fNextReaderNum;
RefStackOf<XMLReader>* fReaderStack;
bool fThrowEOE;
};
// ---------------------------------------------------------------------------
// ReaderMgr: Inlined methods
//
// NOTE: We cannot put these in alphabetical and type order as we usually
// do because some of the compilers we have to support are too stupid to
// understand out of order inlines!
// ---------------------------------------------------------------------------
inline unsigned int ReaderMgr::getCurrentReaderNum() const
{
return fCurReader->getReaderNum();
}
inline bool ReaderMgr::getName(XMLBuffer& toFill)
{
toFill.reset();
return fCurReader->getName(toFill, false);
}
inline bool ReaderMgr::getNameToken(XMLBuffer& toFill)
{
toFill.reset();
return fCurReader->getName(toFill, true);
}
inline bool ReaderMgr::getNextCharIfNot(const XMLCh chNotToGet, XMLCh& chGotten)
{
return fCurReader->getNextCharIfNot(chNotToGet, chGotten);
}
inline void ReaderMgr::movePlainContentChars(XMLBuffer &dest)
{
fCurReader->movePlainContentChars(dest);
}
inline bool ReaderMgr::getThrowEOE() const
{
return fThrowEOE;
}
inline unsigned int ReaderMgr::getSrcOffset() const
{
return fCurReader->getSrcOffset();
}
inline bool ReaderMgr::lookingAtChar(const XMLCh chToCheck)
{
return (chToCheck == peekNextChar());
}
inline bool ReaderMgr::lookingAtSpace()
{
return XMLReader::isWhitespace(peekNextChar());
}
inline void ReaderMgr::setThrowEOE(const bool newValue)
{
fThrowEOE = newValue;
}
inline bool ReaderMgr::skippedString(const XMLCh* const toSkip)
{
return fCurReader->skippedString(toSkip);
}
inline void ReaderMgr::skipToChar(const XMLCh toSkipTo)
{
while (true)
{
// Get chars until we find the one to skip
const XMLCh nextCh = getNextChar();
// Break out at end of input or the char to skip
if ((nextCh == toSkipTo) || !nextCh)
break;
}
}
inline void ReaderMgr::skipPastChar(const XMLCh toSkipPast)
{
while (true)
{
// Get chars until we find the one to skip
const XMLCh nextCh = getNextChar();
if ((nextCh == toSkipPast) || !nextCh)
break;
}
}
inline void ReaderMgr::setEntityHandler(XMLEntityHandler* const newHandler)
{
fEntityHandler = newHandler;
}
//
// This is a simple class to temporarily change the 'throw at end of entity'
// flag of the reader manager. There are some places where we need to
// turn this on and off on a scoped basis.
//
class XMLPARSER_EXPORT ThrowEOEJanitor
{
public :
// -----------------------------------------------------------------------
// Constructors and destructor
// -----------------------------------------------------------------------
ThrowEOEJanitor(ReaderMgr* mgrTarget, const bool newValue) :
fMgr(mgrTarget)
, fOld(mgrTarget->getThrowEOE())
{
mgrTarget->setThrowEOE(newValue);
}
~ThrowEOEJanitor()
{
fMgr->setThrowEOE(fOld);
};
private :
// -----------------------------------------------------------------------
// Private data members
//
// fOld
// The previous value of the flag, which we replaced during ctor,
// and will replace during dtor.
//
// fMgr
// A pointer to the reader manager we are going to set/reset the
// flag on.
// -----------------------------------------------------------------------
bool fOld;
ReaderMgr* fMgr;
};
#endif
<commit_msg>Reordered member variables in ThrowEOEJanitor. Patch submitted by Kirk Wylie.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.12 2000/09/09 00:18:18 andyh
* Reordered member variables in ThrowEOEJanitor. Patch submitted
* by Kirk Wylie.
*
* Revision 1.11 2000/07/08 00:17:13 andyh
* Cleanup of yesterday's speedup changes. Merged new bit into the
* scanner character properties table.
*
* Revision 1.10 2000/07/07 01:08:44 andyh
* Parser speed up in scan of XML content.
*
* Revision 1.9 2000/03/02 19:54:29 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.8 2000/02/24 20:18:07 abagchi
* Swat for removing Log from API docs
*
* Revision 1.7 2000/02/24 02:12:53 aruna1
* ReaderMgr:;getReaderDepth() added
*
* Revision 1.6 2000/02/06 07:47:53 rahulj
* Year 2K copyright swat.
*
* Revision 1.5 2000/01/25 01:04:21 roddey
* Fixes a bogus error about ]]> in char data.
*
* Revision 1.4 2000/01/24 20:40:43 roddey
* Exposed the APIs to get to the byte offset in the source XML buffer. This stuff
* is not tested yet, but I wanted to get the API changes in now so that the API
* can be stablized.
*
* Revision 1.3 2000/01/12 00:15:04 roddey
* Changes to deal with multiply nested, relative pathed, entities and to deal
* with the new URL class changes.
*
* Revision 1.2 1999/12/15 19:48:03 roddey
* Changed to use new split of transcoder interfaces into XML transcoders and
* LCP transcoders, and implementation of intrinsic transcoders as pluggable
* transcoders, and addition of Latin1 intrinsic support.
*
* Revision 1.1.1.1 1999/11/09 01:08:13 twl
* Initial checkin
*
* Revision 1.4 1999/11/08 20:56:54 droddey
* If the main xml entity does not exist, we need to get the error handling for that
* inside the main XMLScanner::scanDocument() try block so that it gets reported
* in the normal way. We have to add a little extra safety code because, when this
* happens, there is no reader on the reader stack to get position ino from.
*
* Revision 1.3 1999/11/08 20:44:43 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
#if !defined(READERMGR_HPP)
#define READERMGR_HPP
#include <util/RefStackOf.hpp>
#include <util/XMLString.hpp>
#include <sax/Locator.hpp>
#include <framework/XMLBuffer.hpp>
#include <internal/XMLReader.hpp>
class XMLBuffer;
class XMLEntityDecl;
class XMLEntityHandler;
class XMLDocumentHandler;
class XMLScanner;
// ---------------------------------------------------------------------------
// This class is used by the scanner. The scanner must deal with expansion
// of entities, some of which are totally different files (external parsed
// entities.) It does so by pushing readers onto a stack. The top reader is
// the one it wants to read out of, but that one must be popped when it is
// empty. To keep that logic from being all over the place, the scanner
// talks to the reader manager, which handles the stack and popping off
// used up readers.
// ---------------------------------------------------------------------------
class XMLPARSER_EXPORT ReaderMgr : public Locator
{
public :
// -----------------------------------------------------------------------
// Class specific types
// -----------------------------------------------------------------------
struct LastExtEntityInfo
{
const XMLCh* systemId;
const XMLCh* publicId;
unsigned int lineNumber;
unsigned int colNumber;
};
// -----------------------------------------------------------------------
// Constructors and Destructor
// -----------------------------------------------------------------------
ReaderMgr();
~ReaderMgr();
// -----------------------------------------------------------------------
// Convenience scanning methods
//
// This are all convenience methods that work in terms of the core
// character spooling methods.
// -----------------------------------------------------------------------
bool atEOF() const;
bool getName(XMLBuffer& toFill);
bool getNameToken(XMLBuffer& toFill);
XMLCh getNextChar();
bool getNextCharIfNot(const XMLCh chNotToGet, XMLCh& chGotten);
void movePlainContentChars(XMLBuffer &dest);
void getSpaces(XMLBuffer& toFill);
void getUpToCharOrWS(XMLBuffer& toFill, const XMLCh toCheck);
bool isEmpty() const;
bool lookingAtChar(const XMLCh toCheck);
bool lookingAtSpace();
XMLCh peekNextChar();
bool skipIfQuote(XMLCh& chGotten);
void skipPastChar(const XMLCh toSkip);
bool skipPastSpaces();
void skipToChar(const XMLCh toSkipTo);
bool skippedChar(const XMLCh toSkip);
bool skippedSpace();
bool skippedString(const XMLCh* const toSkip);
void skipQuotedString(const XMLCh quoteCh);
XMLCh skipUntilIn(const XMLCh* const listToSkip);
XMLCh skipUntilInOrWS(const XMLCh* const listToSkip);
// -----------------------------------------------------------------------
// Control methods
// -----------------------------------------------------------------------
void cleanStackBackTo(const unsigned int readerNum);
XMLReader* createReader
(
const InputSource& src
, const bool xmlDecl
, const XMLReader::RefFrom refFrom
, const XMLReader::Types type
, const XMLReader::Sources source
);
XMLReader* createReader
(
const XMLCh* const sysId
, const XMLCh* const pubId
, const bool xmlDecl
, const XMLReader::RefFrom refFrom
, const XMLReader::Types type
, const XMLReader::Sources source
, InputSource*& srcToFill
);
XMLReader* createIntEntReader
(
const XMLCh* const sysId
, const XMLReader::RefFrom refFrom
, const XMLReader::Types type
, const XMLCh* const dataBuf
, const unsigned int dataLen
, const bool copyBuf
);
bool isScanningPERefOutOfLiteral() const;
bool pushReader
(
XMLReader* const reader
, XMLEntityDecl* const entity
);
void reset();
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
const XMLCh* getCurrentEncodingStr() const;
const XMLEntityDecl* getCurrentEntity() const;
XMLEntityDecl* getCurrentEntity();
const XMLReader* getCurrentReader() const;
XMLReader* getCurrentReader();
unsigned int getCurrentReaderNum() const;
unsigned int getReaderDepth() const;
void getLastExtEntityInfo(LastExtEntityInfo& lastInfo) const;
unsigned int getSrcOffset() const;
bool getThrowEOE() const;
// -----------------------------------------------------------------------
// Setter methods
// -----------------------------------------------------------------------
void setEntityHandler(XMLEntityHandler* const newHandler);
void setThrowEOE(const bool newValue);
// -----------------------------------------------------------------------
// Implement the SAX Locator interface
// -----------------------------------------------------------------------
virtual const XMLCh* getPublicId() const;
virtual const XMLCh* getSystemId() const;
virtual int getLineNumber() const;
virtual int getColumnNumber() const;
private :
// -----------------------------------------------------------------------
// Private helper methods
// -----------------------------------------------------------------------
const XMLReader* getLastExtEntity(const XMLEntityDecl*& itsEntity) const;
bool popReader();
// -----------------------------------------------------------------------
// Private data members
//
// fCurEntity
// This is the current top of stack entity. We pull it off the stack
// and store it here for efficiency.
//
// fCurReader
// This is the current top of stack reader. We pull it off the
// stack and store it here for efficiency.
//
// fEntityHandler
// This is the installed entity handler. Its installed via the
// scanner but he passes it on to us since we need it the most, in
// process of creating external entity readers.
//
// fEntityStack
// We need to keep up with which of the pushed readers are pushed
// entity values that are being spooled. This is done to avoid the
// problem of recursive definitions. This stack consists of refs to
// EntityDecl objects for the pushed entities.
//
// fNextReaderNum
// This is the reader serial number value. Each new reader that is
// created from this reader is given a successive number. This lets
// us catch things like partial markup errors and such.
//
// fReaderStack
// This is the stack of reader references. We own all the readers
// and destroy them when they are used up.
//
// fThrowEOE
// This flag controls whether we throw an exception when we hit an
// end of entity. The scanner doesn't really need to know about ends
// of entities in the int/ext subsets, so it will turn this flag off
// until it gets into the content usually.
// -----------------------------------------------------------------------
XMLEntityDecl* fCurEntity;
XMLReader* fCurReader;
XMLEntityHandler* fEntityHandler;
RefStackOf<XMLEntityDecl>* fEntityStack;
unsigned int fNextReaderNum;
RefStackOf<XMLReader>* fReaderStack;
bool fThrowEOE;
};
// ---------------------------------------------------------------------------
// ReaderMgr: Inlined methods
//
// NOTE: We cannot put these in alphabetical and type order as we usually
// do because some of the compilers we have to support are too stupid to
// understand out of order inlines!
// ---------------------------------------------------------------------------
inline unsigned int ReaderMgr::getCurrentReaderNum() const
{
return fCurReader->getReaderNum();
}
inline bool ReaderMgr::getName(XMLBuffer& toFill)
{
toFill.reset();
return fCurReader->getName(toFill, false);
}
inline bool ReaderMgr::getNameToken(XMLBuffer& toFill)
{
toFill.reset();
return fCurReader->getName(toFill, true);
}
inline bool ReaderMgr::getNextCharIfNot(const XMLCh chNotToGet, XMLCh& chGotten)
{
return fCurReader->getNextCharIfNot(chNotToGet, chGotten);
}
inline void ReaderMgr::movePlainContentChars(XMLBuffer &dest)
{
fCurReader->movePlainContentChars(dest);
}
inline bool ReaderMgr::getThrowEOE() const
{
return fThrowEOE;
}
inline unsigned int ReaderMgr::getSrcOffset() const
{
return fCurReader->getSrcOffset();
}
inline bool ReaderMgr::lookingAtChar(const XMLCh chToCheck)
{
return (chToCheck == peekNextChar());
}
inline bool ReaderMgr::lookingAtSpace()
{
return XMLReader::isWhitespace(peekNextChar());
}
inline void ReaderMgr::setThrowEOE(const bool newValue)
{
fThrowEOE = newValue;
}
inline bool ReaderMgr::skippedString(const XMLCh* const toSkip)
{
return fCurReader->skippedString(toSkip);
}
inline void ReaderMgr::skipToChar(const XMLCh toSkipTo)
{
while (true)
{
// Get chars until we find the one to skip
const XMLCh nextCh = getNextChar();
// Break out at end of input or the char to skip
if ((nextCh == toSkipTo) || !nextCh)
break;
}
}
inline void ReaderMgr::skipPastChar(const XMLCh toSkipPast)
{
while (true)
{
// Get chars until we find the one to skip
const XMLCh nextCh = getNextChar();
if ((nextCh == toSkipPast) || !nextCh)
break;
}
}
inline void ReaderMgr::setEntityHandler(XMLEntityHandler* const newHandler)
{
fEntityHandler = newHandler;
}
//
// This is a simple class to temporarily change the 'throw at end of entity'
// flag of the reader manager. There are some places where we need to
// turn this on and off on a scoped basis.
//
class XMLPARSER_EXPORT ThrowEOEJanitor
{
public :
// -----------------------------------------------------------------------
// Constructors and destructor
// -----------------------------------------------------------------------
ThrowEOEJanitor(ReaderMgr* mgrTarget, const bool newValue) :
fOld(mgrTarget->getThrowEOE())
, fMgr(mgrTarget)
{
mgrTarget->setThrowEOE(newValue);
}
~ThrowEOEJanitor()
{
fMgr->setThrowEOE(fOld);
};
private :
// -----------------------------------------------------------------------
// Private data members
//
// fOld
// The previous value of the flag, which we replaced during ctor,
// and will replace during dtor.
//
// fMgr
// A pointer to the reader manager we are going to set/reset the
// flag on.
// -----------------------------------------------------------------------
bool fOld;
ReaderMgr* fMgr;
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: treefragment.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2006-11-06 14:49:00 $
*
* 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 INCLUDED_SHARABLE_TREEFRAGMENT_HXX
#define INCLUDED_SHARABLE_TREEFRAGMENT_HXX
#ifndef INCLUDED_SHARABLE_BASETYPES_HXX
#include "types.hxx"
#endif
#ifndef INCLUDED_DATA_FLAGS_HXX
#include "flags.hxx"
#endif
#ifndef INCLUDED_SHARABLE_NODE_HXX
#include "node.hxx"
#endif
namespace configmgr
{
//-----------------------------------------------------------------------------
namespace sharable
{
//-----------------------------------------------------------------------------
namespace State = data::State;
//-----------------------------------------------------------------------------
/* a TreeFragment header is interpreted differently, depending on the kind of TreeFragment
- for a set element
name points to the element name (the Name in the root node is the template name)
parent points to the SetNode that is the parent. The containing treefragment can
be recovered from this with some care
next points to the next element of the same set. It is null for the last element.
state is fully used here
- for a template tree
name points to the template name (same as the Name in the root node)
component points to the home component name of the template
(often the same as 'component' in the component tree)
next points to another template TreeFragment. It is null for the last template.
state must be 'replaced' here (rarely it might be marked as mandatory)
- for a component tree
name points to the component name (same as the Name in the root node)
component is equal to name (or NULL ?)
next points to another template TreeFragment. It is null if there is no template.
state must be either 'defaulted' or 'merged'
(it should be marked as mandatory although that is not used yet)
*/
struct TreeFragmentHeader
{
List next; // next sibling set element or template
String name; // element-name/template name
union // context
{
Address parent; // parent node
String component; // component name
};
Offset count; // number of contained nodes
State::Field state;
Byte reserved;
};
//-----------------------------------------------------------------------------
/* a tree fragment is stored as a variable-sized struct
containing a header and a fixed sequence of nodes
R - - A - - A1
| |
| - A2
|
- B
|
- C - - C1 - - C11
| | |
| | - C12
| |
| - C2 - - C21
|
- D
is stored as
H(count = 12) : [R;A;A1;A2;B;C;C1;C11;C12;C2;C21;D]
*/
//-----------------------------------------------------------------------------
/* tree fragments are used for: Component trees, Template trees, Set elements
They are only fragments, as for a TreeFragment a Set is considered a leaf node.
Set elements are maintained as a singly linked list that is accessible from the set node
A cache component has the Root (component tree) TreeFragment at a well-known location.
The 'next' element of the component tree points to the list of template TreeFragments
used in the component.
*/
struct TreeFragment
{
TreeFragmentHeader header; // really variable-sized:
Node nodes[1]; // nodes[header.count]
// header info access
bool hasDefaults() const;
bool hasDefaultsAvailable() const;
bool isDefault() const;
bool isNew() const;
bool isNamed(rtl::OUString const & _aName) const;
rtl::OUString getName() const;
configmgr::node::Attributes getAttributes()const;
};
//-----------------------------------------------------------------------------
}
//-----------------------------------------------------------------------------
}
#endif // INCLUDED_SHARABLE_TREEFRAGMENT_HXX
<commit_msg>INTEGRATION: CWS configrefactor01 (1.5.14); FILE MERGED 2007/01/08 20:48:57 mmeeks 1.5.14.1: Issue number: Submitted by: mmeeks Substantial configmgr re-factoring #1 ... + remove endless typedef chains + remove custom allocator & associated complexity + remove Pointer, and 'Address' classes<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: treefragment.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: ihi $ $Date: 2007-11-23 14:25:38 $
*
* 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 INCLUDED_SHARABLE_TREEFRAGMENT_HXX
#define INCLUDED_SHARABLE_TREEFRAGMENT_HXX
#ifndef INCLUDED_SHARABLE_BASETYPES_HXX
#include "types.hxx"
#endif
#ifndef INCLUDED_DATA_FLAGS_HXX
#include "flags.hxx"
#endif
#ifndef INCLUDED_SHARABLE_NODE_HXX
#include "node.hxx"
#endif
namespace configmgr
{
//-----------------------------------------------------------------------------
namespace sharable
{
//-----------------------------------------------------------------------------
namespace State = data::State;
//-----------------------------------------------------------------------------
/* a TreeFragment header is interpreted differently, depending on the kind of TreeFragment
- for a set element
name points to the element name (the Name in the root node is the template name)
parent points to the SetNode that is the parent. The containing treefragment can
be recovered from this with some care
next points to the next element of the same set. It is null for the last element.
state is fully used here
- for a template tree
name points to the template name (same as the Name in the root node)
component points to the home component name of the template
(often the same as 'component' in the component tree)
next points to another template TreeFragment. It is null for the last template.
state must be 'replaced' here (rarely it might be marked as mandatory)
- for a component tree
name points to the component name (same as the Name in the root node)
component is equal to name (or NULL ?)
next points to another template TreeFragment. It is null if there is no template.
state must be either 'defaulted' or 'merged'
(it should be marked as mandatory although that is not used yet)
*/
struct TreeFragmentHeader
{
struct TreeFragment *next; // next sibling set element or template
String name; // element-name/template name
union // context
{
union Node *parent; // parent node
String component; // component name
};
Offset count; // number of contained nodes
State::Field state;
sal_uInt8 reserved;
};
//-----------------------------------------------------------------------------
/* a tree fragment is stored as a variable-sized struct
containing a header and a fixed sequence of nodes
R - - A - - A1
| |
| - A2
|
- B
|
- C - - C1 - - C11
| | |
| | - C12
| |
| - C2 - - C21
|
- D
is stored as
H(count = 12) : [R;A;A1;A2;B;C;C1;C11;C12;C2;C21;D]
*/
//-----------------------------------------------------------------------------
/* tree fragments are used for: Component trees, Template trees, Set elements
They are only fragments, as for a TreeFragment a Set is considered a leaf node.
Set elements are maintained as a singly linked list that is accessible from the set node
A cache component has the Root (component tree) TreeFragment at a well-known location.
The 'next' element of the component tree points to the list of template TreeFragments
used in the component.
*/
struct TreeFragment
{
TreeFragmentHeader header; // really variable-sized:
Node nodes[1]; // nodes[header.count]
// header info access
bool hasDefaults() const;
bool hasDefaultsAvailable() const;
bool isDefault() const;
bool isNew() const;
bool isNamed(rtl::OUString const & _aName) const;
rtl::OUString getName() const;
configmgr::node::Attributes getAttributes()const;
static TreeFragment *allocate(sal_uInt32 nFragments);
static void free_shallow( TreeFragment *pFragment );
};
//-----------------------------------------------------------------------------
}
namespace data {
typedef sharable::TreeFragment * TreeAddress;
}
//-----------------------------------------------------------------------------
}
#endif // INCLUDED_SHARABLE_TREEFRAGMENT_HXX
<|endoftext|> |
<commit_before>#include <cstdio>
int main() {
puts("ohai");
}
<commit_msg>main: create .wavs from example<commit_after>#include <cmath>
#include <fstream>
#include <iostream>
using namespace std;
template <typename T>
std::ostream& write_word(std::ostream &stream, T value
, unsigned size = sizeof(T)) {
for (; size; --size, value >>= 8)
stream.put(static_cast<char>(value & 0xFF));
return stream;
}
int main() {
ofstream f("out.wav", ios::binary);
// Write the file headers
f << "RIFF----WAVEfmt "; // (chunk size to be filled in later)
write_word(f, 16, 4); // no extension data
write_word(f, 1, 2); // PCM - integer samples
write_word(f, 2, 2); // two channels (stereo file)
write_word(f, 44100, 4); // samples per second (Hz)
write_word(f, 176400, 4); // (Sample Rate * BitsPerSample * Channels) / 8
write_word(f, 4, 2); // data block size (size of two integer samples, one for each channel, in bytes)
write_word(f, 16, 2); // number of bits per sample (use a multiple of 8)
// Write the data chunk header
size_t data_chunk_pos = f.tellp();
f << "data----"; // (chunk size to be filled in later)
// Write the audio samples
// (We'll generate a single C4 note with a sine wave, fading from left to right)
constexpr double two_pi = 6.283185307179586476925286766559;
constexpr double max_amplitude = 32760; // "volume"
double hz = 44100; // samples per second
double frequency = 261.626; // middle C
double seconds = 2.5; // time
int N = hz * seconds; // total number of samples
for (int n = 0; n < N; n++) {
double amplitude = (double)n / N * max_amplitude;
double value = sin((two_pi * n * frequency) / hz);
write_word(f, (int)( amplitude * value), 2);
write_word(f, (int)((max_amplitude - amplitude) * value), 2);
}
// (We'll need the final file size to fix the chunk sizes above)
size_t file_length = f.tellp();
// Fix the data chunk header to contain the data size
f.seekp(data_chunk_pos + 4);
write_word(f, file_length - data_chunk_pos + 8);
// Fix the file header to contain the proper RIFF chunk size, which is (file size - 8) bytes
f.seekp(0 + 4);
write_word(f, file_length - 8, 4);
}
<|endoftext|> |
<commit_before>/*
** Copyright 2015 Robert Fratto. See the LICENSE.txt file at the top-level
** directory of this distribution.
**
** Licensed under the MIT license <http://opensource.org/licenses/MIT>. This file
** may not be copied, modified, or distributed except according to those terms.
*/
#include <iostream>
#include <fstream>
#include <Grammar.h>
#include <Symtab.h>
#include <Nonterminal.h>
#include <Terminal.h>
Grammar* parseGrammar(const char* pathname)
{
auto symtab = new Symtab();
auto grammar = new Grammar(symtab);
extern FILE* yyin;
extern int yyparse(Grammar*);
extern void yyflushbuffer();
auto file = fopen(pathname, "r");
if (file == nullptr)
{
std::cerr << "could not open " << pathname << " for reading\n";
return nullptr;
}
yyflushbuffer();
yyin = file;
yyparse(grammar);
fclose(file);
return grammar;
}
void analyzeGrammar(Grammar* grammar)
{
const unsigned int START_LENGTH = 0;
const unsigned int TAB_SIZE = 4;
unsigned int line_length = START_LENGTH + TAB_SIZE;
auto termlist = grammar->getSymtab()->getTerminals();
auto nontermlist = grammar->getSymtab()->getNonterminals();
std::cout << "Terminals:\n\t";
for (unsigned int i = 0; i < termlist.size(); i++)
{
std::cout << termlist.at(i)->getName();
line_length += termlist.at(i)->getName().length();
if (i + 1 < termlist.size())
{
std::cout << ", ";
line_length += 2;
}
if (line_length > 40)
{
std::cout << "\n\t";
line_length = START_LENGTH + TAB_SIZE;
}
}
std::cout << "\n";
line_length = START_LENGTH + TAB_SIZE;
std::cout << "Nonterminals:\n\t";
for (unsigned int i = 0; i < termlist.size(); i++)
{
std::cout << termlist.at(i)->getName();
line_length += termlist.at(i)->getName().length();
if (i + 1 < termlist.size())
{
std::cout << ", ";
line_length += 2;
}
if (line_length > 40)
{
std::cout << "\n\t";
line_length = START_LENGTH + TAB_SIZE;
}
}
std::cout << "\n";
}
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cerr << "usage: " << argv[0] << " [parser file]\n";
return 1;
}
const char* pathname = argv[1];
auto grammar = parseGrammar(pathname);
if (grammar == nullptr)
{
return 1;
}
analyzeGrammar(grammar);
delete grammar->getSymtab();
delete grammar;
return 0;
}
<commit_msg>Fix issue where termlist was printed out twice.<commit_after>/*
** Copyright 2015 Robert Fratto. See the LICENSE.txt file at the top-level
** directory of this distribution.
**
** Licensed under the MIT license <http://opensource.org/licenses/MIT>. This file
** may not be copied, modified, or distributed except according to those terms.
*/
#include <iostream>
#include <fstream>
#include <Grammar.h>
#include <Symtab.h>
#include <Nonterminal.h>
#include <Terminal.h>
Grammar* parseGrammar(const char* pathname)
{
auto symtab = new Symtab();
auto grammar = new Grammar(symtab);
extern FILE* yyin;
extern int yyparse(Grammar*);
extern void yyflushbuffer();
auto file = fopen(pathname, "r");
if (file == nullptr)
{
std::cerr << "could not open " << pathname << " for reading\n";
return nullptr;
}
yyflushbuffer();
yyin = file;
yyparse(grammar);
fclose(file);
return grammar;
}
void analyzeGrammar(Grammar* grammar)
{
const unsigned int START_LENGTH = 0;
const unsigned int TAB_SIZE = 4;
unsigned int line_length = START_LENGTH + TAB_SIZE;
auto termlist = grammar->getSymtab()->getTerminals();
auto nontermlist = grammar->getSymtab()->getNonterminals();
std::cout << "Terminals:\n\t";
for (unsigned int i = 0; i < termlist.size(); i++)
{
std::cout << termlist.at(i)->getName();
line_length += termlist.at(i)->getName().length();
if (i + 1 < termlist.size())
{
std::cout << ", ";
line_length += 2;
}
if (line_length > 40)
{
std::cout << "\n\t";
line_length = START_LENGTH + TAB_SIZE;
}
}
std::cout << "\n";
line_length = START_LENGTH + TAB_SIZE;
std::cout << "Nonterminals:\n\t";
for (unsigned int i = 0; i < nontermlist.size(); i++)
{
std::cout << nontermlist.at(i)->getName();
line_length += nontermlist.at(i)->getName().length();
if (i + 1 < nontermlist.size())
{
std::cout << ", ";
line_length += 2;
}
if (line_length > 40)
{
std::cout << "\n\t";
line_length = START_LENGTH + TAB_SIZE;
}
}
std::cout << "\n";
}
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cerr << "usage: " << argv[0] << " [parser file]\n";
return 1;
}
const char* pathname = argv[1];
auto grammar = parseGrammar(pathname);
if (grammar == nullptr)
{
return 1;
}
analyzeGrammar(grammar);
delete grammar->getSymtab();
delete grammar;
return 0;
}
<|endoftext|> |
<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2015 Niek J. Bouman
//
// 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 REALEXPRCONV_HPP
#define REALEXPRCONV_HPP
// Niek J. Bouman (EPFL, 2015)
//
// Convenience function for (type-safe) definition of a RealExpr'ession
// in a Commelec Advertisement
//
#include <string>
#include <capnp/message.h>
#include "schema.capnp.h"
#include "polynomial-convenience.hpp"
//#include<iostream>
// some macros for repetitive stuff
#define BINOP(name) struct name { \
void setOp(msg::BinaryOperation::Builder binOp){ \
binOp.initOperation().set ## name(); \
} \
};
#define UNOP(name) struct name { \
void setOp(msg::UnaryOperation::Builder unaryOp){ \
unaryOp.initOperation().set ## name(); \
} \
};
#define UNOPFUN(name,type) template<typename TypeA> \
UnaryOp<TypeA,type> name(TypeA a) \
{ \
return UnaryOp<TypeA,type>(a); \
}
#define BINOPFUN(name,type) template<typename TypeA, typename TypeB> \
BinaryOp<TypeA,TypeB,type> name(TypeA a, TypeB b) \
{ \
return BinaryOp<TypeA,TypeB,type>(a,b); \
}
namespace cv {
// instantiate classes for unary operations
UNOP(Negate)
UNOP(Exp)
UNOP(Sin)
UNOP(Cos)
UNOP(Square)
UNOP(Sqrt)
UNOP(Log10)
UNOP(Ln)
UNOP(Round)
UNOP(Floor)
UNOP(Ceil)
UNOP(MultInv)
UNOP(Abs)
UNOP(Sign)
// instantiate classes for binary operations
BINOP(Sum)
BINOP(Prod)
BINOP(Pow)
BINOP(Min)
BINOP(Max)
BINOP(LessEqThan)
BINOP(GreaterThan)
// Every expression is a RealExprBase
template<typename Kind,typename... CtorArgs>
struct RealExprBase : public Kind
{
RealExprBase(CtorArgs... args)
: Kind(args...) {}
};
struct _Ref {
// Symbolic variable, for example Ref X("X")
_Ref(const std::string &var) : _varname(var) {}
const std::string &getName() const { return _varname; }
void build(msg::RealExpr::Builder realExpr) {
realExpr.setReference(_varname);
}
private:
std::string _varname;
};
using Ref = RealExprBase<_Ref, const std::string &>;
template <typename Expr>
struct _Name {
// can be used to name a (sub-) expression
_Name(const Ref &ref , Expr ex) : _name(ref.getName()), _expr(ex) {}
void build(msg::RealExpr::Builder realExpr) {
realExpr.setName(_name);
_expr.build(realExpr);
}
private:
Expr _expr;
std::string _name;
};
template <typename Expr>
using Name = RealExprBase<_Name<Expr>,const Ref&, Expr>;
template<typename Expr>
Name<Expr> name(const Ref& ref, Expr ex)
{
return Name<Expr>(ref,ex);
}
struct _Real {
_Real(double val): _value(val){}
void setValue(double val) {
_value=val;
}
void build(msg::RealExpr::Builder realExpr) {
realExpr.setReal(_value);
}
private:
double _value=0.0;
};
using Real = RealExprBase<_Real,double>;
struct _Polynomial {
_Polynomial(MonomialSum m) : _expr(m) {}
void build(msg::RealExpr::Builder realExpr) {
buildPolynomial(realExpr.getPolynomial(),_expr);
}
private:
MonomialSum _expr;
};
using Polynomial = RealExprBase<_Polynomial, MonomialSum>;
template <typename TypeA, typename Operation>
struct _UnaryOp : public Operation {
_UnaryOp(TypeA a) : argA(a) {}
void build(msg::RealExpr::Builder realExpr) {
auto unaryop = realExpr.initUnaryOperation();
Operation::setOp(unaryop);
argA.build(unaryop.initArg());
}
private:
TypeA argA;
};
template <typename Type, typename Operation>
using UnaryOp = RealExprBase<_UnaryOp<Type,Operation>,Type>;
template <typename TypeA, typename TypeB, typename Operation>
struct _BinaryOp : public Operation {
_BinaryOp(TypeA a, TypeB b) : argA(a), argB(b) {}
void build(msg::RealExpr::Builder realExpr) {
auto binop = realExpr.initBinaryOperation();
Operation::setOp(binop);
argA.build(binop.initArgA());
argB.build(binop.initArgB());
}
private:
TypeA argA;
TypeB argB;
};
template <typename TypeA, typename TypeB, typename Operation>
using BinaryOp = RealExprBase<_BinaryOp<TypeA,TypeB,Operation>,TypeA,TypeB>;
// instantiate convenience functions for using the unary operation classes
UNOPFUN(exp,Exp)
UNOPFUN(sin,Sin)
UNOPFUN(cos,Sin)
UNOPFUN(sqrt,Sqrt)
UNOPFUN(log10,Log10)
UNOPFUN(ln,Ln)
UNOPFUN(round,Round)
UNOPFUN(floor,Floor)
UNOPFUN(ceil,Ceil)
UNOPFUN(abs,Abs)
UNOPFUN(sign,Sign)
// instantiate convenience functions for using the binary operation classes
BINOPFUN(max,Max)
BINOPFUN(min,Min)
BINOPFUN(pow,Pow)
// define +,-,*,/ operators that bind only to RealExprBase expressions
template<typename TypeA,typename TypeB, typename... CtorArgsA, typename... CtorArgsB>
BinaryOp<RealExprBase<TypeA,CtorArgsA...>, RealExprBase<TypeB,CtorArgsB...>, Sum>
operator+(RealExprBase<TypeA,CtorArgsA...> a, RealExprBase<TypeB,CtorArgsB...> b) {
return BinaryOp<RealExprBase<TypeA,CtorArgsA...>,RealExprBase<TypeB,CtorArgsB...>,Sum>(a, b);
}
template<typename TypeA,typename TypeB, typename... CtorArgsA, typename... CtorArgsB>
BinaryOp<RealExprBase<TypeA,CtorArgsA...>, RealExprBase<TypeB,CtorArgsB...>, Sum>
operator-(RealExprBase<TypeA,CtorArgsA...> a, RealExprBase<TypeB,CtorArgsB...> b) {
return BinaryOp<RealExprBase<TypeA,CtorArgsA...>,RealExprBase<TypeB,CtorArgsB...>,Sum>(a, UnaryOp<RealExprBase<TypeB,CtorArgsB...>,Negate>(b));
}
template<typename TypeA,typename TypeB, typename... CtorArgsA, typename... CtorArgsB>
BinaryOp<RealExprBase<TypeA,CtorArgsA...>, RealExprBase<TypeB,CtorArgsB...>, Prod>
operator*(RealExprBase<TypeA,CtorArgsA...> a, RealExprBase<TypeB,CtorArgsB...> b) {
return BinaryOp<RealExprBase<TypeA,CtorArgsA...>,RealExprBase<TypeB,CtorArgsB...>,Prod>(a, b);
}
template<typename TypeA,typename TypeB, typename... CtorArgsA, typename... CtorArgsB>
BinaryOp<RealExprBase<TypeA,CtorArgsA...>, RealExprBase<TypeB,CtorArgsB...>, Sum>
operator/(RealExprBase<TypeA,CtorArgsA...> a, RealExprBase<TypeB,CtorArgsB...> b) {
return BinaryOp<RealExprBase<TypeA,CtorArgsA...>,RealExprBase<TypeB,CtorArgsB...>,Sum>(a, UnaryOp<RealExprBase<TypeB,CtorArgsB...>,MultInv>(b));
}
// toplevel build function
template<typename Type,typename... CtorArgs>
void buildRealExpr(msg::RealExpr::Builder realExpr,RealExprBase<Type,CtorArgs...> e) {
e.build(realExpr);
}
} // namespace cv
#endif
<commit_msg>Fixed bug in definition of division operator<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2015 Niek J. Bouman
//
// 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 REALEXPRCONV_HPP
#define REALEXPRCONV_HPP
// Niek J. Bouman (EPFL, 2015)
//
// Convenience function for (type-safe) definition of a RealExpr'ession
// in a Commelec Advertisement
//
#include <string>
#include <capnp/message.h>
#include "schema.capnp.h"
#include "polynomial-convenience.hpp"
// some macros for repetitive stuff
#define BINOP(name) struct name { \
void setOp(msg::BinaryOperation::Builder binOp){ \
binOp.initOperation().set ## name(); \
} \
};
#define UNOP(name) struct name { \
void setOp(msg::UnaryOperation::Builder unaryOp){ \
unaryOp.initOperation().set ## name(); \
} \
};
#define UNOPFUN(name,type) template<typename TypeA> \
UnaryOp<TypeA,type> name(TypeA a) \
{ \
return UnaryOp<TypeA,type>(a); \
}
#define BINOPFUN(name,type) template<typename TypeA, typename TypeB> \
BinaryOp<TypeA,TypeB,type> name(TypeA a, TypeB b) \
{ \
return BinaryOp<TypeA,TypeB,type>(a,b); \
}
namespace cv {
// instantiate classes for unary operations
UNOP(Negate)
UNOP(Exp)
UNOP(Sin)
UNOP(Cos)
UNOP(Square)
UNOP(Sqrt)
UNOP(Log10)
UNOP(Ln)
UNOP(Round)
UNOP(Floor)
UNOP(Ceil)
UNOP(MultInv)
UNOP(Abs)
UNOP(Sign)
// instantiate classes for binary operations
BINOP(Sum)
BINOP(Prod)
BINOP(Pow)
BINOP(Min)
BINOP(Max)
BINOP(LessEqThan)
BINOP(GreaterThan)
// Every expression is a RealExprBase
template<typename Kind,typename... CtorArgs>
struct RealExprBase : public Kind
{
RealExprBase(CtorArgs... args)
: Kind(args...) {}
};
struct _Ref {
// Symbolic variable, for example Ref X("X")
_Ref(const std::string &var) : _varname(var) {}
const std::string &getName() const { return _varname; }
void build(msg::RealExpr::Builder realExpr) {
realExpr.setReference(_varname);
}
private:
std::string _varname;
};
using Ref = RealExprBase<_Ref, const std::string &>;
template <typename Expr>
struct _Name {
// can be used to name a (sub-) expression
_Name(const Ref &ref , Expr ex) : _name(ref.getName()), _expr(ex) {}
void build(msg::RealExpr::Builder realExpr) {
realExpr.setName(_name);
_expr.build(realExpr);
}
private:
Expr _expr;
std::string _name;
};
template <typename Expr>
using Name = RealExprBase<_Name<Expr>,const Ref&, Expr>;
template<typename Expr>
Name<Expr> name(const Ref& ref, Expr ex)
{
return Name<Expr>(ref,ex);
}
struct _Real {
_Real(double val): _value(val){}
void setValue(double val) {
_value=val;
}
void build(msg::RealExpr::Builder realExpr) {
realExpr.setReal(_value);
}
private:
double _value=0.0;
};
using Real = RealExprBase<_Real,double>;
struct _Polynomial {
_Polynomial(MonomialSum m) : _expr(m) {}
void build(msg::RealExpr::Builder realExpr) {
buildPolynomial(realExpr.getPolynomial(),_expr);
}
private:
MonomialSum _expr;
};
using Polynomial = RealExprBase<_Polynomial, MonomialSum>;
template <typename TypeA, typename Operation>
struct _UnaryOp : public Operation {
_UnaryOp(TypeA a) : argA(a) {}
void build(msg::RealExpr::Builder realExpr) {
auto unaryop = realExpr.initUnaryOperation();
Operation::setOp(unaryop);
argA.build(unaryop.initArg());
}
private:
TypeA argA;
};
template <typename Type, typename Operation>
using UnaryOp = RealExprBase<_UnaryOp<Type,Operation>,Type>;
template <typename TypeA, typename TypeB, typename Operation>
struct _BinaryOp : public Operation {
_BinaryOp(TypeA a, TypeB b) : argA(a), argB(b) {}
void build(msg::RealExpr::Builder realExpr) {
auto binop = realExpr.initBinaryOperation();
Operation::setOp(binop);
argA.build(binop.initArgA());
argB.build(binop.initArgB());
}
private:
TypeA argA;
TypeB argB;
};
template <typename TypeA, typename TypeB, typename Operation>
using BinaryOp = RealExprBase<_BinaryOp<TypeA,TypeB,Operation>,TypeA,TypeB>;
// instantiate convenience functions for using the unary operation classes
UNOPFUN(exp,Exp)
UNOPFUN(sin,Sin)
UNOPFUN(cos,Sin)
UNOPFUN(sqrt,Sqrt)
UNOPFUN(log10,Log10)
UNOPFUN(ln,Ln)
UNOPFUN(round,Round)
UNOPFUN(floor,Floor)
UNOPFUN(ceil,Ceil)
UNOPFUN(abs,Abs)
UNOPFUN(sign,Sign)
// instantiate convenience functions for using the binary operation classes
BINOPFUN(max,Max)
BINOPFUN(min,Min)
BINOPFUN(pow,Pow)
// define +,-,*,/ operators that bind only to RealExprBase expressions
template<typename TypeA,typename TypeB, typename... CtorArgsA, typename... CtorArgsB>
BinaryOp<RealExprBase<TypeA,CtorArgsA...>, RealExprBase<TypeB,CtorArgsB...>, Sum>
operator+(RealExprBase<TypeA,CtorArgsA...> a, RealExprBase<TypeB,CtorArgsB...> b) {
return BinaryOp<RealExprBase<TypeA,CtorArgsA...>,RealExprBase<TypeB,CtorArgsB...>,Sum>(a, b);
}
template<typename TypeA,typename TypeB, typename... CtorArgsA, typename... CtorArgsB>
BinaryOp<RealExprBase<TypeA,CtorArgsA...>, RealExprBase<TypeB,CtorArgsB...>, Sum>
operator-(RealExprBase<TypeA,CtorArgsA...> a, RealExprBase<TypeB,CtorArgsB...> b) {
return BinaryOp<RealExprBase<TypeA,CtorArgsA...>,RealExprBase<TypeB,CtorArgsB...>,Sum>(a, UnaryOp<RealExprBase<TypeB,CtorArgsB...>,Negate>(b));
}
template<typename TypeA,typename TypeB, typename... CtorArgsA, typename... CtorArgsB>
BinaryOp<RealExprBase<TypeA,CtorArgsA...>, RealExprBase<TypeB,CtorArgsB...>, Prod>
operator*(RealExprBase<TypeA,CtorArgsA...> a, RealExprBase<TypeB,CtorArgsB...> b) {
return BinaryOp<RealExprBase<TypeA,CtorArgsA...>,RealExprBase<TypeB,CtorArgsB...>,Prod>(a, b);
}
template<typename TypeA,typename TypeB, typename... CtorArgsA, typename... CtorArgsB>
BinaryOp<RealExprBase<TypeA,CtorArgsA...>, RealExprBase<TypeB,CtorArgsB...>, Prod>
operator/(RealExprBase<TypeA,CtorArgsA...> a, RealExprBase<TypeB,CtorArgsB...> b) {
return BinaryOp<RealExprBase<TypeA,CtorArgsA...>,RealExprBase<TypeB,CtorArgsB...>,Prod>(a, UnaryOp<RealExprBase<TypeB,CtorArgsB...>,MultInv>(b));
}
// toplevel build function
template<typename Type,typename... CtorArgs>
void buildRealExpr(msg::RealExpr::Builder realExpr,RealExprBase<Type,CtorArgs...> e) {
e.build(realExpr);
}
} // namespace cv
#endif
<|endoftext|> |
<commit_before>#include <ncurses.h>
#include "window.hh"
#include "buffer.hh"
#include "file.hh"
#include "regex_selector.hh"
#include <unordered_map>
#include <cassert>
using namespace Kakoune;
void draw_window(Window& window)
{
window.update_display_buffer();
int max_x,max_y;
getmaxyx(stdscr, max_y, max_x);
max_y -= 1;
LineAndColumn position;
for (const DisplayAtom& atom : window.display_buffer())
{
const std::string& content = atom.content;
if (atom.attribute & UNDERLINE)
attron(A_UNDERLINE);
else
attroff(A_UNDERLINE);
size_t pos = 0;
size_t end;
while (true)
{
move(position.line, position.column);
clrtoeol();
end = content.find_first_of('\n', pos);
std::string line = content.substr(pos, end - pos);
addstr(line.c_str());
if (end != std::string::npos)
{
position.line = position.line + 1;
position.column = 0;
pos = end + 1;
if (position.line >= max_y)
break;
}
else
{
position.column += line.length();
break;
}
}
if (position.line >= max_y)
break;
}
while (++position.line < max_y)
{
move(position.line, 0);
clrtoeol();
addch('~');
}
const LineAndColumn& cursor_position = window.cursor_position();
move(cursor_position.line, cursor_position.column);
}
void init_ncurses()
{
initscr();
cbreak();
noecho();
nonl();
intrflush(stdscr, false);
keypad(stdscr, true);
curs_set(2);
}
void deinit_ncurses()
{
endwin();
}
void do_insert(Window& window)
{
std::string inserted;
LineAndColumn pos = window.cursor_position();
while(true)
{
char c = getch();
if (c == 27)
break;
window.insert(std::string() + c);
draw_window(window);
}
}
std::shared_ptr<Window> current_window;
void edit(const std::string& filename)
{
try
{
Buffer* buffer = create_buffer_from_file(filename);
if (buffer)
current_window = std::make_shared<Window>(std::shared_ptr<Buffer>(buffer));
}
catch (open_file_error& what)
{
assert(false);
}
}
void write_buffer(const std::string& filename)
{
try
{
write_buffer_to_file(*current_window->buffer(), filename);
}
catch(open_file_error& what)
{
assert(false);
}
catch(write_file_error& what)
{
assert(false);
}
}
bool quit_requested = false;
void quit(const std::string&)
{
quit_requested = true;
}
std::unordered_map<std::string, std::function<void (const std::string& param)>> cmdmap =
{
{ "e", edit },
{ "edit", edit },
{ "q", quit },
{ "quit", quit },
{ "w", write_buffer },
{ "write", write_buffer },
};
struct prompt_aborted {};
std::string prompt(const std::string& text)
{
int max_x, max_y;
getmaxyx(stdscr, max_y, max_x);
move(max_y-1, 0);
addstr(text.c_str());
clrtoeol();
std::string result;
while(true)
{
char c = getch();
switch (c)
{
case '\r':
return result;
case 7:
if (not result.empty())
{
move(max_y - 1, text.length() + result.length() - 1);
addch(' ');
result.resize(result.length() - 1);
move(max_y - 1, text.length() + result.length());
refresh();
}
break;
case 27:
throw prompt_aborted();
default:
result += c;
addch(c);
refresh();
}
}
return result;
}
void print_status(const std::string& status)
{
int x,y;
getmaxyx(stdscr, y, x);
move(y-1, 0);
clrtoeol();
addstr(status.c_str());
}
void do_command()
{
try
{
std::string cmd = prompt(":");
size_t cmd_end = cmd.find_first_of(' ');
std::string cmd_name = cmd.substr(0, cmd_end);
size_t param_start = cmd.find_first_not_of(' ', cmd_end);
std::string param;
if (param_start != std::string::npos)
param = cmd.substr(param_start, cmd.length() - param_start);
if (cmdmap.find(cmd_name) != cmdmap.end())
cmdmap[cmd_name](param);
else
print_status(cmd_name + ": no such command");
}
catch (prompt_aborted&) {}
}
bool is_blank(char c)
{
return c == ' ' or c == '\t' or c == '\n';
}
Selection select_to_next_word(const BufferIterator& cursor)
{
BufferIterator end = cursor;
while (not end.is_end() and not is_blank(*end))
++end;
while (not end.is_end() and is_blank(*end))
++end;
return Selection(cursor, end);
}
Selection select_to_next_word_end(const BufferIterator& cursor)
{
BufferIterator end = cursor;
while (not end.is_end() and is_blank(*end))
++end;
while (not end.is_end() and not is_blank(*end))
++end;
return Selection(cursor, end);
}
Selection select_line(const BufferIterator& cursor)
{
BufferIterator begin = cursor;
while (not begin.is_begin() and *(begin -1) != '\n')
--begin;
BufferIterator end = cursor;
while (not end.is_end() and *end != '\n')
++end;
return Selection(begin, end + 1);
}
void do_search(Window& window)
{
try
{
std::string ex = prompt("/");
window.select(false, RegexSelector(ex));
}
catch (boost::regex_error&) {}
catch (prompt_aborted&) {}
}
std::unordered_map<char, std::function<void (Window& window, int count)>> keymap =
{
{ 'h', [](Window& window, int count) { if (count == 0) count = 1; window.move_cursor(LineAndColumn(0, -count)); window.empty_selections(); } },
{ 'j', [](Window& window, int count) { if (count == 0) count = 1; window.move_cursor(LineAndColumn(count, 0)); window.empty_selections(); } },
{ 'k', [](Window& window, int count) { if (count == 0) count = 1; window.move_cursor(LineAndColumn(-count, 0)); window.empty_selections(); } },
{ 'l', [](Window& window, int count) { if (count == 0) count = 1; window.move_cursor(LineAndColumn(0, count)); window.empty_selections(); } },
{ 'd', [](Window& window, int count) { window.erase(); window.empty_selections(); } },
{ 'c', [](Window& window, int count) { window.erase(); do_insert(window); } },
{ 'i', [](Window& window, int count) { do_insert(window); } },
{ ':', [](Window& window, int count) { do_command(); } },
{ ' ', [](Window& window, int count) { window.empty_selections(); } },
{ 'w', [](Window& window, int count) { do { window.select(false, select_to_next_word); } while(--count > 0); } },
{ 'W', [](Window& window, int count) { do { window.select(true, select_to_next_word); } while(--count > 0); } },
{ 'e', [](Window& window, int count) { do { window.select(false, select_to_next_word_end); } while(--count > 0); } },
{ 'E', [](Window& window, int count) { do { window.select(true, select_to_next_word_end); } while(--count > 0); } },
{ '.', [](Window& window, int count) { do { window.select(false, select_line); } while(--count > 0); } },
{ '/', [](Window& window, int count) { do_search(window); } },
};
int main()
{
init_ncurses();
try
{
auto buffer = std::make_shared<Buffer>("<scratch>");
current_window = std::make_shared<Window>(buffer);
draw_window(*current_window);
int count = 0;
while(not quit_requested)
{
char c = getch();
if (isdigit(c))
count = count * 10 + c - '0';
else
{
if (keymap.find(c) != keymap.end())
{
keymap[c](*current_window, count);
draw_window(*current_window);
}
count = 0;
}
}
deinit_ncurses();
}
catch (...)
{
deinit_ncurses();
throw;
}
return 0;
}
<commit_msg>better exception handling in edit and write_buffer<commit_after>#include <ncurses.h>
#include "window.hh"
#include "buffer.hh"
#include "file.hh"
#include "regex_selector.hh"
#include <unordered_map>
#include <cassert>
using namespace Kakoune;
void draw_window(Window& window)
{
window.update_display_buffer();
int max_x,max_y;
getmaxyx(stdscr, max_y, max_x);
max_y -= 1;
LineAndColumn position;
for (const DisplayAtom& atom : window.display_buffer())
{
const std::string& content = atom.content;
if (atom.attribute & UNDERLINE)
attron(A_UNDERLINE);
else
attroff(A_UNDERLINE);
size_t pos = 0;
size_t end;
while (true)
{
move(position.line, position.column);
clrtoeol();
end = content.find_first_of('\n', pos);
std::string line = content.substr(pos, end - pos);
addstr(line.c_str());
if (end != std::string::npos)
{
position.line = position.line + 1;
position.column = 0;
pos = end + 1;
if (position.line >= max_y)
break;
}
else
{
position.column += line.length();
break;
}
}
if (position.line >= max_y)
break;
}
while (++position.line < max_y)
{
move(position.line, 0);
clrtoeol();
addch('~');
}
const LineAndColumn& cursor_position = window.cursor_position();
move(cursor_position.line, cursor_position.column);
}
void init_ncurses()
{
initscr();
cbreak();
noecho();
nonl();
intrflush(stdscr, false);
keypad(stdscr, true);
curs_set(2);
}
void deinit_ncurses()
{
endwin();
}
struct prompt_aborted {};
std::string prompt(const std::string& text)
{
int max_x, max_y;
getmaxyx(stdscr, max_y, max_x);
move(max_y-1, 0);
addstr(text.c_str());
clrtoeol();
std::string result;
while(true)
{
char c = getch();
switch (c)
{
case '\r':
return result;
case 7:
if (not result.empty())
{
move(max_y - 1, text.length() + result.length() - 1);
addch(' ');
result.resize(result.length() - 1);
move(max_y - 1, text.length() + result.length());
refresh();
}
break;
case 27:
throw prompt_aborted();
default:
result += c;
addch(c);
refresh();
}
}
return result;
}
void print_status(const std::string& status)
{
int x,y;
getmaxyx(stdscr, y, x);
move(y-1, 0);
clrtoeol();
addstr(status.c_str());
}
void do_insert(Window& window)
{
std::string inserted;
LineAndColumn pos = window.cursor_position();
while(true)
{
char c = getch();
if (c == 27)
break;
window.insert(std::string() + c);
draw_window(window);
}
}
std::shared_ptr<Window> current_window;
void edit(const std::string& filename)
{
try
{
std::shared_ptr<Buffer> buffer(create_buffer_from_file(filename));
if (buffer)
current_window = std::make_shared<Window>(buffer);
}
catch (file_not_found& what)
{
current_window = std::make_shared<Window>(std::make_shared<Buffer>(filename));
}
catch (open_file_error& what)
{
print_status("error opening '" + filename + "' (" + what.what() + ")");
}
}
void write_buffer(const std::string& filename)
{
try
{
Buffer& buffer = *current_window->buffer();
write_buffer_to_file(buffer,
filename.empty() ? buffer.name() : filename);
}
catch(open_file_error& what)
{
print_status("error opening " + filename + "(" + what.what() + ")");
}
catch(write_file_error& what)
{
print_status("error writing " + filename + "(" + what.what() + ")");
}
}
bool quit_requested = false;
void quit(const std::string&)
{
quit_requested = true;
}
std::unordered_map<std::string, std::function<void (const std::string& param)>> cmdmap =
{
{ "e", edit },
{ "edit", edit },
{ "q", quit },
{ "quit", quit },
{ "w", write_buffer },
{ "write", write_buffer },
};
void do_command()
{
try
{
std::string cmd = prompt(":");
size_t cmd_end = cmd.find_first_of(' ');
std::string cmd_name = cmd.substr(0, cmd_end);
size_t param_start = cmd.find_first_not_of(' ', cmd_end);
std::string param;
if (param_start != std::string::npos)
param = cmd.substr(param_start, cmd.length() - param_start);
if (cmdmap.find(cmd_name) != cmdmap.end())
cmdmap[cmd_name](param);
else
print_status(cmd_name + ": no such command");
}
catch (prompt_aborted&) {}
}
bool is_blank(char c)
{
return c == ' ' or c == '\t' or c == '\n';
}
Selection select_to_next_word(const BufferIterator& cursor)
{
BufferIterator end = cursor;
while (not end.is_end() and not is_blank(*end))
++end;
while (not end.is_end() and is_blank(*end))
++end;
return Selection(cursor, end);
}
Selection select_to_next_word_end(const BufferIterator& cursor)
{
BufferIterator end = cursor;
while (not end.is_end() and is_blank(*end))
++end;
while (not end.is_end() and not is_blank(*end))
++end;
return Selection(cursor, end);
}
Selection select_line(const BufferIterator& cursor)
{
BufferIterator begin = cursor;
while (not begin.is_begin() and *(begin -1) != '\n')
--begin;
BufferIterator end = cursor;
while (not end.is_end() and *end != '\n')
++end;
return Selection(begin, end + 1);
}
void do_search(Window& window)
{
try
{
std::string ex = prompt("/");
window.select(false, RegexSelector(ex));
}
catch (boost::regex_error&) {}
catch (prompt_aborted&) {}
}
std::unordered_map<char, std::function<void (Window& window, int count)>> keymap =
{
{ 'h', [](Window& window, int count) { if (count == 0) count = 1; window.move_cursor(LineAndColumn(0, -count)); window.empty_selections(); } },
{ 'j', [](Window& window, int count) { if (count == 0) count = 1; window.move_cursor(LineAndColumn(count, 0)); window.empty_selections(); } },
{ 'k', [](Window& window, int count) { if (count == 0) count = 1; window.move_cursor(LineAndColumn(-count, 0)); window.empty_selections(); } },
{ 'l', [](Window& window, int count) { if (count == 0) count = 1; window.move_cursor(LineAndColumn(0, count)); window.empty_selections(); } },
{ 'd', [](Window& window, int count) { window.erase(); window.empty_selections(); } },
{ 'c', [](Window& window, int count) { window.erase(); do_insert(window); } },
{ 'i', [](Window& window, int count) { do_insert(window); } },
{ ':', [](Window& window, int count) { do_command(); } },
{ ' ', [](Window& window, int count) { window.empty_selections(); } },
{ 'w', [](Window& window, int count) { do { window.select(false, select_to_next_word); } while(--count > 0); } },
{ 'W', [](Window& window, int count) { do { window.select(true, select_to_next_word); } while(--count > 0); } },
{ 'e', [](Window& window, int count) { do { window.select(false, select_to_next_word_end); } while(--count > 0); } },
{ 'E', [](Window& window, int count) { do { window.select(true, select_to_next_word_end); } while(--count > 0); } },
{ '.', [](Window& window, int count) { do { window.select(false, select_line); } while(--count > 0); } },
{ '/', [](Window& window, int count) { do_search(window); } },
};
int main()
{
init_ncurses();
try
{
auto buffer = std::make_shared<Buffer>("<scratch>");
current_window = std::make_shared<Window>(buffer);
draw_window(*current_window);
int count = 0;
while(not quit_requested)
{
char c = getch();
if (isdigit(c))
count = count * 10 + c - '0';
else
{
if (keymap.find(c) != keymap.end())
{
keymap[c](*current_window, count);
draw_window(*current_window);
}
count = 0;
}
}
deinit_ncurses();
}
catch (...)
{
deinit_ncurses();
throw;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016 Dariusz Stojaczyk. All Rights Reserved.
* The following source code is released under an MIT-style license,
* that can be found in the LICENSE file.
*/
/**
* NOTE: This class requires heavy exception handling.
* If something goes wrong it would be a real hell to debug
*/
#include <memory>
#include <regex>
#include <unordered_map>
#include <cstdlib>
#include "Atlas.h"
#include "TexData.h"
#include "util/collection.h"
#include "util/file.h"
#include "Resampler.h"
#include "util/Packer.h"
#include "exceptions.h"
#include "util/log.h"
#include "util/prof.h"
using namespace texture;
/**
* The following state may not be available on some devices (e.g. OpenGL ES 2.0)
*/
#ifdef GL_TEXTURE_MAX_LEVEL
#define USES_MANUAL_MIPMAPS
#endif
#ifndef USES_MANUAL_MIPMAPS
#include <SOIL.h>
#endif
struct Atlas::impl {
impl(std::vector<std::string> tiles)
: m_tiles(util::collection::filter(tiles, FILE_EXTENSION_REGEX)) {
}
/**
* OpenGL uses enum to determine a number (and type) of texture channels.
* Since we don't handle different types of texture channels in Atlas class,
* just a pure int number of channels is passed between methods.
*/
GLenum getTexGLFormat(uint32_t channels) {
GLenum ret;
switch (channels) {
case 1:
ret = GL_LUMINANCE; /**< If L was converted into RGBA, it would be R=L, G=L, B=L, A=1 */
break;
case 2:
ret = GL_LUMINANCE_ALPHA; /**< If LA' was converted into RGBA, it would be R=L, G=L, B=L, A=A' */
break;
case 3:
ret = GL_RGB; /**< A=1 */
break;
case 4:
ret = GL_RGBA;
break;
default:
char msg[100];
snprintf(msg, sizeof(msg), "Trying to convert invalid channel number into an OpenGL texture format (channels:%d).", channels);
throw invalid_texture_error(msg);
}
return ret;
}
void writeTexToGPU(TexData &tex, uint32_t level) {
uint32_t channels = tex.channels();
if (channels < 1 || channels > 4) {
char msg[90];
snprintf(msg, sizeof(msg), "Trying to write to GPU texture with invalid amount of channels (channels:%d).", channels);
throw invalid_texture_error(msg);
}
#ifdef DBG_COLORMIPMAPS
// color mipmaps in scheme: red (biggest) -> yellow (smallest)
if (channels >= 3) {
for (int i = 0; i < tex.width() * tex.height(); ++i) {
resampled[channels * i + 0] = 255 - level * 40;
resampled[channels * i + 1] = level * 40;
resampled[channels * i + 2] = 0;
if (channels >= 4) {
resampled[channels * i + 3] = 255;
}
}
}
#endif // DBG_COLORMIPMAPS
if (channels == 4) {
// burn alpha into RGB channels
for (int i = 0; i < tex.width() * tex.height(); ++i) {
tex[channels * i + 0] = (uint8_t) ((tex[channels * i + 0] * tex[channels * i + 3] + 128) >> 8);
tex[channels * i + 1] = (uint8_t) ((tex[channels * i + 1] * tex[channels * i + 3] + 128) >> 8);
tex[channels * i + 2] = (uint8_t) ((tex[channels * i + 2] * tex[channels * i + 3] + 128) >> 8);
}
}
glTexImage2D(GL_TEXTURE_2D, level, tex.channels(), tex.width(), tex.height(), 0, getTexGLFormat(tex.channels()), GL_UNSIGNED_BYTE, tex.get());
}
util::Packer m_packer;
std::hash<std::string> m_hash;
std::unordered_map<uint64_t, TexData> m_texData;
std::vector<std::string> m_tiles;
static const std::regex FILE_EXTENSION_REGEX;
};
const std::regex Atlas::impl::FILE_EXTENSION_REGEX = std::regex("(.*)(\\.(jpg|png|gif))", std::regex::ECMAScript | std::regex::icase);
Atlas::Atlas(const std::string &name)
: Texture(name),
m_impl(std::make_unique<Atlas::impl>(util::file::list(util::file::path<util::file::type::texture>(name).c_str()))) {
}
void Atlas::load() {
PROF_START(load);
for (const std::string &tile : m_impl->m_tiles) {
loadTile(tile);
}
m_impl->m_packer.pack();
m_width = m_impl->m_packer.size().width();
m_height = m_impl->m_packer.size().height();
m_channels = 4;
Log::debug("Preparing the texture atlas \"%s\" took %f sec.", m_path.c_str(), PROF_DURATION_PREV(load));
#ifdef USES_MANUAL_MIPMAPS
glGenTextures(1, &m_id);
bindTexture();
uint32_t mipmapLevels = (uint32_t) ceil(log(std::max(width(), height())) / log(2));
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, mipmapLevels - 1);
Log::debug("Preparing the OpenGL texture \"%s\" took %f sec.", m_path.c_str(), PROF_DURATION_PREV(load));
for (uint8_t level = 0; level < mipmapLevels; ++level) {
#else
uint8_t level = 0;
#endif
uint32_t downsample = 1u << level;
TexData atlas(width() / downsample, height() / downsample, channels());
//TODO it's totally unreadable
for (auto &el : m_impl->m_packer.elements()) {
TexData &inTile = m_impl->m_texData.find(el.first)->second;
TexData outTile = texture::Resampler::downsample(inTile, downsample);
util::Rectangle rect(el.second.x() / downsample, el.second.y() / downsample, el.second.width() / downsample, el.second.height() / downsample);
uint32_t inWidth = inTile.width() / downsample;
uint32_t inHeight = inTile.height() / downsample;
uint32_t outWidth = m_impl->m_packer.size().width() / downsample;
for (int yIn = 0; yIn < inHeight; ++yIn) {
for (int xIn = 0; xIn < inWidth; ++xIn) {
uint32_t inPixelPos = xIn + yIn * inWidth;
uint32_t outPixelPos = rect.x() + xIn + (rect.y() + yIn) * outWidth;
for (int channel = 0; channel < channels(); ++channel) {
atlas[4 * outPixelPos + channel] = outTile[channels() * inPixelPos + channel];
}
}
}
}
Log::debug("\tResampling of level %d of the texture atlas \"%s\" took %f sec.", level, m_path.c_str(), PROF_DURATION_PREV(load));
#ifdef USES_MANUAL_MIPMAPS
m_impl->writeTexToGPU(atlas, level);
}
#else
//TODO create additional writeTexToGPU overload (?)
m_id = SOIL_create_OGL_texture(atlas.getData(), m_width, m_height, m_channels, 0, SOIL_FLAG_MULTIPLY_ALPHA);
glGenerateMipmap(GL_TEXTURE_2D);
#endif
Log::debug("Generating the texture atlas \"%s\" took %f sec.", m_path.c_str(), PROF_DURATION_START(load));
}
void Atlas::loadTile(const std::string &fileName) {
TexData tex(m_path + util::file::file_separator_str + fileName);
uint64_t id = m_impl->m_hash(fileName.substr(0, fileName.find_last_of('.')));
m_impl->m_packer.add({id, util::Rectangle(tex.width(), tex.height())});
m_impl->m_texData.emplace(id, std::move(tex));
}
const util::Rectangle Atlas::element(const std::string &name) const {
uint64_t id = m_impl->m_hash(name);
auto elements = m_impl->m_packer.elements();
auto it = std::find_if(elements.begin(), elements.end(), [id](const util::Packer::Element &element) {
return element.first == id;
});
if (it == elements.end()) {
char msg[100];
snprintf(msg, sizeof(msg), "Trying to get inexistent element (\"%d\") from texture atlas.", name.c_str());
throw invalid_texture_error(msg);
}
return it->second;
}
const uint64_t Atlas::getElementsNum() const {
return m_impl->m_texData.size();
}
Atlas::~Atlas() {}<commit_msg>Updated automatic mipmap generation code<commit_after>/*
* Copyright (c) 2016 Dariusz Stojaczyk. All Rights Reserved.
* The following source code is released under an MIT-style license,
* that can be found in the LICENSE file.
*/
/**
* NOTE: This class requires heavy exception handling.
* If something goes wrong it would be a real hell to debug
*/
#include <memory>
#include <regex>
#include <unordered_map>
#include <cstdlib>
#include "Atlas.h"
#include "TexData.h"
#include "util/collection.h"
#include "util/file.h"
#include "Resampler.h"
#include "util/Packer.h"
#include "exceptions.h"
#include "util/log.h"
#include "util/prof.h"
using namespace texture;
/**
* The following state may not be available on some devices (e.g. OpenGL ES 2.0)
*/
#ifdef GL_TEXTURE_MAX_LEVEL
#define USES_MANUAL_MIPMAPS
#endif
#ifndef USES_MANUAL_MIPMAPS
#include <SOIL.h>
#endif
struct Atlas::impl {
impl(std::vector<std::string> tiles)
: m_tiles(util::collection::filter(tiles, FILE_EXTENSION_REGEX)) {
}
/**
* OpenGL uses enum to determine a number (and type) of texture channels.
* Since we don't handle different types of texture channels in Atlas class,
* just a pure int number of channels is passed between methods.
*/
GLenum getTexGLFormat(uint32_t channels) {
GLenum ret;
switch (channels) {
case 1:
ret = GL_LUMINANCE; /**< If L was converted into RGBA, it would be R=L, G=L, B=L, A=1 */
break;
case 2:
ret = GL_LUMINANCE_ALPHA; /**< If LA' was converted into RGBA, it would be R=L, G=L, B=L, A=A' */
break;
case 3:
ret = GL_RGB; /**< A=1 */
break;
case 4:
ret = GL_RGBA;
break;
default:
char msg[100];
snprintf(msg, sizeof(msg), "Trying to convert invalid channel number into an OpenGL texture format (channels:%d).", channels);
throw invalid_texture_error(msg);
}
return ret;
}
void writeTexToGPU(TexData &tex, uint32_t level) {
uint32_t channels = tex.channels();
if (channels < 1 || channels > 4) {
char msg[90];
snprintf(msg, sizeof(msg), "Trying to write to GPU texture with invalid amount of channels (channels:%d).", channels);
throw invalid_texture_error(msg);
}
#ifdef DBG_COLORMIPMAPS
// color mipmaps in scheme: red (biggest) -> yellow (smallest)
if (channels >= 3) {
for (int i = 0; i < tex.width() * tex.height(); ++i) {
resampled[channels * i + 0] = 255 - level * 40;
resampled[channels * i + 1] = level * 40;
resampled[channels * i + 2] = 0;
if (channels >= 4) {
resampled[channels * i + 3] = 255;
}
}
}
#endif // DBG_COLORMIPMAPS
if (channels == 4) {
// burn alpha into RGB channels
for (int i = 0; i < tex.width() * tex.height(); ++i) {
tex[channels * i + 0] = (uint8_t) ((tex[channels * i + 0] * tex[channels * i + 3] + 128) >> 8);
tex[channels * i + 1] = (uint8_t) ((tex[channels * i + 1] * tex[channels * i + 3] + 128) >> 8);
tex[channels * i + 2] = (uint8_t) ((tex[channels * i + 2] * tex[channels * i + 3] + 128) >> 8);
}
}
glTexImage2D(GL_TEXTURE_2D, level, tex.channels(), tex.width(), tex.height(), 0, getTexGLFormat(tex.channels()), GL_UNSIGNED_BYTE, tex.get());
}
util::Packer m_packer;
std::hash<std::string> m_hash;
std::unordered_map<uint64_t, TexData> m_texData;
std::vector<std::string> m_tiles;
static const std::regex FILE_EXTENSION_REGEX;
};
const std::regex Atlas::impl::FILE_EXTENSION_REGEX = std::regex("(.*)(\\.(jpg|png|gif))", std::regex::ECMAScript | std::regex::icase);
Atlas::Atlas(const std::string &name)
: Texture(name),
m_impl(std::make_unique<Atlas::impl>(util::file::list(util::file::path<util::file::type::texture>(name).c_str()))) {
}
void Atlas::load() {
PROF_START(load);
for (const std::string &tile : m_impl->m_tiles) {
loadTile(tile);
}
m_impl->m_packer.pack();
m_width = m_impl->m_packer.size().width();
m_height = m_impl->m_packer.size().height();
m_channels = 4;
Log::debug("Preparing the texture atlas \"%s\" took %f sec.", m_path.c_str(), PROF_DURATION_PREV(load));
#ifdef USES_MANUAL_MIPMAPS
glGenTextures(1, &m_id);
bindTexture();
uint32_t mipmapLevels = (uint32_t) ceil(log(std::max(width(), height())) / log(2));
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, mipmapLevels - 1);
Log::debug("Preparing the OpenGL texture \"%s\" took %f sec.", m_path.c_str(), PROF_DURATION_PREV(load));
for (uint8_t level = 0; level < mipmapLevels; ++level) {
#else
uint8_t level = 0;
#endif
uint32_t downsample = 1u << level;
TexData atlas(width() / downsample, height() / downsample, channels());
//TODO it's totally unreadable
for (auto &el : m_impl->m_packer.elements()) {
TexData &inTile = m_impl->m_texData.find(el.first)->second;
TexData outTile = texture::Resampler::downsample(inTile, downsample);
util::Rectangle rect(el.second.x() / downsample, el.second.y() / downsample, el.second.width() / downsample, el.second.height() / downsample);
uint32_t inWidth = inTile.width() / downsample;
uint32_t inHeight = inTile.height() / downsample;
uint32_t outWidth = m_impl->m_packer.size().width() / downsample;
for (int yIn = 0; yIn < inHeight; ++yIn) {
for (int xIn = 0; xIn < inWidth; ++xIn) {
uint32_t inPixelPos = xIn + yIn * inWidth;
uint32_t outPixelPos = rect.x() + xIn + (rect.y() + yIn) * outWidth;
for (int channel = 0; channel < channels(); ++channel) {
atlas[4 * outPixelPos + channel] = outTile[channels() * inPixelPos + channel];
}
}
}
}
Log::debug("\tResampling of level %d of the texture atlas \"%s\" took %f sec.", level, m_path.c_str(), PROF_DURATION_PREV(load));
#ifdef USES_MANUAL_MIPMAPS
m_impl->writeTexToGPU(atlas, level);
}
#else
//TODO create additional writeTexToGPU overload (?)
m_id = SOIL_create_OGL_texture(atlas.get(), m_width, m_height, m_channels, 0, SOIL_FLAG_MULTIPLY_ALPHA);
glGenerateMipmap(GL_TEXTURE_2D);
#endif
Log::debug("Generating the texture atlas \"%s\" took %f sec.", m_path.c_str(), PROF_DURATION_START(load));
}
void Atlas::loadTile(const std::string &fileName) {
TexData tex(m_path + util::file::file_separator_str + fileName);
uint64_t id = m_impl->m_hash(fileName.substr(0, fileName.find_last_of('.')));
m_impl->m_packer.add({id, util::Rectangle(tex.width(), tex.height())});
m_impl->m_texData.emplace(id, std::move(tex));
}
const util::Rectangle Atlas::element(const std::string &name) const {
uint64_t id = m_impl->m_hash(name);
auto elements = m_impl->m_packer.elements();
auto it = std::find_if(elements.begin(), elements.end(), [id](const util::Packer::Element &element) {
return element.first == id;
});
if (it == elements.end()) {
char msg[100];
snprintf(msg, sizeof(msg), "Trying to get inexistent element (\"%d\") from texture atlas.", name.c_str());
throw invalid_texture_error(msg);
}
return it->second;
}
const uint64_t Atlas::getElementsNum() const {
return m_impl->m_texData.size();
}
Atlas::~Atlas() {}<|endoftext|> |
<commit_before>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <signal.h>
#include <errno.h>
#include "utils.hpp"
#include "worker_pool.hpp"
#include "async_io.hpp"
#include "blackhole_alloc.hpp"
void event_handler(event_queue_t *event_queue, event_t *event) {
int res;
size_t sz;
char buf[256];
if(event->event_type == et_sock_event) {
bzero(buf, sizeof(buf));
// TODO: make sure we don't leave any data in the socket
sz = read(event->source, buf, sizeof(buf));
check("Could not read from socket", sz == -1);
if(sz > 0) {
// See if we have a quit message
if(strncmp(buf, "quit", 4) == 0) {
printf("Quitting server...\n");
res = pthread_kill(event_queue->parent_pool->main_thread, SIGTERM);
check("Could not send kill signal to main thread", res != 0);
return;
}
// Allocate a buffer to read file into
void *gbuf = event_queue->alloc.malloc<buffer_t<512> >();
// Fire off an async IO event
bzero(gbuf, 512);
int offset = atoi(buf);
// TODO: Using parent_pool might cause cache line
// alignment issues. Can we eliminate it (perhaps by
// giving each thread its own private copy of the
// necessary data)?
schedule_aio_read((int)(long)event_queue->parent_pool->data,
offset, 512, gbuf, event_queue, (void*)event->source);
} else {
// No data left, close the socket
printf("Closing socket %d\n", event->source);
queue_forget_resource(event_queue, event->source);
close(event->source);
}
} else {
// We got async IO event back
if(event->result < 0) {
printf("File notify error (fd %d, res: %d) %s\n",
event->source, event->result, strerror(-event->result));
} else {
((char*)event->buf)[11] = 0;
res = write((int)(long)event->state, event->buf, 10);
check("Could not write to socket", res == -1);
// TODO: make sure we write everything we intend to
}
event_queue->alloc.free((buffer_t<512>*)event->buf);
}
}
void term_handler(int signum) {
// Do nothing, we'll naturally break out of the main loop because
// the accept syscall will get interrupted.
}
/******
* Socket handling
**/
void process_socket(int sockfd, worker_pool_t *worker_pool) {
event_queue_t *event_queue = next_active_worker(worker_pool);
queue_watch_resource(event_queue, sockfd, eo_read, NULL);
}
int main(int argc, char *argv[])
{
int res;
// Setup termination handlers
struct sigaction action;
bzero((char*)&action, sizeof(action));
action.sa_handler = term_handler;
res = sigaction(SIGTERM, &action, NULL);
check("Could not install TERM handler", res < 0);
bzero((char*)&action, sizeof(action));
action.sa_handler = term_handler;
res = sigaction(SIGINT, &action, NULL);
check("Could not install INT handler", res < 0);
// Create a pool of workers
worker_pool_t worker_pool;
worker_pool.data = (void*)open("leo.txt", O_DIRECT | O_NOATIME | O_RDONLY);
create_worker_pool(&worker_pool, event_handler, pthread_self());
// Create the socket
int sockfd;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
check("Couldn't create socket", sockfd == -1);
int sockoptval = 1;
res = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &sockoptval, sizeof(sockoptval));
check("Could not set REUSEADDR option", res == -1);
// Bind the socket
sockaddr_in serv_addr;
bzero((char*)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(8080);
serv_addr.sin_addr.s_addr = INADDR_ANY;
res = bind(sockfd, (sockaddr*)&serv_addr, sizeof(serv_addr));
check("Couldn't bind socket", res != 0);
// Start listening to connections
res = listen(sockfd, 5);
check("Couldn't listen to the socket", res != 0);
// Accept incoming connections
while(1) {
// TODO: add a sound way to get out of this loop
int newsockfd;
sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
newsockfd = accept(sockfd,
(sockaddr*)&client_addr,
&client_addr_len);
// Break out of the loop on sigterm
if(newsockfd == -1 && errno == EINTR)
break;
check("Could not accept connection", newsockfd == -1);
// Process the socket
res = fcntl(newsockfd, F_SETFL, O_NONBLOCK);
check("Could not make socket non-blocking", res != 0);
process_socket(newsockfd, &worker_pool);
}
// Cleanup the resources
destroy_worker_pool(&worker_pool);
res = shutdown(sockfd, SHUT_RDWR);
check("Could not shutdown main socket", res == -1);
res = close(sockfd);
check("Could not close main socket", res != 0);
res = close((int)(long)worker_pool.data);
check("Could not close served file", res != 0);
printf("Server offline\n");
}
<commit_msg>More todo items<commit_after>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <signal.h>
#include <errno.h>
#include "utils.hpp"
#include "worker_pool.hpp"
#include "async_io.hpp"
#include "blackhole_alloc.hpp"
void event_handler(event_queue_t *event_queue, event_t *event) {
int res;
size_t sz;
char buf[256];
if(event->event_type == et_sock_event) {
bzero(buf, sizeof(buf));
// TODO: make sure we don't leave any data in the socket
sz = read(event->source, buf, sizeof(buf));
check("Could not read from socket", sz == -1);
if(sz > 0) {
// See if we have a quit message
if(strncmp(buf, "quit", 4) == 0) {
printf("Quitting server...\n");
res = pthread_kill(event_queue->parent_pool->main_thread, SIGTERM);
check("Could not send kill signal to main thread", res != 0);
return;
}
// Allocate a buffer to read file into
void *gbuf = event_queue->alloc.malloc<buffer_t<512> >();
// Fire off an async IO event
bzero(gbuf, 512);
int offset = atoi(buf);
// TODO: Using parent_pool might cause cache line
// alignment issues. Can we eliminate it (perhaps by
// giving each thread its own private copy of the
// necessary data)?
schedule_aio_read((int)(long)event_queue->parent_pool->data,
offset, 512, gbuf, event_queue, (void*)event->source);
} else {
// No data left, close the socket
printf("Closing socket %d\n", event->source);
queue_forget_resource(event_queue, event->source);
close(event->source);
}
} else {
// We got async IO event back
// TODO: what happens to unfreed memory if event doesn't come back? (is it possible?)
if(event->result < 0) {
printf("File notify error (fd %d, res: %d) %s\n",
event->source, event->result, strerror(-event->result));
} else {
((char*)event->buf)[11] = 0;
res = write((int)(long)event->state, event->buf, 10);
check("Could not write to socket", res == -1);
// TODO: make sure we write everything we intend to
}
event_queue->alloc.free((buffer_t<512>*)event->buf);
}
}
void term_handler(int signum) {
// Do nothing, we'll naturally break out of the main loop because
// the accept syscall will get interrupted.
}
/******
* Socket handling
**/
void process_socket(int sockfd, worker_pool_t *worker_pool) {
event_queue_t *event_queue = next_active_worker(worker_pool);
queue_watch_resource(event_queue, sockfd, eo_read, NULL);
}
int main(int argc, char *argv[])
{
int res;
// Setup termination handlers
struct sigaction action;
bzero((char*)&action, sizeof(action));
action.sa_handler = term_handler;
res = sigaction(SIGTERM, &action, NULL);
check("Could not install TERM handler", res < 0);
bzero((char*)&action, sizeof(action));
action.sa_handler = term_handler;
res = sigaction(SIGINT, &action, NULL);
check("Could not install INT handler", res < 0);
// Create a pool of workers
worker_pool_t worker_pool;
worker_pool.data = (void*)open("leo.txt", O_DIRECT | O_NOATIME | O_RDONLY);
create_worker_pool(&worker_pool, event_handler, pthread_self());
// Create the socket
int sockfd;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
check("Couldn't create socket", sockfd == -1);
int sockoptval = 1;
res = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &sockoptval, sizeof(sockoptval));
check("Could not set REUSEADDR option", res == -1);
// Bind the socket
sockaddr_in serv_addr;
bzero((char*)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(8080);
serv_addr.sin_addr.s_addr = INADDR_ANY;
res = bind(sockfd, (sockaddr*)&serv_addr, sizeof(serv_addr));
check("Couldn't bind socket", res != 0);
// Start listening to connections
res = listen(sockfd, 5);
check("Couldn't listen to the socket", res != 0);
// Accept incoming connections
while(1) {
// TODO: add a sound way to get out of this loop
int newsockfd;
sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
newsockfd = accept(sockfd,
(sockaddr*)&client_addr,
&client_addr_len);
// Break out of the loop on sigterm
if(newsockfd == -1 && errno == EINTR)
break;
check("Could not accept connection", newsockfd == -1);
// Process the socket
res = fcntl(newsockfd, F_SETFL, O_NONBLOCK);
check("Could not make socket non-blocking", res != 0);
process_socket(newsockfd, &worker_pool);
}
// Cleanup the resources
destroy_worker_pool(&worker_pool);
res = shutdown(sockfd, SHUT_RDWR);
check("Could not shutdown main socket", res == -1);
res = close(sockfd);
check("Could not close main socket", res != 0);
res = close((int)(long)worker_pool.data);
check("Could not close served file", res != 0);
printf("Server offline\n");
}
<|endoftext|> |
<commit_before>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team
See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
/* Originally by Brad Garton and Doug Scott (SGI code) and Dave Topper
(Linux code). Reworked for v2.3 by John Gibson.
Reworked to use new AudioDevice code for v3.7 by Douglas Scott.
*/
#include <RTcmix.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <errno.h>
#include <assert.h>
#include "audio_devices.h"
#include <ugens.h>
#include <Option.h>
#include "rtdefs.h"
#include "InputFile.h"
/* #define DEBUG */
int
RTcmix::setparams(float sr, int nchans, int bufsamps, bool recording, int bus_count)
{
int i;
int verbose = Option::print();
int play_audio = Option::play();
int record_audio = Option::record(recording);
// FIXME: Need better names for NCHANS and RTBUFSAMPS. -JGG
SR = sr;
NCHANS = nchans;
RTBUFSAMPS = bufsamps;
int numBuffers = Option::bufferCount();
if (SR <= 0.0) {
return die("rtsetparams", "Sampling rate must be greater than 0.");
}
if (bus_count < NCHANS) {
return die("rtsetparams", "Bus count must be >= channel count");
}
if (bus_count < MAXBUS && bus_count >= MINBUS) {
busCount = bus_count;
}
else {
return die("rtsetparams", "Bus count must be between %d and %d", MINBUS, MAXBUS);
}
if (NCHANS > busCount) {
return die("rtsetparams", "You can only have up to %d output channels.", busCount);
}
// Now that much of our global state is dynamically sized, the initialization
// of that state needs to be delayed until after we know the bus count as
// passed via rtsetparams().
init_globals();
/* play_audio is true unless user has called set_option("audio_off") before
rtsetparams. This would let user run multiple jobs, as long as only one
needs the audio drivers. -JGG
record_audio is false unless user has called set_option("full_duplex_on")
or has explicity turned record on by itself via set_option("record_on"),
or has already called rtinput("AUDIO"). -DS
*/
if (play_audio || record_audio) {
int nframes = RTBUFSAMPS;
float srate = SR;
rtcmix_debug(NULL, "RTcmix::setparams creating audio device(s)");
if ((audioDevice = create_audio_devices(record_audio, play_audio,
NCHANS, &srate, &nframes, numBuffers)) == NULL)
return -1;
/* These may have been reset by driver. */
RTBUFSAMPS = nframes;
if (srate != SR) {
if (!Option::requireSampleRate()) {
rtcmix_advise("rtsetparams",
"Sample rate reset by audio device from %f to %f.",
SR, srate);
SR = srate;
}
else {
return die("rtsetparams", "Sample rate could not be set to desired value.\nSet \"require_sample_rate=false\" to allow alternate rates.");
}
}
}
/* Allocate output buffers. Do this *after* opening audio devices,
in case OSS changes our buffer size, for example.
*/
for (i = 0; i < NCHANS; i++) {
allocate_out_buffer(i, RTBUFSAMPS);
}
#ifdef MULTI_THREAD
InputFile::createConversionBuffers(RTBUFSAMPS);
#endif
/* inTraverse waits for this. Set it even if play_audio is false! */
pthread_mutex_lock(&audio_config_lock);
audio_config = 1;
pthread_mutex_unlock(&audio_config_lock);
#ifdef EMBEDDED
if (verbose >= MMP_PRINTALL)
#endif
rtcmix_advise(NULL, "Audio set: %g sampling rate, %d channels\n", SR, NCHANS);
rtsetparams_called = 1; /* Put this at end to allow re-call due to error */
return 0;
}
int RTcmix::resetparams(float sr, int chans, int bufsamps, bool recording)
{
rtcmix_debug(NULL, "RTcmix::resetparams entered");
if (sr != SR) {
rtcmix_warn(NULL, "Resetting SR from %.2f to %.2f", SR, sr);
SR = sr;
}
if (chans != NCHANS) {
rtcmix_warn(NULL, "Resetting NCHANS from %d to %d", NCHANS, chans);
NCHANS = chans;
}
if (bufsamps != RTBUFSAMPS) {
rtcmix_warn(NULL, "Resetting RTBUFSAMPS from %d to %d", RTBUFSAMPS, bufsamps);
RTBUFSAMPS = bufsamps;
}
// For now, we have to do this operation by itself because RTcmix::close() freed these buffers.
// TODO: Make open/close create/destroy methods more intuitive.
init_buf_ptrs();
int numBuffers = Option::bufferCount();
int play_audio = Option::play();
int record_audio = Option::record(recording);
if (play_audio || record_audio) {
int nframes = RTBUFSAMPS;
float srate = SR;
rtcmix_debug(NULL, "RTcmix::resetparams re-creating audio device(s)");
if ((audioDevice = create_audio_devices(record_audio, play_audio,
NCHANS, &srate, &nframes, numBuffers)) == NULL)
{
return -1;
}
/* These may have been reset by driver. */
RTBUFSAMPS = nframes;
SR = srate;
}
/* Reallocate output buffers. Do this *after* opening audio devices,
in case the device changes our buffer size, for example.
*/
for (int i = 0; i < NCHANS; i++) {
allocate_out_buffer(i, RTBUFSAMPS);
}
#ifdef MULTI_THREAD
InputFile::createConversionBuffers(RTBUFSAMPS);
#endif
/* inTraverse waits for this. Set it even if play_audio is false! */
pthread_mutex_lock(&audio_config_lock);
audio_config = 1;
pthread_mutex_unlock(&audio_config_lock);
rtcmix_debug(NULL, "RTcmix::resetparams exited");
return 0;
}
/* ---------------------------------------------------------- rtsetparams --- */
/* Minc function that sets output sampling rate (p0), maximum number of
output channels (p1), and (optionally) I/O buffer size (p2).
On SGI, the optional p3 lets you specify the output port as a string
(e.g., "LINE", "DIGITAL", etc.).
Based on this information, rtsetparams allocates a mono output buffer
for each of the output channels, and opens output devices.
*/
double
RTcmix::rtsetparams(float p[], int n_args, double pp[])
{
#ifdef EMBEDDED
// BGG mm -- ignore this one, use RTcmix::setparams()
// (called by RTcmix_setparams() in main.cpp)
return 0.0;
#endif
if (rtsetparams_was_called()) {
return die("rtsetparams", "You can only call rtsetparams once!");
}
int bufsamps = (n_args > 2) ? (int) p[2] : (int) Option::bufferFrames();
bool recording = Option::record();
int numBusses = (n_args > 3) ? (int)p[3] : DEFAULT_MAXBUS;
return (double) setparams(p[0], (int)p[1], bufsamps, recording, numBusses);
}
<commit_msg>Found one more bug in RTcmix_resetaudio: needed to re-allocate the individual input buffers if we are in record mode.<commit_after>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team
See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
/* Originally by Brad Garton and Doug Scott (SGI code) and Dave Topper
(Linux code). Reworked for v2.3 by John Gibson.
Reworked to use new AudioDevice code for v3.7 by Douglas Scott.
*/
#include <RTcmix.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <errno.h>
#include <assert.h>
#include "audio_devices.h"
#include <ugens.h>
#include <Option.h>
#include "rtdefs.h"
#include "InputFile.h"
/* #define DEBUG */
int
RTcmix::setparams(float sr, int nchans, int bufsamps, bool recording, int bus_count)
{
int i;
int verbose = Option::print();
int play_audio = Option::play();
int record_audio = Option::record(recording);
// FIXME: Need better names for NCHANS and RTBUFSAMPS. -JGG
SR = sr;
NCHANS = nchans;
RTBUFSAMPS = bufsamps;
int numBuffers = Option::bufferCount();
if (SR <= 0.0) {
return die("rtsetparams", "Sampling rate must be greater than 0.");
}
if (bus_count < NCHANS) {
return die("rtsetparams", "Bus count must be >= channel count");
}
if (bus_count < MAXBUS && bus_count >= MINBUS) {
busCount = bus_count;
}
else {
return die("rtsetparams", "Bus count must be between %d and %d", MINBUS, MAXBUS);
}
if (NCHANS > busCount) {
return die("rtsetparams", "You can only have up to %d output channels.", busCount);
}
// Now that much of our global state is dynamically sized, the initialization
// of that state needs to be delayed until after we know the bus count as
// passed via rtsetparams().
init_globals();
/* play_audio is true unless user has called set_option("audio_off") before
rtsetparams. This would let user run multiple jobs, as long as only one
needs the audio drivers. -JGG
record_audio is false unless user has called set_option("full_duplex_on")
or has explicity turned record on by itself via set_option("record_on"),
or has already called rtinput("AUDIO"). -DS
*/
if (play_audio || record_audio) {
int nframes = RTBUFSAMPS;
float srate = SR;
rtcmix_debug(NULL, "RTcmix::setparams creating audio device(s)");
if ((audioDevice = create_audio_devices(record_audio, play_audio,
NCHANS, &srate, &nframes, numBuffers)) == NULL)
return -1;
/* These may have been reset by driver. */
RTBUFSAMPS = nframes;
if (srate != SR) {
if (!Option::requireSampleRate()) {
rtcmix_advise("rtsetparams",
"Sample rate reset by audio device from %f to %f.",
SR, srate);
SR = srate;
}
else {
return die("rtsetparams", "Sample rate could not be set to desired value.\nSet \"require_sample_rate=false\" to allow alternate rates.");
}
}
}
/* Allocate output buffers. Do this *after* opening audio devices,
in case OSS changes our buffer size, for example.
*/
for (i = 0; i < NCHANS; i++) {
allocate_out_buffer(i, RTBUFSAMPS);
}
#ifdef MULTI_THREAD
InputFile::createConversionBuffers(RTBUFSAMPS);
#endif
/* inTraverse waits for this. Set it even if play_audio is false! */
pthread_mutex_lock(&audio_config_lock);
audio_config = 1;
pthread_mutex_unlock(&audio_config_lock);
#ifdef EMBEDDED
if (verbose >= MMP_PRINTALL)
#endif
rtcmix_advise(NULL, "Audio set: %g sampling rate, %d channels\n", SR, NCHANS);
rtsetparams_called = 1; /* Put this at end to allow re-call due to error */
return 0;
}
int RTcmix::resetparams(float sr, int chans, int bufsamps, bool recording)
{
rtcmix_debug(NULL, "RTcmix::resetparams entered");
if (sr != SR) {
rtcmix_warn(NULL, "Resetting SR from %.2f to %.2f", SR, sr);
SR = sr;
}
if (chans != NCHANS) {
rtcmix_warn(NULL, "Resetting NCHANS from %d to %d", NCHANS, chans);
NCHANS = chans;
}
if (bufsamps != RTBUFSAMPS) {
rtcmix_warn(NULL, "Resetting RTBUFSAMPS from %d to %d", RTBUFSAMPS, bufsamps);
RTBUFSAMPS = bufsamps;
}
// For now, we have to do this operation by itself because RTcmix::close() freed these buffers.
// TODO: Make open/close create/destroy methods more intuitive.
init_buf_ptrs();
int numBuffers = Option::bufferCount();
int play_audio = Option::play();
int record_audio = Option::record(recording);
if (play_audio || record_audio) {
int nframes = RTBUFSAMPS;
float srate = SR;
rtcmix_debug(NULL, "RTcmix::resetparams re-creating audio device(s)");
if ((audioDevice = create_audio_devices(record_audio, play_audio,
NCHANS, &srate, &nframes, numBuffers)) == NULL)
{
return -1;
}
/* These may have been reset by driver. */
RTBUFSAMPS = nframes;
SR = srate;
}
/* Reallocate output buffers. Do this *after* opening audio devices,
in case the device changes our buffer size, for example.
*/
for (int i = 0; i < NCHANS; i++) {
allocate_out_buffer(i, RTBUFSAMPS);
}
/* Reallocate input buffers if we are in record mode. This was initially done by rtinput() */
if (record_audio) {
for (int i = 0; i < NCHANS; i++) {
allocate_audioin_buffer(i, RTBUFSAMPS);
}
}
#ifdef MULTI_THREAD
InputFile::createConversionBuffers(RTBUFSAMPS);
#endif
/* inTraverse waits for this. Set it even if play_audio is false! */
pthread_mutex_lock(&audio_config_lock);
audio_config = 1;
pthread_mutex_unlock(&audio_config_lock);
rtcmix_debug(NULL, "RTcmix::resetparams exited");
return 0;
}
/* ---------------------------------------------------------- rtsetparams --- */
/* Minc function that sets output sampling rate (p0), maximum number of
output channels (p1), and (optionally) I/O buffer size (p2).
On SGI, the optional p3 lets you specify the output port as a string
(e.g., "LINE", "DIGITAL", etc.).
Based on this information, rtsetparams allocates a mono output buffer
for each of the output channels, and opens output devices.
*/
double
RTcmix::rtsetparams(float p[], int n_args, double pp[])
{
#ifdef EMBEDDED
// BGG mm -- ignore this one, use RTcmix::setparams()
// (called by RTcmix_setparams() in main.cpp)
return 0.0;
#endif
if (rtsetparams_was_called()) {
return die("rtsetparams", "You can only call rtsetparams once!");
}
int bufsamps = (n_args > 2) ? (int) p[2] : (int) Option::bufferFrames();
bool recording = Option::record();
int numBusses = (n_args > 3) ? (int)p[3] : DEFAULT_MAXBUS;
return (double) setparams(p[0], (int)p[1], bufsamps, recording, numBusses);
}
<|endoftext|> |
<commit_before>/*
* SSL and TLS filter.
*
* author: Max Kellermann <[email protected]>
*/
#include "ssl_filter.hxx"
#include "ssl_factory.hxx"
#include "ssl_config.hxx"
#include "ssl_quark.hxx"
#include "thread_socket_filter.hxx"
#include "pool.hxx"
#include "gerrno.h"
#include "fb_pool.hxx"
#include "SliceFifoBuffer.hxx"
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <assert.h>
#include <string.h>
struct ssl_filter {
/**
* Buffers which can be accessed from within the thread without
* holding locks. These will be copied to/from the according
* #thread_socket_filter buffers.
*/
SliceFifoBuffer decrypted_input, plain_output;
/**
* Memory BIOs for passing data to/from OpenSSL.
*/
BIO *encrypted_input, *encrypted_output;
SSL *ssl;
bool handshaking;
char *peer_subject, *peer_issuer_subject;
};
static void
ssl_set_error(GError **error_r)
{
if (error_r == NULL)
return;
unsigned long error = ERR_get_error();
char buffer[120];
g_set_error(error_r, ssl_quark(), 0, "%s",
ERR_error_string(error, buffer));
}
/**
* Move data from #src to #dest.
*/
static void
Move(BIO *dest, ForeignFifoBuffer<uint8_t> &src)
{
auto r = src.Read();
if (r.IsEmpty())
return;
int nbytes = BIO_write(dest, r.data, r.size);
if (nbytes > 0)
src.Consume(nbytes);
}
static void
Move(ForeignFifoBuffer<uint8_t> &dest, BIO *src)
{
while (true) {
auto w = dest.Write();
if (w.IsEmpty())
return;
int nbytes = BIO_read(src, w.data, w.size);
if (nbytes <= 0)
return;
dest.Append(nbytes);
}
}
static char *
format_name(X509_NAME *name)
{
if (name == NULL)
return NULL;
BIO *bio = BIO_new(BIO_s_mem());
if (bio == NULL)
return NULL;
X509_NAME_print_ex(bio, name, 0,
ASN1_STRFLGS_UTF8_CONVERT | XN_FLAG_SEP_COMMA_PLUS);
char buffer[1024];
int length = BIO_read(bio, buffer, sizeof(buffer) - 1);
BIO_free(bio);
return strndup(buffer, length);
}
static char *
format_subject_name(X509 *cert)
{
return format_name(X509_get_subject_name(cert));
}
static char *
format_issuer_subject_name(X509 *cert)
{
return format_name(X509_get_issuer_name(cert));
}
gcc_pure
static bool
is_ssl_error(SSL *ssl, int ret)
{
if (ret == 0)
/* this is always an error according to the documentation of
SSL_read(), SSL_write() and SSL_do_handshake() */
return true;
switch (SSL_get_error(ssl, ret)) {
case SSL_ERROR_NONE:
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_CONNECT:
case SSL_ERROR_WANT_ACCEPT:
return false;
default:
return true;
}
}
static bool
check_ssl_error(SSL *ssl, int result, GError **error_r)
{
if (is_ssl_error(ssl, result)) {
ssl_set_error(error_r);
return false;
} else
return true;
}
/**
* @return false on error
*/
static bool
ssl_decrypt(SSL *ssl, ForeignFifoBuffer<uint8_t> &buffer, GError **error_r)
{
/* SSL_read() must be called repeatedly until there is no more
data (or until the buffer is full) */
while (true) {
auto w = buffer.Write();
if (w.IsEmpty())
return 0;
int result = SSL_read(ssl, w.data, w.size);
if (result <= 0)
return check_ssl_error(ssl, result, error_r);
buffer.Append(result);
}
}
/**
* @return false on error
*/
static bool
ssl_encrypt(SSL *ssl, ForeignFifoBuffer<uint8_t> &buffer, GError **error_r)
{
auto r = buffer.Read();
if (r.IsEmpty())
return true;
int result = SSL_write(ssl, r.data, r.size);
if (result <= 0)
return check_ssl_error(ssl, result, error_r);
buffer.Consume(result);
return true;
}
/*
* thread_socket_filter_handler
*
*/
static bool
ssl_thread_socket_filter_run(ThreadSocketFilter &f, GError **error_r,
void *ctx)
{
struct ssl_filter *ssl = (struct ssl_filter *)ctx;
/* copy input (and output to make room for more output) */
f.mutex.lock();
f.decrypted_input.MoveFrom(ssl->decrypted_input);
ssl->plain_output.MoveFrom(f.plain_output);
Move(ssl->encrypted_input, f.encrypted_input);
Move(f.encrypted_output, ssl->encrypted_output);
f.mutex.unlock();
/* let OpenSSL work */
ERR_clear_error();
if (gcc_unlikely(ssl->handshaking)) {
int result = SSL_do_handshake(ssl->ssl);
if (result == 1) {
ssl->handshaking = false;
X509 *cert = SSL_get_peer_certificate(ssl->ssl);
if (cert != nullptr) {
ssl->peer_subject = format_subject_name(cert);
ssl->peer_issuer_subject = format_issuer_subject_name(cert);
X509_free(cert);
}
} else if (!check_ssl_error(ssl->ssl, result, error_r))
return false;
}
if (gcc_likely(!ssl->handshaking) &&
(!ssl_encrypt(ssl->ssl, ssl->plain_output, error_r) ||
!ssl_decrypt(ssl->ssl, ssl->decrypted_input, error_r)))
return false;
/* copy output */
f.mutex.lock();
f.decrypted_input.MoveFrom(ssl->decrypted_input);
Move(f.encrypted_output, ssl->encrypted_output);
f.drained = ssl->plain_output.IsEmpty() &&
BIO_eof(ssl->encrypted_output);
f.mutex.unlock();
return true;
}
static void
ssl_thread_socket_filter_destroy(gcc_unused ThreadSocketFilter &f, void *ctx)
{
struct ssl_filter *ssl = (struct ssl_filter *)ctx;
if (ssl->ssl != NULL)
SSL_free(ssl->ssl);
ssl->decrypted_input.Free(fb_pool_get());
ssl->plain_output.Free(fb_pool_get());
free(ssl->peer_subject);
free(ssl->peer_issuer_subject);
}
const struct ThreadSocketFilterHandler ssl_thread_socket_filter = {
ssl_thread_socket_filter_run,
ssl_thread_socket_filter_destroy,
};
/*
* constructor
*
*/
struct ssl_filter *
ssl_filter_new(struct pool *pool, ssl_factory &factory,
GError **error_r)
{
assert(pool != NULL);
ssl_filter *ssl = NewFromPool<ssl_filter>(*pool);
ssl->ssl = ssl_factory_make(factory);
if (ssl->ssl == NULL) {
g_set_error(error_r, ssl_quark(), 0, "SSL_new() failed");
return NULL;
}
ssl->decrypted_input.Allocate(fb_pool_get());
ssl->plain_output.Allocate(fb_pool_get());
ssl->encrypted_input = BIO_new(BIO_s_mem());
ssl->encrypted_output = BIO_new(BIO_s_mem());
SSL_set_bio(ssl->ssl, ssl->encrypted_input, ssl->encrypted_output);
ssl->peer_subject = NULL;
ssl->peer_issuer_subject = NULL;
ssl->handshaking = true;
return ssl;
}
const char *
ssl_filter_get_peer_subject(struct ssl_filter *ssl)
{
assert(ssl != NULL);
return ssl->peer_subject;
}
const char *
ssl_filter_get_peer_issuer_subject(struct ssl_filter *ssl)
{
assert(ssl != NULL);
return ssl->peer_issuer_subject;
}
<commit_msg>ssl_filter: use std::unique_lock<commit_after>/*
* SSL and TLS filter.
*
* author: Max Kellermann <[email protected]>
*/
#include "ssl_filter.hxx"
#include "ssl_factory.hxx"
#include "ssl_config.hxx"
#include "ssl_quark.hxx"
#include "thread_socket_filter.hxx"
#include "pool.hxx"
#include "gerrno.h"
#include "fb_pool.hxx"
#include "SliceFifoBuffer.hxx"
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <assert.h>
#include <string.h>
struct ssl_filter {
/**
* Buffers which can be accessed from within the thread without
* holding locks. These will be copied to/from the according
* #thread_socket_filter buffers.
*/
SliceFifoBuffer decrypted_input, plain_output;
/**
* Memory BIOs for passing data to/from OpenSSL.
*/
BIO *encrypted_input, *encrypted_output;
SSL *ssl;
bool handshaking;
char *peer_subject, *peer_issuer_subject;
};
static void
ssl_set_error(GError **error_r)
{
if (error_r == NULL)
return;
unsigned long error = ERR_get_error();
char buffer[120];
g_set_error(error_r, ssl_quark(), 0, "%s",
ERR_error_string(error, buffer));
}
/**
* Move data from #src to #dest.
*/
static void
Move(BIO *dest, ForeignFifoBuffer<uint8_t> &src)
{
auto r = src.Read();
if (r.IsEmpty())
return;
int nbytes = BIO_write(dest, r.data, r.size);
if (nbytes > 0)
src.Consume(nbytes);
}
static void
Move(ForeignFifoBuffer<uint8_t> &dest, BIO *src)
{
while (true) {
auto w = dest.Write();
if (w.IsEmpty())
return;
int nbytes = BIO_read(src, w.data, w.size);
if (nbytes <= 0)
return;
dest.Append(nbytes);
}
}
static char *
format_name(X509_NAME *name)
{
if (name == NULL)
return NULL;
BIO *bio = BIO_new(BIO_s_mem());
if (bio == NULL)
return NULL;
X509_NAME_print_ex(bio, name, 0,
ASN1_STRFLGS_UTF8_CONVERT | XN_FLAG_SEP_COMMA_PLUS);
char buffer[1024];
int length = BIO_read(bio, buffer, sizeof(buffer) - 1);
BIO_free(bio);
return strndup(buffer, length);
}
static char *
format_subject_name(X509 *cert)
{
return format_name(X509_get_subject_name(cert));
}
static char *
format_issuer_subject_name(X509 *cert)
{
return format_name(X509_get_issuer_name(cert));
}
gcc_pure
static bool
is_ssl_error(SSL *ssl, int ret)
{
if (ret == 0)
/* this is always an error according to the documentation of
SSL_read(), SSL_write() and SSL_do_handshake() */
return true;
switch (SSL_get_error(ssl, ret)) {
case SSL_ERROR_NONE:
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_CONNECT:
case SSL_ERROR_WANT_ACCEPT:
return false;
default:
return true;
}
}
static bool
check_ssl_error(SSL *ssl, int result, GError **error_r)
{
if (is_ssl_error(ssl, result)) {
ssl_set_error(error_r);
return false;
} else
return true;
}
/**
* @return false on error
*/
static bool
ssl_decrypt(SSL *ssl, ForeignFifoBuffer<uint8_t> &buffer, GError **error_r)
{
/* SSL_read() must be called repeatedly until there is no more
data (or until the buffer is full) */
while (true) {
auto w = buffer.Write();
if (w.IsEmpty())
return 0;
int result = SSL_read(ssl, w.data, w.size);
if (result <= 0)
return check_ssl_error(ssl, result, error_r);
buffer.Append(result);
}
}
/**
* @return false on error
*/
static bool
ssl_encrypt(SSL *ssl, ForeignFifoBuffer<uint8_t> &buffer, GError **error_r)
{
auto r = buffer.Read();
if (r.IsEmpty())
return true;
int result = SSL_write(ssl, r.data, r.size);
if (result <= 0)
return check_ssl_error(ssl, result, error_r);
buffer.Consume(result);
return true;
}
/*
* thread_socket_filter_handler
*
*/
static bool
ssl_thread_socket_filter_run(ThreadSocketFilter &f, GError **error_r,
void *ctx)
{
struct ssl_filter *ssl = (struct ssl_filter *)ctx;
/* copy input (and output to make room for more output) */
{
std::unique_lock<std::mutex> lock(f.mutex);
f.decrypted_input.MoveFrom(ssl->decrypted_input);
ssl->plain_output.MoveFrom(f.plain_output);
Move(ssl->encrypted_input, f.encrypted_input);
Move(f.encrypted_output, ssl->encrypted_output);
}
/* let OpenSSL work */
ERR_clear_error();
if (gcc_unlikely(ssl->handshaking)) {
int result = SSL_do_handshake(ssl->ssl);
if (result == 1) {
ssl->handshaking = false;
X509 *cert = SSL_get_peer_certificate(ssl->ssl);
if (cert != nullptr) {
ssl->peer_subject = format_subject_name(cert);
ssl->peer_issuer_subject = format_issuer_subject_name(cert);
X509_free(cert);
}
} else if (!check_ssl_error(ssl->ssl, result, error_r))
return false;
}
if (gcc_likely(!ssl->handshaking) &&
(!ssl_encrypt(ssl->ssl, ssl->plain_output, error_r) ||
!ssl_decrypt(ssl->ssl, ssl->decrypted_input, error_r)))
return false;
/* copy output */
{
std::unique_lock<std::mutex> lock(f.mutex);
f.decrypted_input.MoveFrom(ssl->decrypted_input);
Move(f.encrypted_output, ssl->encrypted_output);
f.drained = ssl->plain_output.IsEmpty() &&
BIO_eof(ssl->encrypted_output);
}
return true;
}
static void
ssl_thread_socket_filter_destroy(gcc_unused ThreadSocketFilter &f, void *ctx)
{
struct ssl_filter *ssl = (struct ssl_filter *)ctx;
if (ssl->ssl != NULL)
SSL_free(ssl->ssl);
ssl->decrypted_input.Free(fb_pool_get());
ssl->plain_output.Free(fb_pool_get());
free(ssl->peer_subject);
free(ssl->peer_issuer_subject);
}
const struct ThreadSocketFilterHandler ssl_thread_socket_filter = {
ssl_thread_socket_filter_run,
ssl_thread_socket_filter_destroy,
};
/*
* constructor
*
*/
struct ssl_filter *
ssl_filter_new(struct pool *pool, ssl_factory &factory,
GError **error_r)
{
assert(pool != NULL);
ssl_filter *ssl = NewFromPool<ssl_filter>(*pool);
ssl->ssl = ssl_factory_make(factory);
if (ssl->ssl == NULL) {
g_set_error(error_r, ssl_quark(), 0, "SSL_new() failed");
return NULL;
}
ssl->decrypted_input.Allocate(fb_pool_get());
ssl->plain_output.Allocate(fb_pool_get());
ssl->encrypted_input = BIO_new(BIO_s_mem());
ssl->encrypted_output = BIO_new(BIO_s_mem());
SSL_set_bio(ssl->ssl, ssl->encrypted_input, ssl->encrypted_output);
ssl->peer_subject = NULL;
ssl->peer_issuer_subject = NULL;
ssl->handshaking = true;
return ssl;
}
const char *
ssl_filter_get_peer_subject(struct ssl_filter *ssl)
{
assert(ssl != NULL);
return ssl->peer_subject;
}
const char *
ssl_filter_get_peer_issuer_subject(struct ssl_filter *ssl)
{
assert(ssl != NULL);
return ssl->peer_issuer_subject;
}
<|endoftext|> |
<commit_before>/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Worcester Polytechnic Institute
* 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 Worcester Polytechnic Institute 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.
*
*********************************************************************/
/*!
* \file robot_pose_publisher.cpp
* \brief Publishes the robot's position in a geometry_msgs/Pose message.
*
* Publishes the robot's position in a geometry_msgs/Pose message based on the TF
* difference between /map and /base_link.
*
* \author Russell Toris, WPI - [email protected]
* \date Sept 12, 2012
*/
#include <geometry_msgs/Pose.h>
#include <ros/ros.h>
#include <tf/transform_listener.h>
/*!
* Creates and runs the robot_pose_publisher node.
*
* \param argc argument count that is passed to ros::init
* \param argv arguments that are passed to ros::init
* \return EXIT_SUCCESS if the node runs correctly
*/
int main(int argc, char ** argv)
{
// initialize ROS and the node
ros::init(argc, argv, "robot_pose_publisher");
ros::NodeHandle nh;
ros::Publisher pose_pub = nh.advertise<geometry_msgs::Pose>("/robot_pose", 1);
// create the listener
tf::TransformListener listener;
listener.waitForTransform("/map", "/base_link", ros::Time(), ros::Duration(1.0));
ros::Rate rate(10.0);
while (nh.ok())
{
tf::StampedTransform transform;
try
{
listener.lookupTransform("/map", "/base_link", ros::Time(0), transform);
// construct a pose message
geometry_msgs::Pose pose;
pose.orientation.x = transform.getRotation().getX();
pose.orientation.y = transform.getRotation().getY();
pose.orientation.z = transform.getRotation().getZ();
pose.orientation.w = transform.getRotation().getW();
pose.position.x = transform.getOrigin().getX();
pose.position.y = transform.getOrigin().getY();
pose.position.z = transform.getOrigin().getZ();
pose_pub.publish(pose);
}
catch (tf::TransformException &ex)
{
// just continue on
}
rate.sleep();
}
return EXIT_SUCCESS;
}
<commit_msg>parameter setting. pose -> posestamped<commit_after>/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Worcester Polytechnic Institute
* 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 Worcester Polytechnic Institute 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.
*
*********************************************************************/
/*!
* \file robot_pose_publisher.cpp
* \brief Publishes the robot's position in a geometry_msgs/Pose message.
*
* Publishes the robot's position in a geometry_msgs/Pose message based on the TF
* difference between /map and /base_link.
*
* \author Russell Toris, WPI - [email protected]
* \date Sept 12, 2012
*/
#include <geometry_msgs/PoseStamped.h>
#include <ros/ros.h>
#include <tf/transform_listener.h>
/*!
* Creates and runs the robot_pose_publisher node.
*
* \param argc argument count that is passed to ros::init
* \param argv arguments that are passed to ros::init
* \return EXIT_SUCCESS if the node runs correctly
*/
int main(int argc, char ** argv)
{
// initialize ROS and the node
ros::init(argc, argv, "robot_pose_publisher");
ros::NodeHandle nh;
// configuring parameters
std::string map_frame, base_frame;
double publish_frequency;
nh.param<std::string>("map_frame",map_frame,"/map");
nh.param<std::string>("base_frame",base_frame,"/base_link");
nh.param<double>("publish_frequency",publish_frequency,10);
ros::Publisher posestamped_pub = nh.advertise<geometry_msgs::PoseStamped>("robot_pose", 1);
// create the listener
tf::TransformListener listener;
listener.waitForTransform(map_frame, base_frame, ros::Time(), ros::Duration(1.0));
ros::Rate rate(publish_frequency);
while (nh.ok())
{
tf::StampedTransform transform;
try
{
listener.lookupTransform(map_frame, base_frame, ros::Time(0), transform);
// construct a pose message
geometry_msgs::PoseStamped pose_stamped;
pose_stamped.header.frame_id = map_frame;
pose_stamped.header.stamp = ros::Time::now();
pose_stamped.pose.orientation.x = transform.getRotation().getX();
pose_stamped.pose.orientation.y = transform.getRotation().getY();
pose_stamped.pose.orientation.z = transform.getRotation().getZ();
pose_stamped.pose.orientation.w = transform.getRotation().getW();
pose_stamped.pose.position.x = transform.getOrigin().getX();
pose_stamped.pose.position.y = transform.getOrigin().getY();
pose_stamped.pose.position.z = transform.getOrigin().getZ();
posestamped_pub.publish(pose_stamped);
}
catch (tf::TransformException &ex)
{
// just continue on
}
rate.sleep();
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// See docs in ../ops/array_ops.cc.
#if defined(INTEL_MKL)
#define EIGEN_USE_THREADS
#if !defined(INTEL_MKL_DNN_ONLY)
#include "mkl_trans.h"
#endif
#include "mkldnn.hpp"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/kernels/transpose_functor.h"
#include "tensorflow/core/kernels/transpose_op.h"
#include "tensorflow/core/util/mkl_types.h"
#include "tensorflow/core/util/mkl_util.h"
using mkldnn::stream;
namespace tensorflow {
// output = TransposeOp(T<any> input, T<int32> perm) takes a tensor
// of type T and rank N, and a permutation of 0, 1, ..., N-1. It
// shuffles the dimensions of the input tensor according to permutation.
//
// Specifically, the returned tensor output meets the following condition:
// 1) output.dims() == input.dims();
// 2) output.dim_size(i) == input.dim_size(perm[i]);
// 3) output.tensor<T, N>(i_0, i_1, ..., i_N-1) ==
// input.tensor<T, N>(j_0, j_1, ..., j_N-1),
// where i_s == j_{perm[s]}
//
// REQUIRES: perm is a vector of int32.
// REQUIRES: input.dims() == perm.size().
// REQUIRES: perm is a permutation.
namespace {
#if !defined(INTEL_MKL_DNN_ONLY)
template <typename T>
Status MKLTranspose2D(const char trans, const Tensor& in, Tensor* out);
// Documentation here: https://software.intel.com/en-us/node/520863
// Parameters: (ordering:row-major, operation:transpose, num_rows, num_cols,
// alpha (for scaling), array, dist_bet_adjacent_cols/rows
// (source), array, dist_bet_adjacent_cols/rows (dest))
#define INSTANTIATE(T, PREFIX) \
template <> \
Status MKLTranspose2D<T>(const char trans, const Tensor& in, Tensor* out) { \
mkl_##PREFIX##omatcopy('R', trans, in.dim_size(0), in.dim_size(1), 1, \
in.flat<T>().data(), in.dim_size(1), \
out->flat<T>().data(), in.dim_size(0)); \
return Status::OK(); \
}
INSTANTIATE(float, s)
INSTANTIATE(double, d)
#undef INSTANTIATE
template <>
Status MKLTranspose2D<complex64>(const char trans, const Tensor& in,
Tensor* out) {
const MKL_Complex8 alpha = {1.0f, 0.0f};
mkl_comatcopy(
'R', trans, in.dim_size(0), in.dim_size(1), alpha,
reinterpret_cast<const MKL_Complex8*>(in.flat<complex64>().data()),
in.dim_size(1), reinterpret_cast<MKL_Complex8*>(const_cast<complex64*>(
out->flat<complex64>().data())),
in.dim_size(0));
return Status::OK();
}
template <>
Status MKLTranspose2D<complex128>(const char trans, const Tensor& in,
Tensor* out) {
const MKL_Complex16 alpha = {1.0, 0.0};
mkl_zomatcopy(
'R', trans, in.dim_size(0), in.dim_size(1), alpha,
reinterpret_cast<const MKL_Complex16*>(in.flat<complex128>().data()),
in.dim_size(1), reinterpret_cast<MKL_Complex16*>(const_cast<complex128*>(
out->flat<complex128>().data())),
in.dim_size(0));
return Status::OK();
}
static const char kMKLTranspose = 'T';
static const char kMKLConjugateTranspose = 'C';
#endif // if !defined(INTEL_MKL_DNN_ONLY)
// MKL-DNN based Transpose implementation
template <typename T>
Status MKLTransposeND(OpKernelContext* ctx, const Tensor& in, Tensor* out,
const gtl::ArraySlice<int32>& perm);
static inline memory::dims ReorderStrides(const memory::dims& strides,
const gtl::ArraySlice<int32>& perm) {
memory::dims reordered_strides;
reordered_strides.resize(strides.size());
for (size_t i = 0; i < strides.size(); ++i) {
reordered_strides[perm[i]] = strides[i];
}
return reordered_strides;
}
// Transpose of N-dimensional tensor using MKL-DNN
template <typename T>
Status MKLTransposeND(OpKernelContext* context, const Tensor& in_tensor,
Tensor* out_tensor, const gtl::ArraySlice<int32>& perm) {
try {
engine cpu_engine = engine(ENGINE_CPU, 0);
MklDnnData<T> in(&cpu_engine);
MklDnnData<T> out(&cpu_engine);
memory::dims in_dims = TFShapeToMklDnnDims(in_tensor.shape());
memory::dims out_dims = TFShapeToMklDnnDims(out_tensor->shape());
memory::dims in_strides = CalculateTFStrides(in_dims);
// Reorder output strides based on permutation requested.
memory::dims out_strides =
ReorderStrides(CalculateTFStrides(out_dims), perm);
in.SetUsrMem(in_dims, in_strides, &in_tensor);
// Output dimensions are same as input dimensions. We adjust the layout
// using strides.
out.SetUsrMem(in_dims, out_strides, out_tensor);
std::vector<primitive> net;
std::shared_ptr<stream> transpose_stream;
transpose_stream.reset(new CPU_STREAM(cpu_engine));
#ifdef ENABLE_MKLDNN_V1
const int net_idx = 0;
net.push_back(reorder(in.GetOpMem(), out.GetOpMem()));
std::vector<std::unordered_map<int, memory>> net_args;
net_args.push_back(
{{MKLDNN_ARG_FROM, in.GetOpMem()}, {MKLDNN_ARG_TO, out.GetOpMem()}});
net.at(net_idx).execute(*transpose_stream, net_args.at(net_idx));
#else
net.push_back(FindOrCreateReorder<T>(in.GetUsrMem(), out.GetUsrMem()));
transpose_stream->submit(net).wait();
#endif //ENABLE_MKLDNN_V1
return Status::OK();
} catch (mkldnn::error& e) {
string error_msg = "Status: " + std::to_string(e.status) + ", message: " +
std::string(e.message) + ", in file " +
std::string(__FILE__) + ":" + std::to_string(__LINE__);
return errors::Aborted("Operation received an exception:", error_msg);
}
}
} // namespace
Status MklTransposeCpuOp::DoTranspose(OpKernelContext* ctx, const Tensor& in,
gtl::ArraySlice<int32> perm,
Tensor* out) {
#if !defined(INTEL_MKL_DNN_ONLY)
if (in.dims() == 2) {
if (perm[0] == 0 && perm[1] == 1) {
return Status::OK();
}
switch (in.dtype()) {
case DT_FLOAT:
return MKLTranspose2D<float>(kMKLTranspose, in, out);
case DT_DOUBLE:
return MKLTranspose2D<double>(kMKLTranspose, in, out);
case DT_COMPLEX64:
return MKLTranspose2D<complex64>(kMKLTranspose, in, out);
case DT_COMPLEX128:
return MKLTranspose2D<complex128>(kMKLTranspose, in, out);
default:
break;
}
}
#endif
// MKL-DNN has limit on the maximum number of dimensions in a tensor.
// Fallback to Eigen for not supported cases.
if (in.dims() <= TENSOR_MAX_DIMS) {
switch (in.dtype()) {
case DT_FLOAT:
return MKLTransposeND<float>(ctx, in, out, perm);
break;
case DT_BFLOAT16:
return MKLTransposeND<bfloat16>(ctx, in, out, perm);
break;
// TODO(nhasabni): support other types such as INT8.
default:
break;
}
}
// Fallback to eigen if transpose parameters not supported by MKL or MKL-DNN
typedef Eigen::ThreadPoolDevice CPUDevice;
return ::tensorflow::DoTranspose(ctx->eigen_device<CPUDevice>(), in, perm,
out);
}
Status MklConjugateTransposeCpuOp::DoTranspose(OpKernelContext* ctx,
const Tensor& in,
gtl::ArraySlice<int32> perm,
Tensor* out) {
#if !defined(INTEL_MKL_DNN_ONLY)
if (in.dims() == 2 && perm[0] == 1 && perm[1] == 0) {
// TODO(rmlarsen): By setting lda and ldb, we could use the MKL kernels
// for any transpose that can be reduced to swapping the last two
// dimensions in a rank-3 tensor. We can even run each outer dimension in
// a separate thread.
switch (in.dtype()) {
case DT_FLOAT:
return MKLTranspose2D<float>(kMKLTranspose, in, out);
case DT_DOUBLE:
return MKLTranspose2D<double>(kMKLTranspose, in, out);
case DT_COMPLEX64:
return MKLTranspose2D<complex64>(kMKLConjugateTranspose, in, out);
case DT_COMPLEX128:
return MKLTranspose2D<complex128>(kMKLConjugateTranspose, in, out);
default:
break;
}
}
#endif
// MKL-DNN has limit on the maximum number of dimensions in a tensor.
// Fallback to Eigen for not supported cases.
if (in.dims() <= TENSOR_MAX_DIMS) {
switch (in.dtype()) {
case DT_FLOAT:
return MKLTransposeND<float>(ctx, in, out, perm);
break;
case DT_BFLOAT16:
return MKLTransposeND<bfloat16>(ctx, in, out, perm);
break;
// TODO(nhasabni): support other types such as INT8.
default:
break;
}
}
// Fallback to eigen if transpose parameters not supported by MKL or MKL-DNN
typedef Eigen::ThreadPoolDevice CPUDevice;
return ::tensorflow::DoConjugateTranspose(ctx->eigen_device<CPUDevice>(), in,
perm, out);
}
#define REGISTER(T) \
REGISTER_KERNEL_BUILDER(Name("_MklTranspose") \
.Device(DEVICE_CPU) \
.TypeConstraint<T>("T") \
.HostMemory("perm") \
.Label(mkl_op_registry::kMklNameChangeOpLabel), \
MklTransposeCpuOp); \
REGISTER_KERNEL_BUILDER(Name("_MklConjugateTranspose") \
.Device(DEVICE_CPU) \
.TypeConstraint<T>("T") \
.HostMemory("perm") \
.Label(mkl_op_registry::kMklNameChangeOpLabel), \
MklConjugateTransposeCpuOp);
TF_CALL_ALL_TYPES(REGISTER)
#undef REGISTER
} // namespace tensorflow
#endif // INTEL_MKL
<commit_msg>minor fix.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// See docs in ../ops/array_ops.cc.
#if defined(INTEL_MKL)
#define EIGEN_USE_THREADS
#if !defined(INTEL_MKL_DNN_ONLY)
#include "mkl_trans.h"
#endif
#include "mkldnn.hpp"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/kernels/transpose_functor.h"
#include "tensorflow/core/kernels/transpose_op.h"
#include "tensorflow/core/util/mkl_types.h"
#include "tensorflow/core/util/mkl_util.h"
using mkldnn::stream;
namespace tensorflow {
// output = TransposeOp(T<any> input, T<int32> perm) takes a tensor
// of type T and rank N, and a permutation of 0, 1, ..., N-1. It
// shuffles the dimensions of the input tensor according to permutation.
//
// Specifically, the returned tensor output meets the following condition:
// 1) output.dims() == input.dims();
// 2) output.dim_size(i) == input.dim_size(perm[i]);
// 3) output.tensor<T, N>(i_0, i_1, ..., i_N-1) ==
// input.tensor<T, N>(j_0, j_1, ..., j_N-1),
// where i_s == j_{perm[s]}
//
// REQUIRES: perm is a vector of int32.
// REQUIRES: input.dims() == perm.size().
// REQUIRES: perm is a permutation.
namespace {
#if !defined(INTEL_MKL_DNN_ONLY)
template <typename T>
Status MKLTranspose2D(const char trans, const Tensor& in, Tensor* out);
// Documentation here: https://software.intel.com/en-us/node/520863
// Parameters: (ordering:row-major, operation:transpose, num_rows, num_cols,
// alpha (for scaling), array, dist_bet_adjacent_cols/rows
// (source), array, dist_bet_adjacent_cols/rows (dest))
#define INSTANTIATE(T, PREFIX) \
template <> \
Status MKLTranspose2D<T>(const char trans, const Tensor& in, Tensor* out) { \
mkl_##PREFIX##omatcopy('R', trans, in.dim_size(0), in.dim_size(1), 1, \
in.flat<T>().data(), in.dim_size(1), \
out->flat<T>().data(), in.dim_size(0)); \
return Status::OK(); \
}
INSTANTIATE(float, s)
INSTANTIATE(double, d)
#undef INSTANTIATE
template <>
Status MKLTranspose2D<complex64>(const char trans, const Tensor& in,
Tensor* out) {
const MKL_Complex8 alpha = {1.0f, 0.0f};
mkl_comatcopy(
'R', trans, in.dim_size(0), in.dim_size(1), alpha,
reinterpret_cast<const MKL_Complex8*>(in.flat<complex64>().data()),
in.dim_size(1), reinterpret_cast<MKL_Complex8*>(const_cast<complex64*>(
out->flat<complex64>().data())),
in.dim_size(0));
return Status::OK();
}
template <>
Status MKLTranspose2D<complex128>(const char trans, const Tensor& in,
Tensor* out) {
const MKL_Complex16 alpha = {1.0, 0.0};
mkl_zomatcopy(
'R', trans, in.dim_size(0), in.dim_size(1), alpha,
reinterpret_cast<const MKL_Complex16*>(in.flat<complex128>().data()),
in.dim_size(1), reinterpret_cast<MKL_Complex16*>(const_cast<complex128*>(
out->flat<complex128>().data())),
in.dim_size(0));
return Status::OK();
}
static const char kMKLTranspose = 'T';
static const char kMKLConjugateTranspose = 'C';
#endif // if !defined(INTEL_MKL_DNN_ONLY)
// MKL-DNN based Transpose implementation
template <typename T>
Status MKLTransposeND(OpKernelContext* ctx, const Tensor& in, Tensor* out,
const gtl::ArraySlice<int32>& perm);
static inline memory::dims ReorderStrides(const memory::dims& strides,
const gtl::ArraySlice<int32>& perm) {
memory::dims reordered_strides;
reordered_strides.resize(strides.size());
for (size_t i = 0; i < strides.size(); ++i) {
reordered_strides[perm[i]] = strides[i];
}
return reordered_strides;
}
// Transpose of N-dimensional tensor using MKL-DNN
template <typename T>
Status MKLTransposeND(OpKernelContext* context, const Tensor& in_tensor,
Tensor* out_tensor, const gtl::ArraySlice<int32>& perm) {
try {
engine cpu_engine = engine(ENGINE_CPU, 0);
MklDnnData<T> in(&cpu_engine);
MklDnnData<T> out(&cpu_engine);
memory::dims in_dims = TFShapeToMklDnnDims(in_tensor.shape());
memory::dims out_dims = TFShapeToMklDnnDims(out_tensor->shape());
memory::dims in_strides = CalculateTFStrides(in_dims);
// Reorder output strides based on permutation requested.
memory::dims out_strides =
ReorderStrides(CalculateTFStrides(out_dims), perm);
in.SetUsrMem(in_dims, in_strides, &in_tensor);
// Output dimensions are same as input dimensions. We adjust the layout
// using strides.
out.SetUsrMem(in_dims, out_strides, out_tensor);
std::vector<primitive> net;
std::shared_ptr<stream> transpose_stream;
transpose_stream.reset(new CPU_STREAM(cpu_engine));
#ifdef ENABLE_MKLDNN_V1
const int net_idx = 0;
net.push_back(reorder(in.GetOpMem(), out.GetOpMem()));
std::vector<std::unordered_map<int, memory>> net_args;
net_args.push_back(
{{MKLDNN_ARG_FROM, in.GetOpMem()}, {MKLDNN_ARG_TO, out.GetOpMem()}});
net.at(net_idx).execute(*transpose_stream, net_args.at(net_idx));
#else
net.push_back(FindOrCreateReorder<T>(in.GetUsrMem(), out.GetUsrMem()));
transpose_stream->submit(net).wait();
#endif // ENABLE_MKLDNN_V1
return Status::OK();
} catch (mkldnn::error& e) {
string error_msg = "Status: " + std::to_string(e.status) + ", message: " +
std::string(e.message) + ", in file " +
std::string(__FILE__) + ":" + std::to_string(__LINE__);
return errors::Aborted("Operation received an exception:", error_msg);
}
}
} // namespace
Status MklTransposeCpuOp::DoTranspose(OpKernelContext* ctx, const Tensor& in,
gtl::ArraySlice<int32> perm,
Tensor* out) {
#if !defined(INTEL_MKL_DNN_ONLY)
if (in.dims() == 2) {
if (perm[0] == 0 && perm[1] == 1) {
return Status::OK();
}
switch (in.dtype()) {
case DT_FLOAT:
return MKLTranspose2D<float>(kMKLTranspose, in, out);
case DT_DOUBLE:
return MKLTranspose2D<double>(kMKLTranspose, in, out);
case DT_COMPLEX64:
return MKLTranspose2D<complex64>(kMKLTranspose, in, out);
case DT_COMPLEX128:
return MKLTranspose2D<complex128>(kMKLTranspose, in, out);
default:
break;
}
}
#endif
// MKL-DNN has limit on the maximum number of dimensions in a tensor.
// Fallback to Eigen for not supported cases.
if (in.dims() <= TENSOR_MAX_DIMS) {
switch (in.dtype()) {
case DT_FLOAT:
return MKLTransposeND<float>(ctx, in, out, perm);
break;
case DT_BFLOAT16:
return MKLTransposeND<bfloat16>(ctx, in, out, perm);
break;
// TODO(nhasabni): support other types such as INT8.
default:
break;
}
}
// Fallback to eigen if transpose parameters not supported by MKL or MKL-DNN
typedef Eigen::ThreadPoolDevice CPUDevice;
return ::tensorflow::DoTranspose(ctx->eigen_device<CPUDevice>(), in, perm,
out);
}
Status MklConjugateTransposeCpuOp::DoTranspose(OpKernelContext* ctx,
const Tensor& in,
gtl::ArraySlice<int32> perm,
Tensor* out) {
#if !defined(INTEL_MKL_DNN_ONLY)
if (in.dims() == 2 && perm[0] == 1 && perm[1] == 0) {
// TODO(rmlarsen): By setting lda and ldb, we could use the MKL kernels
// for any transpose that can be reduced to swapping the last two
// dimensions in a rank-3 tensor. We can even run each outer dimension in
// a separate thread.
switch (in.dtype()) {
case DT_FLOAT:
return MKLTranspose2D<float>(kMKLTranspose, in, out);
case DT_DOUBLE:
return MKLTranspose2D<double>(kMKLTranspose, in, out);
case DT_COMPLEX64:
return MKLTranspose2D<complex64>(kMKLConjugateTranspose, in, out);
case DT_COMPLEX128:
return MKLTranspose2D<complex128>(kMKLConjugateTranspose, in, out);
default:
break;
}
}
#endif
// MKL-DNN has limit on the maximum number of dimensions in a tensor.
// Fallback to Eigen for not supported cases.
if (in.dims() <= TENSOR_MAX_DIMS) {
switch (in.dtype()) {
case DT_FLOAT:
return MKLTransposeND<float>(ctx, in, out, perm);
break;
case DT_BFLOAT16:
return MKLTransposeND<bfloat16>(ctx, in, out, perm);
break;
// TODO(nhasabni): support other types such as INT8.
default:
break;
}
}
// Fallback to eigen if transpose parameters not supported by MKL or MKL-DNN
typedef Eigen::ThreadPoolDevice CPUDevice;
return ::tensorflow::DoConjugateTranspose(ctx->eigen_device<CPUDevice>(), in,
perm, out);
}
#define REGISTER(T) \
REGISTER_KERNEL_BUILDER(Name("_MklTranspose") \
.Device(DEVICE_CPU) \
.TypeConstraint<T>("T") \
.HostMemory("perm") \
.Label(mkl_op_registry::kMklNameChangeOpLabel), \
MklTransposeCpuOp); \
REGISTER_KERNEL_BUILDER(Name("_MklConjugateTranspose") \
.Device(DEVICE_CPU) \
.TypeConstraint<T>("T") \
.HostMemory("perm") \
.Label(mkl_op_registry::kMklNameChangeOpLabel), \
MklConjugateTransposeCpuOp);
TF_CALL_ALL_TYPES(REGISTER)
#undef REGISTER
} // namespace tensorflow
#endif // INTEL_MKL
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014 Yule Fox. All rights reserved.
* http://www.yulefox.com/
*/
#include <elf/elf.h>
#include <elf/net/http.h>
#include <elf/thread.h>
#include <curl/curl.h>
#include <string>
namespace elf {
struct http_req_t {
std::string json;
std::string url;
http_response cb;
void *args;
};
struct http_chunk_t {
char *data;
size_t size;
};
static size_t write_memory_cb(void *ptr, size_t size, size_t nmemb, void *data)
{
size_t realsize = size * nmemb;
struct http_chunk_t *chunk = (struct http_chunk_t*)data;
chunk->data = (char*)E_REALLOC(chunk->data, chunk->size + realsize + 1);
if (chunk->data) {
memcpy((void*)(chunk->data + chunk->size), ptr, realsize);
chunk->size += realsize;
chunk->data[chunk->size] = 0;
}
return realsize;
}
static void *http_post(void *args)
{
http_req_t *post = (http_req_t *)args;
CURL *curl = curl_easy_init();
CURLcode res;
http_chunk_t chunk;
chunk.data = NULL;
chunk.size = 0;
if (curl != NULL) {
struct curl_slist *slist = NULL;
slist = curl_slist_append(slist, "Content-type:application/json;charset=utf-8");
//LOG_DEBUG("http", "prepare do post: url[%s], json[%s]", post->url.c_str(), post->json.c_str());
//curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
//curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 1L);
curl_easy_setopt(curl, CURLOPT_URL, post->url.c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post->json.c_str());
//curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, post->json.size());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_memory_cb);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunk);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
res = curl_easy_perform(curl);
if(res != CURLE_OK) {
LOG_ERROR("http", "curl_easy_perform() failed(%d): %s %s, %s.",
res, curl_easy_strerror(res), post->url.c_str(), post->json.c_str());
if (post->cb) {
post->cb(0, 0, 0, post->args);
}
}
curl_slist_free_all(slist);
curl_easy_cleanup(curl);
} else {
LOG_ERROR("http", "%s", "curl_easy_init() failed.");
}
if (chunk.data == NULL || chunk.size == 0) {
post->cb(0, 0, 0, post->args);
} else {
post->cb((void*)chunk.data, 1, chunk.size, post->args);
E_FREE(chunk.data);
}
E_DELETE post;
return NULL;
}
int http_init(void)
{
MODULE_IMPORT_SWITCH;
/* In windows, this will init the winsock stuff */
CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
/* Check for errors */
if (res != CURLE_OK) {
LOG_ERROR("http", "curl_global_init() failed: %s.",
curl_easy_strerror(res));
return -1;
}
return 0;
}
int http_fini(void)
{
MODULE_IMPORT_SWITCH;
curl_global_cleanup();
return 0;
}
int http_json(const char *url, const char *json,
http_response func, void *args)
{
LOG_DEBUG("http", "url: %s", url);
LOG_DEBUG("http", "json: %s", json);
http_req_t *post = E_NEW http_req_t;
post->url = std::string(url);
post->json = std::string(json);
post->cb = func;
post->args = args;
thread_init(http_post, post);
return 0;
}
int urlencode(const char *in, ssize_t size, std::string &out)
{
CURL *curl = curl_easy_init();
if(curl) {
char *buf = curl_easy_escape(curl, in, size);
if(buf) {
out = std::string(buf);
curl_free(buf);
return 0;
}
}
return -1;
}
} // namespace elf
<commit_msg>[ADD] http request timeout<commit_after>/*
* Copyright (C) 2014 Yule Fox. All rights reserved.
* http://www.yulefox.com/
*/
#include <elf/elf.h>
#include <elf/net/http.h>
#include <elf/thread.h>
#include <curl/curl.h>
#include <string>
const static int HTTP_POST_TIMEOUT = 5; // 5 seconds;
namespace elf {
struct http_req_t {
std::string json;
std::string url;
http_response cb;
void *args;
};
struct http_chunk_t {
char *data;
size_t size;
};
static size_t write_memory_cb(void *ptr, size_t size, size_t nmemb, void *data)
{
size_t realsize = size * nmemb;
struct http_chunk_t *chunk = (struct http_chunk_t*)data;
chunk->data = (char*)E_REALLOC(chunk->data, chunk->size + realsize + 1);
if (chunk->data) {
memcpy((void*)(chunk->data + chunk->size), ptr, realsize);
chunk->size += realsize;
chunk->data[chunk->size] = 0;
}
return realsize;
}
static void *http_post(void *args)
{
http_req_t *post = (http_req_t *)args;
CURL *curl = curl_easy_init();
CURLcode res;
http_chunk_t chunk;
chunk.data = NULL;
chunk.size = 0;
if (curl != NULL) {
struct curl_slist *slist = NULL;
slist = curl_slist_append(slist, "Content-type:application/json;charset=utf-8");
//LOG_DEBUG("http", "prepare do post: url[%s], json[%s]", post->url.c_str(), post->json.c_str());
//curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
//curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 1L);
curl_easy_setopt(curl, CURLOPT_URL, post->url.c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post->json.c_str());
//curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, post->json.size());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_memory_cb);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunk);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, HTTP_POST_TIMEOUT);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
res = curl_easy_perform(curl);
if(res != CURLE_OK) {
LOG_ERROR("http", "curl_easy_perform() failed(%d): %s %s, %s.",
res, curl_easy_strerror(res), post->url.c_str(), post->json.c_str());
if (post->cb) {
post->cb(0, 0, 0, post->args);
}
}
curl_slist_free_all(slist);
curl_easy_cleanup(curl);
} else {
LOG_ERROR("http", "%s", "curl_easy_init() failed.");
}
if (chunk.data == NULL || chunk.size == 0) {
post->cb(0, 0, 0, post->args);
} else {
post->cb((void*)chunk.data, 1, chunk.size, post->args);
E_FREE(chunk.data);
}
E_DELETE post;
return NULL;
}
int http_init(void)
{
MODULE_IMPORT_SWITCH;
/* In windows, this will init the winsock stuff */
CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
/* Check for errors */
if (res != CURLE_OK) {
LOG_ERROR("http", "curl_global_init() failed: %s.",
curl_easy_strerror(res));
return -1;
}
return 0;
}
int http_fini(void)
{
MODULE_IMPORT_SWITCH;
curl_global_cleanup();
return 0;
}
int http_json(const char *url, const char *json,
http_response func, void *args)
{
LOG_DEBUG("http", "url: %s", url);
LOG_DEBUG("http", "json: %s", json);
http_req_t *post = E_NEW http_req_t;
post->url = std::string(url);
post->json = std::string(json);
post->cb = func;
post->args = args;
thread_init(http_post, post);
return 0;
}
int urlencode(const char *in, ssize_t size, std::string &out)
{
CURL *curl = curl_easy_init();
if(curl) {
char *buf = curl_easy_escape(curl, in, size);
if(buf) {
out = std::string(buf);
curl_free(buf);
return 0;
}
}
return -1;
}
} // namespace elf
<|endoftext|> |
<commit_before>/*
This file is part of Groho, a simulator for inter-planetary travel and warfare.
Copyright (c) 2017-2018 by Kaushik Ghose. Some rights reserved, see LICENSE
This file contains some common functions used in parsing scenario files
*/
#pragma once
#include <iterator>
#include <optional>
#include <sstream>
#include <string>
#include <vector>
// For file modification time
#include <sys/stat.h>
#include <sys/types.h>
#ifndef WIN32
#include <unistd.h>
#endif
#ifdef WIN32
#define stat _stat
#endif
#include "vector.hpp"
#define LOGURU_WITH_STREAMS 1
#include "loguru.hpp"
namespace sim {
const double T0 = 2451545.0;
const double S_PER_DAY = 86400.0;
inline double jd2s(double jd) { return (jd - T0) * S_PER_DAY; }
struct KeyValue {
std::string key, value;
};
const std::string wspace = " \t\n\r\f\v";
inline std::string trim_whitespace(std::string line)
{
line.erase(0, line.find_first_not_of(wspace));
line.erase(line.find_last_not_of(wspace) + 1);
return line;
}
inline std::string trim_comments(std::string line)
{
return line.erase(std::min(line.find_first_of(';'), line.size()));
}
inline std::optional<KeyValue> get_key_value(std::string line)
{
KeyValue kv;
size_t n0 = line.find_first_of('=');
if (n0 > line.size()) {
return {};
}
kv.key = trim_whitespace(line.substr(0, n0 - 1));
kv.value = trim_whitespace(line.substr(n0 + 1));
return kv;
}
inline std::vector<std::string> split(std::string line)
{
std::istringstream iss(line);
return std::vector<std::string>(
std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>());
}
inline Vector stoV(std::string v)
{
std::vector<std::string> tokens = split(v);
if (tokens.size() < 3) {
LOG_S(ERROR) << "Vector needs three components: Got " << v;
return {};
}
Vector out{ stof(tokens[0]), stof(tokens[1]), stof(tokens[2]) };
return out;
}
inline time_t file_modification_time(std::string fname)
{
struct stat result;
if (stat(fname.c_str(), &result) == 0) {
return result.st_mtime;
} else {
return 0;
}
}
// Given a list of files, give us the time of latest change among them all
inline time_t file_modification_time(std::vector<std::string> fnames)
{
time_t fmod_time = 0;
for (auto& fn : fnames) {
time_t fn_ft = file_modification_time(fn);
if (fn_ft > fmod_time) {
fmod_time = fn_ft;
}
}
return fmod_time;
}
}<commit_msg>Enable multi-line statements in Scenario files<commit_after>/*
This file is part of Groho, a simulator for inter-planetary travel and warfare.
Copyright (c) 2017-2018 by Kaushik Ghose. Some rights reserved, see LICENSE
This file contains some common functions used in parsing scenario files
*/
#pragma once
#include <fstream>
#include <iterator>
#include <optional>
#include <sstream>
#include <string>
#include <vector>
// For file modification time
#include <sys/stat.h>
#include <sys/types.h>
#ifndef WIN32
#include <unistd.h>
#endif
#ifdef WIN32
#define stat _stat
#endif
#include "vector.hpp"
#define LOGURU_WITH_STREAMS 1
#include "loguru.hpp"
namespace sim {
const double T0 = 2451545.0;
const double S_PER_DAY = 86400.0;
inline double jd2s(double jd) { return (jd - T0) * S_PER_DAY; }
struct KeyValue {
std::string key, value;
};
const std::string wspace = " \t\n\r\f\v";
inline std::string trim_whitespace(std::string line)
{
line.erase(0, line.find_first_not_of(wspace));
line.erase(line.find_last_not_of(wspace) + 1);
return line;
}
inline std::string trim_comments(std::string line)
{
return line.erase(std::min(line.find_first_of(';'), line.size()));
}
inline bool line_continued(std::string line) { return line.back() == '\\'; }
// An iterator in disguise
// Trims leading/trailing whitespace and joins continued lines
struct ScenarioFile {
static std::optional<ScenarioFile> open(std::string fname)
{
ScenarioFile sf;
sf.cfile = std::ifstream(fname);
if (!sf.cfile) {
return {};
}
sf.line_no = 0;
sf.continued_line = "";
return sf;
}
std::optional<std::string> next()
{
std::string line;
continued_line = "";
while (std::getline(cfile, line)) {
line = trim_whitespace(trim_comments(line));
if (line.size() == 0)
continue;
if (line_continued(line)) {
line.pop_back();
continued_line += line;
continue;
} else {
return continued_line + line;
}
}
if (continued_line.size()) {
return continued_line;
} else {
return {};
}
}
std::ifstream cfile;
int line_no = 0;
std::string continued_line;
};
inline std::optional<KeyValue> get_key_value(std::string line)
{
KeyValue kv;
size_t n0 = line.find_first_of('=');
if (n0 > line.size()) {
return {};
}
kv.key = trim_whitespace(line.substr(0, n0 - 1));
kv.value = trim_whitespace(line.substr(n0 + 1));
return kv;
}
inline std::vector<std::string> split(std::string line)
{
std::istringstream iss(line);
return std::vector<std::string>(
std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>());
}
inline Vector stoV(std::string v)
{
std::vector<std::string> tokens = split(v);
if (tokens.size() < 3) {
LOG_S(ERROR) << "Vector needs three components: Got " << v;
return {};
}
Vector out{ stof(tokens[0]), stof(tokens[1]), stof(tokens[2]) };
return out;
}
inline time_t file_modification_time(std::string fname)
{
struct stat result;
if (stat(fname.c_str(), &result) == 0) {
return result.st_mtime;
} else {
return 0;
}
}
// Given a list of files, give us the time of latest change among them all
inline time_t file_modification_time(std::vector<std::string> fnames)
{
time_t fmod_time = 0;
for (auto& fn : fnames) {
time_t fn_ft = file_modification_time(fn);
if (fn_ft > fmod_time) {
fmod_time = fn_ft;
}
}
return fmod_time;
}
}<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#if !defined(_WIN32) && !defined(NDEBUG)
#include <execinfo.h>
#include <signal.h>
#endif
#ifdef ANDROID
#include <android/log.h>
#define LOG(...) __android_log_print(ANDROID_LOG_INFO, "ruberoid", __VA_ARGS__)
#else
#define LOG(...) fprintf(stderr, __VA_ARGS__)
#endif
#include "gason.h"
struct {
bool f;
const char *s;
} SUITE[] = {
{false, R"*(1234567890)*"},
{false, R"*("A JSON payload should be an object or array, not a string.")*"},
{true, R"*(["Unclosed array")*"},
{true, R"*({unquoted_key: "keys must be quoted"})*"},
{false, R"*(["extra comma",])*"},
{true, R"*(["double extra comma",,])*"},
{true, R"*([ , "<-- missing value"])*"},
{true, R"*([ 1 [ , "<-- missing inner value 1"]])*"},
{true, R"*({ "1" [ , "<-- missing inner value 2"]})*"},
{true, R"*([ "1" { , "<-- missing inner value 3":"x"}])*"},
{false, R"*(["Comma after the close"],)*"},
{false, R"*({"Extra comma": true,})*"},
{false, R"*({"Extra value after close": true} "misplaced quoted value")*"},
{true, R"*({"Illegal expression": 1 + 2})*"},
{true, R"*({"Illegal invocation": alert()})*"},
{false, R"*({"Numbers cannot have leading zeroes": 013})*"},
{true, R"*({"Numbers cannot be hex": 0x14})*"},
{true, R"*(["Illegal backslash escape: \x15"])*"},
{true, R"*([\naked])*"},
{true, R"*(["Illegal backslash escape: \017"])*"},
{true, R"*([[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]])*"},
{false, R"*({"Missing colon" null})*"},
{true, R"*({"Unfinished object"})*"},
{true, R"*({"Unfinished object 2" null "x"})*"},
{true, R"*({"Double colon":: null})*"},
{true, R"*({"Comma instead of colon", null})*"},
{true, R"*(["Colon instead of comma": false])*"},
{true, R"*(["Bad value", truth])*"},
{true, R"*(['single quote'])*"},
{true, R"*([" tab character in string "])*"},
{true, R"*(["line
break"])*"},
{true, R"*(["line\
break"])*"},
{false, R"*([0e])*"},
{false, R"*([0e+])*"},
{true, R"*([0e+-1])*"},
{true, R"*({"Comma instead if closing brace": true,)*"},
{true, R"*(["mismatch"})*"},
{false, R"*(
[
"JSON Test Pattern pass1",
{"object with 1 member":["array with 1 element"]},
{},
[],
-42,
true,
false,
null,
{
"integer": 1234567890,
"real": -9876.543210,
"e": 0.123456789e-12,
"E": 1.234567890E+34,
"": 23456789012E66,
"zero": 0,
"one": 1,
"space": " ",
"quote": "\"",
"backslash": "\\",
"controls": "\b\f\n\r\t",
"slash": "/ & \/",
"alpha": "abcdefghijklmnopqrstuvwyz",
"ALPHA": "ABCDEFGHIJKLMNOPQRSTUVWYZ",
"digit": "0123456789",
"0123456789": "digit",
"special": "`1~!@#$%^&*()_+-={':[,]}|;.</>?",
"hex": "\u0123\u4567\u89AB\uCDEF\uabcd\uef4A",
"true": true,
"false": false,
"null": null,
"array":[ ],
"object":{ },
"address": "50 St. James Street",
"url": "http://www.JSON.org/",
"comment": "// /* <!-- --",
"# -- --> */": " ",
" s p a c e d " :[1,2 , 3
,
4 , 5 , 6 ,7 ],"compact":[1,2,3,4,5,6,7],
"jsontext": "{\"object with 1 member\":[\"array with 1 element\"]}",
"quotes": "" \u0022 %22 0x22 034 "",
"\/\\\"\uCAFE\uBABE\uAB98\uFCDE\ubcda\uef4A\b\f\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?"
: "A key can be any string"
},
0.5 ,98.6
,
99.44
,
1066,
1e1,
0.1e1,
1e-1,
1e00,2e+00,2e-00
,"rosebud"])*"},
{false, R"*([[[[[[[[[[[[[[[[[[["Not too deep"]]]]]]]]]]]]]]]]]]])*"},
{false, R"*({
"JSON Test Pattern pass3": {
"The outermost value": "must be an object or array.",
"In this test": "It is an object."
}
}
)*"},
{false, R"*([1, 2, "хУй", [[0.5], 7.11, 13.19e+1], "ba\u0020r", [ [ ] ], -0, -.666, [true, null], {"WAT?!": false}])*"}};
int main() {
#if !defined(_WIN32) && !defined(NDEBUG)
signal(SIGABRT, [](int) {
void *callstack[64];
int size = backtrace(callstack, sizeof(callstack)/sizeof(callstack[0]));
char **strings = backtrace_symbols(callstack, size);
for (int i = 0; i < size; ++i)
fprintf(stderr, "%s\n", strings[i]);
free(strings);
exit(EXIT_FAILURE);
});
#endif
char *endptr;
JsonValue value;
JsonAllocator allocator;
int passed = 0;
int count = 0;
for (auto t : SUITE) {
char *source = strdup(t.s);
int status = jsonParse(source, &endptr, &value, allocator);
free(source);
if (t.f ^ (status == JSON_OK)) {
++passed;
} else {
LOG("%d: must be %s: %s\n", count, t.f ? "fail" : "pass", t.s);
}
++count;
}
LOG("%d/%d\n", passed, count);
return 0;
}
<commit_msg>Test suite refactoring<commit_after>#include "gason.h"
#include <string.h>
#include <stdio.h>
static int parsed;
static int failed;
void parse(const char *csource, bool ok) {
char *source = strdup(csource);
char *endptr;
JsonValue value;
JsonAllocator allocator;
int result = jsonParse(source, &endptr, &value, allocator);
if (ok && result) {
fprintf(stderr, "FAILED %d: %s\n%s\n%*s\n", parsed, jsonStrError(result), csource, (int)(endptr - source + 1), "^");
++failed;
}
if (!ok && !result) {
fprintf(stderr, "PASSED %d:\n%s\n", parsed, csource);
++failed;
}
++parsed;
}
#define pass(csource) parse(csource, true)
#define fail(csource) parse(csource, false)
int main() {
pass(u8R"json(1234567890)json");
pass(u8R"json("A JSON payload should be an object or array, not a string.")json");
fail(u8R"json(["Unclosed array")json");
fail(u8R"json({unquoted_key: "keys must be quoted"})json");
pass(u8R"json(["extra comma",])json");
fail(u8R"json(["double extra comma",,])json");
fail(u8R"json([ , "<-- missing value"])json");
fail(u8R"json([ 1 [ , "<-- missing inner value 1"]])json");
fail(u8R"json({ "1" [ , "<-- missing inner value 2"]})json");
fail(u8R"json([ "1" { , "<-- missing inner value 3":"x"}])json");
pass(u8R"json(["Comma after the close"],)json");
pass(u8R"json({"Extra comma": true,})json");
pass(u8R"json({"Extra value after close": true} "misplaced quoted value")json");
fail(u8R"json({"Illegal expression": 1 + 2})json");
fail(u8R"json({"Illegal invocation": alert()})json");
pass(u8R"json({"Numbers cannot have leading zeroes": 013})json");
fail(u8R"json({"Numbers cannot be hex": 0x14})json");
fail(u8R"json(["Illegal backslash escape: \x15"])json");
fail(u8R"json([\naked])json");
fail(u8R"json(["Illegal backslash escape: \017"])json");
fail(u8R"json([[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]])json");
pass(u8R"json({"Missing colon" null})json");
fail(u8R"json({"Unfinished object"})json");
fail(u8R"json({"Unfinished object 2" null "x"})json");
fail(u8R"json({"Double colon":: null})json");
fail(u8R"json({"Comma instead of colon", null})json");
fail(u8R"json(["Colon instead of comma": false])json");
fail(u8R"json(["Bad value", truth])json");
fail(u8R"json(['single quote'])json");
fail(u8R"json([" tab character in string "])json");
fail(u8R"json(["line
break"])json");
fail(u8R"json(["line\
break"])json");
pass(u8R"json([0e])json");
pass(u8R"json([0e+])json");
fail(u8R"json([0e+-1])json");
fail(u8R"json({"Comma instead if closing brace": true,)json");
fail(u8R"json(["mismatch"})json");
pass(u8R"json(
[
"JSON Test Pattern pass1",
{"object with 1 member":["array with 1 element"]},
{},
[],
-42,
true,
false,
null,
{
"integer": 1234567890,
"real": -9876.543210,
"e": 0.123456789e-12,
"E": 1.234567890E+34,
"": 23456789012E66,
"zero": 0,
"one": 1,
"space": " ",
"quote": "\"",
"backslash": "\\",
"controls": "\b\f\n\r\t",
"slash": "/ & \/",
"alpha": "abcdefghijklmnopqrstuvwyz",
"ALPHA": "ABCDEFGHIJKLMNOPQRSTUVWYZ",
"digit": "0123456789",
"0123456789": "digit",
"special": "`1~!@#$%^&json()_+-={':[,]}|;.</>?",
"hex": "\u0123\u4567\u89AB\uCDEF\uabcd\uef4A",
"true": true,
"false": false,
"null": null,
"array":[ ],
"object":{ },
"address": "50 St. James Street",
"url": "http://www.JSON.org/",
"comment": "// /json <!-- --",
"# -- --> json/": " ",
" s p a c e d " :[1,2 , 3
,
4 , 5 , 6 ,7 ],"compact":[1,2,3,4,5,6,7],
"jsontext": "{\"object with 1 member\":[\"array with 1 element\"]}",
"quotes": "" \u0022 %22 0x22 034 "",
"\/\\\"\uCAFE\uBABE\uAB98\uFCDE\ubcda\uef4A\b\f\n\r\t`1~!@#$%^&json()_+-=[]{}|;:',./<>?"
: "A key can be any string"
},
0.5 ,98.6
,
99.44
,
1066,
1e1,
0.1e1,
1e-1,
1e00,2e+00,2e-00
,"rosebud"])json");
pass(u8R"json([[[[[[[[[[[[[[[[[[["Not too deep"]]]]]]]]]]]]]]]]]]])json");
pass(u8R"json({
"JSON Test Pattern pass3": {
"The outermost value": "must be an object or array.",
"In this test": "It is an object."
}
}
)json");
pass(u8R"json([1, 2, "хУй", [[0.5], 7.11, 13.19e+1], "ba\u0020r", [ [ ] ], -0, -.666, [true, null], {"WAT?!": false}])json");
if (failed)
fprintf(stderr, "%d/%d TESTS FAILED\n", failed, parsed);
else
fprintf(stderr, "ALL TESTS PASSED\n");
return 0;
}
<|endoftext|> |
<commit_before>/*The MIT License (MIT)
Copyright (c) 2016 Jens Malmborg
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 <utils/path-helper.h>
#include "script-engine.h"
#include "script-global.h"
#include "debug/debug-server.h"
#include <iostream>
using namespace v8;
namespace {
class ScriptModule : public ScriptObjectWrap<ScriptModule> {
public:
ScriptModule(v8::Isolate* isolate, std::string path, std::string filename) :
ScriptObjectWrap(isolate) {
v8Object()->Set(v8::String::NewFromUtf8(isolate, "exports"),
v8::Object::New(isolate));
v8Object()->Set(v8::String::NewFromUtf8(isolate, "path"),
v8::String::NewFromUtf8(isolate, path.c_str()));
v8Object()->Set(v8::String::NewFromUtf8(isolate, "filename"),
v8::String::NewFromUtf8(isolate, filename.c_str()));
}
};
class ArrayBufferAllocator : public ArrayBuffer::Allocator {
public:
virtual void* Allocate(size_t length) {
void* data = AllocateUninitialized(length);
return data == NULL ? data : memset(data, 0, length);
}
virtual void* AllocateUninitialized(size_t length) {
return malloc(length);
}
virtual void Free(void* data, size_t) {
free(data);
}
};
void PrintStackTrace(Isolate* isolate, TryCatch* tryCatch) {
HandleScope scope(isolate);
String::Utf8Value stackTrace(tryCatch->StackTrace());
if (stackTrace.length() > 0) {
std::cout << *stackTrace << std::endl;
}
}
void PrintCompileError(Isolate* isolate, TryCatch* tryCatch) {
HandleScope scope(isolate);
Local<Message> message = tryCatch->Message();
String::Utf8Value exception(tryCatch->Exception());
String::Utf8Value filename(message->GetScriptOrigin().ResourceName());
std::cout << *exception << std::endl << " " << "at " << *filename <<
":" << message->GetLineNumber() << ":" <<
message->GetStartColumn() << std::endl;
}
}
ScriptEngine::ScriptEngine() {
V8::InitializeICU();
platform_ = platform::CreateDefaultPlatform();
V8::InitializePlatform(platform_);
V8::Initialize();
}
ScriptEngine::~ScriptEngine() {
V8::Dispose();
V8::ShutdownPlatform();
delete platform_;
}
void ScriptEngine::Run(std::string filename, int argc, char* argv[]) {
V8::SetFlagsFromCommandLine(&argc, argv, true);
executionPath_ = PathHelper::Append(
{PathHelper::Current(), PathHelper::GetPath(filename)});
filename = PathHelper::GetFileName(filename);
bool debug = false;
for (int i=1; i<argc; i++) {
if (strcmp(argv[i], "debug") == 0) {
debug = true;
}
}
ArrayBufferAllocator array_buffer_allocator;
Isolate::CreateParams create_params;
create_params.array_buffer_allocator = &array_buffer_allocator;
isolate_ = v8::Isolate::New(create_params);
{
Isolate::Scope isolate_scope(isolate_);
HandleScope handle_scope(isolate_);
global_.reset(new ScriptGlobal(isolate_));
if (debug) {
DebugServer::current().Start(isolate_);
}
context_ = Context::New(isolate_, NULL, global_->v8Template());
Context::Scope context_scope(context_);
Execute(filename);
}
isolate_->Dispose();
}
Handle<Value> ScriptEngine::Execute(std::string filepath) {
EscapableHandleScope handle_scope(isolate_);
if (!PathHelper::FileNameEndsWith(filepath, ".js")) {
filepath += ".js";
}
auto filename = PathHelper::GetFileName(filepath);
auto resolvedPath = resolvePath(filepath);
// The original script source is being wrapped in an anonymous function
// just to define a local scope.
auto source = "(function (module, exports) { " +
FileReader::ReadAsText(resolvedPath) + "\r\n});";
auto script = String::NewFromUtf8(isolate_, source.c_str());
TryCatch tryCatch;
auto compiled = Script::Compile(
script, String::NewFromUtf8(isolate_, resolvedPath.c_str()));
if (compiled.IsEmpty()) {
PrintCompileError(isolate_, &tryCatch);
return v8::Null(isolate_);
}
if (filepath.compare(0, 2, "./") == 0) {
filepath.erase(0, 2);
}
if (filepath.compare(0, 1, "/") == 0) {
filepath.erase(0, 1);
}
auto p = PathHelper::GetPath(filepath);
scriptPath_.push_back(p);
// The result from the running script is a function that defines the local
// scope for the script.
auto result = compiled->Run();
auto scope = Handle<Function>::Cast(result);
// Create the current module for the script.
auto module = new ScriptModule(isolate_, scriptPath(), filename);
Handle<Value> args[] = { module->v8Object(), module->v8Object()->Get(
v8::String::NewFromUtf8(isolate_, "exports")) };
// Call the function that defines the local scope for the script (the module
// is passed as an argument). An error has occurred when result is empty.
if (scope->Call(scope, 2, args).IsEmpty()) {
PrintStackTrace(isolate_, &tryCatch);
scriptPath_.pop_back();
return v8::Null(isolate_);
}
scriptPath_.pop_back();
return handle_scope.Escape(
module->v8Object()->Get(String::NewFromUtf8(isolate_, "exports")));
}
void ScriptEngine::ThrowTypeError(std::string message) {
isolate_->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate_, message.c_str())));
}<commit_msg>Bugfix for sourcemaps.<commit_after>/*The MIT License (MIT)
Copyright (c) 2016 Jens Malmborg
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 <utils/path-helper.h>
#include "script-engine.h"
#include "script-global.h"
#include "debug/debug-server.h"
#include <iostream>
#ifdef WIN32
#define NewLine "\r\n"
#else
#define NewLine "\n"
#endif
using namespace v8;
namespace {
class ScriptModule : public ScriptObjectWrap<ScriptModule> {
public:
ScriptModule(v8::Isolate* isolate, std::string path, std::string filename) :
ScriptObjectWrap(isolate) {
v8Object()->Set(v8::String::NewFromUtf8(isolate, "exports"),
v8::Object::New(isolate));
v8Object()->Set(v8::String::NewFromUtf8(isolate, "path"),
v8::String::NewFromUtf8(isolate, path.c_str()));
v8Object()->Set(v8::String::NewFromUtf8(isolate, "filename"),
v8::String::NewFromUtf8(isolate, filename.c_str()));
}
};
class ArrayBufferAllocator : public ArrayBuffer::Allocator {
public:
virtual void* Allocate(size_t length) {
void* data = AllocateUninitialized(length);
return data == NULL ? data : memset(data, 0, length);
}
virtual void* AllocateUninitialized(size_t length) {
return malloc(length);
}
virtual void Free(void* data, size_t) {
free(data);
}
};
void PrintStackTrace(Isolate* isolate, TryCatch* tryCatch) {
HandleScope scope(isolate);
String::Utf8Value stackTrace(tryCatch->StackTrace());
if (stackTrace.length() > 0) {
std::cout << *stackTrace << std::endl;
}
}
void PrintCompileError(Isolate* isolate, TryCatch* tryCatch) {
HandleScope scope(isolate);
Local<Message> message = tryCatch->Message();
String::Utf8Value exception(tryCatch->Exception());
String::Utf8Value filename(message->GetScriptOrigin().ResourceName());
std::cout << *exception << std::endl << " " << "at " << *filename <<
":" << message->GetLineNumber() << ":" <<
message->GetStartColumn() << std::endl;
}
}
ScriptEngine::ScriptEngine() {
V8::InitializeICU();
platform_ = platform::CreateDefaultPlatform();
V8::InitializePlatform(platform_);
V8::Initialize();
}
ScriptEngine::~ScriptEngine() {
V8::Dispose();
V8::ShutdownPlatform();
delete platform_;
}
void ScriptEngine::Run(std::string filename, int argc, char* argv[]) {
V8::SetFlagsFromCommandLine(&argc, argv, true);
executionPath_ = PathHelper::Append(
{PathHelper::Current(), PathHelper::GetPath(filename)});
filename = PathHelper::GetFileName(filename);
bool debug = false;
for (int i=1; i<argc; i++) {
if (strcmp(argv[i], "debug") == 0) {
debug = true;
}
}
ArrayBufferAllocator array_buffer_allocator;
Isolate::CreateParams create_params;
create_params.array_buffer_allocator = &array_buffer_allocator;
isolate_ = v8::Isolate::New(create_params);
{
Isolate::Scope isolate_scope(isolate_);
HandleScope handle_scope(isolate_);
global_.reset(new ScriptGlobal(isolate_));
if (debug) {
DebugServer::current().Start(isolate_);
}
context_ = Context::New(isolate_, NULL, global_->v8Template());
Context::Scope context_scope(context_);
Execute(filename);
}
isolate_->Dispose();
}
Handle<Value> ScriptEngine::Execute(std::string filepath) {
EscapableHandleScope handle_scope(isolate_);
if (!PathHelper::FileNameEndsWith(filepath, ".js")) {
filepath += ".js";
}
auto filename = PathHelper::GetFileName(filepath);
auto resolvedPath = resolvePath(filepath);
// The original script source is being wrapped in an anonymous function
// just to define a local scope.
auto source = "(function (module, exports) { " +
FileReader::ReadAsText(resolvedPath) + NewLine + "});";
auto script = String::NewFromUtf8(isolate_, source.c_str());
TryCatch tryCatch;
auto compiled = Script::Compile(
script, String::NewFromUtf8(isolate_, resolvedPath.c_str()));
if (compiled.IsEmpty()) {
PrintCompileError(isolate_, &tryCatch);
return v8::Null(isolate_);
}
if (filepath.compare(0, 2, "./") == 0) {
filepath.erase(0, 2);
}
if (filepath.compare(0, 1, "/") == 0) {
filepath.erase(0, 1);
}
auto p = PathHelper::GetPath(filepath);
scriptPath_.push_back(p);
// The result from the running script is a function that defines the local
// scope for the script.
auto result = compiled->Run();
auto scope = Handle<Function>::Cast(result);
// Create the current module for the script.
auto module = new ScriptModule(isolate_, scriptPath(), filename);
Handle<Value> args[] = { module->v8Object(), module->v8Object()->Get(
v8::String::NewFromUtf8(isolate_, "exports")) };
// Call the function that defines the local scope for the script (the module
// is passed as an argument). An error has occurred when result is empty.
if (scope->Call(scope, 2, args).IsEmpty()) {
PrintStackTrace(isolate_, &tryCatch);
scriptPath_.pop_back();
return v8::Null(isolate_);
}
scriptPath_.pop_back();
return handle_scope.Escape(
module->v8Object()->Get(String::NewFromUtf8(isolate_, "exports")));
}
void ScriptEngine::ThrowTypeError(std::string message) {
isolate_->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate_, message.c_str())));
}<|endoftext|> |
<commit_before>#include "epa_pll_util.hpp"
#include <unordered_map>
#include <algorithm>
#include "pll_util.hpp"
using namespace std;
/* Returns the range of a sequence outside of which there are ONLY indel characters.
* Range starts at the first valid position and ends with the first non-valid position
* Example:
* - - - A T A G C T - -
* 0 1 2 3 4 5 6 7 8 9 10
* Output: (3,9)
*/
tuple<unsigned int, unsigned int> get_valid_range(string sequence)
{
unsigned int lower = 0;
unsigned int upper = sequence.length();
while(sequence.c_str()[lower] == '-')
lower++;
while(sequence.c_str()[upper - 1] == '-')
upper--;
return make_tuple(lower, upper);
}
void link_tree_msa(pll_utree_t * tree, pll_partition_t * partition,
const MSA& msa, const unsigned int num_tip_nodes,
vector<tuple<unsigned int, unsigned int>> &valid_map)
{
// obtain pointers to all tip nodes
vector<pll_utree_t*> tip_nodes(num_tip_nodes);
pll_utree_query_tipnodes(tree, &tip_nodes[0]);
// and associate the sequences from the MSA file with the correct tips
/* create a hash table of size num_tip_nodes */
unordered_map<string, unsigned int> map; // mapping labels to tip clv indices
/* populate the hash table with tree tip labels */
for (unsigned int i = 0; i < num_tip_nodes; ++i)
map[tip_nodes[i]->label] = i;
/* find sequences in hash table and link them with the corresponding taxa */
for (auto const &s : msa)
{
auto map_value = map.find(s.header());
auto clv_index = map_value->second;
if (map_value == map.end())
throw runtime_error{string("Sequence with header does not appear in the tree: ") + s.header()};
// associates the sequence with the tip by calculating the tips clv buffers
pll_set_tip_states(partition, clv_index, pll_map_nt, s.sequence().c_str());
// TODO improvement?
// remember the valid-range of the sequence, indexed by tip clv index
valid_map[clv_index] = get_valid_range(s.sequence());
}
};
void precompute_clvs(pll_utree_t * tree, pll_partition_t * partition, const Tree_Numbers& nums)
{
unsigned int num_matrices, num_ops;
/* various buffers for creating a postorder traversal and operations structures */
vector<pll_utree_t*> travbuffer(nums.nodes);
vector<double> branch_lengths(nums.branches);
vector<unsigned int> matrix_indices(nums.branches);
vector<pll_operation_t> operations(nums.nodes);
// get a list of all tip nodes
vector<pll_utree_t*> tip_nodes(nums.tip_nodes);
pll_utree_query_tipnodes(tree, &tip_nodes[0]);
/* adjust clv indices such that every direction has its own */
set_unique_clv_indices(tree, nums.tip_nodes);
for (auto node : tip_nodes)
{
/* perform a partial postorder traversal of the unrooted tree starting at the current tip
and returning every node whose clv in the direction of the tip hasn't been calculated yet*/
unsigned int traversal_size;
if(pll_utree_traverse(node->back, cb_partial_traversal, &travbuffer[0], &traversal_size)
!= PLL_SUCCESS)
throw runtime_error{"Function pll_utree_traverse() requires inner nodes as parameters"};
/* given the computed traversal descriptor, generate the operations
structure, and the corresponding probability matrix indices that
may need recomputing */
pll_utree_create_operations(&travbuffer[0],
traversal_size,
&branch_lengths[0],
&matrix_indices[0],
&operations[0],
&num_matrices,
&num_ops);
pll_update_prob_matrices(partition,
0, // use model 0
&matrix_indices[0],// matrices to update
&branch_lengths[0],
num_matrices); // how many should be updated
/* use the operations array to compute all num_ops inner CLVs. Operations
will be carried out sequentially starting from operation 0 towrds num_ops-1 */
pll_update_partials(partition, &operations[0], num_ops);
}
}
void split_combined_msa(MSA& source, MSA& target, pll_utree_t * tree, unsigned int num_tip_nodes)
{
vector<pll_utree_t*> tip_nodes(num_tip_nodes);
pll_utree_query_tipnodes(tree, &tip_nodes[0]);
auto falsegroup_begin = partition(source.begin(), source.end(),
[&tip_nodes](const Sequence& em)
{
return find(tip_nodes.begin(), tip_nodes.end(), em) != tip_nodes.end();
});
target.num_sites(source.num_sites());
target.move_sequences(falsegroup_begin, source.end());
source.erase(falsegroup_begin, source.end());
}
bool operator==(const pll_utree_t * node, const Sequence& s)
{
return s.header().compare(node->label) == 0;
}
bool operator==(const Sequence& s, const pll_utree_t * node)
{
return operator==(node, s);
}
<commit_msg>removed get valid range<commit_after>#include "epa_pll_util.hpp"
#include <unordered_map>
#include <algorithm>
#include "pll_util.hpp"
#include "calculation.hpp"
using namespace std;
void link_tree_msa(pll_utree_t * tree, pll_partition_t * partition,
const MSA& msa, const unsigned int num_tip_nodes,
vector<Range> &valid_map)
{
// obtain pointers to all tip nodes
vector<pll_utree_t*> tip_nodes(num_tip_nodes);
pll_utree_query_tipnodes(tree, &tip_nodes[0]);
// and associate the sequences from the MSA file with the correct tips
/* create a hash table of size num_tip_nodes */
unordered_map<string, unsigned int> map; // mapping labels to tip clv indices
/* populate the hash table with tree tip labels */
for (unsigned int i = 0; i < num_tip_nodes; ++i)
map[tip_nodes[i]->label] = i;
/* find sequences in hash table and link them with the corresponding taxa */
for (auto const &s : msa)
{
auto map_value = map.find(s.header());
auto clv_index = map_value->second;
if (map_value == map.end())
throw runtime_error{string("Sequence with header does not appear in the tree: ") + s.header()};
// associates the sequence with the tip by calculating the tips clv buffers
pll_set_tip_states(partition, clv_index, pll_map_nt, s.sequence().c_str());
// TODO improvement?
// remember the valid-range of the sequence, indexed by tip clv index
valid_map[clv_index] = get_valid_range(s.sequence());
}
};
void precompute_clvs(pll_utree_t * tree, pll_partition_t * partition, const Tree_Numbers& nums)
{
unsigned int num_matrices, num_ops;
/* various buffers for creating a postorder traversal and operations structures */
vector<pll_utree_t*> travbuffer(nums.nodes);
vector<double> branch_lengths(nums.branches);
vector<unsigned int> matrix_indices(nums.branches);
vector<pll_operation_t> operations(nums.nodes);
// get a list of all tip nodes
vector<pll_utree_t*> tip_nodes(nums.tip_nodes);
pll_utree_query_tipnodes(tree, &tip_nodes[0]);
/* adjust clv indices such that every direction has its own */
set_unique_clv_indices(tree, nums.tip_nodes);
for (auto node : tip_nodes)
{
/* perform a partial postorder traversal of the unrooted tree starting at the current tip
and returning every node whose clv in the direction of the tip hasn't been calculated yet*/
unsigned int traversal_size;
if(pll_utree_traverse(node->back, cb_partial_traversal, &travbuffer[0], &traversal_size)
!= PLL_SUCCESS)
throw runtime_error{"Function pll_utree_traverse() requires inner nodes as parameters"};
/* given the computed traversal descriptor, generate the operations
structure, and the corresponding probability matrix indices that
may need recomputing */
pll_utree_create_operations(&travbuffer[0],
traversal_size,
&branch_lengths[0],
&matrix_indices[0],
&operations[0],
&num_matrices,
&num_ops);
pll_update_prob_matrices(partition,
0, // use model 0
&matrix_indices[0],// matrices to update
&branch_lengths[0],
num_matrices); // how many should be updated
/* use the operations array to compute all num_ops inner CLVs. Operations
will be carried out sequentially starting from operation 0 towrds num_ops-1 */
pll_update_partials(partition, &operations[0], num_ops);
}
}
void split_combined_msa(MSA& source, MSA& target, pll_utree_t * tree, unsigned int num_tip_nodes)
{
vector<pll_utree_t*> tip_nodes(num_tip_nodes);
pll_utree_query_tipnodes(tree, &tip_nodes[0]);
auto falsegroup_begin = partition(source.begin(), source.end(),
[&tip_nodes](const Sequence& em)
{
return find(tip_nodes.begin(), tip_nodes.end(), em) != tip_nodes.end();
});
target.num_sites(source.num_sites());
target.move_sequences(falsegroup_begin, source.end());
source.erase(falsegroup_begin, source.end());
}
bool operator==(const pll_utree_t * node, const Sequence& s)
{
return s.header().compare(node->label) == 0;
}
bool operator==(const Sequence& s, const pll_utree_t * node)
{
return operator==(node, s);
}
<|endoftext|> |
<commit_before>#include <xcb/xcb.h>
#include <SFML/Graphics.hpp>
#include <curlpp/cURLpp.hpp>
#include <iostream>
using namespace std;
int main()
{
cout << "If this compiled, then the dependencies work" << endl;
return 0;
}
<commit_msg>Removed test_build duplicate<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "server_raft.h"
#ifdef XAPIAND_CLUSTERING
#include "server.h"
#include <assert.h>
using dispatch_func = void (RaftServer::*)(const std::string&);
RaftServer::RaftServer(const std::shared_ptr<XapiandServer>& server_, ev::loop_ref *loop_, const std::shared_ptr<Raft>& raft_)
: BaseServer(server_, loop_, raft_->sock),
raft(raft_)
{
// accept event actually started in BaseServer::BaseServer
L_EV(this, "Start raft's server accept event (sock=%d)", raft->sock);
L_OBJ(this, "CREATED RAFT SERVER!");
}
RaftServer::~RaftServer()
{
L_OBJ(this, "DELETED RAFT SERVER!");
}
void
RaftServer::raft_server(Raft::Message type, const std::string& message)
{
static const dispatch_func dispatch[] = {
&RaftServer::heartbeat_leader,
&RaftServer::request_vote,
&RaftServer::response_vote,
&RaftServer::leader,
&RaftServer::leadership,
&RaftServer::reset,
};
if (static_cast<size_t>(type) >= sizeof(dispatch) / sizeof(dispatch[0])) {
std::string errmsg("Unexpected message type ");
errmsg += std::to_string(toUType(type));
throw MSG_InvalidArgumentError(errmsg);
}
(this->*(dispatch[toUType(type)]))(message);
}
void
RaftServer::heartbeat_leader(const std::string& message)
{
const char *p = message.data();
const char *p_end = p + message.size();
Node remote_node = Node::unserialise(&p, p_end);
if (local_node.region != remote_node.region) {
return;
}
raft->reset_leader_election_timeout();
if (raft->leader != remote_node) {
L_RAFT(this, "Request the raft server's configuration!");
raft->send_message(Raft::Message::LEADERSHIP, local_node.serialise());
}
L_RAFT_PROTO(this, "Listening %s's heartbeat in timestamp: %f!", remote_node.name.c_str(), raft->last_activity);
}
void
RaftServer::request_vote(const std::string& message)
{
const char *p = message.data();
const char *p_end = p + message.size();
Node remote_node = Node::unserialise(&p, p_end);
if (local_node.region != remote_node.region) {
return;
}
uint64_t remote_term = unserialise_length(&p, p_end);
L_RAFT(this, "remote_term: %llu local_term: %llu", remote_term, raft->term);
if (remote_term > raft->term) {
if (raft->state == Raft::State::LEADER && remote_node != local_node) {
L_ERR(this, "ERROR: Remote node %s with term: %llu does not recognize this node with term: %llu as a leader. Therefore, this node will reset!", remote_node.name.c_str(), remote_term, raft->term);
raft->reset();
}
raft->votedFor = remote_node;
raft->term = remote_term;
L_RAFT(this, "It Vote for %s", raft->votedFor.name.c_str());
raft->send_message(Raft::Message::RESPONSE_VOTE, remote_node.serialise() +
serialise_length(true) + serialise_length(remote_term));
} else {
if (raft->state == Raft::State::LEADER && remote_node != local_node) {
L_ERR(this, "ERROR: Remote node %s with term: %llu does not recognize this node with term: %llu as a leader. Therefore, remote node will reset!", remote_node.name.c_str(), remote_term, raft->term);
raft->send_message(Raft::Message::RESET, remote_node.serialise());
return;
}
if (remote_term < raft->term) {
L_RAFT(this, "Vote for %s", raft->votedFor.name.c_str());
raft->send_message(Raft::Message::RESPONSE_VOTE, remote_node.serialise() +
serialise_length(false) + serialise_length(raft->term));
} else if (raft->votedFor.empty()) {
raft->votedFor = remote_node;
L_RAFT(this, "Vote for %s", raft->votedFor.name.c_str());
raft->send_message(Raft::Message::RESPONSE_VOTE, remote_node.serialise() +
serialise_length(true) + serialise_length(raft->term));
} else {
L_RAFT(this, "Vote for %s", raft->votedFor.name.c_str());
raft->send_message(Raft::Message::RESPONSE_VOTE, remote_node.serialise() +
serialise_length(false) + serialise_length(raft->term));
}
}
}
void
RaftServer::response_vote(const std::string& message)
{
const char *p = message.data();
const char *p_end = p + message.size();
Node remote_node = Node::unserialise(&p, p_end);
if (local_node.region != remote_node.region) {
return;
}
if (remote_node == local_node && raft->state == Raft::State::CANDIDATE) {
bool vote = unserialise_length(&p, p_end);
if (vote) {
++raft->votes;
L_RAFT(this, "Number of servers: %d; Votes received: %d", raft->number_servers.load(), raft->votes);
if (raft->votes > raft->number_servers / 2) {
raft->state = Raft::State::LEADER;
if (raft->leader != local_node) {
raft->leader = local_node;
L_INFO(this, "Raft: New leader is %s (1)", raft->leader.name.c_str());
}
raft->start_leader_heartbeat();
}
return;
}
uint64_t remote_term = unserialise_length(&p, p_end);
if (raft->term < remote_term) {
raft->term = remote_term;
raft->state = Raft::State::FOLLOWER;
return;
}
}
}
void
RaftServer::leader(const std::string& message)
{
const char *p = message.data();
const char *p_end = p + message.size();
Node remote_node = Node::unserialise(&p, p_end);
if (local_node.region != remote_node.region) {
return;
}
if (raft->state == Raft::State::LEADER) {
if (remote_node != local_node) {
L_CRIT(this, "I'm leader, other responded as leader!");
raft->reset();
}
return;
}
raft->state = Raft::State::FOLLOWER;
raft->number_servers.store(unserialise_length(&p, p_end));
raft->term = unserialise_length(&p, p_end);
if (raft->leader != remote_node) {
raft->leader = remote_node;
L_INFO(this, "Raft: New leader is %s (2)", raft->leader.name.c_str());
}
raft->reset_leader_election_timeout();
}
void
RaftServer::leadership(const std::string& message)
{
const char *p = message.data();
const char *p_end = p + message.size();
Node remote_node = Node::unserialise(&p, p_end);
if (local_node.region != remote_node.region) {
return;
}
if (raft->state == Raft::State::LEADER) {
L_DEBUG(this, "Sending Data!");
raft->send_message(Raft::Message::LEADER, local_node.serialise() +
serialise_length(raft->number_servers) +
serialise_length(raft->term));
}
}
void
RaftServer::reset(const std::string& message)
{
const char *p = message.data();
const char *p_end = p + message.size();
Node remote_node = Node::unserialise(&p, p_end);
if (local_node.region != remote_node.region) {
return;
}
if (local_node == remote_node) {
raft->reset();
}
}
void
RaftServer::io_accept_cb(ev::io& watcher, int revents)
{
L_EV_BEGIN(this, "RaftServer::io_accept_cb:BEGIN");
if (EV_ERROR & revents) {
L_EV(this, "ERROR: got invalid raft event (sock=%d): %s", raft->sock, strerror(errno));
L_EV_END(this, "RaftServer::io_accept_cb:END");
return;
}
assert(raft->sock == watcher.fd || raft->sock == -1);
if (revents & EV_READ) {
while (manager()->state == XapiandManager::State::READY) {
try {
std::string message;
Raft::Message type = static_cast<Raft::Message>(raft->get_message(message, static_cast<char>(Raft::Message::MAX)));
if (type != Raft::Message::HEARTBEAT_LEADER) {
L_RAFT(this, ">> get_message(%s)", Raft::MessageNames[static_cast<int>(type)]);
}
L_RAFT_PROTO(this, "message: '%s'", repr(message).c_str());
raft_server(type, message);
} catch (DummyException) {
break; // no message
} catch (const Exception& exc) {
L_WARNING(this, "WARNING: %s", *exc.get_context() ? exc.get_context() : "Unkown Exception!");
break;
} catch (...) {
L_EV_END(this, "RaftServer::io_accept_cb:END %lld", now);
throw;
}
}
}
L_EV_END(this, "RaftServer::io_accept_cb:END %lld", now);
}
#endif
<commit_msg>Promote "New leader" messages to L_NOTICE<commit_after>/*
* Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "server_raft.h"
#ifdef XAPIAND_CLUSTERING
#include "server.h"
#include <assert.h>
using dispatch_func = void (RaftServer::*)(const std::string&);
RaftServer::RaftServer(const std::shared_ptr<XapiandServer>& server_, ev::loop_ref *loop_, const std::shared_ptr<Raft>& raft_)
: BaseServer(server_, loop_, raft_->sock),
raft(raft_)
{
// accept event actually started in BaseServer::BaseServer
L_EV(this, "Start raft's server accept event (sock=%d)", raft->sock);
L_OBJ(this, "CREATED RAFT SERVER!");
}
RaftServer::~RaftServer()
{
L_OBJ(this, "DELETED RAFT SERVER!");
}
void
RaftServer::raft_server(Raft::Message type, const std::string& message)
{
static const dispatch_func dispatch[] = {
&RaftServer::heartbeat_leader,
&RaftServer::request_vote,
&RaftServer::response_vote,
&RaftServer::leader,
&RaftServer::leadership,
&RaftServer::reset,
};
if (static_cast<size_t>(type) >= sizeof(dispatch) / sizeof(dispatch[0])) {
std::string errmsg("Unexpected message type ");
errmsg += std::to_string(toUType(type));
throw MSG_InvalidArgumentError(errmsg);
}
(this->*(dispatch[toUType(type)]))(message);
}
void
RaftServer::heartbeat_leader(const std::string& message)
{
const char *p = message.data();
const char *p_end = p + message.size();
Node remote_node = Node::unserialise(&p, p_end);
if (local_node.region != remote_node.region) {
return;
}
raft->reset_leader_election_timeout();
if (raft->leader != remote_node) {
L_RAFT(this, "Request the raft server's configuration!");
raft->send_message(Raft::Message::LEADERSHIP, local_node.serialise());
}
L_RAFT_PROTO(this, "Listening %s's heartbeat in timestamp: %f!", remote_node.name.c_str(), raft->last_activity);
}
void
RaftServer::request_vote(const std::string& message)
{
const char *p = message.data();
const char *p_end = p + message.size();
Node remote_node = Node::unserialise(&p, p_end);
if (local_node.region != remote_node.region) {
return;
}
uint64_t remote_term = unserialise_length(&p, p_end);
L_RAFT(this, "remote_term: %llu local_term: %llu", remote_term, raft->term);
if (remote_term > raft->term) {
if (raft->state == Raft::State::LEADER && remote_node != local_node) {
L_ERR(this, "ERROR: Remote node %s with term: %llu does not recognize this node with term: %llu as a leader. Therefore, this node will reset!", remote_node.name.c_str(), remote_term, raft->term);
raft->reset();
}
raft->votedFor = remote_node;
raft->term = remote_term;
L_RAFT(this, "It Vote for %s", raft->votedFor.name.c_str());
raft->send_message(Raft::Message::RESPONSE_VOTE, remote_node.serialise() +
serialise_length(true) + serialise_length(remote_term));
} else {
if (raft->state == Raft::State::LEADER && remote_node != local_node) {
L_ERR(this, "ERROR: Remote node %s with term: %llu does not recognize this node with term: %llu as a leader. Therefore, remote node will reset!", remote_node.name.c_str(), remote_term, raft->term);
raft->send_message(Raft::Message::RESET, remote_node.serialise());
return;
}
if (remote_term < raft->term) {
L_RAFT(this, "Vote for %s", raft->votedFor.name.c_str());
raft->send_message(Raft::Message::RESPONSE_VOTE, remote_node.serialise() +
serialise_length(false) + serialise_length(raft->term));
} else if (raft->votedFor.empty()) {
raft->votedFor = remote_node;
L_RAFT(this, "Vote for %s", raft->votedFor.name.c_str());
raft->send_message(Raft::Message::RESPONSE_VOTE, remote_node.serialise() +
serialise_length(true) + serialise_length(raft->term));
} else {
L_RAFT(this, "Vote for %s", raft->votedFor.name.c_str());
raft->send_message(Raft::Message::RESPONSE_VOTE, remote_node.serialise() +
serialise_length(false) + serialise_length(raft->term));
}
}
}
void
RaftServer::response_vote(const std::string& message)
{
const char *p = message.data();
const char *p_end = p + message.size();
Node remote_node = Node::unserialise(&p, p_end);
if (local_node.region != remote_node.region) {
return;
}
if (remote_node == local_node && raft->state == Raft::State::CANDIDATE) {
bool vote = unserialise_length(&p, p_end);
if (vote) {
++raft->votes;
L_RAFT(this, "Number of servers: %d; Votes received: %d", raft->number_servers.load(), raft->votes);
if (raft->votes > raft->number_servers / 2) {
raft->state = Raft::State::LEADER;
if (raft->leader != local_node) {
raft->leader = local_node;
L_NOTICE(this, "Raft: New leader is %s (1)", raft->leader.name.c_str());
}
raft->start_leader_heartbeat();
}
return;
}
uint64_t remote_term = unserialise_length(&p, p_end);
if (raft->term < remote_term) {
raft->term = remote_term;
raft->state = Raft::State::FOLLOWER;
return;
}
}
}
void
RaftServer::leader(const std::string& message)
{
const char *p = message.data();
const char *p_end = p + message.size();
Node remote_node = Node::unserialise(&p, p_end);
if (local_node.region != remote_node.region) {
return;
}
if (raft->state == Raft::State::LEADER) {
if (remote_node != local_node) {
L_CRIT(this, "I'm leader, other responded as leader!");
raft->reset();
}
return;
}
raft->state = Raft::State::FOLLOWER;
raft->number_servers.store(unserialise_length(&p, p_end));
raft->term = unserialise_length(&p, p_end);
if (raft->leader != remote_node) {
raft->leader = remote_node;
L_NOTICE(this, "Raft: New leader is %s (2)", raft->leader.name.c_str());
}
raft->reset_leader_election_timeout();
}
void
RaftServer::leadership(const std::string& message)
{
const char *p = message.data();
const char *p_end = p + message.size();
Node remote_node = Node::unserialise(&p, p_end);
if (local_node.region != remote_node.region) {
return;
}
if (raft->state == Raft::State::LEADER) {
L_DEBUG(this, "Sending Data!");
raft->send_message(Raft::Message::LEADER, local_node.serialise() +
serialise_length(raft->number_servers) +
serialise_length(raft->term));
}
}
void
RaftServer::reset(const std::string& message)
{
const char *p = message.data();
const char *p_end = p + message.size();
Node remote_node = Node::unserialise(&p, p_end);
if (local_node.region != remote_node.region) {
return;
}
if (local_node == remote_node) {
raft->reset();
}
}
void
RaftServer::io_accept_cb(ev::io& watcher, int revents)
{
L_EV_BEGIN(this, "RaftServer::io_accept_cb:BEGIN");
if (EV_ERROR & revents) {
L_EV(this, "ERROR: got invalid raft event (sock=%d): %s", raft->sock, strerror(errno));
L_EV_END(this, "RaftServer::io_accept_cb:END");
return;
}
assert(raft->sock == watcher.fd || raft->sock == -1);
if (revents & EV_READ) {
while (manager()->state == XapiandManager::State::READY) {
try {
std::string message;
Raft::Message type = static_cast<Raft::Message>(raft->get_message(message, static_cast<char>(Raft::Message::MAX)));
if (type != Raft::Message::HEARTBEAT_LEADER) {
L_RAFT(this, ">> get_message(%s)", Raft::MessageNames[static_cast<int>(type)]);
}
L_RAFT_PROTO(this, "message: '%s'", repr(message).c_str());
raft_server(type, message);
} catch (DummyException) {
break; // no message
} catch (const Exception& exc) {
L_WARNING(this, "WARNING: %s", *exc.get_context() ? exc.get_context() : "Unkown Exception!");
break;
} catch (...) {
L_EV_END(this, "RaftServer::io_accept_cb:END %lld", now);
throw;
}
}
}
L_EV_END(this, "RaftServer::io_accept_cb:END %lld", now);
}
#endif
<|endoftext|> |
<commit_before>/* Authors: Don Sanders <[email protected]>
Copyright (C) 2000 Don Sanders <[email protected]>
Includes KMLittleProgressDlg which is based on KIOLittleProgressDlg
by Matt Koss <[email protected]>
License GPL
*/
#include "kmbroadcaststatus.h"
#include "kmbroadcaststatus.moc"
#include "ssllabel.h"
using KMail::SSLLabel;
#include <kprogress.h>
#include <kdebug.h>
#include <qlabel.h>
#include <qpushbutton.h>
#include <qtooltip.h>
#include <klocale.h>
#include <qlayout.h>
#include <qwidgetstack.h>
#include <qdatetime.h>
//-----------------------------------------------------------------------------
KMBroadcastStatus* KMBroadcastStatus::instance_ = 0;
KMBroadcastStatus* KMBroadcastStatus::instance()
{
if (!instance_)
instance_ = new KMBroadcastStatus();
return instance_;
}
KMBroadcastStatus::KMBroadcastStatus()
{
reset();
}
void KMBroadcastStatus::setUsingSSL( bool isUsing )
{
emit signalUsingSSL( isUsing );
}
void KMBroadcastStatus::setStatusMsg( const QString& message )
{
emit statusMsg( message );
}
void KMBroadcastStatus::setStatusMsgWithTimestamp( const QString& message )
{
KLocale* locale = KGlobal::locale();
setStatusMsg( i18n( "%1 is a time, %2 is a status message", "[%1] %2" )
.arg( locale->formatTime( QTime::currentTime(),
true /* with seconds */ ) )
.arg( message ) );
}
void KMBroadcastStatus::setStatusMsgTransmissionCompleted( int numMessages,
int numBytes,
int numBytesRead,
int numBytesToRead,
bool mLeaveOnServer )
{
QString statusMsg;
if( numMessages > 0 ) {
if( numBytes != -1 ) {
if( ( numBytesToRead != numBytes ) && mLeaveOnServer )
statusMsg = i18n( "Transmission complete. %n new message in %1 KB "
"(%2 KB remaining on the server).",
"Transmission complete. %n new messages in %1 KB "
"(%2 KB remaining on the server).",
numMessages )
.arg( numBytesRead / 1024 )
.arg( numBytes / 1024 );
else
statusMsg = i18n( "Transmission complete. %n message in %1 KB.",
"Transmission complete. %n messages in %1 KB.",
numMessages )
.arg( numBytesRead / 1024 );
}
else
statusMsg = i18n( "Transmission complete. %n new message.",
"Transmission complete. %n new messages.",
numMessages );
}
else
statusMsg = i18n( "Transmission complete. No new messages." );
setStatusMsgWithTimestamp( statusMsg );
}
void KMBroadcastStatus::setStatusMsgTransmissionCompleted( const QString& account,
int numMessages,
int numBytes,
int numBytesRead,
int numBytesToRead,
bool mLeaveOnServer )
{
QString statusMsg;
if( numMessages > 0 ) {
if( numBytes != -1 ) {
if( ( numBytesToRead != numBytes ) && mLeaveOnServer )
statusMsg = i18n( "Transmission for account %3 complete. "
"%n new message in %1 KB "
"(%2 KB remaining on the server).",
"Transmission for account %3 complete. "
"%n new messages in %1 KB "
"(%2 KB remaining on the server).",
numMessages )
.arg( numBytesRead / 1024 )
.arg( numBytes / 1024 )
.arg( account );
else
statusMsg = i18n( "Transmission for account %2 complete. "
"%n message in %1 KB.",
"Transmission for account %2 complete. "
"%n messages in %1 KB.",
numMessages )
.arg( numBytesRead / 1024 )
.arg( account );
}
else
statusMsg = i18n( "Transmission for account %1 complete. "
"%n new message.",
"Transmission for account %1 complete. "
"%n new messages.",
numMessages )
.arg( account );
}
else
statusMsg = i18n( "Transmission for account %1 complete. No new messages.")
.arg( account );
setStatusMsgWithTimestamp( statusMsg );
}
void KMBroadcastStatus::setStatusProgressEnable( const QString &id,
bool enable )
{
bool wasEmpty = ids.isEmpty();
if (enable) ids.insert(id, 0);
else ids.remove(id);
if (!wasEmpty && !ids.isEmpty())
setStatusProgressPercent("", 0);
else
emit statusProgressEnable( !ids.isEmpty() );
}
void KMBroadcastStatus::setStatusProgressPercent( const QString &id,
unsigned long percent )
{
if (!id.isEmpty() && ids.contains(id)) ids.insert(id, percent);
unsigned long sum = 0, count = 0;
for (QMap<QString,unsigned long>::iterator it = ids.begin();
it != ids.end(); it++)
{
sum += *it;
count++;
}
emit statusProgressPercent( count ? (sum / count) : sum );
}
void KMBroadcastStatus::reset()
{
abortRequested_ = false;
if (ids.isEmpty())
emit resetRequested();
}
bool KMBroadcastStatus::abortRequested()
{
return abortRequested_;
}
void KMBroadcastStatus::requestAbort()
{
abortRequested_ = true;
emit signalAbortRequested();
}
//-----------------------------------------------------------------------------
KMLittleProgressDlg::KMLittleProgressDlg( QWidget* parent, bool button )
: QFrame( parent )
{
m_bShowButton = button;
int w = fontMetrics().width( " 999.9 kB/s 00:00:01 " ) + 8;
box = new QHBoxLayout( this, 0, 0 );
m_pButton = new QPushButton( "X", this );
m_pButton->setMinimumWidth(fontMetrics().width("XXXX"));
box->addWidget( m_pButton );
stack = new QWidgetStack( this );
stack->setMaximumHeight( fontMetrics().height() );
box->addWidget( stack );
m_sslLabel = new SSLLabel( this );
box->addWidget( m_sslLabel );
QToolTip::add( m_pButton, i18n("Cancel job") );
m_pProgressBar = new KProgress( this );
m_pProgressBar->setLineWidth( 1 );
m_pProgressBar->setFrameStyle( QFrame::Box );
m_pProgressBar->installEventFilter( this );
m_pProgressBar->setMinimumWidth( w );
stack->addWidget( m_pProgressBar, 1 );
m_pLabel = new QLabel( "", this );
m_pLabel->setAlignment( AlignHCenter | AlignVCenter );
m_pLabel->installEventFilter( this );
m_pLabel->setMinimumWidth( w );
stack->addWidget( m_pLabel, 2 );
m_pButton->setMaximumHeight( fontMetrics().height() );
setMinimumWidth( minimumSizeHint().width() );
mode = None;
setMode();
connect( m_pButton, SIGNAL( clicked() ),
KMBroadcastStatus::instance(), SLOT( requestAbort() ));
}
void KMLittleProgressDlg::slotEnable( bool enabled )
{
if (enabled) {
m_pButton->setDown( false );
mode = Progress;
kdDebug(5006) << "enable progress" << endl;
}
else {
mode = None;
}
setMode();
}
void KMLittleProgressDlg::slotSetSSL( bool ssl )
{
m_sslLabel->setEncrypted( ssl );
}
void KMLittleProgressDlg::setMode() {
switch ( mode ) {
case None:
if ( m_bShowButton ) {
m_pButton->hide();
}
m_sslLabel->setState( SSLLabel::Done );
// show the empty label in order to make the status bar look better
stack->show();
stack->raiseWidget( m_pLabel );
break;
case Clean:
if ( m_bShowButton ) {
m_pButton->hide();
}
m_sslLabel->setState( SSLLabel::Clean );
// show the empty label in order to make the status bar look better
stack->show();
stack->raiseWidget( m_pLabel );
break;
case Label:
if ( m_bShowButton ) {
m_pButton->show();
}
m_sslLabel->setState( m_sslLabel->lastState() );
stack->show();
stack->raiseWidget( m_pLabel );
break;
case Progress:
if (stack->isVisible()) {
stack->show();
stack->raiseWidget( m_pProgressBar );
if ( m_bShowButton ) {
m_pButton->show();
}
m_sslLabel->setState( m_sslLabel->lastState() );
}
break;
}
}
void KMLittleProgressDlg::slotJustPercent( unsigned long _percent )
{
m_pProgressBar->setValue( _percent );
}
void KMLittleProgressDlg::slotClean()
{
m_pProgressBar->setValue( 0 );
m_pLabel->clear();
mode = Clean;
setMode();
}
bool KMLittleProgressDlg::eventFilter( QObject *, QEvent *ev )
{
if ( ev->type() == QEvent::MouseButtonPress ) {
QMouseEvent *e = (QMouseEvent*)ev;
if ( e->button() == LeftButton ) { // toggle view on left mouse button
if ( mode == Label ) {
mode = Progress;
} else if ( mode == Progress ) {
mode = Label;
}
setMode();
return true;
}
}
return false;
}
<commit_msg>Marc and I agreed on it, so commiting<commit_after>/* Authors: Don Sanders <[email protected]>
Copyright (C) 2000 Don Sanders <[email protected]>
Includes KMLittleProgressDlg which is based on KIOLittleProgressDlg
by Matt Koss <[email protected]>
License GPL
*/
#include "kmbroadcaststatus.h"
#include "kmbroadcaststatus.moc"
#include "ssllabel.h"
using KMail::SSLLabel;
#include <kprogress.h>
#include <kdebug.h>
#include <qlabel.h>
#include <qpushbutton.h>
#include <qtooltip.h>
#include <klocale.h>
#include <qlayout.h>
#include <qwidgetstack.h>
#include <qdatetime.h>
//-----------------------------------------------------------------------------
KMBroadcastStatus* KMBroadcastStatus::instance_ = 0;
KMBroadcastStatus* KMBroadcastStatus::instance()
{
if (!instance_)
instance_ = new KMBroadcastStatus();
return instance_;
}
KMBroadcastStatus::KMBroadcastStatus()
{
reset();
}
void KMBroadcastStatus::setUsingSSL( bool isUsing )
{
emit signalUsingSSL( isUsing );
}
void KMBroadcastStatus::setStatusMsg( const QString& message )
{
emit statusMsg( message );
}
void KMBroadcastStatus::setStatusMsgWithTimestamp( const QString& message )
{
KLocale* locale = KGlobal::locale();
setStatusMsg( i18n( "%1 is a time, %2 is a status message", "[%1] %2" )
.arg( locale->formatTime( QTime::currentTime(),
true /* with seconds */ ) )
.arg( message ) );
}
void KMBroadcastStatus::setStatusMsgTransmissionCompleted( int numMessages,
int numBytes,
int numBytesRead,
int numBytesToRead,
bool mLeaveOnServer )
{
QString statusMsg;
if( numMessages > 0 ) {
if( numBytes != -1 ) {
if( ( numBytesToRead != numBytes ) && mLeaveOnServer )
statusMsg = i18n( "Transmission complete. %n new message in %1 KB "
"(%2 KB remaining on the server).",
"Transmission complete. %n new messages in %1 KB "
"(%2 KB remaining on the server).",
numMessages )
.arg( numBytesRead / 1024 )
.arg( numBytes / 1024 );
else
statusMsg = i18n( "Transmission complete. %n message in %1 KB.",
"Transmission complete. %n messages in %1 KB.",
numMessages )
.arg( numBytesRead / 1024 );
}
else
statusMsg = i18n( "Transmission complete. %n new message.",
"Transmission complete. %n new messages.",
numMessages );
}
else
statusMsg = i18n( "Transmission complete. No new messages." );
setStatusMsgWithTimestamp( statusMsg );
}
void KMBroadcastStatus::setStatusMsgTransmissionCompleted( const QString& account,
int numMessages,
int numBytes,
int numBytesRead,
int numBytesToRead,
bool mLeaveOnServer )
{
QString statusMsg;
if( numMessages > 0 ) {
if( numBytes != -1 ) {
if( ( numBytesToRead != numBytes ) && mLeaveOnServer )
statusMsg = i18n( "Transmission for account %3 complete. "
"%n new message in %1 KB "
"(%2 KB remaining on the server).",
"Transmission for account %3 complete. "
"%n new messages in %1 KB "
"(%2 KB remaining on the server).",
numMessages )
.arg( numBytesRead / 1024 )
.arg( numBytes / 1024 )
.arg( account );
else
statusMsg = i18n( "Transmission for account %2 complete. "
"%n message in %1 KB.",
"Transmission for account %2 complete. "
"%n messages in %1 KB.",
numMessages )
.arg( numBytesRead / 1024 )
.arg( account );
}
else
statusMsg = i18n( "Transmission for account %1 complete. "
"%n new message.",
"Transmission for account %1 complete. "
"%n new messages.",
numMessages )
.arg( account );
}
else
statusMsg = i18n( "Transmission for account %1 complete. No new messages.")
.arg( account );
setStatusMsgWithTimestamp( statusMsg );
}
void KMBroadcastStatus::setStatusProgressEnable( const QString &id,
bool enable )
{
bool wasEmpty = ids.isEmpty();
if (enable) ids.insert(id, 0);
else ids.remove(id);
if (!wasEmpty && !ids.isEmpty())
setStatusProgressPercent("", 0);
else
emit statusProgressEnable( !ids.isEmpty() );
}
void KMBroadcastStatus::setStatusProgressPercent( const QString &id,
unsigned long percent )
{
if (!id.isEmpty() && ids.contains(id)) ids.insert(id, percent);
unsigned long sum = 0, count = 0;
for (QMap<QString,unsigned long>::iterator it = ids.begin();
it != ids.end(); it++)
{
sum += *it;
count++;
}
emit statusProgressPercent( count ? (sum / count) : sum );
}
void KMBroadcastStatus::reset()
{
abortRequested_ = false;
if (ids.isEmpty())
emit resetRequested();
}
bool KMBroadcastStatus::abortRequested()
{
return abortRequested_;
}
void KMBroadcastStatus::requestAbort()
{
abortRequested_ = true;
emit signalAbortRequested();
}
//-----------------------------------------------------------------------------
KMLittleProgressDlg::KMLittleProgressDlg( QWidget* parent, bool button )
: QFrame( parent )
{
m_bShowButton = button;
int w = fontMetrics().width( " 999.9 kB/s 00:00:01 " ) + 8;
box = new QHBoxLayout( this, 0, 0 );
m_pButton = new QPushButton( "X", this );
m_pButton->setMinimumWidth(fontMetrics().width("XXXX"));
box->addWidget( m_pButton );
stack = new QWidgetStack( this );
stack->setMaximumHeight( fontMetrics().height() );
box->addWidget( stack );
m_sslLabel = new SSLLabel( this );
box->addWidget( m_sslLabel );
QToolTip::add( m_pButton, i18n("Cancel job") );
m_pProgressBar = new KProgress( this );
m_pProgressBar->setLineWidth( 1 );
m_pProgressBar->setFrameStyle( QFrame::Box );
m_pProgressBar->installEventFilter( this );
m_pProgressBar->setMinimumWidth( w );
stack->addWidget( m_pProgressBar, 1 );
m_pLabel = new QLabel( "", this );
m_pLabel->setAlignment( AlignHCenter | AlignVCenter );
m_pLabel->installEventFilter( this );
m_pLabel->setMinimumWidth( w );
stack->addWidget( m_pLabel, 2 );
m_pButton->setMaximumHeight( fontMetrics().height() );
setMinimumWidth( minimumSizeHint().width() );
mode = None;
setMode();
connect( m_pButton, SIGNAL( clicked() ),
KMBroadcastStatus::instance(), SLOT( requestAbort() ));
}
void KMLittleProgressDlg::slotEnable( bool enabled )
{
if (enabled) {
if (mode == Progress) // it's already enabled
return;
m_pButton->setDown( false );
mode = Progress;
kdDebug(5006) << "enable progress" << endl;
}
else {
if (mode == None)
return;
mode = None;
}
setMode();
}
void KMLittleProgressDlg::slotSetSSL( bool ssl )
{
m_sslLabel->setEncrypted( ssl );
}
void KMLittleProgressDlg::setMode() {
switch ( mode ) {
case None:
if ( m_bShowButton ) {
m_pButton->hide();
}
m_sslLabel->setState( SSLLabel::Done );
// show the empty label in order to make the status bar look better
stack->show();
stack->raiseWidget( m_pLabel );
break;
case Clean:
if ( m_bShowButton ) {
m_pButton->hide();
}
m_sslLabel->setState( SSLLabel::Clean );
// show the empty label in order to make the status bar look better
stack->show();
stack->raiseWidget( m_pLabel );
break;
case Label:
if ( m_bShowButton ) {
m_pButton->show();
}
m_sslLabel->setState( m_sslLabel->lastState() );
stack->show();
stack->raiseWidget( m_pLabel );
break;
case Progress:
if (stack->isVisible()) {
stack->show();
stack->raiseWidget( m_pProgressBar );
if ( m_bShowButton ) {
m_pButton->show();
}
m_sslLabel->setState( m_sslLabel->lastState() );
}
break;
}
}
void KMLittleProgressDlg::slotJustPercent( unsigned long _percent )
{
m_pProgressBar->setValue( _percent );
}
void KMLittleProgressDlg::slotClean()
{
m_pProgressBar->setValue( 0 );
m_pLabel->clear();
mode = Clean;
setMode();
}
bool KMLittleProgressDlg::eventFilter( QObject *, QEvent *ev )
{
if ( ev->type() == QEvent::MouseButtonPress ) {
QMouseEvent *e = (QMouseEvent*)ev;
if ( e->button() == LeftButton ) { // toggle view on left mouse button
if ( mode == Label ) {
mode = Progress;
} else if ( mode == Progress ) {
mode = Label;
}
setMode();
return true;
}
}
return false;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: scmod.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: rt $ $Date: 2003-09-19 08:20:57 $
*
* 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 SC_SCMOD_HXX
#define SC_SCMOD_HXX
#ifndef SC_SCDLL_HXX
#include "scdll.hxx"
#endif
#ifndef _TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#ifndef SC_SCGLOB_HXX
#include "global.hxx" // ScInputMode
#endif
#ifndef SC_MARKDATA_HXX //@05.01.98
#include "markdata.hxx" //ScMarkData
#endif
#ifndef SC_SHELLIDS_HXX
#include "shellids.hxx"
#endif
class KeyEvent;
class SdrModel;
class SdrView;
class EditView;
class SfxErrorHandler;
class SvxErrorHandler;
class SvtAccessibilityOptions;
class SvtCTLOptions;
namespace svtools { class ColorConfig; }
class ScRange;
class ScDocument;
class ScViewCfg;
class ScDocCfg;
class ScAppCfg;
class ScInputCfg;
class ScPrintCfg;
class ScViewOptions;
class ScDocOptions;
class ScAppOptions;
class ScInputOptions;
class ScPrintOptions;
class ScInputHandler;
class ScInputWindow;
class ScTabViewShell;
class ScFunctionDlg;
class ScArgDlgBase;
class ScTeamDlg;
class ScEditFunctionDlg;
class ScMessagePool;
class EditFieldInfo;
class ScNavipiCfg;
class ScFormEditData;
class ScTransferObj;
class ScDrawTransferObj;
class ScSelectionTransferObj;
//==================================================================
// for internal Drag&Drop:
#define SC_DROP_NAVIGATOR 1
#define SC_DROP_TABLE 2
struct ScDragData
{
ScTransferObj* pCellTransfer;
ScDrawTransferObj* pDrawTransfer;
String aLinkDoc;
String aLinkTable;
String aLinkArea;
ScDocument* pJumpLocalDoc;
String aJumpTarget;
String aJumpText;
};
struct ScClipData
{
ScTransferObj* pCellClipboard;
ScDrawTransferObj* pDrawClipboard;
};
//==================================================================
class ScModule: public SfxModule, public SfxListener
{
Timer aIdleTimer;
Timer aSpellTimer;
ScDragData aDragData;
ScClipData aClipData;
ScSelectionTransferObj* pSelTransfer;
ScMessagePool* pMessagePool;
// globalen InputHandler gibt's nicht mehr, jede View hat einen
ScInputHandler* pRefInputHandler;
ScTeamDlg* pTeamDlg;
ScViewCfg* pViewCfg;
ScDocCfg* pDocCfg;
ScAppCfg* pAppCfg;
ScInputCfg* pInputCfg;
ScPrintCfg* pPrintCfg;
ScNavipiCfg* pNavipiCfg;
svtools::ColorConfig* pColorConfig;
SvtAccessibilityOptions* pAccessOptions;
SvtCTLOptions* pCTLOptions;
SfxErrorHandler* pErrorHdl;
SvxErrorHandler* pSvxErrorHdl;
ScFormEditData* pFormEditData;
USHORT nCurRefDlgId;
BOOL bIsWaterCan;
BOOL bIsInEditCommand;
public:
SFX_DECL_INTERFACE(SCID_APP);
ScModule( SfxObjectFactory* pFact );
virtual ~ScModule();
virtual void FillStatusBar(StatusBar &rBar);
virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
void DeleteCfg();
void CloseDialogs();
// von der Applikation verschoben:
DECL_LINK( IdleHandler, Timer* ); // Timer statt idle
DECL_LINK( SpellTimerHdl, Timer* );
DECL_LINK( CalcFieldValueHdl, EditFieldInfo* );
void Execute( SfxRequest& rReq );
void GetState( SfxItemSet& rSet );
void AnythingChanged();
// Drag & Drop:
const ScDragData& GetDragData() const { return aDragData; }
void SetDragObject( ScTransferObj* pCellObj, ScDrawTransferObj* pDrawObj );
void ResetDragObject();
void SetDragLink( const String& rDoc, const String& rTab, const String& rArea );
void SetDragJump( ScDocument* pLocalDoc,
const String& rTarget, const String& rText );
// clipboard:
const ScClipData& GetClipData() const { return aClipData; }
void SetClipObject( ScTransferObj* pCellObj, ScDrawTransferObj* pDrawObj );
ScDocument* GetClipDoc(); // called from document - should be removed later
// X selection:
ScSelectionTransferObj* GetSelectionTransfer() const { return pSelTransfer; }
void SetSelectionTransfer( ScSelectionTransferObj* pNew );
void SetWaterCan( BOOL bNew ) { bIsWaterCan = bNew; }
BOOL GetIsWaterCan() const { return bIsWaterCan; }
void SetInEditCommand( BOOL bNew ) { bIsInEditCommand = bNew; }
BOOL IsInEditCommand() const { return bIsInEditCommand; }
// Options:
const ScViewOptions& GetViewOptions ();
const ScDocOptions& GetDocOptions ();
const ScAppOptions& GetAppOptions ();
const ScInputOptions& GetInputOptions ();
const ScPrintOptions& GetPrintOptions ();
void SetViewOptions ( const ScViewOptions& rOpt );
void SetDocOptions ( const ScDocOptions& rOpt );
void SetAppOptions ( const ScAppOptions& rOpt );
void SetInputOptions ( const ScInputOptions& rOpt );
void SetPrintOptions ( const ScPrintOptions& rOpt );
void InsertEntryToLRUList(USHORT nFIndex);
void RecentFunctionsChanged();
static void GetSpellSettings( USHORT& rDefLang, USHORT& rCjkLang, USHORT& rCtlLang,
BOOL& rAutoSpell, BOOL& rHideAuto );
static void SetAutoSpellProperty( BOOL bSet );
static void SetHideAutoProperty( BOOL bSet );
static BOOL HasThesaurusLanguage( USHORT nLang );
USHORT GetOptDigitLanguage(); // from CTL options
ScNavipiCfg& GetNavipiCfg();
svtools::ColorConfig& GetColorConfig();
SvtAccessibilityOptions& GetAccessOptions();
SvtCTLOptions& GetCTLOptions();
void ModifyOptions( const SfxItemSet& rOptSet );
// InputHandler:
BOOL IsEditMode(); // nicht bei SC_INPUT_TYPE
BOOL IsInputMode(); // auch bei SC_INPUT_TYPE
void SetInputMode( ScInputMode eMode );
BOOL InputKeyEvent( const KeyEvent& rKEvt, BOOL bStartEdit = FALSE );
void InputEnterHandler( BYTE nBlockMode = 0 );
void InputCancelHandler();
void InputSelection( EditView* pView );
void InputChanged( EditView* pView );
ScInputHandler* GetInputHdl( ScTabViewShell* pViewSh = NULL, BOOL bUseRef = TRUE );
void SetRefInputHdl( ScInputHandler* pNew );
ScInputHandler* GetRefInputHdl();
void SetInputWindow( ScInputWindow* pWin );
void ViewShellGone(ScTabViewShell* pViewSh);
void ViewShellChanged();
// Kommunikation mit Funktionsautopilot
void InputGetSelection( xub_StrLen& rStart, xub_StrLen& rEnd );
void InputSetSelection( xub_StrLen nStart, xub_StrLen nEnd );
void InputReplaceSelection( const String& rStr );
String InputGetFormulaStr();
void ActivateInputWindow( const String* pStr = NULL,
BOOL bMatrix = FALSE );
void InitFormEditData();
void ClearFormEditData();
ScFormEditData* GetFormEditData() { return pFormEditData; }
// Referenzeingabe:
void SetRefDialog( USHORT nId, BOOL bVis, SfxViewFrame* pViewFrm = NULL );
BOOL IsModalMode(SfxObjectShell* pDocSh = NULL);
BOOL IsFormulaMode();
BOOL IsRefDialogOpen();
BOOL IsTableLocked();
void OpenTeamDlg();
void SetTeamDlg( ScTeamDlg* pDlg ) { pTeamDlg = pDlg; }
ScTeamDlg* GetTeamDlg() const { return pTeamDlg; }
void SetReference( const ScRange& rRef, ScDocument* pDoc,
const ScMarkData* pMarkData = NULL );
void AddRefEntry();
void EndReference();
USHORT GetCurRefDlgId() const { return nCurRefDlgId; }
//virtuelle Methoden fuer den Optionendialog
virtual SfxItemSet* CreateItemSet( USHORT nId );
virtual void ApplyItemSet( USHORT nId, const SfxItemSet& rSet );
virtual SfxTabPage* CreateTabPage( USHORT nId, Window* pParent, const SfxItemSet& rSet );
};
#define SC_MOD() ( *(ScModule**) GetAppData(SHL_CALC) )
#endif
<commit_msg>INTEGRATION: CWS os12 (1.12.44); FILE MERGED 2003/10/22 16:46:08 os 1.12.44.2: RESYNC: (1.12-1.13); FILE MERGED 2003/07/09 13:04:26 os 1.12.44.1: #103299# SvxAddressItem removed<commit_after>/*************************************************************************
*
* $RCSfile: scmod.hxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: obo $ $Date: 2004-04-29 16:33:52 $
*
* 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 SC_SCMOD_HXX
#define SC_SCMOD_HXX
#ifndef SC_SCDLL_HXX
#include "scdll.hxx"
#endif
#ifndef _TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#ifndef SC_SCGLOB_HXX
#include "global.hxx" // ScInputMode
#endif
#ifndef SC_MARKDATA_HXX //@05.01.98
#include "markdata.hxx" //ScMarkData
#endif
#ifndef SC_SHELLIDS_HXX
#include "shellids.hxx"
#endif
class KeyEvent;
class SdrModel;
class SdrView;
class EditView;
class SfxErrorHandler;
class SvxErrorHandler;
class SvtAccessibilityOptions;
class SvtCTLOptions;
class SvtUserOptions;
namespace svtools { class ColorConfig; }
class ScRange;
class ScDocument;
class ScViewCfg;
class ScDocCfg;
class ScAppCfg;
class ScInputCfg;
class ScPrintCfg;
class ScViewOptions;
class ScDocOptions;
class ScAppOptions;
class ScInputOptions;
class ScPrintOptions;
class ScInputHandler;
class ScInputWindow;
class ScTabViewShell;
class ScFunctionDlg;
class ScArgDlgBase;
class ScTeamDlg;
class ScEditFunctionDlg;
class ScMessagePool;
class EditFieldInfo;
class ScNavipiCfg;
class ScFormEditData;
class ScTransferObj;
class ScDrawTransferObj;
class ScSelectionTransferObj;
//==================================================================
// for internal Drag&Drop:
#define SC_DROP_NAVIGATOR 1
#define SC_DROP_TABLE 2
struct ScDragData
{
ScTransferObj* pCellTransfer;
ScDrawTransferObj* pDrawTransfer;
String aLinkDoc;
String aLinkTable;
String aLinkArea;
ScDocument* pJumpLocalDoc;
String aJumpTarget;
String aJumpText;
};
struct ScClipData
{
ScTransferObj* pCellClipboard;
ScDrawTransferObj* pDrawClipboard;
};
//==================================================================
class ScModule: public SfxModule, public SfxListener
{
Timer aIdleTimer;
Timer aSpellTimer;
ScDragData aDragData;
ScClipData aClipData;
ScSelectionTransferObj* pSelTransfer;
ScMessagePool* pMessagePool;
// globalen InputHandler gibt's nicht mehr, jede View hat einen
ScInputHandler* pRefInputHandler;
ScTeamDlg* pTeamDlg;
ScViewCfg* pViewCfg;
ScDocCfg* pDocCfg;
ScAppCfg* pAppCfg;
ScInputCfg* pInputCfg;
ScPrintCfg* pPrintCfg;
ScNavipiCfg* pNavipiCfg;
svtools::ColorConfig* pColorConfig;
SvtAccessibilityOptions* pAccessOptions;
SvtCTLOptions* pCTLOptions;
SvtUserOptions* pUserOptions;
SfxErrorHandler* pErrorHdl;
SvxErrorHandler* pSvxErrorHdl;
ScFormEditData* pFormEditData;
USHORT nCurRefDlgId;
BOOL bIsWaterCan;
BOOL bIsInEditCommand;
public:
SFX_DECL_INTERFACE(SCID_APP);
ScModule( SfxObjectFactory* pFact );
virtual ~ScModule();
virtual void FillStatusBar(StatusBar &rBar);
virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
void DeleteCfg();
void CloseDialogs();
// von der Applikation verschoben:
DECL_LINK( IdleHandler, Timer* ); // Timer statt idle
DECL_LINK( SpellTimerHdl, Timer* );
DECL_LINK( CalcFieldValueHdl, EditFieldInfo* );
void Execute( SfxRequest& rReq );
void GetState( SfxItemSet& rSet );
void AnythingChanged();
// Drag & Drop:
const ScDragData& GetDragData() const { return aDragData; }
void SetDragObject( ScTransferObj* pCellObj, ScDrawTransferObj* pDrawObj );
void ResetDragObject();
void SetDragLink( const String& rDoc, const String& rTab, const String& rArea );
void SetDragJump( ScDocument* pLocalDoc,
const String& rTarget, const String& rText );
// clipboard:
const ScClipData& GetClipData() const { return aClipData; }
void SetClipObject( ScTransferObj* pCellObj, ScDrawTransferObj* pDrawObj );
ScDocument* GetClipDoc(); // called from document - should be removed later
// X selection:
ScSelectionTransferObj* GetSelectionTransfer() const { return pSelTransfer; }
void SetSelectionTransfer( ScSelectionTransferObj* pNew );
void SetWaterCan( BOOL bNew ) { bIsWaterCan = bNew; }
BOOL GetIsWaterCan() const { return bIsWaterCan; }
void SetInEditCommand( BOOL bNew ) { bIsInEditCommand = bNew; }
BOOL IsInEditCommand() const { return bIsInEditCommand; }
// Options:
const ScViewOptions& GetViewOptions ();
const ScDocOptions& GetDocOptions ();
const ScAppOptions& GetAppOptions ();
const ScInputOptions& GetInputOptions ();
const ScPrintOptions& GetPrintOptions ();
void SetViewOptions ( const ScViewOptions& rOpt );
void SetDocOptions ( const ScDocOptions& rOpt );
void SetAppOptions ( const ScAppOptions& rOpt );
void SetInputOptions ( const ScInputOptions& rOpt );
void SetPrintOptions ( const ScPrintOptions& rOpt );
void InsertEntryToLRUList(USHORT nFIndex);
void RecentFunctionsChanged();
static void GetSpellSettings( USHORT& rDefLang, USHORT& rCjkLang, USHORT& rCtlLang,
BOOL& rAutoSpell, BOOL& rHideAuto );
static void SetAutoSpellProperty( BOOL bSet );
static void SetHideAutoProperty( BOOL bSet );
static BOOL HasThesaurusLanguage( USHORT nLang );
USHORT GetOptDigitLanguage(); // from CTL options
ScNavipiCfg& GetNavipiCfg();
svtools::ColorConfig& GetColorConfig();
SvtAccessibilityOptions& GetAccessOptions();
SvtCTLOptions& GetCTLOptions();
SvtUserOptions& GetUserOptions();
void ModifyOptions( const SfxItemSet& rOptSet );
// InputHandler:
BOOL IsEditMode(); // nicht bei SC_INPUT_TYPE
BOOL IsInputMode(); // auch bei SC_INPUT_TYPE
void SetInputMode( ScInputMode eMode );
BOOL InputKeyEvent( const KeyEvent& rKEvt, BOOL bStartEdit = FALSE );
void InputEnterHandler( BYTE nBlockMode = 0 );
void InputCancelHandler();
void InputSelection( EditView* pView );
void InputChanged( EditView* pView );
ScInputHandler* GetInputHdl( ScTabViewShell* pViewSh = NULL, BOOL bUseRef = TRUE );
void SetRefInputHdl( ScInputHandler* pNew );
ScInputHandler* GetRefInputHdl();
void SetInputWindow( ScInputWindow* pWin );
void ViewShellGone(ScTabViewShell* pViewSh);
void ViewShellChanged();
// Kommunikation mit Funktionsautopilot
void InputGetSelection( xub_StrLen& rStart, xub_StrLen& rEnd );
void InputSetSelection( xub_StrLen nStart, xub_StrLen nEnd );
void InputReplaceSelection( const String& rStr );
String InputGetFormulaStr();
void ActivateInputWindow( const String* pStr = NULL,
BOOL bMatrix = FALSE );
void InitFormEditData();
void ClearFormEditData();
ScFormEditData* GetFormEditData() { return pFormEditData; }
// Referenzeingabe:
void SetRefDialog( USHORT nId, BOOL bVis, SfxViewFrame* pViewFrm = NULL );
BOOL IsModalMode(SfxObjectShell* pDocSh = NULL);
BOOL IsFormulaMode();
BOOL IsRefDialogOpen();
BOOL IsTableLocked();
void OpenTeamDlg();
void SetTeamDlg( ScTeamDlg* pDlg ) { pTeamDlg = pDlg; }
ScTeamDlg* GetTeamDlg() const { return pTeamDlg; }
void SetReference( const ScRange& rRef, ScDocument* pDoc,
const ScMarkData* pMarkData = NULL );
void AddRefEntry();
void EndReference();
USHORT GetCurRefDlgId() const { return nCurRefDlgId; }
//virtuelle Methoden fuer den Optionendialog
virtual SfxItemSet* CreateItemSet( USHORT nId );
virtual void ApplyItemSet( USHORT nId, const SfxItemSet& rSet );
virtual SfxTabPage* CreateTabPage( USHORT nId, Window* pParent, const SfxItemSet& rSet );
};
#define SC_MOD() ( *(ScModule**) GetAppData(SHL_CALC) )
#endif
<|endoftext|> |
<commit_before>#include <string>
#include <vector>
#include <boost/optional.hpp>
#include "prompt.hh"
#include "configuration.hh"
#include "to_str.hh"
#include "move.hh"
#include "show_message.hh"
#include "visual.hh"
void mvline(contents& contents, boost::optional<int> line) {
if(line) {
contents.x = 0;
int cont = line.get();
if(cont < 0) {
show_message("Can't move to a negative line!");
contents.y = 0;
return;
}
contents.y = cont;
if(cont >= contents.cont.size()) {
contents.y = contents.cont.size() - 1;
show_message("Can't move past end of buffer!");
}
} else {
while(true) {
std::string str = prompt("Goto line: ");
try {
int res = std::stoi(str);
mvline(contents, res);
return;
} catch(std::invalid_argument) {
continue;
}
}
}
}
void mv(contents& contents, unsigned long _y, unsigned long _x) {
contents.y = _y;
contents.x = _x;
if((long) contents.y < 0) contents.y = 0;
if(contents.y >= contents.cont.size())
contents.y = contents.cont.size() - 1;
if((long) contents.x < 0) contents.x = 0;
if(contents.x >= contents.cont[contents.y].size())
contents.x = contents.cont[contents.y].size() - 1;
}
void mvrel(contents& contents, long y, long x) {
if(y < 0) mvu(contents,-y);
else mvd(contents, y);
if(x < 0) mvb(contents,-x);
else mvf(contents, x);
}
void mvcol(contents& contents, boost::optional<int> col) {
if(col) {
unsigned int len = contents.cont[contents.y].length();
if(len >= col.get()) {
contents.x = col.get();
contents.waiting_for_desired = false;
} else {
show_message((std::string("Can't move to column: ")
+ int_to_str(col.get())).c_str());
}
} else {
while(true) {
std::string str = prompt("Goto column: ");
try {
int res = std::stoi(str);
mvcol(contents, res);
return;
} catch(std::invalid_argument) {
continue;
}
}
}
}
void mvsot(contents& contents, boost::optional<int> op) {
mvsol(contents, op);
const std::string& str = contents.cont[contents.y];
for(unsigned int i = 0; i < str.length(); i++) {
if(str[i] == ' ' || str[i] == '\t')
mvf(contents, op);
else break;
}
}
void mveol(contents& contents, boost::optional<int>) {
mvcol(contents,contents.cont[contents.y].length() - 1);
}
void mvsol(contents& contents, boost::optional<int>) {
mvcol(contents,0);
}
void mvsop(contents& contents, boost::optional<int>) {
contents.y = 0;
contents.x = 0;
contents.waiting_for_desired = false;
contents.y_offset = 0;
}
void mveop(contents& contents, boost::optional<int>) {
contents.y = contents.cont.size() - 1;
contents.x = 0;
contents.y_offset = contents.y - contents.max_y + 2;
contents.waiting_for_desired = false;
}
void mvd(contents& contents, boost::optional<int> op) {
int times = op ? op.get() : 1;
if(contents.y + times < 0 || contents.y + times >= contents.cont.size()) {
show_message("Can't move to that location (start/end of buffer)");
return;
}
int vis = to_visual(contents.cont[contents.y],contents.x);
contents.y += times;
unsigned int len = contents.cont[contents.y].length();
if(contents.waiting_for_desired) {
if((int)contents.x < 0) {
contents.x = len - 1;
unsigned int vis = from_visual(contents.cont[contents.y],
contents.desired_x);
if(vis < contents.x) {
contents.x = vis;
contents.waiting_for_desired = false;
}
} else if(contents.x >= len) {
contents.x = len - 1;
} else if((contents.desired_x > contents.x
&& contents.desired_x < len)
|| contents.desired_x == 0) {
// x desired len
contents.x = contents.desired_x;
contents.waiting_for_desired = false;
} else {
// x len desired
contents.x = len - 1;
}
} else if(len <= contents.x && len > 0) {
contents.waiting_for_desired = true;
contents.desired_x = contents.x;
contents.x = len - 1;
} else {
int des = contents.x;
contents.x = from_visual(contents.cont[contents.y],vis);
if(len == 0) {
contents.waiting_for_desired = true;
contents.desired_x = des;
}
}
contents.x = (long) contents.x >= 0 ? contents.x : 0;
if(contents.y - contents.y_offset >= contents.max_y)
contents.y_offset = contents.y - contents.y_offset + 1;
if(contents.y < contents.y_offset)
contents.y_offset = contents.y;
}
void mvu(contents& contents, boost::optional<int> op) {
if(op) mvd(contents,-op.get());
else mvd(contents,-1);
}
static bool isDeliminator(char ch) {
for(auto i : DELIMINATORS)
if(i == ch) return true;
return false;
}
void mvfw(contents& contents, boost::optional<int> op) {
//move over deliminators
//move over non deliminators
}
void mvfeow(contents& contents, boost::optional<int> op) {
//move at least one forward
//move over non deliminators
//move over deliminators
}
void mvbw(contents& contents, boost::optional<int> op) {
}
inline static unsigned int fixLen(unsigned int len) {
return len ? len : 1;
}
void mvf(contents& contents, boost::optional<int> op) {
int times = op ? op.get() : 1;
long newx = contents.x + times;
try {
while(fixLen(contents.cont.at(contents.y).length()) <= newx) {
newx -= fixLen(contents.cont[contents.y].length());
contents.y++;
}
} catch(...) { }
if(contents.y >= contents.cont.size()) contents.y = contents.cont.size()-1;
if(contents.x < 0) contents.x = 0;
else contents.x = newx;
contents.waiting_for_desired = false;
}
void mvb(contents& contents, boost::optional<int> op) {
int times = op ? op.get() : 1;
if(contents.y == 0 && contents.x == 0) return;
long newx = contents.x - times;
try {
while(newx < 0) {
contents.y--;
newx += fixLen(contents.cont.at(contents.y).length());
}
} catch(...) { }
if(newx < 0) contents.x = 0;
else contents.x = newx;
contents.waiting_for_desired = false;
}
<commit_msg>Description of what move back word does<commit_after>#include <string>
#include <vector>
#include <boost/optional.hpp>
#include "prompt.hh"
#include "configuration.hh"
#include "to_str.hh"
#include "move.hh"
#include "show_message.hh"
#include "visual.hh"
void mvline(contents& contents, boost::optional<int> line) {
if(line) {
contents.x = 0;
int cont = line.get();
if(cont < 0) {
show_message("Can't move to a negative line!");
contents.y = 0;
return;
}
contents.y = cont;
if(cont >= contents.cont.size()) {
contents.y = contents.cont.size() - 1;
show_message("Can't move past end of buffer!");
}
} else {
while(true) {
std::string str = prompt("Goto line: ");
try {
int res = std::stoi(str);
mvline(contents, res);
return;
} catch(std::invalid_argument) {
continue;
}
}
}
}
void mv(contents& contents, unsigned long _y, unsigned long _x) {
contents.y = _y;
contents.x = _x;
if((long) contents.y < 0) contents.y = 0;
if(contents.y >= contents.cont.size())
contents.y = contents.cont.size() - 1;
if((long) contents.x < 0) contents.x = 0;
if(contents.x >= contents.cont[contents.y].size())
contents.x = contents.cont[contents.y].size() - 1;
}
void mvrel(contents& contents, long y, long x) {
if(y < 0) mvu(contents,-y);
else mvd(contents, y);
if(x < 0) mvb(contents,-x);
else mvf(contents, x);
}
void mvcol(contents& contents, boost::optional<int> col) {
if(col) {
unsigned int len = contents.cont[contents.y].length();
if(len >= col.get()) {
contents.x = col.get();
contents.waiting_for_desired = false;
} else {
show_message((std::string("Can't move to column: ")
+ int_to_str(col.get())).c_str());
}
} else {
while(true) {
std::string str = prompt("Goto column: ");
try {
int res = std::stoi(str);
mvcol(contents, res);
return;
} catch(std::invalid_argument) {
continue;
}
}
}
}
void mvsot(contents& contents, boost::optional<int> op) {
mvsol(contents, op);
const std::string& str = contents.cont[contents.y];
for(unsigned int i = 0; i < str.length(); i++) {
if(str[i] == ' ' || str[i] == '\t')
mvf(contents, op);
else break;
}
}
void mveol(contents& contents, boost::optional<int>) {
mvcol(contents,contents.cont[contents.y].length() - 1);
}
void mvsol(contents& contents, boost::optional<int>) {
mvcol(contents,0);
}
void mvsop(contents& contents, boost::optional<int>) {
contents.y = 0;
contents.x = 0;
contents.waiting_for_desired = false;
contents.y_offset = 0;
}
void mveop(contents& contents, boost::optional<int>) {
contents.y = contents.cont.size() - 1;
contents.x = 0;
contents.y_offset = contents.y - contents.max_y + 2;
contents.waiting_for_desired = false;
}
void mvd(contents& contents, boost::optional<int> op) {
int times = op ? op.get() : 1;
if(contents.y + times < 0 || contents.y + times >= contents.cont.size()) {
show_message("Can't move to that location (start/end of buffer)");
return;
}
int vis = to_visual(contents.cont[contents.y],contents.x);
contents.y += times;
unsigned int len = contents.cont[contents.y].length();
if(contents.waiting_for_desired) {
if((int)contents.x < 0) {
contents.x = len - 1;
unsigned int vis = from_visual(contents.cont[contents.y],
contents.desired_x);
if(vis < contents.x) {
contents.x = vis;
contents.waiting_for_desired = false;
}
} else if(contents.x >= len) {
contents.x = len - 1;
} else if((contents.desired_x > contents.x
&& contents.desired_x < len)
|| contents.desired_x == 0) {
// x desired len
contents.x = contents.desired_x;
contents.waiting_for_desired = false;
} else {
// x len desired
contents.x = len - 1;
}
} else if(len <= contents.x && len > 0) {
contents.waiting_for_desired = true;
contents.desired_x = contents.x;
contents.x = len - 1;
} else {
int des = contents.x;
contents.x = from_visual(contents.cont[contents.y],vis);
if(len == 0) {
contents.waiting_for_desired = true;
contents.desired_x = des;
}
}
contents.x = (long) contents.x >= 0 ? contents.x : 0;
if(contents.y - contents.y_offset >= contents.max_y)
contents.y_offset = contents.y - contents.y_offset + 1;
if(contents.y < contents.y_offset)
contents.y_offset = contents.y;
}
void mvu(contents& contents, boost::optional<int> op) {
if(op) mvd(contents,-op.get());
else mvd(contents,-1);
}
static bool isDeliminator(char ch) {
for(auto i : DELIMINATORS)
if(i == ch) return true;
return false;
}
void mvfw(contents& contents, boost::optional<int> op) {
//move over deliminators
//move over non deliminators
}
void mvfeow(contents& contents, boost::optional<int> op) {
//move at least one forward
//move over non deliminators
//move over deliminators
}
void mvbw(contents& contents, boost::optional<int> op) {
//move back one then
//if delimitor then move back until no delimitor
//else if whitespace then move back until not whitespace then
// move back consistently over delimitors or word chars
//else /*word char*/ move back until not word char or
// whitespace
//move forward one
}
inline static unsigned int fixLen(unsigned int len) {
return len ? len : 1;
}
void mvf(contents& contents, boost::optional<int> op) {
int times = op ? op.get() : 1;
long newx = contents.x + times;
try {
while(fixLen(contents.cont.at(contents.y).length()) <= newx) {
newx -= fixLen(contents.cont[contents.y].length());
contents.y++;
}
} catch(...) { }
if(contents.y >= contents.cont.size()) contents.y = contents.cont.size()-1;
if(contents.x < 0) contents.x = 0;
else contents.x = newx;
contents.waiting_for_desired = false;
}
void mvb(contents& contents, boost::optional<int> op) {
int times = op ? op.get() : 1;
if(contents.y == 0 && contents.x == 0) return;
long newx = contents.x - times;
try {
while(newx < 0) {
contents.y--;
newx += fixLen(contents.cont.at(contents.y).length());
}
} catch(...) { }
if(newx < 0) contents.x = 0;
else contents.x = newx;
contents.waiting_for_desired = false;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2015, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include <QMutex>
#include <QDataStream>
#include <QLocalSocket>
#include <QTimer>
#include <TWebApplication>
#include <TApplicationServerBase>
#include "tsystembus.h"
#include "tsystemglobal.h"
#include "tprocessinfo.h"
#include "tfcore.h"
const int HEADER_LEN = 5;
const QString SYSTEMBUS_DOMAIN_PREFIX = "treefrog_systembus_";
static TSystemBus *systemBus = nullptr;
TSystemBus::TSystemBus()
: readBuffer(), sendBuffer(), mutexRead(QMutex::NonRecursive), mutexWrite(QMutex::NonRecursive)
{
busSocket = new QLocalSocket();
QObject::connect(busSocket, SIGNAL(readyRead()), this, SLOT(readBus()));
QObject::connect(busSocket, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
QObject::connect(busSocket, SIGNAL(error(QLocalSocket::LocalSocketError)), this, SLOT(handleError(QLocalSocket::LocalSocketError)));
}
TSystemBus::~TSystemBus()
{
busSocket->close();
delete busSocket;
}
bool TSystemBus::send(const TSystemBusMessage &message)
{
QMutexLocker locker(&mutexWrite);
sendBuffer += message.toByteArray();
QTimer::singleShot(0, this, SLOT(writeBus())); // Writes in main thread
return true;
}
bool TSystemBus::send(Tf::ServerOpCode opcode, const QString &dst, const QByteArray &payload)
{
return send(TSystemBusMessage(opcode, dst, payload));
}
QList<TSystemBusMessage> TSystemBus::recvAll()
{
QList<TSystemBusMessage> ret;
quint8 opcode;
quint32 length;
QMutexLocker locker(&mutexRead);
for (;;) {
QDataStream ds(readBuffer);
ds.setByteOrder(QDataStream::BigEndian);
ds >> opcode >> length;
if ((uint)readBuffer.length() < length + HEADER_LEN) {
break;
}
auto message = TSystemBusMessage::parse(readBuffer);
if (message.isValid()) {
ret << message;
}
}
return ret;
}
void TSystemBus::readBus()
{
bool ready = false;
{
QMutexLocker locker(&mutexRead);
readBuffer += busSocket->readAll();
QDataStream ds(readBuffer);
ds.setByteOrder(QDataStream::BigEndian);
quint8 opcode;
quint32 length;
ds >> opcode >> length;
ready = ((uint)readBuffer.length() >= length + HEADER_LEN);
}
if (ready) {
emit readyReceive();
}
}
void TSystemBus::writeBus()
{
QMutexLocker locker(&mutexWrite);
for (;;) {
int len = busSocket->write(sendBuffer.data(), sendBuffer.length());
if (Q_UNLIKELY(len <= 0)) {
tSystemError("System Bus write error res:%d [%s:%d]", len, __FILE__, __LINE__);
sendBuffer.resize(0);
} else {
sendBuffer.remove(0, len);
}
if (sendBuffer.isEmpty()) {
break;
}
if (!busSocket->waitForBytesWritten(1000)) {
tSystemError("System Bus write-wait error res:%d [%s:%d]", len, __FILE__, __LINE__);
sendBuffer.resize(0);
break;
}
}
}
void TSystemBus::connect()
{
busSocket->connectToServer(connectionName());
}
void TSystemBus::handleError(QLocalSocket::LocalSocketError error)
{
switch (error) {
case QLocalSocket::PeerClosedError:
tSystemError("Remote socket closed the connection");
break;
default:
tSystemError("Local socket error : %d", (int)error);
break;
}
}
TSystemBus *TSystemBus::instance()
{
return systemBus;
}
void TSystemBus::instantiate()
{
if (!systemBus) {
systemBus = new TSystemBus;
systemBus->connect();
}
}
QString TSystemBus::connectionName()
{
#if defined(Q_OS_WIN) && !defined(TF_NO_DEBUG)
const QString processName = "tadpoled";
#else
const QString processName = "tadpole";
#endif
qint64 pid = 0;
QString cmd = TWebApplication::arguments().first();
if (cmd.endsWith(processName)) {
pid = TProcessInfo(TWebApplication::applicationPid()).ppid();
} else {
pid = TWebApplication::applicationPid();
}
return connectionName(pid);
}
QString TSystemBus::connectionName(qint64 pid)
{
return SYSTEMBUS_DOMAIN_PREFIX + QString::number(pid);
}
TSystemBusMessage::TSystemBusMessage()
: firstByte_(0), payload_(), valid_(false)
{ }
TSystemBusMessage::TSystemBusMessage(quint8 op, const QByteArray &d)
: firstByte_(0), payload_(), valid_(false)
{
firstByte_ = 0x80 | (op & 0x3F);
QDataStream ds(&payload_, QIODevice::WriteOnly);
ds.setByteOrder(QDataStream::BigEndian);
ds << QByteArray() << d;
}
TSystemBusMessage::TSystemBusMessage(quint8 op, const QString &t, const QByteArray &d)
: firstByte_(0), payload_(), valid_(false)
{
firstByte_ = 0x80 | (op & 0x3F);
QDataStream ds(&payload_, QIODevice::WriteOnly);
ds.setByteOrder(QDataStream::BigEndian);
ds << t << d;
}
QString TSystemBusMessage::target() const
{
QString ret;
QDataStream ds(payload_);
ds.setByteOrder(QDataStream::BigEndian);
ds >> ret;
return ret;
}
QByteArray TSystemBusMessage::data() const
{
QByteArray ret;
QString target;
QDataStream ds(payload_);
ds.setByteOrder(QDataStream::BigEndian);
ds >> target >> ret;
return ret;
}
bool TSystemBusMessage::validate()
{
valid_ = true;
valid_ &= (firstBit() == true);
valid_ &= (rsvBit() == false);
if (!valid_) {
tSystemError("Invalid byte: 0x%x [%s:%d]", firstByte_, __FILE__, __LINE__);
}
valid_ &= (opCode() > 0 && opCode() <= MaxOpCode);
if (!valid_) {
tSystemError("Invalid opcode: %d [%s:%d]", (int)opCode(), __FILE__, __LINE__);
}
return valid_;
}
QByteArray TSystemBusMessage::toByteArray() const
{
QByteArray buf;
buf.reserve(HEADER_LEN + payload_.length());
QDataStream ds(&buf, QIODevice::WriteOnly);
ds.setByteOrder(QDataStream::BigEndian);
ds << firstByte_ << (quint32)payload_.length();
ds.writeRawData(payload_.data(), payload_.length());
return buf;
}
TSystemBusMessage TSystemBusMessage::parse(QByteArray &bytes)
{
QDataStream ds(bytes);
ds.setByteOrder(QDataStream::BigEndian);
quint8 opcode;
quint32 length;
ds >> opcode >> length;
if ((uint)bytes.length() < HEADER_LEN || (uint)bytes.length() < HEADER_LEN + length) {
tSystemError("Invalid length: %d [%s:%d]", length, __FILE__, __LINE__);
bytes.resize(0);
return TSystemBusMessage();
}
TSystemBusMessage message;
message.firstByte_ = opcode;
message.payload_ = bytes.mid(HEADER_LEN, length);
message.validate();
bytes.remove(0, HEADER_LEN + length);
return message;
}
/* Data format for system bus
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-----------+-----------------------------------------------+
|F|R| opcode | Payload length |
|L|S| (6) | (32) |
|G|V| | |
+-+-+-----------+-----------------------------------------------+
| | Payload data : target (QString format) |
| | (x) |
+---------------+-----------------------------------------------+
| Payload data : QByteArray format |
| (y) |
+---------------+-----------------------------------------------+
*/
<commit_msg>fix compilation error on qt4.<commit_after>/* Copyright (c) 2015, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include <QMutex>
#include <QDataStream>
#include <QLocalSocket>
#include <QTimer>
#include <QStringList>
#include <TWebApplication>
#include <TApplicationServerBase>
#include "tsystembus.h"
#include "tsystemglobal.h"
#include "tprocessinfo.h"
#include "tfcore.h"
const int HEADER_LEN = 5;
const QString SYSTEMBUS_DOMAIN_PREFIX = "treefrog_systembus_";
static TSystemBus *systemBus = nullptr;
TSystemBus::TSystemBus()
: readBuffer(), sendBuffer(), mutexRead(QMutex::NonRecursive), mutexWrite(QMutex::NonRecursive)
{
busSocket = new QLocalSocket();
QObject::connect(busSocket, SIGNAL(readyRead()), this, SLOT(readBus()));
QObject::connect(busSocket, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
QObject::connect(busSocket, SIGNAL(error(QLocalSocket::LocalSocketError)), this, SLOT(handleError(QLocalSocket::LocalSocketError)));
}
TSystemBus::~TSystemBus()
{
busSocket->close();
delete busSocket;
}
bool TSystemBus::send(const TSystemBusMessage &message)
{
QMutexLocker locker(&mutexWrite);
sendBuffer += message.toByteArray();
QTimer::singleShot(0, this, SLOT(writeBus())); // Writes in main thread
return true;
}
bool TSystemBus::send(Tf::ServerOpCode opcode, const QString &dst, const QByteArray &payload)
{
return send(TSystemBusMessage(opcode, dst, payload));
}
QList<TSystemBusMessage> TSystemBus::recvAll()
{
QList<TSystemBusMessage> ret;
quint8 opcode;
quint32 length;
QMutexLocker locker(&mutexRead);
for (;;) {
QDataStream ds(readBuffer);
ds.setByteOrder(QDataStream::BigEndian);
ds >> opcode >> length;
if ((uint)readBuffer.length() < length + HEADER_LEN) {
break;
}
auto message = TSystemBusMessage::parse(readBuffer);
if (message.isValid()) {
ret << message;
}
}
return ret;
}
void TSystemBus::readBus()
{
bool ready = false;
{
QMutexLocker locker(&mutexRead);
readBuffer += busSocket->readAll();
QDataStream ds(readBuffer);
ds.setByteOrder(QDataStream::BigEndian);
quint8 opcode;
quint32 length;
ds >> opcode >> length;
ready = ((uint)readBuffer.length() >= length + HEADER_LEN);
}
if (ready) {
emit readyReceive();
}
}
void TSystemBus::writeBus()
{
QMutexLocker locker(&mutexWrite);
for (;;) {
int len = busSocket->write(sendBuffer.data(), sendBuffer.length());
if (Q_UNLIKELY(len <= 0)) {
tSystemError("System Bus write error res:%d [%s:%d]", len, __FILE__, __LINE__);
sendBuffer.resize(0);
} else {
sendBuffer.remove(0, len);
}
if (sendBuffer.isEmpty()) {
break;
}
if (!busSocket->waitForBytesWritten(1000)) {
tSystemError("System Bus write-wait error res:%d [%s:%d]", len, __FILE__, __LINE__);
sendBuffer.resize(0);
break;
}
}
}
void TSystemBus::connect()
{
busSocket->connectToServer(connectionName());
}
void TSystemBus::handleError(QLocalSocket::LocalSocketError error)
{
switch (error) {
case QLocalSocket::PeerClosedError:
tSystemError("Remote socket closed the connection");
break;
default:
tSystemError("Local socket error : %d", (int)error);
break;
}
}
TSystemBus *TSystemBus::instance()
{
return systemBus;
}
void TSystemBus::instantiate()
{
if (!systemBus) {
systemBus = new TSystemBus;
systemBus->connect();
}
}
QString TSystemBus::connectionName()
{
#if defined(Q_OS_WIN) && !defined(TF_NO_DEBUG)
const QString processName = "tadpoled";
#else
const QString processName = "tadpole";
#endif
qint64 pid = 0;
QString cmd = TWebApplication::arguments().first();
if (cmd.endsWith(processName)) {
pid = TProcessInfo(TWebApplication::applicationPid()).ppid();
} else {
pid = TWebApplication::applicationPid();
}
return connectionName(pid);
}
QString TSystemBus::connectionName(qint64 pid)
{
return SYSTEMBUS_DOMAIN_PREFIX + QString::number(pid);
}
TSystemBusMessage::TSystemBusMessage()
: firstByte_(0), payload_(), valid_(false)
{ }
TSystemBusMessage::TSystemBusMessage(quint8 op, const QByteArray &d)
: firstByte_(0), payload_(), valid_(false)
{
firstByte_ = 0x80 | (op & 0x3F);
QDataStream ds(&payload_, QIODevice::WriteOnly);
ds.setByteOrder(QDataStream::BigEndian);
ds << QByteArray() << d;
}
TSystemBusMessage::TSystemBusMessage(quint8 op, const QString &t, const QByteArray &d)
: firstByte_(0), payload_(), valid_(false)
{
firstByte_ = 0x80 | (op & 0x3F);
QDataStream ds(&payload_, QIODevice::WriteOnly);
ds.setByteOrder(QDataStream::BigEndian);
ds << t << d;
}
QString TSystemBusMessage::target() const
{
QString ret;
QDataStream ds(payload_);
ds.setByteOrder(QDataStream::BigEndian);
ds >> ret;
return ret;
}
QByteArray TSystemBusMessage::data() const
{
QByteArray ret;
QString target;
QDataStream ds(payload_);
ds.setByteOrder(QDataStream::BigEndian);
ds >> target >> ret;
return ret;
}
bool TSystemBusMessage::validate()
{
valid_ = true;
valid_ &= (firstBit() == true);
valid_ &= (rsvBit() == false);
if (!valid_) {
tSystemError("Invalid byte: 0x%x [%s:%d]", firstByte_, __FILE__, __LINE__);
}
valid_ &= (opCode() > 0 && opCode() <= MaxOpCode);
if (!valid_) {
tSystemError("Invalid opcode: %d [%s:%d]", (int)opCode(), __FILE__, __LINE__);
}
return valid_;
}
QByteArray TSystemBusMessage::toByteArray() const
{
QByteArray buf;
buf.reserve(HEADER_LEN + payload_.length());
QDataStream ds(&buf, QIODevice::WriteOnly);
ds.setByteOrder(QDataStream::BigEndian);
ds << firstByte_ << (quint32)payload_.length();
ds.writeRawData(payload_.data(), payload_.length());
return buf;
}
TSystemBusMessage TSystemBusMessage::parse(QByteArray &bytes)
{
QDataStream ds(bytes);
ds.setByteOrder(QDataStream::BigEndian);
quint8 opcode;
quint32 length;
ds >> opcode >> length;
if ((uint)bytes.length() < HEADER_LEN || (uint)bytes.length() < HEADER_LEN + length) {
tSystemError("Invalid length: %d [%s:%d]", length, __FILE__, __LINE__);
bytes.resize(0);
return TSystemBusMessage();
}
TSystemBusMessage message;
message.firstByte_ = opcode;
message.payload_ = bytes.mid(HEADER_LEN, length);
message.validate();
bytes.remove(0, HEADER_LEN + length);
return message;
}
/* Data format for system bus
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-----------+-----------------------------------------------+
|F|R| opcode | Payload length |
|L|S| (6) | (32) |
|G|V| | |
+-+-+-----------+-----------------------------------------------+
| | Payload data : target (QString format) |
| | (x) |
+---------------+-----------------------------------------------+
| Payload data : QByteArray format |
| (y) |
+---------------+-----------------------------------------------+
*/
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>
using namespace std;
#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1
typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;
const double eps = 1e-6;
const ll LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;
#define x first
#define y second
#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);
typedef pair<int,string> user;
priority_queue<user > pq;
int usernum;
void Init(){
scanf("%d",&usernum);
return ;
}
void Solve(){
user temp;
int ttime=-1;
int lv;
string name;
user out;
int outusernum=0;
int p=0;//%5
int ttweight=99999;
while(usernum--){
cin>>ttime>>lv>>name;
while(ttime-p>0){
if(!pq.empty()){
cout<<pq.top().second<<endl;
pq.pop();
}
outusernum++;
p+=5;
}
pq.push(make_pair(lv*100000+ttweight,name));
ttweight--;
}
while(!pq.empty()){
cout<<pq.top().second<<endl;
pq.pop();
outusernum++;
}
return ;
}
int main(){
#ifdef LOCAL
freopen("uoj18105.in","r",stdin);
#endif
Init(),Solve();
return 0;
}<commit_msg>update uoj18105<commit_after>/*
18105 银行的叫号顺序
时间限制:8000MS 内存限制:65535K
提交次数:0 通过次数:0
题型: 编程题 语言: G++;GCC;VC
Description
银行的叫号过程是一个优先队列的典型应用,假设,银行有4类客户,分别用优先级1,2,3,4表示,级别越高
则更优先得到服务,例如,当前有三个人排队,两个1级客户,一个3级客户,则银行叫号时,3级客户将先得到服务
,即使另两个1级有客户比他先到。当多个同级的客户将获得服务时,由先到的客户先得到服务。
假设,银行只有一个服务窗口,一次只能服务一个客户,假设该窗口每5分钟服务一个客户,即叫号的时刻分别
为0分钟、5分钟、10分钟、.....如果在叫号的时侯,没有客户,银行职员会去喝杯咖啡或上个洗手间,5分钟后
再继续叫号。
银行给出一系列客户到来的记录,每条记录包括“客户到来的时”,“客户等级”,“客户姓名”(由一个单词构成),请输
出银行服务的客户的顺序。
输入格式
第一数字是客户的数量n(n<=100000)
此后,每一行是一个客户来访信息,包括3个数字,到来的时刻(分钟整点,最大10的8次方)、等级、姓名(最多20个字母)
(已经按到来时刻排序)
输出格式
按服务的先后顺序输出客户的姓名
输入样例
4
0 1 John
3 1 Smith
3 1 Tom
4 2 Flod
输出样例
John
Flod
Smith
Tom
*/
//下面是模板,不用看,都一样;
//****************************************
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>
using namespace std;
#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1
typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;
const double eps = 1e-6;
const ll LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;
#define x first
#define y second
#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);
//*****模板结束************************
typedef pair<int,string> user;// 客户
priority_queue<user > pq; //客户的优先队列
int usernum;
void Init(){
scanf("%d",&usernum);
return ;
}
void Solve(){
user temp;
int ttime,lv;
string name;
int p=0;//%5
int ttweight=99999;
while(usernum--){
cin>>ttime>>lv>>name;
pq.push(make_pair(lv*100000+ttweight,name));
ttweight--;
}
while(!pq.empty()){
cout<<pq.top().second<<endl;
pq.pop();
}
return ;
}
int main(){
#ifdef LOCAL
freopen("uoj18105.in","r",stdin);
#endif
Init(),Solve();
return 0;
}<|endoftext|> |
<commit_before>#include "twsWrapper.h"
#include "twsUtil.h"
#include "debug.h"
// from global installed ibapi
#include "ibtws/Contract.h"
#include "ibtws/Order.h"
#include "ibtws/OrderState.h"
#include <QtCore/QString>
#include <QtCore/QDateTime>
DebugTwsWrapper::~DebugTwsWrapper()
{
}
void DebugTwsWrapper::tickPrice( IB::TickerId tickerId, IB::TickType field,
double price, int canAutoExecute )
{
DEBUG_PRINTF( "TICK_PRICE: %ld %s %g %d",
tickerId, ibToString(field).c_str(), price, canAutoExecute);
}
void DebugTwsWrapper::tickSize( IB::TickerId tickerId, IB::TickType field,
int size )
{
DEBUG_PRINTF( "TICK_SIZE: %ld %s %d",
tickerId, ibToString(field).c_str(), size );
}
void DebugTwsWrapper::tickOptionComputation ( IB::TickerId tickerId,
IB::TickType tickType, double impliedVol, double delta, double optPrice,
double pvDividend, double gamma, double vega, double theta,
double undPrice )
{
DEBUG_PRINTF( "TICK_OPTION_COMPUTATION: %ld %s %g %g %g %g %g %g %g %g",
tickerId, ibToString(tickType).c_str(), impliedVol, delta,
optPrice, pvDividend, gamma, vega, theta, undPrice );
}
void DebugTwsWrapper::tickGeneric( IB::TickerId tickerId, IB::TickType tickType,
double value )
{
DEBUG_PRINTF( "TICK_GENERIC: %ld %s %g",
tickerId, ibToString(tickType).c_str(), value );
}
void DebugTwsWrapper::tickString( IB::TickerId tickerId, IB::TickType tickType,
const IB::IBString& value )
{
QString _val = toQString(value);
if( tickType == IB::LAST_TIMESTAMP ) {
_val = QDateTime::fromTime_t(_val.toInt()).toString();
}
DEBUG_PRINTF( "TICK_STRING: %ld %s %s",
tickerId, ibToString(tickType).c_str(), toIBString(_val).c_str());
}
void DebugTwsWrapper::tickEFP( IB::TickerId tickerId, IB::TickType tickType,
double basisPoints, const IB::IBString& formattedBasisPoints,
double totalDividends, int holdDays, const IB::IBString& futureExpiry,
double dividendImpact, double dividendsToExpiry )
{
// TODO
DEBUG_PRINTF( "TICK_EFP: %ld %s", tickerId, ibToString(tickType).c_str() );
}
void DebugTwsWrapper::orderStatus ( IB::OrderId orderId,
const IB::IBString &status, int filled, int remaining, double avgFillPrice,
int permId, int parentId, double lastFillPrice, int clientId,
const IB::IBString& whyHeld )
{
DEBUG_PRINTF( "ORDER_STATUS: "
"orderId:%ld, status:%s, filled:%d, remaining:%d, %d %d %g %g %d, %s",
orderId, status.c_str(), filled, remaining, permId, parentId,
avgFillPrice, lastFillPrice, clientId, whyHeld.c_str());
}
void DebugTwsWrapper::openOrder( IB::OrderId orderId,
const IB::Contract &contract, const IB::Order &order,
const IB::OrderState &orderState )
{
DEBUG_PRINTF( "OPEN_ORDER: %ld %s %s "
"warnTxt:%s, status:%s, com:%g, comCur:%s, minCom:%g, maxCom:%g, "
"initMarg:%s, maintMarg:%s, ewl:%s",
orderId, contract.symbol.c_str(), order.action.c_str(),
orderState.warningText.c_str(),
orderState.status.c_str(),
orderState.commission,
orderState.commissionCurrency.c_str(),
orderState.minCommission,
orderState.maxCommission,
orderState.initMargin.c_str(),
orderState.maintMargin.c_str(),
orderState.equityWithLoan.c_str() );
}
void DebugTwsWrapper::openOrderEnd()
{
DEBUG_PRINTF( "OPEN_ORDER_END" );
}
void DebugTwsWrapper::winError( const IB::IBString &str, int lastError )
{
DEBUG_PRINTF( "WIN_ERROR: %s %d", str.c_str(), lastError );
}
void DebugTwsWrapper::connectionClosed()
{
DEBUG_PRINTF( "CONNECTION_CLOSED" );
}
void DebugTwsWrapper::updateAccountValue( const IB::IBString& key,
const IB::IBString& val, const IB::IBString& currency,
const IB::IBString& accountName )
{
DEBUG_PRINTF( "ACCT_VALUE: %s %s %s %s",
key.c_str(), val.c_str(), currency.c_str(), accountName.c_str() );
}
void DebugTwsWrapper::updatePortfolio( const IB::Contract& contract,
int position, double marketPrice, double marketValue, double averageCost,
double unrealizedPNL, double realizedPNL, const IB::IBString& accountName)
{
DEBUG_PRINTF( "PORTFOLIO_VALUE: %s %s %d %g %g %g %g %g %s",
contract.symbol.c_str(), contract.localSymbol.c_str(), position,
marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL,
accountName.c_str() );
}
void DebugTwsWrapper::updateAccountTime( const IB::IBString& timeStamp )
{
DEBUG_PRINTF( "ACCT_UPDATE_TIME: %s", timeStamp.c_str() );
}
void DebugTwsWrapper::accountDownloadEnd( const IB::IBString& accountName )
{
DEBUG_PRINTF( "ACCT_DOWNLOAD_END: %s", accountName.c_str() );
}
void DebugTwsWrapper::nextValidId( IB::OrderId orderId )
{
DEBUG_PRINTF( "NEXT_VALID_ID: %ld", orderId );
}
void DebugTwsWrapper::contractDetails( int reqId,
const IB::ContractDetails& contractDetails )
{
DEBUG_PRINTF( "CONTRACT_DATA: %d %s %s %s %g %s %s %s %s %s %s",
reqId,
contractDetails.summary.symbol.c_str(),
contractDetails.summary.secType.c_str(),
contractDetails.summary.expiry.c_str(),
contractDetails.summary.strike,
contractDetails.summary.right.c_str(),
contractDetails.summary.exchange.c_str(),
contractDetails.summary.currency.c_str(),
contractDetails.summary.localSymbol.c_str(),
contractDetails.marketName.c_str(),
contractDetails.tradingClass.c_str() );
}
void DebugTwsWrapper::bondContractDetails( int reqId,
const IB::ContractDetails& contractDetails )
{
//TODO
DEBUG_PRINTF( "BOND_CONTRACT_DATA: %d %s %s %s %g %s %s %s %s %s %s",
reqId,
contractDetails.summary.symbol.c_str(),
contractDetails.summary.secType.c_str(),
contractDetails.summary.expiry.c_str(),
contractDetails.summary.strike,
contractDetails.summary.right.c_str(),
contractDetails.summary.exchange.c_str(),
contractDetails.summary.currency.c_str(),
contractDetails.summary.localSymbol.c_str(),
contractDetails.marketName.c_str(),
contractDetails.tradingClass.c_str() );
}
void DebugTwsWrapper::contractDetailsEnd( int reqId )
{
DEBUG_PRINTF( "CONTRACT_DATA_END: %d", reqId );
}
void DebugTwsWrapper::execDetails ( int orderId, const IB::Contract& contract,
const IB::Execution& execution )
{
DEBUG_PRINTF( "EXECUTION_DATA: %d %s %s", orderId,
contract.localSymbol.c_str(), ibToString(execution).c_str());
}
void DebugTwsWrapper::execDetailsEnd( int reqId )
{
DEBUG_PRINTF( "EXECUTION_DATA_END: %d", reqId );
}
void DebugTwsWrapper::error( int id, int errorCode,
const IB::IBString errorMsg )
{
DEBUG_PRINTF( "ERR_MSG: %d %d %s", id, errorCode, errorMsg.c_str() );
}
void DebugTwsWrapper::updateMktDepth( IB::TickerId id, int position,
int operation, int side, double price, int size )
{
// TODO
DEBUG_PRINTF( "MARKET_DEPTH: %ld", id );
}
void DebugTwsWrapper::updateMktDepthL2( IB::TickerId id, int position,
IB::IBString marketMaker, int operation, int side, double price,
int size )
{
// TODO
DEBUG_PRINTF( "MARKET_DEPTH_L2: %ld", id );
}
void DebugTwsWrapper::updateNewsBulletin( int msgId, int msgType,
const IB::IBString& newsMessage, const IB::IBString& originExch )
{
// TODO
DEBUG_PRINTF( "NEWS_BULLETINS: %d", msgId );
}
void DebugTwsWrapper::managedAccounts( const IB::IBString& accountsList )
{
DEBUG_PRINTF( "MANAGED_ACCTS: %s", accountsList.c_str() );
}
void DebugTwsWrapper::receiveFA( IB::faDataType pFaDataType,
const IB::IBString& cxml )
{
// TODO
DEBUG_PRINTF( "RECEIVE_FA: %s", cxml.c_str() );
}
void DebugTwsWrapper::historicalData( IB::TickerId reqId,
const IB::IBString& date, double open, double high, double low,
double close, int volume, int barCount, double WAP, int hasGaps )
{
DEBUG_PRINTF( "HISTORICAL_DATA: %ld %s %g %g %g %g %d %d %g %d", reqId,
date.c_str(), open, high, low, close, volume, barCount, WAP, hasGaps );
}
void DebugTwsWrapper::scannerParameters( const IB::IBString &xml )
{
DEBUG_PRINTF( "SCANNER_PARAMETERS: %s", xml.c_str() );
}
void DebugTwsWrapper::scannerData( int reqId, int rank,
const IB::ContractDetails &contractDetails, const IB::IBString &distance,
const IB::IBString &benchmark, const IB::IBString &projection,
const IB::IBString &legsStr )
{
// TODO
DEBUG_PRINTF( "SCANNER_DATA: %d", reqId );
}
void DebugTwsWrapper::scannerDataEnd(int reqId)
{
DEBUG_PRINTF( "SCANNER_DATA_END: %d", reqId );
}
void DebugTwsWrapper::realtimeBar( IB::TickerId reqId, long time, double open,
double high, double low, double close, long volume, double wap, int count )
{
// TODO
DEBUG_PRINTF( "REAL_TIME_BARS: %ld %ld", reqId, time );
}
void DebugTwsWrapper::currentTime( long time )
{
DEBUG_PRINTF( "CURRENT_TIME: %ld", time );
}
void DebugTwsWrapper::fundamentalData( IB::TickerId reqId,
const IB::IBString& data )
{
DEBUG_PRINTF( "FUNDAMENTAL_DATA: %ld %s", reqId, data.c_str() );
}
void DebugTwsWrapper::deltaNeutralValidation( int reqId,
const IB::UnderComp& underComp )
{
// TODO
DEBUG_PRINTF( "DELTA_NEUTRAL_VALIDATION: %d", reqId );
}
void DebugTwsWrapper::tickSnapshotEnd( int reqId )
{
DEBUG_PRINTF( "TICK_SNAPSHOT_END: %d", reqId );
}
<commit_msg>twsWrapper.cpp completely without Qt<commit_after>#include "twsWrapper.h"
#include "twsUtil.h"
#include "debug.h"
// from global installed ibapi
#include "ibtws/Contract.h"
#include "ibtws/Order.h"
#include "ibtws/OrderState.h"
DebugTwsWrapper::~DebugTwsWrapper()
{
}
void DebugTwsWrapper::tickPrice( IB::TickerId tickerId, IB::TickType field,
double price, int canAutoExecute )
{
DEBUG_PRINTF( "TICK_PRICE: %ld %s %g %d",
tickerId, ibToString(field).c_str(), price, canAutoExecute);
}
void DebugTwsWrapper::tickSize( IB::TickerId tickerId, IB::TickType field,
int size )
{
DEBUG_PRINTF( "TICK_SIZE: %ld %s %d",
tickerId, ibToString(field).c_str(), size );
}
void DebugTwsWrapper::tickOptionComputation ( IB::TickerId tickerId,
IB::TickType tickType, double impliedVol, double delta, double optPrice,
double pvDividend, double gamma, double vega, double theta,
double undPrice )
{
DEBUG_PRINTF( "TICK_OPTION_COMPUTATION: %ld %s %g %g %g %g %g %g %g %g",
tickerId, ibToString(tickType).c_str(), impliedVol, delta,
optPrice, pvDividend, gamma, vega, theta, undPrice );
}
void DebugTwsWrapper::tickGeneric( IB::TickerId tickerId, IB::TickType tickType,
double value )
{
DEBUG_PRINTF( "TICK_GENERIC: %ld %s %g",
tickerId, ibToString(tickType).c_str(), value );
}
void DebugTwsWrapper::tickString( IB::TickerId tickerId, IB::TickType tickType,
const IB::IBString& value )
{
if( tickType == IB::LAST_TIMESTAMP ) {
// here we format unix timestamp value
}
DEBUG_PRINTF( "TICK_STRING: %ld %s %s",
tickerId, ibToString(tickType).c_str(), value.c_str() );
}
void DebugTwsWrapper::tickEFP( IB::TickerId tickerId, IB::TickType tickType,
double basisPoints, const IB::IBString& formattedBasisPoints,
double totalDividends, int holdDays, const IB::IBString& futureExpiry,
double dividendImpact, double dividendsToExpiry )
{
// TODO
DEBUG_PRINTF( "TICK_EFP: %ld %s", tickerId, ibToString(tickType).c_str() );
}
void DebugTwsWrapper::orderStatus ( IB::OrderId orderId,
const IB::IBString &status, int filled, int remaining, double avgFillPrice,
int permId, int parentId, double lastFillPrice, int clientId,
const IB::IBString& whyHeld )
{
DEBUG_PRINTF( "ORDER_STATUS: "
"orderId:%ld, status:%s, filled:%d, remaining:%d, %d %d %g %g %d, %s",
orderId, status.c_str(), filled, remaining, permId, parentId,
avgFillPrice, lastFillPrice, clientId, whyHeld.c_str());
}
void DebugTwsWrapper::openOrder( IB::OrderId orderId,
const IB::Contract &contract, const IB::Order &order,
const IB::OrderState &orderState )
{
DEBUG_PRINTF( "OPEN_ORDER: %ld %s %s "
"warnTxt:%s, status:%s, com:%g, comCur:%s, minCom:%g, maxCom:%g, "
"initMarg:%s, maintMarg:%s, ewl:%s",
orderId, contract.symbol.c_str(), order.action.c_str(),
orderState.warningText.c_str(),
orderState.status.c_str(),
orderState.commission,
orderState.commissionCurrency.c_str(),
orderState.minCommission,
orderState.maxCommission,
orderState.initMargin.c_str(),
orderState.maintMargin.c_str(),
orderState.equityWithLoan.c_str() );
}
void DebugTwsWrapper::openOrderEnd()
{
DEBUG_PRINTF( "OPEN_ORDER_END" );
}
void DebugTwsWrapper::winError( const IB::IBString &str, int lastError )
{
DEBUG_PRINTF( "WIN_ERROR: %s %d", str.c_str(), lastError );
}
void DebugTwsWrapper::connectionClosed()
{
DEBUG_PRINTF( "CONNECTION_CLOSED" );
}
void DebugTwsWrapper::updateAccountValue( const IB::IBString& key,
const IB::IBString& val, const IB::IBString& currency,
const IB::IBString& accountName )
{
DEBUG_PRINTF( "ACCT_VALUE: %s %s %s %s",
key.c_str(), val.c_str(), currency.c_str(), accountName.c_str() );
}
void DebugTwsWrapper::updatePortfolio( const IB::Contract& contract,
int position, double marketPrice, double marketValue, double averageCost,
double unrealizedPNL, double realizedPNL, const IB::IBString& accountName)
{
DEBUG_PRINTF( "PORTFOLIO_VALUE: %s %s %d %g %g %g %g %g %s",
contract.symbol.c_str(), contract.localSymbol.c_str(), position,
marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL,
accountName.c_str() );
}
void DebugTwsWrapper::updateAccountTime( const IB::IBString& timeStamp )
{
DEBUG_PRINTF( "ACCT_UPDATE_TIME: %s", timeStamp.c_str() );
}
void DebugTwsWrapper::accountDownloadEnd( const IB::IBString& accountName )
{
DEBUG_PRINTF( "ACCT_DOWNLOAD_END: %s", accountName.c_str() );
}
void DebugTwsWrapper::nextValidId( IB::OrderId orderId )
{
DEBUG_PRINTF( "NEXT_VALID_ID: %ld", orderId );
}
void DebugTwsWrapper::contractDetails( int reqId,
const IB::ContractDetails& contractDetails )
{
DEBUG_PRINTF( "CONTRACT_DATA: %d %s %s %s %g %s %s %s %s %s %s",
reqId,
contractDetails.summary.symbol.c_str(),
contractDetails.summary.secType.c_str(),
contractDetails.summary.expiry.c_str(),
contractDetails.summary.strike,
contractDetails.summary.right.c_str(),
contractDetails.summary.exchange.c_str(),
contractDetails.summary.currency.c_str(),
contractDetails.summary.localSymbol.c_str(),
contractDetails.marketName.c_str(),
contractDetails.tradingClass.c_str() );
}
void DebugTwsWrapper::bondContractDetails( int reqId,
const IB::ContractDetails& contractDetails )
{
//TODO
DEBUG_PRINTF( "BOND_CONTRACT_DATA: %d %s %s %s %g %s %s %s %s %s %s",
reqId,
contractDetails.summary.symbol.c_str(),
contractDetails.summary.secType.c_str(),
contractDetails.summary.expiry.c_str(),
contractDetails.summary.strike,
contractDetails.summary.right.c_str(),
contractDetails.summary.exchange.c_str(),
contractDetails.summary.currency.c_str(),
contractDetails.summary.localSymbol.c_str(),
contractDetails.marketName.c_str(),
contractDetails.tradingClass.c_str() );
}
void DebugTwsWrapper::contractDetailsEnd( int reqId )
{
DEBUG_PRINTF( "CONTRACT_DATA_END: %d", reqId );
}
void DebugTwsWrapper::execDetails ( int orderId, const IB::Contract& contract,
const IB::Execution& execution )
{
DEBUG_PRINTF( "EXECUTION_DATA: %d %s %s", orderId,
contract.localSymbol.c_str(), ibToString(execution).c_str());
}
void DebugTwsWrapper::execDetailsEnd( int reqId )
{
DEBUG_PRINTF( "EXECUTION_DATA_END: %d", reqId );
}
void DebugTwsWrapper::error( int id, int errorCode,
const IB::IBString errorMsg )
{
DEBUG_PRINTF( "ERR_MSG: %d %d %s", id, errorCode, errorMsg.c_str() );
}
void DebugTwsWrapper::updateMktDepth( IB::TickerId id, int position,
int operation, int side, double price, int size )
{
// TODO
DEBUG_PRINTF( "MARKET_DEPTH: %ld", id );
}
void DebugTwsWrapper::updateMktDepthL2( IB::TickerId id, int position,
IB::IBString marketMaker, int operation, int side, double price,
int size )
{
// TODO
DEBUG_PRINTF( "MARKET_DEPTH_L2: %ld", id );
}
void DebugTwsWrapper::updateNewsBulletin( int msgId, int msgType,
const IB::IBString& newsMessage, const IB::IBString& originExch )
{
// TODO
DEBUG_PRINTF( "NEWS_BULLETINS: %d", msgId );
}
void DebugTwsWrapper::managedAccounts( const IB::IBString& accountsList )
{
DEBUG_PRINTF( "MANAGED_ACCTS: %s", accountsList.c_str() );
}
void DebugTwsWrapper::receiveFA( IB::faDataType pFaDataType,
const IB::IBString& cxml )
{
// TODO
DEBUG_PRINTF( "RECEIVE_FA: %s", cxml.c_str() );
}
void DebugTwsWrapper::historicalData( IB::TickerId reqId,
const IB::IBString& date, double open, double high, double low,
double close, int volume, int barCount, double WAP, int hasGaps )
{
DEBUG_PRINTF( "HISTORICAL_DATA: %ld %s %g %g %g %g %d %d %g %d", reqId,
date.c_str(), open, high, low, close, volume, barCount, WAP, hasGaps );
}
void DebugTwsWrapper::scannerParameters( const IB::IBString &xml )
{
DEBUG_PRINTF( "SCANNER_PARAMETERS: %s", xml.c_str() );
}
void DebugTwsWrapper::scannerData( int reqId, int rank,
const IB::ContractDetails &contractDetails, const IB::IBString &distance,
const IB::IBString &benchmark, const IB::IBString &projection,
const IB::IBString &legsStr )
{
// TODO
DEBUG_PRINTF( "SCANNER_DATA: %d", reqId );
}
void DebugTwsWrapper::scannerDataEnd(int reqId)
{
DEBUG_PRINTF( "SCANNER_DATA_END: %d", reqId );
}
void DebugTwsWrapper::realtimeBar( IB::TickerId reqId, long time, double open,
double high, double low, double close, long volume, double wap, int count )
{
// TODO
DEBUG_PRINTF( "REAL_TIME_BARS: %ld %ld", reqId, time );
}
void DebugTwsWrapper::currentTime( long time )
{
DEBUG_PRINTF( "CURRENT_TIME: %ld", time );
}
void DebugTwsWrapper::fundamentalData( IB::TickerId reqId,
const IB::IBString& data )
{
DEBUG_PRINTF( "FUNDAMENTAL_DATA: %ld %s", reqId, data.c_str() );
}
void DebugTwsWrapper::deltaNeutralValidation( int reqId,
const IB::UnderComp& underComp )
{
// TODO
DEBUG_PRINTF( "DELTA_NEUTRAL_VALIDATION: %d", reqId );
}
void DebugTwsWrapper::tickSnapshotEnd( int reqId )
{
DEBUG_PRINTF( "TICK_SNAPSHOT_END: %d", reqId );
}
<|endoftext|> |
<commit_before>#pragma once
#include <algorithm>
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "abstract_operator.hpp"
#include "storage/reference_column.hpp"
namespace opossum {
template <typename T>
class SortImpl;
class Sort : public AbstractOperator {
public:
Sort(const std::shared_ptr<AbstractOperator> in, const std::string &sort_column_name, const bool ascending = true);
virtual void execute();
virtual std::shared_ptr<Table> get_output() const;
protected:
virtual const std::string get_name() const;
virtual uint8_t get_num_in_tables() const;
virtual uint8_t get_num_out_tables() const;
const std::unique_ptr<AbstractOperatorImpl> _impl;
};
template <typename T>
class SortImpl : public AbstractOperatorImpl {
public:
SortImpl(const std::shared_ptr<AbstractOperator> in, const std::string &sort_column_name, const bool ascending = true)
: _in_table(in->get_output()),
_sort_column_id(_in_table->get_column_id_by_name(sort_column_name)),
_ascending(ascending),
_output(new Table),
_pos_list(new PosList),
_row_id_value_vector(new std::vector<std::pair<RowID, T>>()) {
for (size_t column_id = 0; column_id < _in_table->col_count(); ++column_id) {
std::shared_ptr<ReferenceColumn> ref;
if (auto ref_col = std::dynamic_pointer_cast<ReferenceColumn>(_in_table->get_chunk(0).get_column(column_id))) {
ref = std::make_shared<ReferenceColumn>(ref_col->get_referenced_table(), column_id, _pos_list);
} else {
ref = std::make_shared<ReferenceColumn>(_in_table, column_id, _pos_list);
}
_output->add_column(_in_table->get_column_name(column_id), _in_table->get_column_type(column_id), false);
_output->get_chunk(0).add_column(ref);
// TODO(Anyone): do we want to distinguish between chunk tables and "reference tables"?
}
}
virtual void execute() {
for (size_t chunk = 0; chunk < _in_table->chunk_count(); chunk++) {
if (auto value_column =
std::dynamic_pointer_cast<ValueColumn<T>>(_in_table->get_chunk(chunk).get_column(_sort_column_id))) {
auto &values = value_column->get_values();
for (size_t offset = 0; offset < values.size(); offset++) {
_row_id_value_vector->emplace_back(get_row_id_from_chunk_id_and_chunk_offset(chunk, offset), values[offset]);
}
} else if (auto referenced_column = std::dynamic_pointer_cast<ReferenceColumn>(
_in_table->get_chunk(chunk).get_column(_sort_column_id))) {
std::shared_ptr<PosList> in_pos_list;
bool not_full_table = (in_pos_list = referenced_column->get_pos_list());
auto val_table = referenced_column->get_referenced_table();
std::vector<std::vector<T>> ref_values = {};
for (size_t chunk = 0; chunk < val_table->chunk_count(); chunk++) {
if (auto val_col =
std::dynamic_pointer_cast<ValueColumn<T>>(val_table->get_chunk(chunk).get_column(_sort_column_id))) {
if (not_full_table) {
ref_values.emplace_back(val_col->get_values());
} else {
auto &values = val_col->get_values();
for (size_t offset = 0; offset < values.size(); offset++) {
_row_id_value_vector->emplace_back(get_row_id_from_chunk_id_and_chunk_offset(chunk, offset),
values[offset]);
}
}
} else {
throw std::logic_error("Referenced table must only contain value columns");
}
}
if (not_full_table) {
for (size_t pos = 0; pos < in_pos_list->size(); pos++) {
auto row_id = (*in_pos_list)[pos];
auto chunk_id = get_chunk_id_from_row_id(row_id);
auto chunk_offset = get_chunk_offset_from_row_id(row_id);
_row_id_value_vector->emplace_back(row_id, ref_values[chunk_id][chunk_offset]);
}
}
} else {
throw std::logic_error("Column must either be a value or reference column");
}
}
if (_ascending) {
sort_with_operator<std::less<>>();
} else {
sort_with_operator<std::greater<>>();
}
for (size_t row = 0; row < _row_id_value_vector->size(); row++) {
_pos_list->emplace_back(_row_id_value_vector->at(row).first);
}
}
template <typename Comp>
void sort_with_operator() {
Comp comp;
std::sort(_row_id_value_vector->begin(), _row_id_value_vector->end(),
[comp](std::pair<RowID, T> a, std::pair<RowID, T> b) { return comp(a.second, b.second); });
}
virtual std::shared_ptr<Table> get_output() const { return _output; }
const std::shared_ptr<Table> _in_table;
const size_t _sort_column_id;
const bool _ascending;
std::shared_ptr<Table> _output;
std::shared_ptr<PosList> _pos_list;
std::shared_ptr<std::vector<std::pair<RowID, T>>> _row_id_value_vector;
};
} // namespace opossum
<commit_msg>refactoring with regard to the comments on merge request 5<commit_after>#pragma once
#include <algorithm>
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "abstract_operator.hpp"
#include "storage/reference_column.hpp"
namespace opossum {
template <typename T>
class SortImpl;
class Sort : public AbstractOperator {
public:
Sort(const std::shared_ptr<AbstractOperator> in, const std::string &sort_column_name, const bool ascending = true);
virtual void execute();
virtual std::shared_ptr<Table> get_output() const;
protected:
virtual const std::string get_name() const;
virtual uint8_t get_num_in_tables() const;
virtual uint8_t get_num_out_tables() const;
const std::unique_ptr<AbstractOperatorImpl> _impl;
};
template <typename T>
class SortImpl : public AbstractOperatorImpl {
public:
SortImpl(const std::shared_ptr<AbstractOperator> in, const std::string &sort_column_name, const bool ascending = true)
: _in_table(in->get_output()),
_sort_column_id(_in_table->get_column_id_by_name(sort_column_name)),
_ascending(ascending),
_output(new Table),
_pos_list(new PosList),
_row_id_value_vector(new std::vector<std::pair<RowID, T>>()) {
for (size_t column_id = 0; column_id < _in_table->col_count(); ++column_id) {
std::shared_ptr<ReferenceColumn> ref;
if (auto reference_col =
std::dynamic_pointer_cast<ReferenceColumn>(_in_table->get_chunk(0).get_column(column_id))) {
ref = std::make_shared<ReferenceColumn>(reference_col->get_referenced_table(), column_id, _pos_list);
} else {
ref = std::make_shared<ReferenceColumn>(_in_table, column_id, _pos_list);
}
_output->add_column(_in_table->get_column_name(column_id), _in_table->get_column_type(column_id), false);
_output->get_chunk(0).add_column(ref);
// TODO(Anyone): do we want to distinguish between chunk tables and "reference tables"?
}
}
virtual void execute() {
for (size_t chunk = 0; chunk < _in_table->chunk_count(); chunk++) {
if (auto value_column =
std::dynamic_pointer_cast<ValueColumn<T>>(_in_table->get_chunk(chunk).get_column(_sort_column_id))) {
auto &values = value_column->get_values();
for (size_t offset = 0; offset < values.size(); offset++) {
_row_id_value_vector->emplace_back(get_row_id_from_chunk_id_and_chunk_offset(chunk, offset), values[offset]);
}
} else if (auto referenced_column = std::dynamic_pointer_cast<ReferenceColumn>(
_in_table->get_chunk(chunk).get_column(_sort_column_id))) {
auto val_table = referenced_column->get_referenced_table();
std::vector<std::vector<T>> reference_values = {};
for (size_t chunk = 0; chunk < val_table->chunk_count(); chunk++) {
if (auto val_col =
std::dynamic_pointer_cast<ValueColumn<T>>(val_table->get_chunk(chunk).get_column(_sort_column_id))) {
if (referenced_column->get_pos_list()) {
reference_values.emplace_back(val_col->get_values());
} else {
auto &values = val_col->get_values();
for (size_t offset = 0; offset < values.size(); offset++) {
_row_id_value_vector->emplace_back(get_row_id_from_chunk_id_and_chunk_offset(chunk, offset),
values[offset]);
}
}
} else {
throw std::logic_error("Referenced table must only contain value columns");
}
}
if (referenced_column->get_pos_list()) {
auto pos_list_in = referenced_column->get_pos_list();
for (size_t pos = 0; pos < pos_list_in->size(); pos++) {
auto row_id = (*pos_list_in)[pos];
auto chunk_id = get_chunk_id_from_row_id(row_id);
auto chunk_offset = get_chunk_offset_from_row_id(row_id);
_row_id_value_vector->emplace_back(row_id, reference_values[chunk_id][chunk_offset]);
}
}
} else {
throw std::logic_error("Column must either be a value or reference column");
}
}
if (_ascending) {
sort_with_operator<std::less<>>();
} else {
sort_with_operator<std::greater<>>();
}
for (size_t row = 0; row < _row_id_value_vector->size(); row++) {
_pos_list->emplace_back(_row_id_value_vector->at(row).first);
}
}
template <typename Comp>
void sort_with_operator() {
Comp comp;
std::sort(_row_id_value_vector->begin(), _row_id_value_vector->end(),
[comp](std::pair<RowID, T> a, std::pair<RowID, T> b) { return comp(a.second, b.second); });
}
virtual std::shared_ptr<Table> get_output() const { return _output; }
const std::shared_ptr<Table> _in_table;
const size_t _sort_column_id;
const bool _ascending;
std::shared_ptr<Table> _output;
std::shared_ptr<PosList> _pos_list;
std::shared_ptr<std::vector<std::pair<RowID, T>>> _row_id_value_vector;
};
} // namespace opossum
<|endoftext|> |
<commit_before>// -*- Mode:C++ -*-
/**************************************************************************************************/
/* */
/* Copyright (C) 2014 University of Hull */
/* */
/**************************************************************************************************/
/* */
/* module : support/string.cpp */
/* project : */
/* description: */
/* */
/**************************************************************************************************/
// include i/f header
#include "support/thread.hpp"
// includes, system
#define GLIBCXX_NO_CODECVT 20140911
#if !defined(__GLIBCXX__) || (defined(__GLIBCXX__) && (__GLIBCXX__ > GLIBCXX_NO_CODECVT))
# include <codecvt> // std::codecvt_utf8<>
#endif
#include <locale> // std::wstring_convert<>
// includes, project
// #include <>
#define UKACHULLDCS_USE_TRACE
#undef UKACHULLDCS_USE_TRACE
#include <support/trace.hpp>
// internal unnamed namespace
namespace {
// types, internal (class, enum, struct, union, typedef)
// variables, internal
// functions, internal
} // namespace {
namespace support {
// variables, exported
// functions, exported
std::string
wstring_to_string(std::wstring const& a)
{
TRACE("support::wstring_to_string");
#if defined(__GLIBCXX__) && (__GLIBCXX__ <= GLIBCXX_NO_CODECVT)
return std::string(a.begin(), a.end());
#else
return std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t>().to_bytes(a);
#endif
}
std::wstring
string_to_wstring(std::string const& a)
{
TRACE("support::string_to_wstring");
return std::wstring(a.begin(), a.end());
}
} // namespace support {
<commit_msg>update: gcc 4.9<commit_after>// -*- Mode:C++ -*-
/**************************************************************************************************/
/* */
/* Copyright (C) 2014 University of Hull */
/* */
/**************************************************************************************************/
/* */
/* module : support/string.cpp */
/* project : */
/* description: */
/* */
/**************************************************************************************************/
// include i/f header
#include "support/thread.hpp"
// includes, system
#define GLIBCXX_NO_CODECVT 20141101
#if !defined(__GLIBCXX__) || (defined(__GLIBCXX__) && (__GLIBCXX__ > GLIBCXX_NO_CODECVT))
# include <codecvt> // std::codecvt_utf8<>
#endif
#include <locale> // std::wstring_convert<>
// includes, project
// #include <>
#define UKACHULLDCS_USE_TRACE
#undef UKACHULLDCS_USE_TRACE
#include <support/trace.hpp>
// internal unnamed namespace
namespace {
// types, internal (class, enum, struct, union, typedef)
// variables, internal
// functions, internal
} // namespace {
namespace support {
// variables, exported
// functions, exported
std::string
wstring_to_string(std::wstring const& a)
{
TRACE("support::wstring_to_string");
#if defined(__GLIBCXX__) && (__GLIBCXX__ <= GLIBCXX_NO_CODECVT)
return std::string(a.begin(), a.end());
#else
return std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t>().to_bytes(a);
#endif
}
std::wstring
string_to_wstring(std::string const& a)
{
TRACE("support::string_to_wstring");
return std::wstring(a.begin(), a.end());
}
} // namespace support {
<|endoftext|> |
<commit_before>#pragma once
#include <type_traits>
#include <algorithm>
#include <stdexcept>
#include <cstddef>
#include <utility>
#include <string>
#include <vector>
#include <array>
#include <uv.h>
namespace uvw {
namespace details {
enum class UVHandleType: std::underlying_type_t<uv_handle_type> {
UNKNOWN = UV_UNKNOWN_HANDLE,
ASYNC = UV_ASYNC,
CHECK = UV_CHECK,
FS_EVENT = UV_FS_EVENT,
FS_POLL = UV_FS_POLL,
HANDLE = UV_HANDLE,
IDLE = UV_IDLE,
PIPE = UV_NAMED_PIPE,
POLL = UV_POLL,
PREPARE = UV_PREPARE,
PROCESS = UV_PROCESS,
STREAM = UV_STREAM,
TCP = UV_TCP,
TIMER = UV_TIMER,
TTY = UV_TTY,
UDP = UV_UDP,
SIGNAL = UV_SIGNAL,
FILE = UV_FILE
};
template<typename T>
struct UVTypeWrapper {
using Type = T;
constexpr UVTypeWrapper(Type val): value{val} { }
constexpr operator Type() const noexcept { return value; }
private:
const Type value;
};
}
/**
* @brief Utility class to handle flags.
*
* This class can be used to handle flags of a same enumeration type.<br/>
* It is meant to be used as an argument for functions and member methods and
* as part of events.<br/>
* `Flags<E>` objects can be easily _or-ed_ and _and-ed_ with other instances of
* the same type or with instances of the type `E` (that is, the actual flag
* type), thus converted to the underlying type when needed.
*/
template<typename E>
class Flags final {
using InnerType = std::underlying_type_t<E>;
constexpr InnerType toInnerType(E flag) const noexcept { return static_cast<InnerType>(flag); }
public:
using Type = InnerType;
/**
* @brief Constructs a Flags object from a value of the enum `E`.
* @param flag An value of the enum `E`.
*/
constexpr Flags(E flag) noexcept: flags{toInnerType(flag)} { }
/**
* @brief Constructs a Flags object from an instance of the underlying type
* of the enum `E`.
* @param f An instance of the underlying type of the enum `E`.
*/
constexpr Flags(Type f): flags{f} { }
/**
* @brief Constructs an uninitialized Flags object.
*/
constexpr Flags(): flags{} { }
constexpr Flags(const Flags &f) noexcept: flags{f.flags} { }
constexpr Flags(Flags &&f) noexcept: flags{std::move(f.flags)} { }
~Flags() noexcept { static_assert(std::is_enum<E>::value, "!"); }
constexpr Flags& operator=(const Flags &f) noexcept {
flags = f.flags;
return *this;
}
constexpr Flags& operator=(Flags &&f) noexcept {
flags = std::move(f.flags);
return *this;
}
/**
* @brief Or operator.
* @param f A valid instance of Flags.
* @return This instance _or-ed_ with `f`.
*/
constexpr Flags operator|(const Flags &f) const noexcept { return Flags(flags | f.flags); }
/**
* @brief Or operator.
* @param flag A value of the enum `E`.
* @return This instance _or-ed_ with `flag`.
*/
constexpr Flags operator|(E flag) const noexcept { return Flags(flags | toInnerType(flag)); }
/**
* @brief And operator.
* @param f A valid instance of Flags.
* @return This instance _and-ed_ with `f`.
*/
constexpr Flags operator&(const Flags &f) const noexcept { return Flags(flags & f.flags); }
/**
* @brief And operator.
* @param flag A value of the enum `E`.
* @return This instance _and-ed_ with `flag`.
*/
constexpr Flags operator&(E flag) const noexcept { return Flags(flags & toInnerType(flag)); }
/**
* @brief Checks if this instance is initialized.
* @return False if it's uninitialized, true otherwise.
*/
explicit constexpr operator bool() const noexcept { return !(flags == InnerType{}); }
/**
* @brief Casts the instance to the underlying type of `E`.
* @return An integral representation of the contained flags.
*/
constexpr operator Type() const noexcept { return flags; }
private:
InnerType flags;
};
/**
* @brief Windows size representation.
*/
struct WinSize {
int width; /*!< The _width_ of the given window. */
int height; /*!< The _height_ of the given window. */
};
using HandleType = details::UVHandleType;
using FileHandle = details::UVTypeWrapper<uv_file>;
using OSSocketHandle = details::UVTypeWrapper<uv_os_sock_t>;
using OSFileDescriptor = details::UVTypeWrapper<uv_os_fd_t>;
using TimeSpec = uv_timespec_t;
using Stat = uv_stat_t;
using Uid = uv_uid_t;
using Gid = uv_gid_t;
/**
* @brief The IPv4 tag.
*
* To be used as template parameter to switch between IPv4 and IPv6.
*/
struct IPv4 { };
/**
* @brief The IPv6 tag.
*
* To be used as template parameter to switch between IPv4 and IPv6.
*/
struct IPv6 { };
/**
* @brief Address representation.
*/
struct Addr {
std::string ip; /*!< Either an IPv4 or an IPv6. */
unsigned int port; /*!< A valid service identifier. */
};
/**
* \brief CPU information.
*/
struct CPUInfo {
using CPUTime = decltype(uv_cpu_info_t::cpu_times);
std::string model; /*!< The model of the CPU. */
int speed; /*!< The frequency of the CPU. */
/**
* @brief CPU times.
*
* It is built up of the following data members: `user`, `nice`, `sys`,
* `idle`, `irq`, all of them having type `uint64_t`.
*/
CPUTime times;
};
/**
* \brief Interface address.
*/
struct InterfaceAddress {
std::string name; /*!< The name of the interface (as an example _eth0_). */
std::string physical; /*!< The physical address. */
bool internal; /*!< True if it is an internal interface (as an example _loopback_), false otherwise. */
Addr address; /*!< The address of the given interface. */
Addr netmask; /*!< The netmask of the given interface. */
};
namespace details {
template<typename>
struct IpTraits;
template<>
struct IpTraits<IPv4> {
using Type = sockaddr_in;
using AddrFuncType = int(*)(const char *, int, Type *);
using NameFuncType = int(*)(const Type *, char *, std::size_t);
static constexpr AddrFuncType addrFunc = &uv_ip4_addr;
static constexpr NameFuncType nameFunc = &uv_ip4_name;
static constexpr auto sinPort(const Type *addr) { return addr->sin_port; }
};
template<>
struct IpTraits<IPv6> {
using Type = sockaddr_in6;
using AddrFuncType = int(*)(const char *, int, Type *);
using NameFuncType = int(*)(const Type *, char *, std::size_t);
static constexpr AddrFuncType addrFunc = &uv_ip6_addr;
static constexpr NameFuncType nameFunc = &uv_ip6_name;
static constexpr auto sinPort(const Type *addr) { return addr->sin6_port; }
};
template<typename I, typename..., std::size_t N = 128>
Addr address(const typename details::IpTraits<I>::Type *aptr) noexcept {
Addr addr;
char name[N];
int err = details::IpTraits<I>::nameFunc(aptr, name, N);
if(0 == err) {
addr.port = ntohs(details::IpTraits<I>::sinPort(aptr));
addr.ip = std::string{name};
}
return addr;
}
template<typename I, typename F, typename H>
Addr address(F &&f, const H *handle) noexcept {
sockaddr_storage ssto;
int len = sizeof(ssto);
Addr addr{};
int err = std::forward<F>(f)(handle, reinterpret_cast<sockaddr *>(&ssto), &len);
if(0 == err) {
typename IpTraits<I>::Type *aptr = reinterpret_cast<typename IpTraits<I>::Type *>(&ssto);
addr = address<I>(aptr);
}
return addr;
}
template<typename F, typename H, typename..., std::size_t N = 128>
std::string path(F &&f, H *handle) noexcept {
std::size_t size = N;
char buf[size];
std::string str{};
auto err = std::forward<F>(f)(handle, buf, &size);
if(UV_ENOBUFS == err) {
std::unique_ptr<char[]> data{new char[size]};
err = std::forward<F>(f)(handle, data.get(), &size);
if(0 == err) {
str = data.get();
}
} else {
str.assign(buf, size);
}
return str;
}
}
/**
* @brief Miscellaneous utilities.
*
* Miscellaneous functions that don’t really belong to any other class.
*/
struct Utilities {
using MallocFuncType = void*(*)(size_t);
using ReallocFuncType = void*(*)(void*, size_t);
using CallocFuncType = void*(*)(size_t, size_t);
using FreeFuncType = void(*)(void*);
/**
* @brief Gets the type of the stream to be used with the given descriptor.
*
* Returns the type of stream that should be used with a given file
* descriptor.<br/>
* Usually this will be used during initialization to guess the type of the
* stdio streams.
*
* @param file A valid descriptor.
* @return One of the following types:
*
* * `HandleType::UNKNOWN`
* * `HandleType::PIPE`
* * `HandleType::TCP`
* * `HandleType::TTY`
* * `HandleType::UDP`
* * `HandleType::FILE`
*/
static HandleType guessHandle(FileHandle file) noexcept {
auto type = uv_guess_handle(file);
switch(type) {
case UV_ASYNC:
return HandleType::ASYNC;
case UV_CHECK:
return HandleType::CHECK;
case UV_FS_EVENT:
return HandleType::FS_EVENT;
case UV_FS_POLL:
return HandleType::FS_POLL;
case UV_HANDLE:
return HandleType::HANDLE;
case UV_IDLE:
return HandleType::IDLE;
case UV_NAMED_PIPE:
return HandleType::PIPE;
case UV_POLL:
return HandleType::POLL;
case UV_PREPARE:
return HandleType::PREPARE;
case UV_PROCESS:
return HandleType::PROCESS;
case UV_STREAM:
return HandleType::STREAM;
case UV_TCP:
return HandleType::TCP;
case UV_TIMER:
return HandleType::TIMER;
case UV_TTY:
return HandleType::TTY;
case UV_UDP:
return HandleType::UDP;
case UV_SIGNAL:
return HandleType::SIGNAL;
case UV_FILE:
return HandleType::FILE;
default:
return HandleType::UNKNOWN;
}
}
/** @brief Gets information about the CPUs on the system.
*
* This function can be used to query the underlying system and get a set of
* descriptors of all the available CPUs.
*
* @return A set of descriptors of all the available CPUs.
*/
static std::vector<CPUInfo> cpuInfo() noexcept {
std::vector<CPUInfo> cpuinfos;
uv_cpu_info_t *infos;
int count;
if(0 == uv_cpu_info(&infos, &count)) {
std::for_each(infos, infos+count, [&cpuinfos](const auto &info) {
CPUInfo cpuinfo;
cpuinfo.model = info.model;
cpuinfo.speed = info.speed;
cpuinfo.times = info.cpu_times;
cpuinfos.push_back(std::move(cpuinfo));
});
uv_free_cpu_info(infos, count);
}
return cpuinfos;
}
/**
* @brief Gets a set of descriptors of all the available interfaces.
*
* This function can be used to query the underlying system and get a set of
* descriptors of all the available interfaces, either internal or not.
*
* @return A set of descriptors of all the available interfaces.
*/
static std::vector<InterfaceAddress> interfaceAddresses() noexcept {
std::vector<InterfaceAddress> interfaces;
uv_interface_address_t *ifaces;
int count;
if(0 == uv_interface_addresses(&ifaces, &count)) {
std::for_each(ifaces, ifaces+count, [&interfaces](const auto &iface) {
InterfaceAddress interface;
interface.name = iface.name;
interface.physical = iface.phys_addr;
interface.internal = iface.is_internal;
if(iface.address.address4.sin_family == AF_INET) {
interface.address = details::address<IPv4>(&iface.address.address4);
interface.netmask = details::address<IPv4>(&iface.netmask.netmask4);
} else if(iface.address.address4.sin_family == AF_INET6) {
interface.address = details::address<IPv6>(&iface.address.address6);
interface.netmask = details::address<IPv6>(&iface.netmask.netmask6);
}
interfaces.push_back(std::move(interface));
});
uv_free_interface_addresses(ifaces, count);
}
return interfaces;
}
/**
* @brief Override the use of some standard library’s functions.
*
* Override the use of the standard library’s memory allocation
* functions.<br/>
* This method must be invoked before any other `uvw` function is called or
* after all resources have been freed and thus the underlying library
* doesn’t reference any allocated memory chunk.
*
* If any of the function pointers is _null_, the invokation will fail.
*
* **Note**: there is no protection against changing the allocator multiple
* times. If the user changes it they are responsible for making sure the
* allocator is changed while no memory was allocated with the previous
* allocator, or that they are compatible.
*
* @param mallocFunc Replacement function for _malloc_.
* @param reallocFunc Replacement function for _realloc_.
* @param callocFunc Replacement function for _calloc_.
* @param freeFunc Replacement function for _free_.
* @return True in case of success, false otherwise.
*/
static bool replaceAllocator(MallocFuncType mallocFunc, ReallocFuncType reallocFunc, CallocFuncType callocFunc, FreeFuncType freeFunc) noexcept {
return (0 == uv_replace_allocator(mallocFunc, reallocFunc, callocFunc, freeFunc));
}
/**
* @brief Gets the load average.
* @return `[0,0,0]` on Windows (not available), the load average otherwise.
*/
static std::array<double, 3> loadAverage() noexcept {
std::array<double, 3> avg;
uv_loadavg(avg.data());
return avg;
}
};
/**
* TODO
*
* * uv_uptime
* * uv_getrusage
* * uv_exepath
* * uv_cwd
* * uv_chdir
* * uv_os_homedir
* * uv_os_tmpdir
* * uv_os_get_passwd
* * uv_os_free_passwd
* * uv_get_total_memory
* * uv_hrtime
*/
}
<commit_msg>added Utilities::totalMemory<commit_after>#pragma once
#include <type_traits>
#include <algorithm>
#include <stdexcept>
#include <cstddef>
#include <utility>
#include <string>
#include <vector>
#include <array>
#include <uv.h>
namespace uvw {
namespace details {
enum class UVHandleType: std::underlying_type_t<uv_handle_type> {
UNKNOWN = UV_UNKNOWN_HANDLE,
ASYNC = UV_ASYNC,
CHECK = UV_CHECK,
FS_EVENT = UV_FS_EVENT,
FS_POLL = UV_FS_POLL,
HANDLE = UV_HANDLE,
IDLE = UV_IDLE,
PIPE = UV_NAMED_PIPE,
POLL = UV_POLL,
PREPARE = UV_PREPARE,
PROCESS = UV_PROCESS,
STREAM = UV_STREAM,
TCP = UV_TCP,
TIMER = UV_TIMER,
TTY = UV_TTY,
UDP = UV_UDP,
SIGNAL = UV_SIGNAL,
FILE = UV_FILE
};
template<typename T>
struct UVTypeWrapper {
using Type = T;
constexpr UVTypeWrapper(Type val): value{val} { }
constexpr operator Type() const noexcept { return value; }
private:
const Type value;
};
}
/**
* @brief Utility class to handle flags.
*
* This class can be used to handle flags of a same enumeration type.<br/>
* It is meant to be used as an argument for functions and member methods and
* as part of events.<br/>
* `Flags<E>` objects can be easily _or-ed_ and _and-ed_ with other instances of
* the same type or with instances of the type `E` (that is, the actual flag
* type), thus converted to the underlying type when needed.
*/
template<typename E>
class Flags final {
using InnerType = std::underlying_type_t<E>;
constexpr InnerType toInnerType(E flag) const noexcept { return static_cast<InnerType>(flag); }
public:
using Type = InnerType;
/**
* @brief Constructs a Flags object from a value of the enum `E`.
* @param flag An value of the enum `E`.
*/
constexpr Flags(E flag) noexcept: flags{toInnerType(flag)} { }
/**
* @brief Constructs a Flags object from an instance of the underlying type
* of the enum `E`.
* @param f An instance of the underlying type of the enum `E`.
*/
constexpr Flags(Type f): flags{f} { }
/**
* @brief Constructs an uninitialized Flags object.
*/
constexpr Flags(): flags{} { }
constexpr Flags(const Flags &f) noexcept: flags{f.flags} { }
constexpr Flags(Flags &&f) noexcept: flags{std::move(f.flags)} { }
~Flags() noexcept { static_assert(std::is_enum<E>::value, "!"); }
constexpr Flags& operator=(const Flags &f) noexcept {
flags = f.flags;
return *this;
}
constexpr Flags& operator=(Flags &&f) noexcept {
flags = std::move(f.flags);
return *this;
}
/**
* @brief Or operator.
* @param f A valid instance of Flags.
* @return This instance _or-ed_ with `f`.
*/
constexpr Flags operator|(const Flags &f) const noexcept { return Flags(flags | f.flags); }
/**
* @brief Or operator.
* @param flag A value of the enum `E`.
* @return This instance _or-ed_ with `flag`.
*/
constexpr Flags operator|(E flag) const noexcept { return Flags(flags | toInnerType(flag)); }
/**
* @brief And operator.
* @param f A valid instance of Flags.
* @return This instance _and-ed_ with `f`.
*/
constexpr Flags operator&(const Flags &f) const noexcept { return Flags(flags & f.flags); }
/**
* @brief And operator.
* @param flag A value of the enum `E`.
* @return This instance _and-ed_ with `flag`.
*/
constexpr Flags operator&(E flag) const noexcept { return Flags(flags & toInnerType(flag)); }
/**
* @brief Checks if this instance is initialized.
* @return False if it's uninitialized, true otherwise.
*/
explicit constexpr operator bool() const noexcept { return !(flags == InnerType{}); }
/**
* @brief Casts the instance to the underlying type of `E`.
* @return An integral representation of the contained flags.
*/
constexpr operator Type() const noexcept { return flags; }
private:
InnerType flags;
};
/**
* @brief Windows size representation.
*/
struct WinSize {
int width; /*!< The _width_ of the given window. */
int height; /*!< The _height_ of the given window. */
};
using HandleType = details::UVHandleType;
using FileHandle = details::UVTypeWrapper<uv_file>;
using OSSocketHandle = details::UVTypeWrapper<uv_os_sock_t>;
using OSFileDescriptor = details::UVTypeWrapper<uv_os_fd_t>;
using TimeSpec = uv_timespec_t;
using Stat = uv_stat_t;
using Uid = uv_uid_t;
using Gid = uv_gid_t;
/**
* @brief The IPv4 tag.
*
* To be used as template parameter to switch between IPv4 and IPv6.
*/
struct IPv4 { };
/**
* @brief The IPv6 tag.
*
* To be used as template parameter to switch between IPv4 and IPv6.
*/
struct IPv6 { };
/**
* @brief Address representation.
*/
struct Addr {
std::string ip; /*!< Either an IPv4 or an IPv6. */
unsigned int port; /*!< A valid service identifier. */
};
/**
* \brief CPU information.
*/
struct CPUInfo {
using CPUTime = decltype(uv_cpu_info_t::cpu_times);
std::string model; /*!< The model of the CPU. */
int speed; /*!< The frequency of the CPU. */
/**
* @brief CPU times.
*
* It is built up of the following data members: `user`, `nice`, `sys`,
* `idle`, `irq`, all of them having type `uint64_t`.
*/
CPUTime times;
};
/**
* \brief Interface address.
*/
struct InterfaceAddress {
std::string name; /*!< The name of the interface (as an example _eth0_). */
std::string physical; /*!< The physical address. */
bool internal; /*!< True if it is an internal interface (as an example _loopback_), false otherwise. */
Addr address; /*!< The address of the given interface. */
Addr netmask; /*!< The netmask of the given interface. */
};
namespace details {
template<typename>
struct IpTraits;
template<>
struct IpTraits<IPv4> {
using Type = sockaddr_in;
using AddrFuncType = int(*)(const char *, int, Type *);
using NameFuncType = int(*)(const Type *, char *, std::size_t);
static constexpr AddrFuncType addrFunc = &uv_ip4_addr;
static constexpr NameFuncType nameFunc = &uv_ip4_name;
static constexpr auto sinPort(const Type *addr) { return addr->sin_port; }
};
template<>
struct IpTraits<IPv6> {
using Type = sockaddr_in6;
using AddrFuncType = int(*)(const char *, int, Type *);
using NameFuncType = int(*)(const Type *, char *, std::size_t);
static constexpr AddrFuncType addrFunc = &uv_ip6_addr;
static constexpr NameFuncType nameFunc = &uv_ip6_name;
static constexpr auto sinPort(const Type *addr) { return addr->sin6_port; }
};
template<typename I, typename..., std::size_t N = 128>
Addr address(const typename details::IpTraits<I>::Type *aptr) noexcept {
Addr addr;
char name[N];
int err = details::IpTraits<I>::nameFunc(aptr, name, N);
if(0 == err) {
addr.port = ntohs(details::IpTraits<I>::sinPort(aptr));
addr.ip = std::string{name};
}
return addr;
}
template<typename I, typename F, typename H>
Addr address(F &&f, const H *handle) noexcept {
sockaddr_storage ssto;
int len = sizeof(ssto);
Addr addr{};
int err = std::forward<F>(f)(handle, reinterpret_cast<sockaddr *>(&ssto), &len);
if(0 == err) {
typename IpTraits<I>::Type *aptr = reinterpret_cast<typename IpTraits<I>::Type *>(&ssto);
addr = address<I>(aptr);
}
return addr;
}
template<typename F, typename H, typename..., std::size_t N = 128>
std::string path(F &&f, H *handle) noexcept {
std::size_t size = N;
char buf[size];
std::string str{};
auto err = std::forward<F>(f)(handle, buf, &size);
if(UV_ENOBUFS == err) {
std::unique_ptr<char[]> data{new char[size]};
err = std::forward<F>(f)(handle, data.get(), &size);
if(0 == err) {
str = data.get();
}
} else {
str.assign(buf, size);
}
return str;
}
}
/**
* @brief Miscellaneous utilities.
*
* Miscellaneous functions that don’t really belong to any other class.
*/
struct Utilities {
using MallocFuncType = void*(*)(size_t);
using ReallocFuncType = void*(*)(void*, size_t);
using CallocFuncType = void*(*)(size_t, size_t);
using FreeFuncType = void(*)(void*);
/**
* @brief Gets the type of the stream to be used with the given descriptor.
*
* Returns the type of stream that should be used with a given file
* descriptor.<br/>
* Usually this will be used during initialization to guess the type of the
* stdio streams.
*
* @param file A valid descriptor.
* @return One of the following types:
*
* * `HandleType::UNKNOWN`
* * `HandleType::PIPE`
* * `HandleType::TCP`
* * `HandleType::TTY`
* * `HandleType::UDP`
* * `HandleType::FILE`
*/
static HandleType guessHandle(FileHandle file) noexcept {
auto type = uv_guess_handle(file);
switch(type) {
case UV_ASYNC:
return HandleType::ASYNC;
case UV_CHECK:
return HandleType::CHECK;
case UV_FS_EVENT:
return HandleType::FS_EVENT;
case UV_FS_POLL:
return HandleType::FS_POLL;
case UV_HANDLE:
return HandleType::HANDLE;
case UV_IDLE:
return HandleType::IDLE;
case UV_NAMED_PIPE:
return HandleType::PIPE;
case UV_POLL:
return HandleType::POLL;
case UV_PREPARE:
return HandleType::PREPARE;
case UV_PROCESS:
return HandleType::PROCESS;
case UV_STREAM:
return HandleType::STREAM;
case UV_TCP:
return HandleType::TCP;
case UV_TIMER:
return HandleType::TIMER;
case UV_TTY:
return HandleType::TTY;
case UV_UDP:
return HandleType::UDP;
case UV_SIGNAL:
return HandleType::SIGNAL;
case UV_FILE:
return HandleType::FILE;
default:
return HandleType::UNKNOWN;
}
}
/** @brief Gets information about the CPUs on the system.
*
* This function can be used to query the underlying system and get a set of
* descriptors of all the available CPUs.
*
* @return A set of descriptors of all the available CPUs.
*/
static std::vector<CPUInfo> cpuInfo() noexcept {
std::vector<CPUInfo> cpuinfos;
uv_cpu_info_t *infos;
int count;
if(0 == uv_cpu_info(&infos, &count)) {
std::for_each(infos, infos+count, [&cpuinfos](const auto &info) {
CPUInfo cpuinfo;
cpuinfo.model = info.model;
cpuinfo.speed = info.speed;
cpuinfo.times = info.cpu_times;
cpuinfos.push_back(std::move(cpuinfo));
});
uv_free_cpu_info(infos, count);
}
return cpuinfos;
}
/**
* @brief Gets a set of descriptors of all the available interfaces.
*
* This function can be used to query the underlying system and get a set of
* descriptors of all the available interfaces, either internal or not.
*
* @return A set of descriptors of all the available interfaces.
*/
static std::vector<InterfaceAddress> interfaceAddresses() noexcept {
std::vector<InterfaceAddress> interfaces;
uv_interface_address_t *ifaces;
int count;
if(0 == uv_interface_addresses(&ifaces, &count)) {
std::for_each(ifaces, ifaces+count, [&interfaces](const auto &iface) {
InterfaceAddress interface;
interface.name = iface.name;
interface.physical = iface.phys_addr;
interface.internal = iface.is_internal;
if(iface.address.address4.sin_family == AF_INET) {
interface.address = details::address<IPv4>(&iface.address.address4);
interface.netmask = details::address<IPv4>(&iface.netmask.netmask4);
} else if(iface.address.address4.sin_family == AF_INET6) {
interface.address = details::address<IPv6>(&iface.address.address6);
interface.netmask = details::address<IPv6>(&iface.netmask.netmask6);
}
interfaces.push_back(std::move(interface));
});
uv_free_interface_addresses(ifaces, count);
}
return interfaces;
}
/**
* @brief Override the use of some standard library’s functions.
*
* Override the use of the standard library’s memory allocation
* functions.<br/>
* This method must be invoked before any other `uvw` function is called or
* after all resources have been freed and thus the underlying library
* doesn’t reference any allocated memory chunk.
*
* If any of the function pointers is _null_, the invokation will fail.
*
* **Note**: there is no protection against changing the allocator multiple
* times. If the user changes it they are responsible for making sure the
* allocator is changed while no memory was allocated with the previous
* allocator, or that they are compatible.
*
* @param mallocFunc Replacement function for _malloc_.
* @param reallocFunc Replacement function for _realloc_.
* @param callocFunc Replacement function for _calloc_.
* @param freeFunc Replacement function for _free_.
* @return True in case of success, false otherwise.
*/
static bool replaceAllocator(MallocFuncType mallocFunc, ReallocFuncType reallocFunc, CallocFuncType callocFunc, FreeFuncType freeFunc) noexcept {
return (0 == uv_replace_allocator(mallocFunc, reallocFunc, callocFunc, freeFunc));
}
/**
* @brief Gets the load average.
* @return `[0,0,0]` on Windows (not available), the load average otherwise.
*/
static std::array<double, 3> loadAverage() noexcept {
std::array<double, 3> avg;
uv_loadavg(avg.data());
return avg;
}
/**
* @brief Gets memory information (in bytes).
* @return Memory information.
*/
static uint64_t totalMemory() noexcept {
return uv_get_total_memory();
}
};
/**
* TODO
*
* * uv_uptime
* * uv_getrusage
* * uv_exepath
* * uv_cwd
* * uv_chdir
* * uv_os_homedir
* * uv_os_tmpdir
* * uv_os_get_passwd
* * uv_os_free_passwd
* * uv_hrtime
*/
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: acceptor.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2006-05-02 17:13:21 $
*
* 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 _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_
#include <com/sun/star/uno/Exception.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_CONNECTION_XACCEPTOR_HPP_
#include <com/sun/star/connection/XAcceptor.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_BRIDGE_XINSTANCEPROVIDER_HPP_
#include <com/sun/star/bridge/XInstanceProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_BRIDGE_XBRIDGEFACTORY_HPP_
#include <com/sun/star/bridge/XBridgeFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif
#ifndef _RTL_LOGFILE_HXX_
#include <rtl/logfile.hxx>
#endif
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <osl/mutex.hxx>
#include <osl/conditn.hxx>
#include <osl/thread.hxx>
using namespace ::rtl;
using namespace ::osl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::bridge;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::connection;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::registry;
namespace desktop {
class Acceptor
: public ::cppu::WeakImplHelper2<XServiceInfo, XInitialization>
{
private:
static const sal_Char *serviceName;
static const sal_Char *implementationName;
static const sal_Char *supportedServiceNames[];
static Mutex m_aMutex;
Condition m_cEnable;
Reference< XMultiServiceFactory > m_rSMgr;
Reference< XInterface > m_rContext;
Reference< XAcceptor > m_rAcceptor;
Reference< XBridgeFactory > m_rBridgeFactory;
OUString m_aAcceptString;
OUString m_aConnectString;
OUString m_aProtocol;
sal_Bool m_bInit;
oslThread m_aThread;
public:
Acceptor( const Reference< XMultiServiceFactory >& aFactory );
virtual ~Acceptor();
void SAL_CALL run();
// XService info
static OUString impl_getImplementationName();
virtual OUString SAL_CALL getImplementationName()
throw (RuntimeException);
static Sequence<OUString> impl_getSupportedServiceNames();
virtual Sequence<OUString> SAL_CALL getSupportedServiceNames()
throw (RuntimeException);
static sal_Bool impl_supportsService( const OUString& aName );
virtual sal_Bool SAL_CALL supportsService( const OUString& aName )
throw (RuntimeException);
// XInitialize
virtual void SAL_CALL initialize( const Sequence<Any>& aArguments )
throw ( Exception );
static Reference<XInterface> impl_getInstance( const Reference< XMultiServiceFactory >& aFactory );
};
class AccInstanceProvider : public ::cppu::WeakImplHelper1<XInstanceProvider>
{
private:
Reference<XMultiServiceFactory> m_rSMgr;
Reference<XConnection> m_rConnection;
public:
AccInstanceProvider(const Reference< XMultiServiceFactory >& aFactory,
const Reference< XConnection >& rConnection);
virtual ~AccInstanceProvider();
// XInstanceProvider
virtual Reference<XInterface> SAL_CALL getInstance (const OUString& aName )
throw ( NoSuchElementException );
};
} //namespace desktop
<commit_msg>INTEGRATION: CWS sb59 (1.4.52); FILE MERGED 2006/07/20 07:55:34 sb 1.4.52.1: #i67537# Made code warning-free.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: acceptor.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-10-12 14:15:13 $
*
* 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 _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_
#include <com/sun/star/uno/Exception.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_CONNECTION_XACCEPTOR_HPP_
#include <com/sun/star/connection/XAcceptor.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_BRIDGE_XINSTANCEPROVIDER_HPP_
#include <com/sun/star/bridge/XInstanceProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_BRIDGE_XBRIDGEFACTORY_HPP_
#include <com/sun/star/bridge/XBridgeFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif
#ifndef _RTL_LOGFILE_HXX_
#include <rtl/logfile.hxx>
#endif
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <osl/mutex.hxx>
#include <osl/conditn.hxx>
#include <osl/thread.hxx>
using namespace ::rtl;
using namespace ::osl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::bridge;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::connection;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::registry;
namespace desktop {
class Acceptor
: public ::cppu::WeakImplHelper2<XServiceInfo, XInitialization>
{
private:
static const sal_Char *serviceName;
static const sal_Char *implementationName;
static const sal_Char *supportedServiceNames[];
static Mutex m_aMutex;
Condition m_cEnable;
Reference< XMultiServiceFactory > m_rSMgr;
Reference< XInterface > m_rContext;
Reference< XAcceptor > m_rAcceptor;
Reference< XBridgeFactory > m_rBridgeFactory;
OUString m_aAcceptString;
OUString m_aConnectString;
OUString m_aProtocol;
sal_Bool m_bInit;
public:
Acceptor( const Reference< XMultiServiceFactory >& aFactory );
virtual ~Acceptor();
void SAL_CALL run();
// XService info
static OUString impl_getImplementationName();
virtual OUString SAL_CALL getImplementationName()
throw (RuntimeException);
static Sequence<OUString> impl_getSupportedServiceNames();
virtual Sequence<OUString> SAL_CALL getSupportedServiceNames()
throw (RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const OUString& aName )
throw (RuntimeException);
// XInitialize
virtual void SAL_CALL initialize( const Sequence<Any>& aArguments )
throw ( Exception );
static Reference<XInterface> impl_getInstance( const Reference< XMultiServiceFactory >& aFactory );
};
class AccInstanceProvider : public ::cppu::WeakImplHelper1<XInstanceProvider>
{
private:
Reference<XMultiServiceFactory> m_rSMgr;
Reference<XConnection> m_rConnection;
public:
AccInstanceProvider(const Reference< XMultiServiceFactory >& aFactory,
const Reference< XConnection >& rConnection);
virtual ~AccInstanceProvider();
// XInstanceProvider
virtual Reference<XInterface> SAL_CALL getInstance (const OUString& aName )
throw ( NoSuchElementException );
};
} //namespace desktop
<|endoftext|> |
<commit_before>
#include "helper.h"
#include <iostream>
#include "ops.h"
#include "vector.h"
#include "face.h"
#include "solid.h"
#include <TopAbs_ShapeEnum.hxx>
#include <BRepPrimAPI_MakePrism.hxx>
#include <TColgp_Array1OfPnt2d.hxx>
#include <Geom2dAPI_PointsToBSpline.hxx>
#include <Geom2d_BSplineCurve.hxx>
#include <Geom2d_BezierCurve.hxx>
#include <Geom2dConvert_BSplineCurveToBezierCurve.hxx>
void mox::ops::Init(v8::Local<v8::Object> namespc)
{
NODE_SET_METHOD(namespc, "extrude", mox::ops::extrude);
NODE_SET_METHOD(namespc, "approximate2d", mox::ops::approximate2d);
}
void mox::ops::extrude(const v8::FunctionCallbackInfo<v8::Value>& info)
{
mox::Face *face = Nan::ObjectWrap::Unwrap<mox::Face>(info[0]->ToObject());
mox::Vector *dir = Nan::ObjectWrap::Unwrap<mox::Vector>(info[1]->ToObject());
TopoDS_Shape occSolid = BRepPrimAPI_MakePrism(face->toOCC(), dir->toOCC());
if(occSolid.ShapeType() != TopAbs_SOLID) {
Nan::ThrowError("Extrude didn't generate Solid");
return;
}
v8::Local<v8::Object> jsSolid = mox::Solid::NewInstance();
mox::Solid *solid = Nan::ObjectWrap::Unwrap<mox::Solid>(jsSolid);
assert(solid != NULL);
solid->setOCC(occSolid);
info.GetReturnValue().Set(jsSolid);
}
void mox::ops::approximate2d(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate *isolate = info.GetIsolate();
uint nPoints = info.Length();
TColgp_Array1OfPnt2d arrPoints(1, nPoints);
for(uint i=0; i<nPoints; i++) {
v8::Local<v8::Array> coord = v8::Handle<v8::Array>::Cast(info[i]);
arrPoints.SetValue(i+1,
gp_Pnt2d(coord->Get(0)->NumberValue(), coord->Get(1)->NumberValue()));
}
Geom2dAPI_PointsToBSpline api(arrPoints, 3,3,GeomAbs_G1, 1e-6);
Geom2dConvert_BSplineCurveToBezierCurve convapi(api.Curve());
v8::Local<v8::Array> bezArray =
v8::Array::New(v8::Isolate::GetCurrent(), convapi.NbArcs());
for(uint i=1; i<=convapi.NbArcs(); i++) {
assert(convapi.Arc(i)->Degree() == 3);
v8::Local<v8::Array> cpointsArray =
v8::Array::New(v8::Isolate::GetCurrent(), 4);
for(uint j=1; j<=convapi.Arc(i)->NbPoles(); j++) {
v8::Local<v8::Array> cpoint = v8::Array::New(isolate, 2);
gp_Pnt2d pole = convapi.Arc(i)->Pole(j);
cpoint->Set(0, v8::Number::New(isolate, pole.X()));
cpoint->Set(1, v8::Number::New(isolate, pole.Y()));
cpointsArray->Set(j-1, cpoint);
}
bezArray->Set(i-1, cpointsArray);
}
info.GetReturnValue().Set(bezArray);
}
<commit_msg>Use Nan::New with v8::Array<commit_after>
#include "helper.h"
#include <iostream>
#include "ops.h"
#include "vector.h"
#include "face.h"
#include "solid.h"
#include <TopAbs_ShapeEnum.hxx>
#include <BRepPrimAPI_MakePrism.hxx>
#include <TColgp_Array1OfPnt2d.hxx>
#include <Geom2dAPI_PointsToBSpline.hxx>
#include <Geom2d_BSplineCurve.hxx>
#include <Geom2d_BezierCurve.hxx>
#include <Geom2dConvert_BSplineCurveToBezierCurve.hxx>
void mox::ops::Init(v8::Local<v8::Object> namespc)
{
NODE_SET_METHOD(namespc, "extrude", mox::ops::extrude);
NODE_SET_METHOD(namespc, "approximate2d", mox::ops::approximate2d);
}
void mox::ops::extrude(const v8::FunctionCallbackInfo<v8::Value>& info)
{
mox::Face *face = Nan::ObjectWrap::Unwrap<mox::Face>(info[0]->ToObject());
mox::Vector *dir = Nan::ObjectWrap::Unwrap<mox::Vector>(info[1]->ToObject());
TopoDS_Shape occSolid = BRepPrimAPI_MakePrism(face->toOCC(), dir->toOCC());
if(occSolid.ShapeType() != TopAbs_SOLID) {
Nan::ThrowError("Extrude didn't generate Solid");
return;
}
v8::Local<v8::Object> jsSolid = mox::Solid::NewInstance();
mox::Solid *solid = Nan::ObjectWrap::Unwrap<mox::Solid>(jsSolid);
assert(solid != NULL);
solid->setOCC(occSolid);
info.GetReturnValue().Set(jsSolid);
}
void mox::ops::approximate2d(const v8::FunctionCallbackInfo<v8::Value>& info)
{
uint nPoints = info.Length();
TColgp_Array1OfPnt2d arrPoints(1, nPoints);
for(uint i=0; i<nPoints; i++) {
v8::Local<v8::Array> coord = v8::Handle<v8::Array>::Cast(info[i]);
arrPoints.SetValue(i+1,
gp_Pnt2d(coord->Get(0)->NumberValue(), coord->Get(1)->NumberValue()));
}
Geom2dAPI_PointsToBSpline api(arrPoints, 3,3,GeomAbs_G1, 1e-6);
Geom2dConvert_BSplineCurveToBezierCurve convapi(api.Curve());
v8::Local<v8::Array> bezArray = Nan::New<v8::Array>(convapi.NbArcs());
for(uint i=1; i<=convapi.NbArcs(); i++) {
assert(convapi.Arc(i)->Degree() == 3);
v8::Local<v8::Array> cpointsArray = Nan::New<v8::Array>(4);
for(uint j=1; j<=convapi.Arc(i)->NbPoles(); j++) {
v8::Local<v8::Array> cpoint = Nan::New<v8::Array>(2);
gp_Pnt2d pole = convapi.Arc(i)->Pole(j);
cpoint->Set(0, Nan::New<v8::Number>(pole.X()));
cpoint->Set(1, Nan::New<v8::Number>(pole.Y()));
cpointsArray->Set(j-1, cpoint);
}
bezArray->Set(i-1, cpointsArray);
}
info.GetReturnValue().Set(bezArray);
}
<|endoftext|> |
<commit_before>// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: [email protected] (Joshua Marantz)
// Author: [email protected] (Shawn Ligocki)
// Author: [email protected] (Jeff Kaufman)
// TODO(jefftk): share more of this code with apache's log_message_handler
#include "log_message_handler.h"
#include <unistd.h>
#include <limits>
#include <string>
#include "base/debug/debugger.h"
#include "base/debug/stack_trace.h"
#include "base/logging.h"
#include "net/instaweb/public/version.h"
#include "net/instaweb/util/public/string_util.h"
// Make sure we don't attempt to use LOG macros here, since doing so
// would cause us to go into an infinite log loop.
#undef LOG
#define LOG USING_LOG_HERE_WOULD_CAUSE_INFINITE_RECURSION
namespace {
ngx_log_t* log = NULL;
ngx_uint_t GetNgxLogLevel(int severity) {
switch (severity) {
case logging::LOG_INFO:
return NGX_LOG_INFO;
case logging::LOG_WARNING:
return NGX_LOG_WARN;
case logging::LOG_ERROR:
return NGX_LOG_ERR;
case logging::LOG_ERROR_REPORT:
case logging::LOG_FATAL:
return NGX_LOG_ALERT;
default: // For VLOG(s)
return NGX_LOG_DEBUG;
}
}
bool LogMessageHandler(int severity, const char* file, int line,
size_t message_start, const GoogleString& str) {
ngx_uint_t this_log_level = GetNgxLogLevel(severity);
GoogleString message = str;
if (severity == logging::LOG_FATAL) {
if (base::debug::BeingDebugged()) {
base::debug::BreakDebugger();
} else {
base::debug::StackTrace trace;
std::ostringstream stream;
trace.OutputToStream(&stream);
message.append(stream.str());
}
}
// Trim the newline off the end of the message string.
size_t last_msg_character_index = message.length() - 1;
if (message[last_msg_character_index] == '\n') {
message.resize(last_msg_character_index);
}
ngx_log_error(this_log_level, log, 0, "[ngx_pagespeed %s] %s",
net_instaweb::kModPagespeedVersion,
message.c_str());
if (severity == logging::LOG_FATAL) {
// Crash the process to generate a dump.
base::debug::BreakDebugger();
}
return true;
}
} // namespace
namespace net_instaweb {
namespace log_message_handler {
const int kDebugLogLevel = -2;
void Install(ngx_log_t* log_in) {
log = log_in;
logging::SetLogMessageHandler(&LogMessageHandler);
// All VLOG(2) and higher will be displayed as DEBUG logs if the nginx log
// level is DEBUG.
if (log->log_level >= NGX_LOG_DEBUG) {
logging::SetMinLogLevel(-2);
}
}
} // namespace log_message_handler
} // namespace net_instaweb
<commit_msg>logging: remove unused constant<commit_after>// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: [email protected] (Joshua Marantz)
// Author: [email protected] (Shawn Ligocki)
// Author: [email protected] (Jeff Kaufman)
// TODO(jefftk): share more of this code with apache's log_message_handler
#include "log_message_handler.h"
#include <unistd.h>
#include <limits>
#include <string>
#include "base/debug/debugger.h"
#include "base/debug/stack_trace.h"
#include "base/logging.h"
#include "net/instaweb/public/version.h"
#include "net/instaweb/util/public/string_util.h"
// Make sure we don't attempt to use LOG macros here, since doing so
// would cause us to go into an infinite log loop.
#undef LOG
#define LOG USING_LOG_HERE_WOULD_CAUSE_INFINITE_RECURSION
namespace {
ngx_log_t* log = NULL;
ngx_uint_t GetNgxLogLevel(int severity) {
switch (severity) {
case logging::LOG_INFO:
return NGX_LOG_INFO;
case logging::LOG_WARNING:
return NGX_LOG_WARN;
case logging::LOG_ERROR:
return NGX_LOG_ERR;
case logging::LOG_ERROR_REPORT:
case logging::LOG_FATAL:
return NGX_LOG_ALERT;
default: // For VLOG(s)
return NGX_LOG_DEBUG;
}
}
bool LogMessageHandler(int severity, const char* file, int line,
size_t message_start, const GoogleString& str) {
ngx_uint_t this_log_level = GetNgxLogLevel(severity);
GoogleString message = str;
if (severity == logging::LOG_FATAL) {
if (base::debug::BeingDebugged()) {
base::debug::BreakDebugger();
} else {
base::debug::StackTrace trace;
std::ostringstream stream;
trace.OutputToStream(&stream);
message.append(stream.str());
}
}
// Trim the newline off the end of the message string.
size_t last_msg_character_index = message.length() - 1;
if (message[last_msg_character_index] == '\n') {
message.resize(last_msg_character_index);
}
ngx_log_error(this_log_level, log, 0, "[ngx_pagespeed %s] %s",
net_instaweb::kModPagespeedVersion,
message.c_str());
if (severity == logging::LOG_FATAL) {
// Crash the process to generate a dump.
base::debug::BreakDebugger();
}
return true;
}
} // namespace
namespace net_instaweb {
namespace log_message_handler {
void Install(ngx_log_t* log_in) {
log = log_in;
logging::SetLogMessageHandler(&LogMessageHandler);
// All VLOG(2) and higher will be displayed as DEBUG logs if the nginx log
// level is DEBUG.
if (log->log_level >= NGX_LOG_DEBUG) {
logging::SetMinLogLevel(-2);
}
}
} // namespace log_message_handler
} // namespace net_instaweb
<|endoftext|> |
<commit_before>#ifndef UTIL_HPP
#define UTIL_HPP
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
#include <set>
#include <memory>
#include <typeinfo>
#include <functional>
#include <cxxabi.h>
#include "suppressWarnings.hpp"
#define abs(x) (x < 0 ? -x : x)
#define UNUSED(expr) (void)(expr)
#define ALL(container) std::begin(container), std::end(container)
typedef long long int64;
typedef unsigned long long uint64;
typedef unsigned int uint;
typedef std::set<std::string> TypeList;
template<typename T>
void println(T thing) {
std::cout << thing << std::endl;
}
template<typename T>
void print(T thing) {
std::cout << thing;
}
template<typename T, typename... Args>
void println(T thing, Args... args) {
if (sizeof...(args) == 1) {
print(thing);
print(" ");
print(args...);
std::cout << std::endl;
return;
}
print(thing);
print(" ");
print(args...);
}
template<typename T, typename... Args>
void print(T thing, Args... args) {
print(thing);
print(" ");
print(args...);
}
template<typename T>
bool contains(std::vector<T> vec, T item) {
return std::find(vec.begin(), vec.end(), item) != vec.end();
}
std::vector<std::string> split(const std::string& str, char delim) {
std::vector<std::string> vec {};
std::stringstream ss(str);
std::string item;
while (getline(ss, item, delim)) vec.push_back(item);
return vec;
}
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec) {
for (auto obj : vec) {
os << obj << " ";
}
return os;
}
template<typename T>
struct PtrUtil {
typedef std::unique_ptr<T> U;
typedef std::shared_ptr<T> Link;
typedef std::weak_ptr<T> WeakLink;
template<typename... Args>
static U unique(Args... args) {
return std::make_unique<T>(args...);
}
template<typename... Args>
static Link make(Args... args) {
return std::make_shared<T>(args...);
}
template<typename U>
static inline bool isSameType(std::shared_ptr<U> link) {
return typeid(T) == typeid(*link);
}
template<typename U>
static inline Link dynPtrCast(std::shared_ptr<U> link) {
return std::dynamic_pointer_cast<T>(link);
}
};
template<typename T>
struct VectorHash {
std::size_t operator()(const std::vector<T>& vec) const {
std::size_t seed = vec.size();
std::hash<T> hash;
for (const T& i : vec) {
seed ^= hash(i) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
};
std::string getAddressStringFrom(const void* ptr) {
std::stringstream ss;
ss << "0x" << std::hex << reinterpret_cast<std::uintptr_t>(ptr);
return ss.str();
}
std::string demangle(std::string name) {
int status;
return abi::__cxa_demangle(name.c_str(), 0, 0, &status);
}
#define COLLATE_TYPE const typename Container::value_type&
static const auto defaultCollateCombine = [](std::string prev, std::string current) {return prev + ", " + current;};
template<typename Container>
std::string collate(Container c,
std::function<std::string(COLLATE_TYPE)> objToString,
std::function<std::string(std::string, std::string)> combine = defaultCollateCombine
) {
if (c.size() == 0) return "";
if (c.size() == 1) return objToString(*c.begin());
if (c.size() >= 2) {
std::string str = objToString(*c.begin());
std::for_each(++c.begin(), c.end(), [&str, &objToString, &combine](COLLATE_TYPE object) {
str = combine(str, objToString(object));
});
return str;
}
throw std::logic_error("Size of container must be a positive integer");
}
#undef COLLATE_TYPE
std::string collateTypeList(TypeList typeList) {
return collate<TypeList>(typeList, [](std::string s) {return s;});
}
#endif
<commit_msg>Added default value for collate parameter<commit_after>#ifndef UTIL_HPP
#define UTIL_HPP
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
#include <set>
#include <memory>
#include <typeinfo>
#include <functional>
#include <cxxabi.h>
#include "suppressWarnings.hpp"
#define abs(x) (x < 0 ? -x : x)
#define UNUSED(expr) (void)(expr)
#define ALL(container) std::begin(container), std::end(container)
typedef long long int64;
typedef unsigned long long uint64;
typedef unsigned int uint;
typedef std::set<std::string> TypeList;
template<typename T>
void println(T thing) {
std::cout << thing << std::endl;
}
template<typename T>
void print(T thing) {
std::cout << thing;
}
template<typename T, typename... Args>
void println(T thing, Args... args) {
if (sizeof...(args) == 1) {
print(thing);
print(" ");
print(args...);
std::cout << std::endl;
return;
}
print(thing);
print(" ");
print(args...);
}
template<typename T, typename... Args>
void print(T thing, Args... args) {
print(thing);
print(" ");
print(args...);
}
template<typename T>
bool contains(std::vector<T> vec, T item) {
return std::find(vec.begin(), vec.end(), item) != vec.end();
}
std::vector<std::string> split(const std::string& str, char delim) {
std::vector<std::string> vec {};
std::stringstream ss(str);
std::string item;
while (getline(ss, item, delim)) vec.push_back(item);
return vec;
}
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec) {
for (auto obj : vec) {
os << obj << " ";
}
return os;
}
template<typename T>
struct PtrUtil {
typedef std::unique_ptr<T> U;
typedef std::shared_ptr<T> Link;
typedef std::weak_ptr<T> WeakLink;
template<typename... Args>
static U unique(Args... args) {
return std::make_unique<T>(args...);
}
template<typename... Args>
static Link make(Args... args) {
return std::make_shared<T>(args...);
}
template<typename U>
static inline bool isSameType(std::shared_ptr<U> link) {
return typeid(T) == typeid(*link);
}
template<typename U>
static inline Link dynPtrCast(std::shared_ptr<U> link) {
return std::dynamic_pointer_cast<T>(link);
}
};
struct Identity {
template<typename T>
constexpr auto operator()(T&& v) const noexcept -> decltype(std::forward<T>(v)) {
return std::forward<T>(v);
}
};
template<typename T>
struct VectorHash {
std::size_t operator()(const std::vector<T>& vec) const {
std::size_t seed = vec.size();
std::hash<T> hash;
for (const T& i : vec) {
seed ^= hash(i) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
};
std::string getAddressStringFrom(const void* ptr) {
std::stringstream ss;
ss << "0x" << std::hex << reinterpret_cast<std::uintptr_t>(ptr);
return ss.str();
}
std::string demangle(std::string name) {
int status;
return abi::__cxa_demangle(name.c_str(), 0, 0, &status);
}
#define COLLATE_TYPE const typename Container::value_type&
static const auto defaultCollateCombine = [](std::string prev, std::string current) {return prev + ", " + current;};
template<typename Container>
std::string collate(Container c,
std::function<std::string(COLLATE_TYPE)> objToString = Identity(),
std::function<std::string(std::string, std::string)> combine = defaultCollateCombine
) {
if (c.size() == 0) return "";
if (c.size() == 1) return objToString(*c.begin());
if (c.size() >= 2) {
std::string str = objToString(*c.begin());
std::for_each(++c.begin(), c.end(), [&str, &objToString, &combine](COLLATE_TYPE object) {
str = combine(str, objToString(object));
});
return str;
}
throw std::logic_error("Size of container must be a positive integer");
}
#undef COLLATE_TYPE
std::string collateTypeList(TypeList typeList) {
return collate<TypeList>(typeList);
}
#endif
<|endoftext|> |
<commit_before>/*
This file is part of Akregator.
Copyright (C) 2004 Stanislav Karchebny <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "aboutdata.h"
#include "mainwindow.h"
#include "akregator_options.h"
#include <kcmdlineargs.h>
#include <klocale.h>
#include <knotifyclient.h>
#include <kuniqueapplication.h>
#include <QtDBus>
#include <QStringList>
namespace Akregator {
class Application : public KUniqueApplication {
public:
Application() : mMainWindow( ) {}
~Application() {}
int newInstance();
private:
Akregator::MainWindow *mMainWindow;
};
int Application::newInstance()
{
if (!isSessionRestored())
{
QDBusInterface akr("org.kde.akregator", "/Akregator", "org.kde.akregator.part");
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
if ( !mMainWindow ) {
mMainWindow = new Akregator::MainWindow();
setMainWidget( mMainWindow );
mMainWindow->loadPart();
mMainWindow->setupProgressWidgets();
if (!args->isSet("hide-mainwindow"))
mMainWindow->show();
akr.call( "openStandardFeedList");
}
QString addFeedGroup = !args->getOption("group").isEmpty() ? args->getOption("group") : i18n("Imported Folder");
QByteArrayList feeds = args->getOptionList("addfeed");
QStringList feedsToAdd;
QByteArrayList::ConstIterator end( feeds.end() );
for (QByteArrayList::ConstIterator it = feeds.begin(); it != end; ++it)
feedsToAdd.append(*it);
if (!feedsToAdd.isEmpty())
akr.call("addFeedsToGroup", feedsToAdd, addFeedGroup );
args->clear();
}
return KUniqueApplication::newInstance();
}
} // namespace Akregator
int main(int argc, char **argv)
{
Akregator::AboutData about;
KCmdLineArgs::init(argc, argv, &about);
KCmdLineArgs::addCmdLineOptions( Akregator::akregator_options );
KUniqueApplication::addCmdLineOptions();
Akregator::Application app;
// start knotifyclient if not already started. makes it work for people who doesn't use full kde, according to kmail devels
//KNotifyClient::startDaemon();
// see if we are starting with session management
if (app.isSessionRestored())
{
#undef RESTORE
#define RESTORE(type) { int n = 1;\
while (KMainWindow::canBeRestored(n)){\
(new type)->restore(n, false);\
n++;}}
RESTORE(Akregator::MainWindow);
}
return app.exec();
}
<commit_msg>port encoding fix to trunk CCBUG:136559<commit_after>/*
This file is part of Akregator.
Copyright (C) 2004 Stanislav Karchebny <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "aboutdata.h"
#include "mainwindow.h"
#include "akregator_options.h"
#include <kcmdlineargs.h>
#include <klocale.h>
#include <knotifyclient.h>
#include <kuniqueapplication.h>
#include <QtDBus>
#include <QStringList>
namespace Akregator {
class Application : public KUniqueApplication {
public:
Application() : mMainWindow( ) {}
~Application() {}
int newInstance();
private:
Akregator::MainWindow *mMainWindow;
};
int Application::newInstance()
{
if (!isSessionRestored())
{
QDBusInterface akr("org.kde.akregator", "/Akregator", "org.kde.akregator.part");
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
if ( !mMainWindow ) {
mMainWindow = new Akregator::MainWindow();
setMainWidget( mMainWindow );
mMainWindow->loadPart();
mMainWindow->setupProgressWidgets();
if (!args->isSet("hide-mainwindow"))
mMainWindow->show();
akr.call( "openStandardFeedList");
}
QString addFeedGroup = !args->getOption("group").isEmpty() ?
QString::fromLocal8Bit(args->getOption("group"))
: i18n("Imported Folder");
QByteArrayList feeds = args->getOptionList("addfeed");
QStringList feedsToAdd;
QByteArrayList::ConstIterator end( feeds.end() );
for (QByteArrayList::ConstIterator it = feeds.begin(); it != end; ++it)
feedsToAdd.append(*it);
if (!feedsToAdd.isEmpty())
akr.call("addFeedsToGroup", feedsToAdd, addFeedGroup );
args->clear();
}
return KUniqueApplication::newInstance();
}
} // namespace Akregator
int main(int argc, char **argv)
{
Akregator::AboutData about;
KCmdLineArgs::init(argc, argv, &about);
KCmdLineArgs::addCmdLineOptions( Akregator::akregator_options );
KUniqueApplication::addCmdLineOptions();
Akregator::Application app;
// start knotifyclient if not already started. makes it work for people who doesn't use full kde, according to kmail devels
//KNotifyClient::startDaemon();
// see if we are starting with session management
if (app.isSessionRestored())
{
#undef RESTORE
#define RESTORE(type) { int n = 1;\
while (KMainWindow::canBeRestored(n)){\
(new type)->restore(n, false);\
n++;}}
RESTORE(Akregator::MainWindow);
}
return app.exec();
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* 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 Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#include <pcl/visualization/common/common.h>
#include <stdlib.h>
#include <eigen3/Eigen/src/Core/PlainObjectBase.h>
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::getRandomColors (double &r, double &g, double &b, double min, double max)
{
double sum;
static unsigned stepRGBA = 100;
do
{
sum = 0;
r = (rand () % stepRGBA) / (double)stepRGBA;
while ((g = (rand () % stepRGBA) / (double)stepRGBA) == r) {}
while (((b = (rand () % stepRGBA) / (double)stepRGBA) == r) && (b == g)) {}
sum = r + g + b;
}
while (sum <= min || sum >= max);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::Camera::computeViewMatrix(Eigen::Matrix4d& view_mat) const
{
//constructs view matrix from camera pos, view up, and the point it is looking at
//this code is based off of gluLookAt http://www.opengl.org/wiki/GluLookAt_code
Eigen::Vector3d focal_point (focal[0], focal[1], focal[2]);
Eigen::Vector3d posv (pos[0] , pos[1] , pos[2]);
Eigen::Vector3d up (view[0] , view[1] , view[2]);
Eigen::Vector3d zAxis = (focal_point - posv).normalized();
Eigen::Vector3d xAxis = zAxis.cross(up).normalized();
// make sure the y-axis is orthogonal to the other two
Eigen::Vector3d yAxis = xAxis.cross (zAxis);
view_mat.block <1, 3> (0, 0) = xAxis;
view_mat.block <1, 3> (1, 0) = yAxis;
view_mat.block <1, 3> (2, 0) = -zAxis;
view_mat.row (3) << 0, 0, 0, 1;
view_mat.block <3, 1> (0, 3) = view_mat.topLeftCorner<3, 3> () * (-posv);
}
///////////////////////////////////////////////////////////////////////
void
pcl::visualization::Camera::computeProjectionMatrix(Eigen::Matrix4d& proj) const
{
float top = clip[0] * tan(0.5 * fovy);
float left = -top * window_size[0] / window_size[1];
float right = -left;
float bottom = -top;
float temp1, temp2, temp3, temp4;
temp1 = 2.0 * clip[0];
temp2 = 1.0 / (right - left);
temp3 = 1.0 / (top - bottom);
temp4 = 1.0 / (clip[1] - clip[0]);
proj.setZero ();
proj(0,0) = temp1 * temp2;
proj(1,1) = temp1 * temp3;
proj(0,2) = (right + left) * temp2;
proj(1,2) = (top + bottom) * temp3;
proj(2,2) = (-clip[1] - clip[0]) * temp4;
proj(3,2) = -1.0;
proj(2,3) = (-temp1 * clip[1]) * temp4;
}
<commit_msg>arggghhhh Suat! :)<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* 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 Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#include <pcl/visualization/common/common.h>
#include <stdlib.h>
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::getRandomColors (double &r, double &g, double &b, double min, double max)
{
double sum;
static unsigned stepRGBA = 100;
do
{
sum = 0;
r = (rand () % stepRGBA) / (double)stepRGBA;
while ((g = (rand () % stepRGBA) / (double)stepRGBA) == r) {}
while (((b = (rand () % stepRGBA) / (double)stepRGBA) == r) && (b == g)) {}
sum = r + g + b;
}
while (sum <= min || sum >= max);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::Camera::computeViewMatrix(Eigen::Matrix4d& view_mat) const
{
//constructs view matrix from camera pos, view up, and the point it is looking at
//this code is based off of gluLookAt http://www.opengl.org/wiki/GluLookAt_code
Eigen::Vector3d focal_point (focal[0], focal[1], focal[2]);
Eigen::Vector3d posv (pos[0] , pos[1] , pos[2]);
Eigen::Vector3d up (view[0] , view[1] , view[2]);
Eigen::Vector3d zAxis = (focal_point - posv).normalized();
Eigen::Vector3d xAxis = zAxis.cross(up).normalized();
// make sure the y-axis is orthogonal to the other two
Eigen::Vector3d yAxis = xAxis.cross (zAxis);
view_mat.block <1, 3> (0, 0) = xAxis;
view_mat.block <1, 3> (1, 0) = yAxis;
view_mat.block <1, 3> (2, 0) = -zAxis;
view_mat.row (3) << 0, 0, 0, 1;
view_mat.block <3, 1> (0, 3) = view_mat.topLeftCorner<3, 3> () * (-posv);
}
///////////////////////////////////////////////////////////////////////
void
pcl::visualization::Camera::computeProjectionMatrix(Eigen::Matrix4d& proj) const
{
float top = clip[0] * tan(0.5 * fovy);
float left = -top * window_size[0] / window_size[1];
float right = -left;
float bottom = -top;
float temp1, temp2, temp3, temp4;
temp1 = 2.0 * clip[0];
temp2 = 1.0 / (right - left);
temp3 = 1.0 / (top - bottom);
temp4 = 1.0 / (clip[1] - clip[0]);
proj.setZero ();
proj(0,0) = temp1 * temp2;
proj(1,1) = temp1 * temp3;
proj(0,2) = (right + left) * temp2;
proj(1,2) = (top + bottom) * temp3;
proj(2,2) = (-clip[1] - clip[0]) * temp4;
proj(3,2) = -1.0;
proj(2,3) = (-temp1 * clip[1]) * temp4;
}
<|endoftext|> |
<commit_before>// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013-present David Ok <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
//! @file
/*!
* This file implements a part of the method published in:
*
* Efficient and Scalable 4th-order Match Propagation
* David Ok, Renaud Marlet, and Jean-Yves Audibert.
* ACCV 2012, Daejeon, South Korea.
*/
#pragma once
#include <DO/Sara/Core/EigenExtension.hpp>
#include <DO/Sara/Geometry/Tools/Utilities.hpp>
namespace DO::Sara {
//! @brief Simple criterion to test if the triangle is too flat.
class TriangleFlatness
{
public:
TriangleFlatness(double lowest_angle_degree, double second_lowest_degree)
: lb(std::cos(to_radian(lowest_angle_degree)))
, lb2(std::cos(to_radian(second_lowest_degree)))
{
}
inline bool operator()(const Point2d& a, const Point2d& b,
const Point2d& c) const
{
return !is_not_flat(a, b, c);
}
bool is_not_flat(const Point2d& a, const Point2d& b, const Point2d& c) const
{
Vector2d d[3] = {(b - a), (c - a), (c - b)};
for (int i = 0; i < 3; ++i)
d[i].normalize();
// Find the two smallest angles. They necessarily have non negative
// dot products.
double dot[3] = {d[0].dot(d[1]), d[1].dot(d[2]), -d[2].dot(d[0])};
// Sort dot products in increasing order.
std::sort(dot, dot + 3);
// We need to consider two cases:
// 1. All the dot products are non negative.
// Then the three angles are less than 90 degrees.
// 2. One dot product is negative. It corresponds to the greatest
// angle of the triangle.
// In the end, the smallest angles have the greatest cosines which
// are in both cases dot[1] and dot[2] with dot[1] < dot[2].
// In our case dot[1] <= cos(40)=lb2 and dot[2] <= cos(30)=lb1
return (lb2 >= dot[1] && lb >= dot[2]);
}
private:
const double lb;
const double lb2;
};
class PredParams
{
public:
PredParams(int featType, double delta_x, double delta_S_x,
double delta_theta, double squaredRhoMin)
: feat_type_(featType)
, delta_x_(delta_x)
, delta_S_x_(delta_S_x)
, delta_theta_(delta_theta)
{
}
int featType() const
{
return feat_type_;
}
double deltaX() const
{
return delta_x_;
}
double deltaSx() const
{
return delta_S_x_;
}
double deltaTheta() const
{
return delta_theta_;
}
double squaredRhoMin() const
{
return squared_rho_min_;
}
private:
int feat_type_;
double delta_x_, delta_S_x_, delta_theta_;
double squared_rho_min_;
};
class GrowthParams
{
public:
GrowthParams(size_t K = 80, double rhoMin = 0.5, double angleDeg1 = 15,
double angleDeg2 = 25)
: K_(K)
, rho_min_(rhoMin)
, flat_triangle_test_(angleDeg1, angleDeg2)
{
}
static GrowthParams defaultGrowingParams()
{
return GrowthParams();
};
void add_pred_params(const PredParams& params)
{
pf_params_.push_back(params);
}
size_t K() const
{
return K_;
}
double rho_min() const
{
return rho_min_;
}
const PredParams& pf_params(size_t i) const
{
if (i >= pf_params_.size())
{
const char* msg = "Fatal Error: pf_params_[i] out of bounds!";
throw std::out_of_range(msg);
}
return pf_params_[i];
}
bool is_flat(const Vector2d triangle[3]) const
{
return flat_triangle_test_(triangle[0], triangle[1], triangle[2]);
}
private:
size_t K_;
double rho_min_;
TriangleFlatness flat_triangle_test_;
std::vector<PredParams> pf_params_;
};
} // namespace DO::Sara
<commit_msg>MAINT: fix unused parameters.<commit_after>// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013-present David Ok <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
//! @file
/*!
* This file implements a part of the method published in:
*
* Efficient and Scalable 4th-order Match Propagation
* David Ok, Renaud Marlet, and Jean-Yves Audibert.
* ACCV 2012, Daejeon, South Korea.
*/
#pragma once
#include <DO/Sara/Core/EigenExtension.hpp>
#include <DO/Sara/Geometry/Tools/Utilities.hpp>
namespace DO::Sara {
//! @brief Simple criterion to test if the triangle is too flat.
class TriangleFlatness
{
public:
TriangleFlatness(double lowest_angle_degree, double second_lowest_degree)
: lb(std::cos(to_radian(lowest_angle_degree)))
, lb2(std::cos(to_radian(second_lowest_degree)))
{
}
inline bool operator()(const Point2d& a, const Point2d& b,
const Point2d& c) const
{
return !is_not_flat(a, b, c);
}
bool is_not_flat(const Point2d& a, const Point2d& b, const Point2d& c) const
{
Vector2d d[3] = {(b - a), (c - a), (c - b)};
for (int i = 0; i < 3; ++i)
d[i].normalize();
// Find the two smallest angles. They necessarily have non negative
// dot products.
double dot[3] = {d[0].dot(d[1]), d[1].dot(d[2]), -d[2].dot(d[0])};
// Sort dot products in increasing order.
std::sort(dot, dot + 3);
// We need to consider two cases:
// 1. All the dot products are non negative.
// Then the three angles are less than 90 degrees.
// 2. One dot product is negative. It corresponds to the greatest
// angle of the triangle.
// In the end, the smallest angles have the greatest cosines which
// are in both cases dot[1] and dot[2] with dot[1] < dot[2].
// In our case dot[1] <= cos(40)=lb2 and dot[2] <= cos(30)=lb1
return (lb2 >= dot[1] && lb >= dot[2]);
}
private:
const double lb;
const double lb2;
};
class PredParams
{
public:
PredParams(int featType, double delta_x, double delta_S_x,
double delta_theta, double squaredRhoMin)
: feat_type_(featType)
, delta_x_(delta_x)
, delta_S_x_(delta_S_x)
, delta_theta_(delta_theta)
, squared_rho_min_{squaredRhoMin}
{
}
int featType() const
{
return feat_type_;
}
double deltaX() const
{
return delta_x_;
}
double deltaSx() const
{
return delta_S_x_;
}
double deltaTheta() const
{
return delta_theta_;
}
double squaredRhoMin() const
{
return squared_rho_min_;
}
private:
int feat_type_;
double delta_x_, delta_S_x_, delta_theta_;
double squared_rho_min_;
};
class GrowthParams
{
public:
GrowthParams(size_t K = 80, double rhoMin = 0.5, double angleDeg1 = 15,
double angleDeg2 = 25)
: K_(K)
, rho_min_(rhoMin)
, flat_triangle_test_(angleDeg1, angleDeg2)
{
}
static GrowthParams defaultGrowingParams()
{
return GrowthParams();
};
void add_pred_params(const PredParams& params)
{
pf_params_.push_back(params);
}
size_t K() const
{
return K_;
}
double rho_min() const
{
return rho_min_;
}
const PredParams& pf_params(size_t i) const
{
if (i >= pf_params_.size())
{
const char* msg = "Fatal Error: pf_params_[i] out of bounds!";
throw std::out_of_range(msg);
}
return pf_params_[i];
}
bool is_flat(const Vector2d triangle[3]) const
{
return flat_triangle_test_(triangle[0], triangle[1], triangle[2]);
}
private:
size_t K_;
double rho_min_;
TriangleFlatness flat_triangle_test_;
std::vector<PredParams> pf_params_;
};
} // namespace DO::Sara
<|endoftext|> |
<commit_before>/*
* This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT)
*
* Copyright (c) 2017 Grégory Van den Borre
*
* More infos available: https://www.yildiz-games.be
*
* 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.
*/
/**
*@author Grégory Van den Borre
*/
#include "../includes/JniShader.h"
#include "../includes/JniUtil.h"
JNIEXPORT jlong JNICALL Java_be_yildiz_module_graphic_ogre_OgreShader_createFragmentShader(
JNIEnv* env, jobject o, jstring jname, jstring jpath) {
JniStringWrapper name = JniStringWrapper(env, jname);
JniStringWrapper path = JniStringWrapper(env, jpath);
Ogre::GpuProgram* shader = Ogre::HighLevelGpuProgramManager::getSingleton().createProgram(
name.getValue(),
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
"glsl",
Ogre::GPT_FRAGMENT_PROGRAM).get();
shader->setSource(path.getValue());
return reinterpret_cast<jlong>(shader);
}
JNIEXPORT jlong JNICALL Java_be_yildiz_module_graphic_ogre_OgreShader_createVertexShader(
JNIEnv* env, jobject o, jstring jname, jstring jpath) {
JniStringWrapper name = JniStringWrapper(env, jname);
JniStringWrapper path = JniStringWrapper(env, jpath);
Ogre::GpuProgram* shader = Ogre::HighLevelGpuProgramManager::getSingleton().createProgram(
name.getValue(),
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
"glsl",
Ogre::GPT_VERTEX_PROGRAM).get();
shader->setSource(path.getValue());
return reinterpret_cast<jlong>(shader);
}
JNIEXPORT void JNICALL Java_be_yildiz_module_graphic_ogre_OgreShader_setParameter(
JNIEnv* env, jobject o, jlong pointer, jstring jname, jstring jvalue) {
JniStringWrapper name = JniStringWrapper(env, jname);
JniStringWrapper value = JniStringWrapper(env, jvalue);
Ogre::GpuProgram* shader = reinterpret_cast<Ogre::GpuProgram*>(pointer);
shader->setParameter(name, value);
}
<commit_msg>[NO-JIRA] Fix shader for GLSL.<commit_after>/*
* This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT)
*
* Copyright (c) 2017 Grégory Van den Borre
*
* More infos available: https://www.yildiz-games.be
*
* 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.
*/
/**
*@author Grégory Van den Borre
*/
#include "../includes/JniShader.h"
#include "../includes/JniUtil.h"
JNIEXPORT jlong JNICALL Java_be_yildiz_module_graphic_ogre_OgreShader_createFragmentShader(
JNIEnv* env, jobject o, jstring jname, jstring jpath) {
JniStringWrapper name = JniStringWrapper(env, jname);
JniStringWrapper path = JniStringWrapper(env, jpath);
Ogre::GpuProgram* shader = Ogre::HighLevelGpuProgramManager::getSingleton().createProgram(
name.getValue(),
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
"glsl",
Ogre::GPT_FRAGMENT_PROGRAM).get();
shader->setSource(path.getValue());
return reinterpret_cast<jlong>(shader);
}
JNIEXPORT jlong JNICALL Java_be_yildiz_module_graphic_ogre_OgreShader_createVertexShader(
JNIEnv* env, jobject o, jstring jname, jstring jpath) {
JniStringWrapper name = JniStringWrapper(env, jname);
JniStringWrapper path = JniStringWrapper(env, jpath);
Ogre::GpuProgram* shader = Ogre::HighLevelGpuProgramManager::getSingleton().createProgram(
name.getValue(),
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
"glsl",
Ogre::GPT_VERTEX_PROGRAM).get();
shader->setSource(path.getValue());
return reinterpret_cast<jlong>(shader);
}
JNIEXPORT void JNICALL Java_be_yildiz_module_graphic_ogre_OgreShader_setParameter(
JNIEnv* env, jobject o, jlong pointer, jstring jname, jstring jvalue) {
JniStringWrapper name = JniStringWrapper(env, jname);
JniStringWrapper value = JniStringWrapper(env, jvalue);
Ogre::GpuProgram* shader = reinterpret_cast<Ogre::GpuProgram*>(pointer);
shader->setParameter(name.getValue(), value.getValue());
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <[email protected]>
//------------------------------------------------------------------------------
#include "cling/UserInterface/UserInterface.h"
#include "cling/MetaProcessor/MetaProcessor.h"
#include "textinput/TextInput.h"
#include "textinput/StreamReader.h"
#include "textinput/TerminalDisplay.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/PathV1.h"
// Fragment copied from LLVM's raw_ostream.cpp
#if defined(HAVE_UNISTD_H)
# include <unistd.h>
#endif
#if defined(_MSC_VER)
#ifndef STDIN_FILENO
# define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
# define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
# define STDERR_FILENO 2
#endif
#endif
namespace cling {
UserInterface::UserInterface(Interpreter& interp) {
// We need stream that doesn't close its file descriptor, thus we are not
// using llvm::outs. Keeping file descriptor open we will be able to use
// the results in pipes (Savannah #99234).
static llvm::raw_fd_ostream m_MPOuts (STDOUT_FILENO, /*ShouldClose*/false);
m_MetaProcessor.reset(new MetaProcessor(interp, m_MPOuts));
}
UserInterface::~UserInterface() {}
void UserInterface::runInteractively(bool nologo /* = false */) {
if (!nologo) {
PrintLogo();
}
// History file is $HOME/.cling_history
static const char* histfile = ".cling_history";
llvm::sys::Path histfilePath = llvm::sys::Path::GetUserHomeDirectory();
histfilePath.appendComponent(histfile);
using namespace textinput;
StreamReader* R = StreamReader::Create();
TerminalDisplay* D = TerminalDisplay::Create();
TextInput TI(*R, *D, histfilePath.c_str());
TI.SetPrompt("[cling]$ ");
std::string line;
while (true) {
m_MetaProcessor->getOuts().flush();
TextInput::EReadResult RR = TI.ReadInput();
TI.TakeInput(line);
if (RR == TextInput::kRREOF) {
break;
}
int indent = m_MetaProcessor->process(line.c_str());
// Quit requested
if (indent < 0)
break;
std::string Prompt = "[cling]";
if (m_MetaProcessor->getInterpreter().isRawInputEnabled())
Prompt.append("! ");
else
Prompt.append("$ ");
if (indent > 0)
// Continuation requested.
Prompt.append('?' + std::string(indent * 3, ' '));
TI.SetPrompt(Prompt.c_str());
}
}
void UserInterface::PrintLogo() {
llvm::raw_ostream& outs = m_MetaProcessor->getOuts();
outs << "\n";
outs << "****************** CLING ******************" << "\n";
outs << "* Type C++ code and press enter to run it *" << "\n";
outs << "* Type .q to exit *" << "\n";
outs << "*******************************************" << "\n";
}
} // end namespace cling
<commit_msg>We use HAVE_UNISTD_H, so #include config.h which defines it.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <[email protected]>
//------------------------------------------------------------------------------
#include "cling/UserInterface/UserInterface.h"
#include "cling/MetaProcessor/MetaProcessor.h"
#include "textinput/TextInput.h"
#include "textinput/StreamReader.h"
#include "textinput/TerminalDisplay.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/PathV1.h"
#include "llvm/Config/config.h"
// Fragment copied from LLVM's raw_ostream.cpp
#if defined(HAVE_UNISTD_H)
# include <unistd.h>
#endif
#if defined(_MSC_VER)
#ifndef STDIN_FILENO
# define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
# define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
# define STDERR_FILENO 2
#endif
#endif
namespace cling {
UserInterface::UserInterface(Interpreter& interp) {
// We need stream that doesn't close its file descriptor, thus we are not
// using llvm::outs. Keeping file descriptor open we will be able to use
// the results in pipes (Savannah #99234).
static llvm::raw_fd_ostream m_MPOuts (STDOUT_FILENO, /*ShouldClose*/false);
m_MetaProcessor.reset(new MetaProcessor(interp, m_MPOuts));
}
UserInterface::~UserInterface() {}
void UserInterface::runInteractively(bool nologo /* = false */) {
if (!nologo) {
PrintLogo();
}
// History file is $HOME/.cling_history
static const char* histfile = ".cling_history";
llvm::sys::Path histfilePath = llvm::sys::Path::GetUserHomeDirectory();
histfilePath.appendComponent(histfile);
using namespace textinput;
StreamReader* R = StreamReader::Create();
TerminalDisplay* D = TerminalDisplay::Create();
TextInput TI(*R, *D, histfilePath.c_str());
TI.SetPrompt("[cling]$ ");
std::string line;
while (true) {
m_MetaProcessor->getOuts().flush();
TextInput::EReadResult RR = TI.ReadInput();
TI.TakeInput(line);
if (RR == TextInput::kRREOF) {
break;
}
int indent = m_MetaProcessor->process(line.c_str());
// Quit requested
if (indent < 0)
break;
std::string Prompt = "[cling]";
if (m_MetaProcessor->getInterpreter().isRawInputEnabled())
Prompt.append("! ");
else
Prompt.append("$ ");
if (indent > 0)
// Continuation requested.
Prompt.append('?' + std::string(indent * 3, ' '));
TI.SetPrompt(Prompt.c_str());
}
}
void UserInterface::PrintLogo() {
llvm::raw_ostream& outs = m_MetaProcessor->getOuts();
outs << "\n";
outs << "****************** CLING ******************" << "\n";
outs << "* Type C++ code and press enter to run it *" << "\n";
outs << "* Type .q to exit *" << "\n";
outs << "*******************************************" << "\n";
}
} // end namespace cling
<|endoftext|> |
<commit_before>/*
DepSpawn: Data Dependent Spawn library
Copyright (C) 2012-2016 Carlos H. Gonzalez, Basilio B. Fraguela. Universidade da Coruna
This file is part of DepSpawn.
DepSpawn is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation;
either version 2 as published by the Free Software Foundation.
DepSpawn is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Threading Building Blocks; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
As a special exception, you may use this file as part of a free software
library without restriction. Specifically, if other files instantiate
templates or use macros or inline functions from this file, or you compile
this file and link it with other files to produce an executable, this
file does not by itself cause the resulting executable to be covered by
the GNU General Public License. This exception does not however
invalidate any other reasons why the executable file might be covered by
the GNU General Public License.
*/
///
/// \file workitem.cpp
/// \brief Implementation of Workitem
/// \author Carlos H. Gonzalez <[email protected]>
/// \author Basilio B. Fraguela <[email protected]>
///
namespace depspawn {
namespace internal {
Workitem::Workitem(arg_info *iargs, int nargs) :
status(Status_t::Filling), optFlags_(0), nargs_(static_cast<char>(nargs)),
args(iargs), next(nullptr), father(enum_thr_spec_father.local()),
task(nullptr), deps(nullptr), lastdep(nullptr)
{
deps_mutex_ = 0;
guard_ = 0;
ndependencies = 0;
nchildren = 1;
if(father)
father->nchildren.fetch_and_increment();
}
AbstractBoxedFunction * Workitem::steal() {
AbstractBoxedFunction * ret = nullptr;
if( (status == Status_t::Ready) && (guard_.compare_and_swap(1, 0) == 0) ) {
ret = task->steal();
guard_ = 2;
}
return ret;
}
void Workitem::insert_in_worklist(AbstractRunner* itask)
{ Workitem* p;
arg_info *arg_p, *arg_w;
//Save original list of arguments
int nargs = static_cast<int>(nargs_);
arg_info* argv[nargs+1];
arg_w = args;
for (int i = 0; arg_w != nullptr; i++) {
argv[i] = arg_w; //printf("Fill %d %lu\n", i, arg_w->addr);
arg_w = arg_w->next;
}
argv[nargs] = nullptr;
DEPSPAWN_PROFILEDEFINITION(unsigned int profile_workitems_in_list_lcl = 0,
profile_workitems_in_list_active_lcl = 0);
DEPSPAWN_PROFILEDEFINITION(bool profile_early_termination_lcl = false);
DEPSPAWN_PROFILEACTION(profile_jobs++);
#ifdef DEPSPAWN_FAST_START
AbstractBoxedFunction *stolen_abf = nullptr;
Workitem* fast_arr[FAST_ARR_SZ];
int nready = 0, nfillwait = 0;
#endif
task = itask;
Workitem* ancestor = father;
do {
p = worklist;
next = p;
} while(worklist.compare_and_swap(this, p) != p);
for(p = next; p != nullptr; p = p->next) {
DEPSPAWN_PROFILEACTION(profile_workitems_in_list_lcl++);
// sometimes p == this, even if it shouldn't
if(p == this) { // fprintf(stderr, "myself?\n");
continue; // FIXIT
}
if(p == ancestor) {
ancestor = p->father;
/// TODO: is_contained should be adapted to use argv
if ( (ancestor != nullptr) && is_contained(this, ancestor)) {
DEPSPAWN_PROFILEACTION(profile_early_termination_lcl = true);
optFlags_ |= OptFlags::FatherScape;
break;
}
} else {
const auto tmp_status = p->status;
if(tmp_status < Status_t::Done) {
DEPSPAWN_PROFILEACTION(profile_workitems_in_list_active_lcl++);
int arg_w_i = 0;
arg_p = p->args; // preexisting workitem
arg_w = argv[0]; // New workitem
while(arg_p && arg_w) {
const bool conflict = arg_w->is_array()
? ( (arg_p->addr == arg_w->addr) && arg_w->overlap_array(arg_p) )
: ( (arg_p->wr || arg_w->wr) && overlaps(arg_p, arg_w) );
if(conflict) { // Found a dependency
ndependencies++;
Workitem::_dep* newdep = Workitem::_dep::Pool.malloc();
newdep->next = nullptr;
newdep->w = this;
//tbb::mutex::scoped_lock lock(p->deps_mutex);
while (p->deps_mutex_.compare_and_swap(1, 0) != 0) { }
if(!p->deps)
p->deps = p->lastdep = newdep;
else {
p->lastdep->next = newdep;
p->lastdep = p->lastdep->next;
}
//lock.release();
p->deps_mutex_ = 0;
DEPSPAWN_DEBUGACTION(
/* You can be linking to Done's that are waiting for you to Fill-in
but NOT for Deallocatable Workitems */
if(p->status == Status_t::Deallocatable) {
printf("%p -> Deallocatable %p (was %d)", this, p, (int)tmp_status);
assert(false);
}
); // END DEPSPAWN_DEBUGACTION
if (arg_p->wr &&
(arg_w->is_array() ? arg_w->is_contained_array(arg_p) : contains(arg_p, arg_w))) {
nargs--;
/*
if (!nargs) {
DEPSPAWN_PROFILEACTION(profile_early_termination_lcl = true); //not true actually...
// The optimal thing would be to just make this goto to leave the main loop and insert
// the Workitem waiting. But in tests with repeated spawns this leads to very fast insertion
// that slows down the performance. Other advantages of continuing down the list:
// - More likely DEPSPAWN_FAST_START is triggered and it uses oldest tasks
// - optFlags_ is correctly computed
//goto OUT_MAIN_insert_in_worklist_LOOP;
argv[0] = nullptr;
//break; //There is another break anyway there down
} else {
*/
for (int i = arg_w_i; i <= nargs; i++) {
argv[i] = argv[i+1];
}
/*}*/
}
break;
} else {
if(arg_p->addr < arg_w->addr) {
arg_p = arg_p->next;
} else {
arg_w = argv[++arg_w_i];
}
}
}
#ifdef DEPSPAWN_FAST_START
const auto tmp_status = p->status;
nfillwait += ( tmp_status < Status_t::Ready );
if ( tmp_status == Status_t::Ready ) {
fast_arr[nready & (FAST_ARR_SZ - 1)] = p;
nready++;
}
#endif
if( p->status == Status_t::Filling ) {
optFlags_ |= OptFlags::PendingFills;
}
}
}
}
//OUT_MAIN_insert_in_worklist_LOOP:
#ifdef DEPSPAWN_FAST_START
if ((nready > FAST_THRESHOLD) || ((nready > Nthreads) && (nfillwait > FAST_THRESHOLD))) {
DEPSPAWN_PROFILEACTION(profile_steal_attempts++);
nready = (nready - 1) & (FAST_ARR_SZ - 1);
do {
p = fast_arr[nready--];
stolen_abf = p->steal();
} while ( (stolen_abf == nullptr) && (nready >= 0) );
}
#endif
// This is set after stealing work because this way
// the fast_arr workitems should not have been deallocated
//status = (!ndependencies) ? Ready : Waiting;
if (!ndependencies) {
status = Status_t::Ready;
master_task->spawn(*task);
} else {
status = Status_t::Waiting;
}
#ifdef DEPSPAWN_FAST_START
if (stolen_abf != nullptr) {
DEPSPAWN_PROFILEACTION(profile_steals++);
stolen_abf->run_in_env(false);
delete stolen_abf;
}
#endif
DEPSPAWN_PROFILEACTION(
if(profile_early_termination_lcl) {
profile_early_terminations++;
profile_workitems_in_list_early_termination += profile_workitems_in_list_lcl;
profile_workitems_in_list_active_early_termination += profile_workitems_in_list_active_lcl;
}
profile_workitems_in_list += profile_workitems_in_list_lcl;
profile_workitems_in_list_active += profile_workitems_in_list_active_lcl;
);
}
void Workitem::finish_execution()
{ Workitem *p, *ph;
if(nchildren.fetch_and_decrement() != 1)
return;
bool erase = false;
Workitem *current = this;
do {
// Finish work
current->status = Status_t::Done;
/* Without this fence the change of status can be unseen by Workitems that are Filling in */
tbb::atomic_fence();
erase = erase || ((((((intptr_t)current)>>8)&0xfff) < 32) && !ObserversAtWork && !eraser_assigned && !eraser_assigned.compare_and_swap(true, false));
ph = worklist;
//lastkeep = ph;
for(p = ph; p && p != this; p = p->next) { //wait until this, not current
while(p->status == Status_t::Filling) {}
//if(p->status != Deallocatable)
// lastkeep = p;
if(!(p->optFlags_ & OptFlags::PendingFills)) {
if(p->optFlags_ & OptFlags::FatherScape) {
if (p->status < Status_t::Done) { //The father of a Done/Deallocated could be freed
p = p->father; //the iterator sets p = p->next;
}
} else {
break;
}
}
}
assert(current->status == Status_t::Done);
// free lists
//delete ctx_->task;
Workitem::_dep *idep = current->deps;
if (idep != nullptr) {
do {
if(idep->w->ndependencies.fetch_and_decrement() == 1) {
idep->w->post();
}
idep = idep->next;
} while (idep != nullptr);
Workitem::_dep::Pool.freeLinkedList(current->deps, current->lastdep);
current->deps = current->lastdep = nullptr;
}
assert(current->status == Status_t::Done);
if (current->args != nullptr) {
arg_info::Pool.freeLinkedList(current->args, [](arg_info *i) { if(i->is_array()) delete [] i->array_range; } );
current->args = nullptr;
}
p = current->father;
current->status = Status_t::Deallocatable;
current = p;
} while ((p != nullptr) && (p->nchildren.fetch_and_decrement() == 1));
if(erase) {
DEPSPAWN_PROFILEDEFINITION(const tbb::tick_count t0 = tbb::tick_count::now());
DEPSPAWN_PROFILEACTION(profile_erases++;);
Workitem *lastkeep = this;
Workitem *last_workitem, *q;
int deletable_workitems = 0;
assert((this->status >= 0) && (this->status <= Status_t::Deallocatable));
assert((lastkeep->status >= 0) && (lastkeep->status <= Status_t::Deallocatable));
for(p = lastkeep->next; ; p = p->next) {
assert((p == nullptr) || (p->status >= 0) && (p->status <= Status_t::Deallocatable));
if( (p == nullptr) ||
(p->status != Status_t::Deallocatable) ||
!(p->optFlags_ & OptFlags::TaskRun) ) {
if (deletable_workitems > 4) { //We ask for a minimum that justifies the cost
Workitem *dp = lastkeep->next; // Everything from here will be deleted
lastkeep->next = p;
assert(dp != nullptr);
tbb::atomic_fence();
Workitem *nextph = worklist;
for(q = nextph; q != ph; q = q->next) {
while(q->status == Status_t::Filling) { } // Waits until work q has its dependencies
if(! (q->optFlags_ & (OptFlags::PendingFills|OptFlags::FatherScape)) ) {
break;
}
}
ph = nextph;
DEPSPAWN_DEBUGACTION(
for(q = dp; q != last_workitem->next; q = q->next) {
assert(q->args == nullptr);
assert(q->status == Status_t::Deallocatable);
assert(q->optFlags_ & OptFlags::TaskRun);
if (q->deps) {
printf("%p -> %p\n", q, q->deps);
assert(q->deps == nullptr);
}
}
); // END DEPSPAWN_DEBUGACTION
//last_workitem->next = nullptr; //Should not be necessary
Workitem::Pool.freeLinkedList(dp, last_workitem);
}
if( p == nullptr) {
break;
}
lastkeep = p;
deletable_workitems = 0;
} else {
deletable_workitems++;
}
last_workitem = p;
}
DEPSPAWN_PROFILEACTION(profile_time_eraser_waiting += (tbb::tick_count::now() - t0).seconds());
/*
for(p = next; p; p = p->next) {
last_workitem = p;
if((p->status != Status_t::Deallocatable) || !(p->optFlags_ & OptFlags::TaskRun))
lastkeep = p;
}
Workitem *dp = lastkeep->next; // Everything from here will be deleted
lastkeep->next = nullptr;
if (dp != nullptr) {
for(p = worklist; p != ph; p = p->next) {
while(p->status == Status_t::Filling) { } // Waits until work p has its dependencies
if(! (p->optFlags_ & (OptFlags::PendingFills|OptFlags::FatherScape)) ) {
break;
}
}
DEPSPAWN_PROFILEACTION(profile_time_eraser_waiting += (tbb::tick_count::now() - t0).seconds());
DEPSPAWN_DEBUGACTION(
for(p = dp; p; p = p->next) {
assert(p-> args == nullptr);
if (p->deps) {
printf("%p -> %p\n", p, p->deps);
assert(p->deps == nullptr);
}
}
); // END DEPSPAWN_DEBUGACTION
Workitem::Pool.freeLinkedList(dp, last_workitem);
}
*/
eraser_assigned = false;
}
}
} //namespace internal
} //namespace depspawn
<commit_msg>works scanning deletes from beginning<commit_after>/*
DepSpawn: Data Dependent Spawn library
Copyright (C) 2012-2016 Carlos H. Gonzalez, Basilio B. Fraguela. Universidade da Coruna
This file is part of DepSpawn.
DepSpawn is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation;
either version 2 as published by the Free Software Foundation.
DepSpawn is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Threading Building Blocks; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
As a special exception, you may use this file as part of a free software
library without restriction. Specifically, if other files instantiate
templates or use macros or inline functions from this file, or you compile
this file and link it with other files to produce an executable, this
file does not by itself cause the resulting executable to be covered by
the GNU General Public License. This exception does not however
invalidate any other reasons why the executable file might be covered by
the GNU General Public License.
*/
///
/// \file workitem.cpp
/// \brief Implementation of Workitem
/// \author Carlos H. Gonzalez <[email protected]>
/// \author Basilio B. Fraguela <[email protected]>
///
#include <vector>
namespace depspawn {
namespace internal {
Workitem::Workitem(arg_info *iargs, int nargs) :
status(Status_t::Filling), optFlags_(0), nargs_(static_cast<char>(nargs)),
args(iargs), next(nullptr), father(enum_thr_spec_father.local()),
task(nullptr), deps(nullptr), lastdep(nullptr)
{
deps_mutex_ = 0;
guard_ = 0;
ndependencies = 0;
nchildren = 1;
if(father)
father->nchildren.fetch_and_increment();
}
AbstractBoxedFunction * Workitem::steal() {
AbstractBoxedFunction * ret = nullptr;
if( (status == Status_t::Ready) && (guard_.compare_and_swap(1, 0) == 0) ) {
ret = task->steal();
guard_ = 2;
}
return ret;
}
void Workitem::insert_in_worklist(AbstractRunner* itask)
{ Workitem* p;
arg_info *arg_p, *arg_w;
//Save original list of arguments
int nargs = static_cast<int>(nargs_);
arg_info* argv[nargs+1];
arg_w = args;
for (int i = 0; arg_w != nullptr; i++) {
argv[i] = arg_w; //printf("Fill %d %lu\n", i, arg_w->addr);
arg_w = arg_w->next;
}
argv[nargs] = nullptr;
DEPSPAWN_PROFILEDEFINITION(unsigned int profile_workitems_in_list_lcl = 0,
profile_workitems_in_list_active_lcl = 0);
DEPSPAWN_PROFILEDEFINITION(bool profile_early_termination_lcl = false);
DEPSPAWN_PROFILEACTION(profile_jobs++);
#ifdef DEPSPAWN_FAST_START
AbstractBoxedFunction *stolen_abf = nullptr;
Workitem* fast_arr[FAST_ARR_SZ];
int nready = 0, nfillwait = 0;
#endif
task = itask;
Workitem* ancestor = father;
do {
p = worklist;
next = p;
} while(worklist.compare_and_swap(this, p) != p);
for(p = next; p != nullptr; p = p->next) {
DEPSPAWN_PROFILEACTION(profile_workitems_in_list_lcl++);
// sometimes p == this, even if it shouldn't
if(p == this) { // fprintf(stderr, "myself?\n");
continue; // FIXIT
}
if(p == ancestor) {
ancestor = p->father;
/// TODO: is_contained should be adapted to use argv
if ( (ancestor != nullptr) && is_contained(this, ancestor)) {
DEPSPAWN_PROFILEACTION(profile_early_termination_lcl = true);
optFlags_ |= OptFlags::FatherScape;
break;
}
} else {
const auto tmp_status = p->status;
if(tmp_status < Status_t::Done) {
DEPSPAWN_PROFILEACTION(profile_workitems_in_list_active_lcl++);
int arg_w_i = 0;
arg_p = p->args; // preexisting workitem
arg_w = argv[0]; // New workitem
while(arg_p && arg_w) {
const bool conflict = arg_w->is_array()
? ( (arg_p->addr == arg_w->addr) && arg_w->overlap_array(arg_p) )
: ( (arg_p->wr || arg_w->wr) && overlaps(arg_p, arg_w) );
if(conflict) { // Found a dependency
ndependencies++;
Workitem::_dep* newdep = Workitem::_dep::Pool.malloc();
newdep->next = nullptr;
newdep->w = this;
//tbb::mutex::scoped_lock lock(p->deps_mutex);
while (p->deps_mutex_.compare_and_swap(1, 0) != 0) { }
if(!p->deps)
p->deps = p->lastdep = newdep;
else {
p->lastdep->next = newdep;
p->lastdep = p->lastdep->next;
}
//lock.release();
p->deps_mutex_ = 0;
DEPSPAWN_DEBUGACTION(
/* You can be linking to Done's that are waiting for you to Fill-in
but NOT for Deallocatable Workitems */
if(p->status == Status_t::Deallocatable) {
printf("%p -> Deallocatable %p (was %d)", this, p, (int)tmp_status);
assert(false);
}
); // END DEPSPAWN_DEBUGACTION
if (arg_p->wr &&
(arg_w->is_array() ? arg_w->is_contained_array(arg_p) : contains(arg_p, arg_w))) {
nargs--;
/*
if (!nargs) {
DEPSPAWN_PROFILEACTION(profile_early_termination_lcl = true); //not true actually...
// The optimal thing would be to just make this goto to leave the main loop and insert
// the Workitem waiting. But in tests with repeated spawns this leads to very fast insertion
// that slows down the performance. Other advantages of continuing down the list:
// - More likely DEPSPAWN_FAST_START is triggered and it uses oldest tasks
// - optFlags_ is correctly computed
//goto OUT_MAIN_insert_in_worklist_LOOP;
argv[0] = nullptr;
//break; //There is another break anyway there down
} else {
*/
for (int i = arg_w_i; i <= nargs; i++) {
argv[i] = argv[i+1];
}
/*}*/
}
break;
} else {
if(arg_p->addr < arg_w->addr) {
arg_p = arg_p->next;
} else {
arg_w = argv[++arg_w_i];
}
}
}
#ifdef DEPSPAWN_FAST_START
const auto tmp_status = p->status;
nfillwait += ( tmp_status < Status_t::Ready );
if ( tmp_status == Status_t::Ready ) {
fast_arr[nready & (FAST_ARR_SZ - 1)] = p;
nready++;
}
#endif
if( p->status == Status_t::Filling ) {
optFlags_ |= OptFlags::PendingFills;
}
}
}
}
//OUT_MAIN_insert_in_worklist_LOOP:
#ifdef DEPSPAWN_FAST_START
if ((nready > FAST_THRESHOLD) || ((nready > Nthreads) && (nfillwait > FAST_THRESHOLD))) {
DEPSPAWN_PROFILEACTION(profile_steal_attempts++);
nready = (nready - 1) & (FAST_ARR_SZ - 1);
do {
p = fast_arr[nready--];
stolen_abf = p->steal();
} while ( (stolen_abf == nullptr) && (nready >= 0) );
}
#endif
// This is set after stealing work because this way
// the fast_arr workitems should not have been deallocated
//status = (!ndependencies) ? Ready : Waiting;
if (!ndependencies) {
status = Status_t::Ready;
master_task->spawn(*task);
} else {
status = Status_t::Waiting;
}
#ifdef DEPSPAWN_FAST_START
if (stolen_abf != nullptr) {
DEPSPAWN_PROFILEACTION(profile_steals++);
stolen_abf->run_in_env(false);
delete stolen_abf;
}
#endif
DEPSPAWN_PROFILEACTION(
if(profile_early_termination_lcl) {
profile_early_terminations++;
profile_workitems_in_list_early_termination += profile_workitems_in_list_lcl;
profile_workitems_in_list_active_early_termination += profile_workitems_in_list_active_lcl;
}
profile_workitems_in_list += profile_workitems_in_list_lcl;
profile_workitems_in_list_active += profile_workitems_in_list_active_lcl;
);
}
void Workitem::finish_execution()
{ Workitem *p, *ph;
static std::vector<Workitem *> Dones;
static std::vector< std::pair<Workitem *, Workitem*> > Deletable_Sublists;
if(nchildren.fetch_and_decrement() != 1)
return;
bool erase = false;
Workitem *current = this;
do {
// Finish work
current->status = Status_t::Done;
/* Without this fence the change of status can be unseen by Workitems that are Filling in */
tbb::atomic_fence();
erase = erase || ((((((intptr_t)current)>>8)&0xfff) < 32) && !ObserversAtWork && !eraser_assigned && !eraser_assigned.compare_and_swap(true, false));
ph = worklist;
//lastkeep = ph;
for(p = ph; p && p != this; p = p->next) { //wait until this, not current
while(p->status == Status_t::Filling) {}
//if(p->status != Deallocatable)
// lastkeep = p;
if(!(p->optFlags_ & OptFlags::PendingFills)) {
if(p->optFlags_ & OptFlags::FatherScape) {
if (p->status < Status_t::Done) { //The father of a Done/Deallocated could be freed
p = p->father; //the iterator sets p = p->next;
}
} else {
break;
}
}
}
// free lists
//delete ctx_->task;
Workitem::_dep *idep = current->deps;
if (idep != nullptr) {
do {
if(idep->w->ndependencies.fetch_and_decrement() == 1) {
idep->w->post();
}
idep = idep->next;
} while (idep != nullptr);
Workitem::_dep::Pool.freeLinkedList(current->deps, current->lastdep);
current->deps = current->lastdep = nullptr;
}
if (current->args != nullptr) {
arg_info::Pool.freeLinkedList(current->args, [](arg_info *i) { if(i->is_array()) delete [] i->array_range; } );
current->args = nullptr;
}
p = current->father;
current->status = Status_t::Deallocatable;
current = p;
} while ((p != nullptr) && (p->nchildren.fetch_and_decrement() == 1));
if(erase) {
DEPSPAWN_PROFILEDEFINITION(const tbb::tick_count t0 = tbb::tick_count::now());
DEPSPAWN_PROFILEDEFINITION(unsigned int profile_deleted_workitems = 0);
DEPSPAWN_PROFILEACTION(profile_erases++);
Workitem *lastkeep = worklist;
Workitem *last_workitem;
unsigned int deletable_workitems = 0;
for(p = lastkeep->next; p != nullptr; p = p->next) {
if( (p->status < Status_t::Deallocatable) ||
!(p->optFlags_ & OptFlags::TaskRun) ) {
if(p->status == Status_t::Done) {
Dones.push_back(p);
}
if (deletable_workitems > 4) { //We ask for a minimum that justifies the cost
Deletable_Sublists.emplace_back(lastkeep->next, last_workitem); // Deleted sublist
lastkeep->next = p;
DEPSPAWN_PROFILEACTION(profile_deleted_workitems += deletable_workitems);
}
lastkeep = p;
deletable_workitems = 0;
} else {
deletable_workitems++;
}
last_workitem = p;
}
if (lastkeep->next != nullptr) {
Deletable_Sublists.emplace_back(lastkeep->next, last_workitem);
lastkeep->next = nullptr;
DEPSPAWN_PROFILEACTION(profile_deleted_workitems += deletable_workitems);
}
DEPSPAWN_PROFILEACTION(printf("D %u (%u) (%u)\n", profile_deleted_workitems, (unsigned)Dones.size(), (unsigned)Deletable_Sublists.size()));
for(p = worklist; p != ph; p = p->next) {
while(p->status == Status_t::Filling) { } // Waits until work p has its dependencies
if(! (p->optFlags_ & (OptFlags::PendingFills|OptFlags::FatherScape)) ) {
break;
}
}
for (int i = 0; i < Dones.size(); i++) {
while (Dones[i]->status == Status_t::Done) { }
}
Dones.clear();
for (int i = 0; i < Deletable_Sublists.size(); i++) {
Workitem *begin = Deletable_Sublists[i].first;
Workitem *end = Deletable_Sublists[i].second;
DEPSPAWN_DEBUGACTION(
for(Workitem *q = begin; q != end->next; q = q->next) {
assert(q->args == nullptr);
assert(q->status == Status_t::Deallocatable);
assert(q->optFlags_ & OptFlags::TaskRun);
if (q->deps) {
printf("%p -> %p\n", q, q->deps);
assert(q->deps == nullptr);
}
}
); // END DEPSPAWN_DEBUGACTION
Workitem::Pool.freeLinkedList(begin, end);
}
Deletable_Sublists.clear();
DEPSPAWN_PROFILEACTION(profile_time_eraser_waiting += (tbb::tick_count::now() - t0).seconds());
/*
for(p = next; p; p = p->next) {
last_workitem = p;
if((p->status != Status_t::Deallocatable) || !(p->optFlags_ & OptFlags::TaskRun))
lastkeep = p;
}
Workitem *dp = lastkeep->next; // Everything from here will be deleted
lastkeep->next = nullptr;
if (dp != nullptr) {
for(p = worklist; p != ph; p = p->next) {
while(p->status == Status_t::Filling) { } // Waits until work p has its dependencies
if(! (p->optFlags_ & (OptFlags::PendingFills|OptFlags::FatherScape)) ) {
break;
}
}
DEPSPAWN_PROFILEACTION(profile_time_eraser_waiting += (tbb::tick_count::now() - t0).seconds());
DEPSPAWN_DEBUGACTION(
for(p = dp; p; p = p->next) {
assert(p-> args == nullptr);
if (p->deps) {
printf("%p -> %p\n", p, p->deps);
assert(p->deps == nullptr);
}
}
); // END DEPSPAWN_DEBUGACTION
Workitem::Pool.freeLinkedList(dp, last_workitem);
}
*/
eraser_assigned = false;
}
}
} //namespace internal
} //namespace depspawn
<|endoftext|> |
<commit_before>#include <system/System.h>
#ifdef HX_MACOS
#include <CoreFoundation/CoreFoundation.h>
#endif
#include <SDL_rwops.h>
#include <SDL_timer.h>
namespace lime {
double System::GetTimer () {
return SDL_GetTicks ();
}
FILE* FILE_HANDLE::getFile () {
if (((SDL_RWops*)handle)->type == SDL_RWOPS_STDFILE) {
return ((SDL_RWops*)handle)->hidden.stdio.fp;
} else if (((SDL_RWops*)handle)->type == SDL_RWOPS_JNIFILE) {
#ifdef ANDROID
FILE* file = ::fdopen (((SDL_RWops*)handle)->hidden.androidio.fd, "rb");
::fseek (file, ((SDL_RWops*)handle)->hidden.androidio.offset, 0);
return file;
#endif
}
return NULL;
}
int FILE_HANDLE::getLength () {
return SDL_RWsize (((SDL_RWops*)handle));
}
bool FILE_HANDLE::isFile () {
return ((SDL_RWops*)handle)->type == SDL_RWOPS_STDFILE;
}
int fclose (FILE_HANDLE *stream) {
if (stream) {
return SDL_RWclose ((SDL_RWops*)stream->handle);
}
return 0;
}
FILE_HANDLE *fdopen (int fd, const char *mode) {
FILE* fp = ::fdopen (fd, mode);
SDL_RWops *result = SDL_RWFromFP (fp, SDL_TRUE);
if (result) {
return new FILE_HANDLE (result);
}
return NULL;
}
FILE_HANDLE *fopen (const char *filename, const char *mode) {
SDL_RWops *result;
#ifdef HX_MACOS
result = SDL_RWFromFile (filename, "rb");
if (!result) {
CFStringRef str = CFStringCreateWithCString (NULL, filename, kCFStringEncodingUTF8);
CFURLRef path = CFBundleCopyResourceURL (CFBundleGetMainBundle (), str, NULL, NULL);
CFRelease (str);
if (path) {
str = CFURLCopyPath (path);
CFIndex maxSize = CFStringGetMaximumSizeForEncoding (CFStringGetLength (str), kCFStringEncodingUTF8);
char *buffer = (char *)malloc (maxSize);
if (CFStringGetCString (str, buffer, maxSize, kCFStringEncodingUTF8)) {
result = SDL_RWFromFP (::fopen (buffer, "rb"), true);
free (buffer);
}
CFRelease (str);
CFRelease (path);
}
}
#else
result = SDL_RWFromFile (filename, mode);
#endif
if (result) {
return new FILE_HANDLE (result);
}
return NULL;
}
size_t fread (void *ptr, size_t size, size_t count, FILE_HANDLE *stream) {
return SDL_RWread (stream ? (SDL_RWops*)stream->handle : NULL, ptr, size, count);
}
int fseek (FILE_HANDLE *stream, long int offset, int origin) {
return SDL_RWseek (stream ? (SDL_RWops*)stream->handle : NULL, offset, origin);
}
long int ftell (FILE_HANDLE *stream) {
return SDL_RWtell (stream ? (SDL_RWops*)stream->handle : NULL);
}
size_t fwrite (const void *ptr, size_t size, size_t count, FILE_HANDLE *stream) {
return SDL_RWwrite (stream ? (SDL_RWops*)stream->handle : NULL, ptr, size, count);
}
}<commit_msg>Mac fix<commit_after>#include <system/System.h>
#ifdef HX_MACOS
#include <CoreFoundation/CoreFoundation.h>
#endif
#include <SDL_rwops.h>
#include <SDL_timer.h>
namespace lime {
double System::GetTimer () {
return SDL_GetTicks ();
}
FILE* FILE_HANDLE::getFile () {
if (((SDL_RWops*)handle)->type == SDL_RWOPS_STDFILE) {
return ((SDL_RWops*)handle)->hidden.stdio.fp;
} else if (((SDL_RWops*)handle)->type == SDL_RWOPS_JNIFILE) {
#ifdef ANDROID
FILE* file = ::fdopen (((SDL_RWops*)handle)->hidden.androidio.fd, "rb");
::fseek (file, ((SDL_RWops*)handle)->hidden.androidio.offset, 0);
return file;
#endif
}
return NULL;
}
int FILE_HANDLE::getLength () {
return SDL_RWsize (((SDL_RWops*)handle));
}
bool FILE_HANDLE::isFile () {
return ((SDL_RWops*)handle)->type == SDL_RWOPS_STDFILE;
}
int fclose (FILE_HANDLE *stream) {
if (stream) {
return SDL_RWclose ((SDL_RWops*)stream->handle);
}
return 0;
}
FILE_HANDLE *fdopen (int fd, const char *mode) {
FILE* fp = ::fdopen (fd, mode);
SDL_RWops *result = SDL_RWFromFP (fp, SDL_TRUE);
if (result) {
return new FILE_HANDLE (result);
}
return NULL;
}
FILE_HANDLE *fopen (const char *filename, const char *mode) {
SDL_RWops *result;
#ifdef HX_MACOS
result = SDL_RWFromFile (filename, "rb");
if (!result) {
CFStringRef str = CFStringCreateWithCString (NULL, filename, kCFStringEncodingUTF8);
CFURLRef path = CFBundleCopyResourceURL (CFBundleGetMainBundle (), str, NULL, NULL);
CFRelease (str);
if (path) {
str = CFURLCopyPath (path);
CFIndex maxSize = CFStringGetMaximumSizeForEncoding (CFStringGetLength (str), kCFStringEncodingUTF8);
char *buffer = (char *)malloc (maxSize);
if (CFStringGetCString (str, buffer, maxSize, kCFStringEncodingUTF8)) {
result = SDL_RWFromFP (::fopen (buffer, "rb"), SDL_TRUE);
free (buffer);
}
CFRelease (str);
CFRelease (path);
}
}
#else
result = SDL_RWFromFile (filename, mode);
#endif
if (result) {
return new FILE_HANDLE (result);
}
return NULL;
}
size_t fread (void *ptr, size_t size, size_t count, FILE_HANDLE *stream) {
return SDL_RWread (stream ? (SDL_RWops*)stream->handle : NULL, ptr, size, count);
}
int fseek (FILE_HANDLE *stream, long int offset, int origin) {
return SDL_RWseek (stream ? (SDL_RWops*)stream->handle : NULL, offset, origin);
}
long int ftell (FILE_HANDLE *stream) {
return SDL_RWtell (stream ? (SDL_RWops*)stream->handle : NULL);
}
size_t fwrite (const void *ptr, size_t size, size_t count, FILE_HANDLE *stream) {
return SDL_RWwrite (stream ? (SDL_RWops*)stream->handle : NULL, ptr, size, count);
}
}<|endoftext|> |
<commit_before>#ifndef PAINTER_BRUSH_HPP
#define PAINTER_BRUSH_HPP
#include <algorithm>
#include <bitset>
#include <utility>
#include <vector>
#include <optional/optional.hpp>
#include <cppurses/painter/attribute.hpp>
#include <cppurses/painter/color.hpp>
namespace cppurses {
class Brush {
public:
template <typename... Attributes>
explicit Brush(Attributes... attrs) {
this->add_attributes(std::forward<Attributes>(attrs)...);
}
// Base Case
void add_attributes() {}
// Recursive Case
template <typename T, typename... Others>
void add_attributes(T attr, Others... others) {
this->set_attr(attr);
this->add_attributes(others...);
}
void remove_attribute(Attribute attr);
void clear_attributes() { attributes_.reset(); }
void set_background(Color color) { background_color_ = color; }
void set_foreground(Color color) { foreground_color_ = color; }
std::vector<Attribute> attributes() const;
const opt::Optional<Color>& background_color() const {
return background_color_;
}
opt::Optional<Color>& background_color() { return background_color_; }
const opt::Optional<Color>& foreground_color() const {
return foreground_color_;
}
opt::Optional<Color>& foreground_color() { return foreground_color_; }
friend bool operator==(const Brush& lhs, const Brush& rhs);
private:
void set_attr(detail::BackgroundColor bc) {
this->set_background(static_cast<Color>(bc));
}
void set_attr(detail::ForegroundColor fc) {
this->set_foreground(static_cast<Color>(fc));
}
void set_attr(Attribute attr);
std::bitset<8> attributes_;
opt::Optional<Color> background_color_;
opt::Optional<Color> foreground_color_;
};
} // namespace cppurses
#endif // PAINTER_BRUSH_HPP
<commit_msg>Add ability to remove a color from Brush.<commit_after>#ifndef PAINTER_BRUSH_HPP
#define PAINTER_BRUSH_HPP
#include <algorithm>
#include <bitset>
#include <utility>
#include <vector>
#include <optional/optional.hpp>
#include <cppurses/painter/attribute.hpp>
#include <cppurses/painter/color.hpp>
namespace cppurses {
class Brush {
public:
template <typename... Attributes>
explicit Brush(Attributes... attrs) {
this->add_attributes(std::forward<Attributes>(attrs)...);
}
// Base Case
void add_attributes() {}
// Recursive Case
template <typename T, typename... Others>
void add_attributes(T attr, Others... others) {
this->set_attr(attr);
this->add_attributes(others...);
}
void remove_attribute(Attribute attr);
void clear_attributes() { attributes_.reset(); }
void set_background(Color color) { background_color_ = color; }
void set_foreground(Color color) { foreground_color_ = color; }
void remove_background() { background_color_ = opt::none; }
void remove_foreground() { foreground_color_ = opt::none; }
std::vector<Attribute> attributes() const;
const opt::Optional<Color>& background_color() const {
return background_color_;
}
opt::Optional<Color>& background_color() { return background_color_; }
const opt::Optional<Color>& foreground_color() const {
return foreground_color_;
}
opt::Optional<Color>& foreground_color() { return foreground_color_; }
friend bool operator==(const Brush& lhs, const Brush& rhs);
private:
void set_attr(detail::BackgroundColor bc) {
this->set_background(static_cast<Color>(bc));
}
void set_attr(detail::ForegroundColor fc) {
this->set_foreground(static_cast<Color>(fc));
}
void set_attr(Attribute attr);
std::bitset<8> attributes_;
opt::Optional<Color> background_color_;
opt::Optional<Color> foreground_color_;
};
} // namespace cppurses
#endif // PAINTER_BRUSH_HPP
<|endoftext|> |
<commit_before>#include <stan/math/rev/mat.hpp>
#include <gtest/gtest.h>
#include <stan/math/prim/scal/fun/value_of.hpp>
#include <chrono>
using stan::math::var;
using Eigen::Dynamic;
using Eigen::Matrix;
typedef std::chrono::high_resolution_clock::time_point TimeVar;
#define duration(a) std::chrono::duration_cast<std::chrono::nanoseconds>(a).count()
#define timeNow() std::chrono::high_resolution_clock::now()
// We check that the values of the new regression match those of one built
// from existing primitives.
TEST(ProbDistributionsBernoulliLogitGLM, glm_matches_bernoulli_logit_doubles) {
Matrix<int,Dynamic,1> n(3,1);
n << 1, 0, 1;
Matrix<double,Dynamic,Dynamic> x(3,2);
x << -12, 46, -42,
24, 25, 27;
Matrix<double,Dynamic,1> beta(2,1);
beta << 0.3, 2;
Matrix<double,Dynamic,1> alpha(3,1);
alpha << 10, 23, 13;
Matrix<double,Dynamic,1> theta(3,1);
theta = x * beta + alpha;
EXPECT_FLOAT_EQ((stan::math::bernoulli_logit_lpmf(n, theta)),
(stan::math::bernoulli_logit_glm_lpmf(n, x, beta, alpha)));
EXPECT_FLOAT_EQ((stan::math::bernoulli_logit_lpmf<true>(n, theta)),
(stan::math::bernoulli_logit_glm_lpmf<true>(n, x, beta, alpha)));
EXPECT_FLOAT_EQ((stan::math::bernoulli_logit_lpmf<false>(n, theta)),
(stan::math::bernoulli_logit_glm_lpmf<false>(n, x, beta, alpha)));
EXPECT_FLOAT_EQ((stan::math::bernoulli_logit_lpmf<true, Matrix<int,Dynamic,1> >(n, theta)),
(stan::math::bernoulli_logit_glm_lpmf<true, Matrix<int,Dynamic,1> >(n, x, beta, alpha)));
EXPECT_FLOAT_EQ((stan::math::bernoulli_logit_lpmf<false, Matrix<int,Dynamic,1> >(n, theta)),
(stan::math::bernoulli_logit_glm_lpmf<false, Matrix<int,Dynamic,1>>(n, x, beta, alpha)));
EXPECT_FLOAT_EQ((stan::math::bernoulli_logit_lpmf<Matrix<int,Dynamic,1> >(n, theta)),
(stan::math::bernoulli_logit_glm_lpmf< Matrix<int,Dynamic,1> >(n, x, beta, alpha)));
}
// We check that the gradients of the new regression match those of one built
// from existing primitives.
TEST(ProbDistributionsBernoulliLogitGLM, glm_matches_bernoulli_logit_vars) {
Matrix<int,Dynamic,1> n(3,1);
n << 1, 0, 1;
Matrix<var,Dynamic,Dynamic> x(3,2);
x << -12, 46, -42,
24, 25, 27;
Matrix<var,Dynamic,1> beta(2,1);
beta << 0.3, 2;
Matrix<var,Dynamic,1> alpha(3,1);
alpha << 10, 23, 13;
Matrix<var,Dynamic,1> theta(3,1);
theta = x * beta + alpha;
var lp = stan::math::bernoulli_logit_lpmf(n, theta);
lp.grad();
stan::math::recover_memory();
Matrix<int,Dynamic,1> n2(3,1);
n2 << 1, 0, 1;
Matrix<var,Dynamic,Dynamic> x2(3,2);
x2 << -12, 46, -42,
24, 25, 27;
Matrix<var,Dynamic,1> beta2(2,1);
beta2 << 0.3, 2;
Matrix<var,Dynamic,1> alpha2(3,1);
alpha2 << 10, 23, 13;
var lp2 = stan::math::bernoulli_logit_glm_lpmf(n2, x2, beta2, alpha2);
lp2.grad();
EXPECT_FLOAT_EQ(lp.val(),
lp2.val());
for (size_t i = 0; i < 2; i++) {
EXPECT_FLOAT_EQ(beta[i].adj(), beta2[i].adj());
}
for (size_t j = 0; j < 3; j++) {
EXPECT_FLOAT_EQ(alpha[j].adj(), alpha2[j].adj());
for (size_t i = 0; i < 2; i++) {
EXPECT_FLOAT_EQ(x(j,i).adj(), x2(j,i).adj());
}
}
}
// Here, we compare the speed of the new regression to that of one built from
// existing primitives.
TEST(ProbDistributionsBernoulliLogitGLM, glm_matches_bernoulli_logit_speed) {
int R = 30000;
int C = 1000;
Matrix<int,Dynamic,1> n(R,1);
for (size_t i = 0; i < R; i++) {
n[i] = rand()%2;
}
Matrix<double,Dynamic,Dynamic> xreal = Eigen::MatrixXd::Random(R,C);
Matrix<double,Dynamic,1> betareal = Eigen::MatrixXd::Random(C,1);
Matrix<double,Dynamic,1> alphareal = Eigen::MatrixXd::Random(R,1);
Matrix<var,Dynamic,1> beta = betareal;
Matrix<var,Dynamic,1> theta(R,1);
theta = xreal * beta + alphareal;
TimeVar t1 = timeNow();
var lp = stan::math::bernoulli_logit_lpmf(n, theta);
lp.grad();
TimeVar t2 = timeNow();
stan::math::recover_memory();
Matrix<var,Dynamic,1> beta2 = betareal;
TimeVar t3 = timeNow();
var lp2 = stan::math::bernoulli_logit_glm_lpmf(n, xreal, beta2, alphareal);
lp2.grad();
TimeVar t4 = timeNow();
std::cout << "Existing Primitives:" << std::endl << duration(t2-t1) << std::endl << "New Primitives:" << std::endl << duration(t4-t3) << std::endl;
}
<commit_msg>commented out performance test, to satisfy Travis<commit_after>#include <stan/math/rev/mat.hpp>
#include <gtest/gtest.h>
#include <stan/math/prim/scal/fun/value_of.hpp>
#include <chrono>
using stan::math::var;
using Eigen::Dynamic;
using Eigen::Matrix;
typedef std::chrono::high_resolution_clock::time_point TimeVar;
#define duration(a) std::chrono::duration_cast<std::chrono::nanoseconds>(a).count()
#define timeNow() std::chrono::high_resolution_clock::now()
// We check that the values of the new regression match those of one built
// from existing primitives.
TEST(ProbDistributionsBernoulliLogitGLM, glm_matches_bernoulli_logit_doubles) {
Matrix<int,Dynamic,1> n(3,1);
n << 1, 0, 1;
Matrix<double,Dynamic,Dynamic> x(3,2);
x << -12, 46, -42,
24, 25, 27;
Matrix<double,Dynamic,1> beta(2,1);
beta << 0.3, 2;
Matrix<double,Dynamic,1> alpha(3,1);
alpha << 10, 23, 13;
Matrix<double,Dynamic,1> theta(3,1);
theta = x * beta + alpha;
EXPECT_FLOAT_EQ((stan::math::bernoulli_logit_lpmf(n, theta)),
(stan::math::bernoulli_logit_glm_lpmf(n, x, beta, alpha)));
EXPECT_FLOAT_EQ((stan::math::bernoulli_logit_lpmf<true>(n, theta)),
(stan::math::bernoulli_logit_glm_lpmf<true>(n, x, beta, alpha)));
EXPECT_FLOAT_EQ((stan::math::bernoulli_logit_lpmf<false>(n, theta)),
(stan::math::bernoulli_logit_glm_lpmf<false>(n, x, beta, alpha)));
EXPECT_FLOAT_EQ((stan::math::bernoulli_logit_lpmf<true, Matrix<int,Dynamic,1> >(n, theta)),
(stan::math::bernoulli_logit_glm_lpmf<true, Matrix<int,Dynamic,1> >(n, x, beta, alpha)));
EXPECT_FLOAT_EQ((stan::math::bernoulli_logit_lpmf<false, Matrix<int,Dynamic,1> >(n, theta)),
(stan::math::bernoulli_logit_glm_lpmf<false, Matrix<int,Dynamic,1>>(n, x, beta, alpha)));
EXPECT_FLOAT_EQ((stan::math::bernoulli_logit_lpmf<Matrix<int,Dynamic,1> >(n, theta)),
(stan::math::bernoulli_logit_glm_lpmf< Matrix<int,Dynamic,1> >(n, x, beta, alpha)));
}
// We check that the gradients of the new regression match those of one built
// from existing primitives.
TEST(ProbDistributionsBernoulliLogitGLM, glm_matches_bernoulli_logit_vars) {
Matrix<int,Dynamic,1> n(3,1);
n << 1, 0, 1;
Matrix<var,Dynamic,Dynamic> x(3,2);
x << -12, 46, -42,
24, 25, 27;
Matrix<var,Dynamic,1> beta(2,1);
beta << 0.3, 2;
Matrix<var,Dynamic,1> alpha(3,1);
alpha << 10, 23, 13;
Matrix<var,Dynamic,1> theta(3,1);
theta = x * beta + alpha;
var lp = stan::math::bernoulli_logit_lpmf(n, theta);
lp.grad();
stan::math::recover_memory();
Matrix<int,Dynamic,1> n2(3,1);
n2 << 1, 0, 1;
Matrix<var,Dynamic,Dynamic> x2(3,2);
x2 << -12, 46, -42,
24, 25, 27;
Matrix<var,Dynamic,1> beta2(2,1);
beta2 << 0.3, 2;
Matrix<var,Dynamic,1> alpha2(3,1);
alpha2 << 10, 23, 13;
var lp2 = stan::math::bernoulli_logit_glm_lpmf(n2, x2, beta2, alpha2);
lp2.grad();
EXPECT_FLOAT_EQ(lp.val(),
lp2.val());
for (size_t i = 0; i < 2; i++) {
EXPECT_FLOAT_EQ(beta[i].adj(), beta2[i].adj());
}
for (size_t j = 0; j < 3; j++) {
EXPECT_FLOAT_EQ(alpha[j].adj(), alpha2[j].adj());
for (size_t i = 0; i < 2; i++) {
EXPECT_FLOAT_EQ(x(j,i).adj(), x2(j,i).adj());
}
}
}
// Here, we compare the speed of the new regression to that of one built from
// existing primitives.
/*
TEST(ProbDistributionsBernoulliLogitGLM, glm_matches_bernoulli_logit_speed) {
int R = 30000;
int C = 1000;
Matrix<int,Dynamic,1> n(R,1);
for (size_t i = 0; i < R; i++) {
n[i] = rand()%2;
}
Matrix<double,Dynamic,Dynamic> xreal = Eigen::MatrixXd::Random(R,C);
Matrix<double,Dynamic,1> betareal = Eigen::MatrixXd::Random(C,1);
Matrix<double,Dynamic,1> alphareal = Eigen::MatrixXd::Random(R,1);
Matrix<var,Dynamic,1> beta = betareal;
Matrix<var,Dynamic,1> theta(R,1);
theta = xreal * beta + alphareal;
TimeVar t1 = timeNow();
var lp = stan::math::bernoulli_logit_lpmf(n, theta);
lp.grad();
TimeVar t2 = timeNow();
stan::math::recover_memory();
Matrix<var,Dynamic,1> beta2 = betareal;
TimeVar t3 = timeNow();
var lp2 = stan::math::bernoulli_logit_glm_lpmf(n, xreal, beta2, alphareal);
lp2.grad();
TimeVar t4 = timeNow();
std::cout << "Existing Primitives:" << std::endl << duration(t2-t1) << std::endl << "New Primitives:" << std::endl << duration(t4-t3) << std::endl;
}
*/
<|endoftext|> |
<commit_before>/**
* \file
* \brief StaticThread class header
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2014-10-27
*/
#ifndef INCLUDE_DISTORTOS_STATICTHREAD_HPP_
#define INCLUDE_DISTORTOS_STATICTHREAD_HPP_
#include "distortos/Thread.hpp"
namespace distortos
{
/**
* \brief StaticThread class is a templated interface for thread that has automatic storage of stack.
*
* \param StackSize is the size of stack, bytes
* \param Function is the function that will be executed in separate thread
* \param Args are the arguments for Function
*/
template<size_t StackSize, typename Function, typename... Args>
class StaticThread : private Thread<Function, Args...>
{
public:
/// base of StaticThread
using Base = Thread<Function, Args...>;
/**
* \brief StaticThread's constructor
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*/
StaticThread(const uint8_t priority, Function&& function, Args&&... args) :
Base{&stack_, sizeof(stack_), priority, std::forward<Function>(function), std::forward<Args>(args)...}
{
}
using Base::getPriority;
using Base::join;
using Base::setPriority;
using Base::start;
private:
/// stack buffer
typename std::aligned_storage<StackSize>::type stack_;
};
/**
* \brief Helper factory function to make StaticThread object with partially deduced template arguments
*
* \param StackSize is the size of stack, bytes
* \param Function is the function that will be executed
* \param Args are the arguments for Function
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*
* \return StaticThread object with partially deduced template arguments
*/
template<size_t StackSize, typename Function, typename... Args>
StaticThread<StackSize, Function, Args...> makeStaticThread(const uint8_t priority, Function&& function, Args&&... args)
{
return {priority, std::forward<Function>(function), std::forward<Args>(args)...};
}
} // namespace distortos
#endif // INCLUDE_DISTORTOS_STATICTHREAD_HPP_
<commit_msg>StaticThread: expose getEffectivePriority() from base class<commit_after>/**
* \file
* \brief StaticThread class header
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2014-11-11
*/
#ifndef INCLUDE_DISTORTOS_STATICTHREAD_HPP_
#define INCLUDE_DISTORTOS_STATICTHREAD_HPP_
#include "distortos/Thread.hpp"
namespace distortos
{
/**
* \brief StaticThread class is a templated interface for thread that has automatic storage of stack.
*
* \param StackSize is the size of stack, bytes
* \param Function is the function that will be executed in separate thread
* \param Args are the arguments for Function
*/
template<size_t StackSize, typename Function, typename... Args>
class StaticThread : private Thread<Function, Args...>
{
public:
/// base of StaticThread
using Base = Thread<Function, Args...>;
/**
* \brief StaticThread's constructor
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*/
StaticThread(const uint8_t priority, Function&& function, Args&&... args) :
Base{&stack_, sizeof(stack_), priority, std::forward<Function>(function), std::forward<Args>(args)...}
{
}
using Base::getEffectivePriority;
using Base::getPriority;
using Base::join;
using Base::setPriority;
using Base::start;
private:
/// stack buffer
typename std::aligned_storage<StackSize>::type stack_;
};
/**
* \brief Helper factory function to make StaticThread object with partially deduced template arguments
*
* \param StackSize is the size of stack, bytes
* \param Function is the function that will be executed
* \param Args are the arguments for Function
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*
* \return StaticThread object with partially deduced template arguments
*/
template<size_t StackSize, typename Function, typename... Args>
StaticThread<StackSize, Function, Args...> makeStaticThread(const uint8_t priority, Function&& function, Args&&... args)
{
return {priority, std::forward<Function>(function), std::forward<Args>(args)...};
}
} // namespace distortos
#endif // INCLUDE_DISTORTOS_STATICTHREAD_HPP_
<|endoftext|> |
<commit_before>#pragma once
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <structmember.h>
#define _mgl_str(x) #x
#define _mgl_xstr(x) _mgl_str(x)
#define mgl_mod _mgl_xstr(MODERNGL_MODULE)
#define mgl_ext mgl_mod ".mgl"
/* Wrapper classes for internal objects are defined in python. They must have __slots__ defined.
* A slot can be accessed in O(1) once detect_class(...) and slot_offset(...) is called.
*/
#define SLOT(obj, type, offset) (*(type **)((char *)obj + offset))
/* Shortcuts */
#define NEW_REF(obj) (Py_INCREF(obj), obj)
/* Classes defined in python must be instantiated using new_object(...)
* The allocated memory is initialized to zero.
* Slots can be set using the SLOT(...) macro.
*/
inline PyObject * _new_object(PyTypeObject * type) {
PyObject * res = 0;
Py_INCREF(type);
if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
res = PyObject_GC_New(PyObject, type);
} else {
res = PyObject_New(PyObject, type);
}
return res;
}
#define new_object(type, typeobj) (type *)_new_object(typeobj)
#define call_function(function, ...) PyObject_CallFunctionObjArgs(function, __VA_ARGS__, (void *)0)
inline void replace_object(PyObject *& src, PyObject * dst) {
Py_INCREF(dst);
Py_DECREF(src);
src = dst;
}
<commit_msg>samplers need XSETREF<commit_after>#pragma once
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <structmember.h>
#define _mgl_str(x) #x
#define _mgl_xstr(x) _mgl_str(x)
#define mgl_mod _mgl_xstr(MODERNGL_MODULE)
#define mgl_ext mgl_mod ".mgl"
/* Wrapper classes for internal objects are defined in python. They must have __slots__ defined.
* A slot can be accessed in O(1) once detect_class(...) and slot_offset(...) is called.
*/
#define SLOT(obj, type, offset) (*(type **)((char *)obj + offset))
/* Shortcuts */
#define NEW_REF(obj) (Py_INCREF(obj), obj)
#ifndef Py_SETREF
#define Py_SETREF(op, op2) \
do { \
PyObject *_py_tmp = (PyObject *)(op); \
(op) = (op2); \
Py_DECREF(_py_tmp); \
} while (0)
#endif
#ifndef Py_XSETREF
#define Py_XSETREF(op, op2) \
do { \
PyObject *_py_tmp = (PyObject *)(op); \
(op) = (op2); \
Py_XDECREF(_py_tmp); \
} while (0)
#endif
/* Classes defined in python must be instantiated using new_object(...)
* The allocated memory is initialized to zero.
* Slots can be set using the SLOT(...) macro.
*/
inline PyObject * _new_object(PyTypeObject * type) {
PyObject * res = 0;
Py_INCREF(type);
if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
res = PyObject_GC_New(PyObject, type);
} else {
res = PyObject_New(PyObject, type);
}
return res;
}
#define new_object(type, typeobj) (type *)_new_object(typeobj)
#define call_function(function, ...) PyObject_CallFunctionObjArgs(function, __VA_ARGS__, (void *)0)
inline void replace_object(PyObject *& src, PyObject * dst) {
Py_INCREF(dst);
Py_DECREF(src);
src = dst;
}
<|endoftext|> |
<commit_before>// ===== ---- ofp/sys/tcp_connection.ipp ------------------*- C++ -*- ===== //
//
// Copyright (c) 2013 William W. Fisher
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ===== ------------------------------------------------------------ ===== //
/// \file
/// \brief Implements sys::TCP_Connection class.
// ===== ------------------------------------------------------------ ===== //
#include "ofp/sys/tcp_connection.h"
#include "ofp/sys/tcp_server.h"
#include "ofp/sys/engine.h"
#include "ofp/log.h"
#include "ofp/defaulthandshake.h"
namespace ofp {
namespace sys {
template <class SocketType>
TCP_Connection<SocketType>::TCP_Connection(Engine *engine, Driver::Role role,
ProtocolVersions versions,
ChannelListener::Factory factory)
: Connection{engine, new DefaultHandshake{this, role, versions, factory}},
message_{this}, socket_{engine->io(), engine->context()}, idleTimer_{engine->io()} {}
template <class SocketType>
TCP_Connection<SocketType>::TCP_Connection(Engine *engine, tcp::socket socket,
Driver::Role role, ProtocolVersions versions,
ChannelListener::Factory factory)
: Connection{engine, new DefaultHandshake{this, role, versions, factory}},
message_{this}, socket_{std::move(socket), engine->context()}, idleTimer_{engine->io()} {}
/// \brief Construct connection object for reconnect attempt.
template <class SocketType>
TCP_Connection<SocketType>::TCP_Connection(Engine *engine, DefaultHandshake *handshake)
: Connection{engine, handshake}, message_{this}, socket_{engine->io(), engine->context()},
idleTimer_{engine->io()} {
handshake->setConnection(this);
}
template <class SocketType>
ofp::IPv6Endpoint TCP_Connection<SocketType>::remoteEndpoint() const {
if (isOutgoing()) {
return convertEndpoint<tcp>(endpoint_);
} else {
return convertEndpoint<tcp>(socket_.lowest_layer().remote_endpoint());
}
}
template <class SocketType>
void TCP_Connection<SocketType>::flush() {
auto self(this->shared_from_this());
socket_.buf_flush([self](const std::error_code &error){});
}
template <class SocketType>
void TCP_Connection<SocketType>::shutdown() {
auto self(this->shared_from_this());
socket_.async_shutdown([this, self](const std::error_code &error){
socket_.shutdownLowestLayer();
});
}
template <class SocketType>
ofp::Deferred<std::error_code>
TCP_Connection<SocketType>::asyncConnect(const tcp::endpoint &endpt, Milliseconds delay) {
assert(deferredExc_ == nullptr);
endpoint_ = endpt;
deferredExc_ = Deferred<std::error_code>::makeResult();
if (delay > 0_ms) {
asyncDelayConnect(delay);
} else {
asyncConnect();
}
return deferredExc_;
}
template <class SocketType>
void TCP_Connection<SocketType>::asyncAccept() {
// Do nothing if socket is not open.
if (!socket_.is_open())
return;
// We always send and receive complete messages; disable Nagle algorithm.
socket_.lowest_layer().set_option(tcp::no_delay(true));
asyncHandshake();
}
template <class SocketType>
void TCP_Connection<SocketType>::channelUp() {
assert(channelListener());
channelListener()->onChannelUp(this);
asyncReadHeader();
updateLatestActivity();
asyncIdleCheck();
}
template <class SocketType>
void TCP_Connection<SocketType>::channelDown() {
assert(channelListener());
channelListener()->onChannelDown(this);
if (wantsReconnect()) {
reconnect();
}
}
template <class SocketType>
void TCP_Connection<SocketType>::asyncReadHeader() {
// Do nothing if socket is not open.
if (!socket_.is_open()) {
log::debug("asyncReadHeader called with socket closed.");
return;
}
auto self(this->shared_from_this());
asio::async_read(socket_, asio::buffer(message_.mutableData(sizeof(Header)),
sizeof(Header)),
[this, self](const asio::error_code &err, size_t length) {
log::Lifetime lifetime{"asyncReadHeader callback."};
if (!err) {
assert(length == sizeof(Header));
const Header *hdr = message_.header();
if (hdr->validateInput(version())) {
// The header has passed our rudimentary validation checks.
UInt16 msgLength = hdr->length();
if (msgLength == sizeof(Header)) {
postMessage(this, &message_);
if (socket_.is_open()) {
asyncReadHeader();
} else {
// Rare: postMessage() closed the socket forcefully.
channelDown();
}
} else {
asyncReadMessage(msgLength);
}
} else {
// The header failed our rudimentary validation checks.
log::debug("asyncReadHeader header validation failed");
channelDown();
}
} else {
if (err != asio::error::eof) {
log::debug("asyncReadHeader error ", err);
}
channelDown();
}
updateLatestActivity();
});
}
template <class SocketType>
void TCP_Connection<SocketType>::asyncReadMessage(size_t msgLength) {
assert(msgLength > sizeof(Header));
assert(socket_.is_open());
auto self(this->shared_from_this());
asio::async_read(
socket_, asio::buffer(message_.mutableData(msgLength) + sizeof(Header),
msgLength - sizeof(Header)),
[this, self](const asio::error_code &err, size_t bytes_transferred) {
if (!err) {
assert(bytes_transferred == message_.size() - sizeof(Header));
postMessage(this, &message_);
if (socket_.is_open()) {
asyncReadHeader();
} else {
// Rare: postMessage() closed the socket forcefully.
channelDown();
}
} else {
if (err != asio::error::eof) {
log::info("asyncReadMessage error ", err);
}
channelDown();
}
updateLatestActivity();
});
}
template <class SocketType>
void TCP_Connection<SocketType>::asyncHandshake() {
// Start async handshake.
auto mode = isOutgoing() ? asio::ssl::stream_base::client : asio::ssl::stream_base::server;
auto self(this->shared_from_this());
socket_.async_handshake(mode, [this, self](const asio::error_code &err) {
if (!err) {
channelUp();
} else {
log::debug("async_handshake failed", err.message());
}
});
}
template <class SocketType>
void TCP_Connection<SocketType>::asyncConnect() {
auto self(this->shared_from_this());
socket_.lowest_layer().async_connect(
endpoint_, [this, self](const asio::error_code &err) {
// `async_connect` may not report an error when the connection attempt
// fails. We need to double-check that we are connected.
if (!err) {
socket_.lowest_layer().set_option(tcp::no_delay(true));
asyncHandshake();
} else if (wantsReconnect()) {
reconnect();
}
deferredExc_->done(err);
deferredExc_ = nullptr;
});
}
template <class SocketType>
void TCP_Connection<SocketType>::asyncDelayConnect(Milliseconds delay) {
auto self(this->shared_from_this());
asio::error_code error;
idleTimer_.expires_from_now(delay, error);
if (error)
return;
idleTimer_.async_wait([this, self](const asio::error_code &err) {
if (err != asio::error::operation_aborted) {
asyncConnect();
} else {
assert(deferredExc_ != nullptr);
deferredExc_->done(err);
deferredExc_ = nullptr;
}
});
}
template <class SocketType>
void TCP_Connection<SocketType>::asyncIdleCheck() {
std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
auto interval =
std::chrono::duration_cast<Milliseconds>(now - latestActivity_);
Milliseconds delay;
if (interval >= 5000_ms) {
postIdle();
delay = 5000_ms;
} else {
delay = 5000_ms - interval;
}
asio::error_code error;
idleTimer_.expires_from_now(delay, error);
if (error)
return;
idleTimer_.async_wait([this](const asio::error_code &err) {
if (err != asio::error::operation_aborted) {
asyncIdleCheck();
}
});
}
template <class SocketType>
void TCP_Connection<SocketType>::reconnect() {
DefaultHandshake *hs = handshake();
assert(hs);
hs->setStartingVersion(version());
hs->setStartingXid(nextXid());
log::debug("reconnecting...", remoteEndpoint());
engine()->reconnect(hs, remoteEndpoint(), 750_ms);
setHandshake(nullptr);
if (channelListener() == hs) {
setChannelListener(nullptr);
}
assert(channelListener() != hs);
}
} // namespace sys
} // namespace ofp
<commit_msg>If there is an error flushing the write buffer, close the socket forcibly.<commit_after>// ===== ---- ofp/sys/tcp_connection.ipp ------------------*- C++ -*- ===== //
//
// Copyright (c) 2013 William W. Fisher
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ===== ------------------------------------------------------------ ===== //
/// \file
/// \brief Implements sys::TCP_Connection class.
// ===== ------------------------------------------------------------ ===== //
#include "ofp/sys/tcp_connection.h"
#include "ofp/sys/tcp_server.h"
#include "ofp/sys/engine.h"
#include "ofp/log.h"
#include "ofp/defaulthandshake.h"
namespace ofp {
namespace sys {
template <class SocketType>
TCP_Connection<SocketType>::TCP_Connection(Engine *engine, Driver::Role role,
ProtocolVersions versions,
ChannelListener::Factory factory)
: Connection{engine, new DefaultHandshake{this, role, versions, factory}},
message_{this}, socket_{engine->io(), engine->context()}, idleTimer_{engine->io()} {}
template <class SocketType>
TCP_Connection<SocketType>::TCP_Connection(Engine *engine, tcp::socket socket,
Driver::Role role, ProtocolVersions versions,
ChannelListener::Factory factory)
: Connection{engine, new DefaultHandshake{this, role, versions, factory}},
message_{this}, socket_{std::move(socket), engine->context()}, idleTimer_{engine->io()} {}
/// \brief Construct connection object for reconnect attempt.
template <class SocketType>
TCP_Connection<SocketType>::TCP_Connection(Engine *engine, DefaultHandshake *handshake)
: Connection{engine, handshake}, message_{this}, socket_{engine->io(), engine->context()},
idleTimer_{engine->io()} {
handshake->setConnection(this);
}
template <class SocketType>
ofp::IPv6Endpoint TCP_Connection<SocketType>::remoteEndpoint() const {
if (isOutgoing()) {
return convertEndpoint<tcp>(endpoint_);
} else {
return convertEndpoint<tcp>(socket_.lowest_layer().remote_endpoint());
}
}
template <class SocketType>
void TCP_Connection<SocketType>::flush() {
auto self(this->shared_from_this());
socket_.buf_flush([this, self](const std::error_code &error){
if (error) {
socket_.lowest_layer().close();
}
});
}
template <class SocketType>
void TCP_Connection<SocketType>::shutdown() {
auto self(this->shared_from_this());
socket_.async_shutdown([this, self](const std::error_code &error){
socket_.shutdownLowestLayer();
});
}
template <class SocketType>
ofp::Deferred<std::error_code>
TCP_Connection<SocketType>::asyncConnect(const tcp::endpoint &endpt, Milliseconds delay) {
assert(deferredExc_ == nullptr);
endpoint_ = endpt;
deferredExc_ = Deferred<std::error_code>::makeResult();
if (delay > 0_ms) {
asyncDelayConnect(delay);
} else {
asyncConnect();
}
return deferredExc_;
}
template <class SocketType>
void TCP_Connection<SocketType>::asyncAccept() {
// Do nothing if socket is not open.
if (!socket_.is_open())
return;
// We always send and receive complete messages; disable Nagle algorithm.
socket_.lowest_layer().set_option(tcp::no_delay(true));
asyncHandshake();
}
template <class SocketType>
void TCP_Connection<SocketType>::channelUp() {
assert(channelListener());
channelListener()->onChannelUp(this);
asyncReadHeader();
updateLatestActivity();
asyncIdleCheck();
}
template <class SocketType>
void TCP_Connection<SocketType>::channelDown() {
assert(channelListener());
channelListener()->onChannelDown(this);
if (wantsReconnect()) {
reconnect();
}
}
template <class SocketType>
void TCP_Connection<SocketType>::asyncReadHeader() {
// Do nothing if socket is not open.
if (!socket_.is_open()) {
log::debug("asyncReadHeader called with socket closed.");
return;
}
auto self(this->shared_from_this());
asio::async_read(socket_, asio::buffer(message_.mutableData(sizeof(Header)),
sizeof(Header)),
[this, self](const asio::error_code &err, size_t length) {
log::Lifetime lifetime{"asyncReadHeader callback."};
if (!err) {
assert(length == sizeof(Header));
const Header *hdr = message_.header();
if (hdr->validateInput(version())) {
// The header has passed our rudimentary validation checks.
UInt16 msgLength = hdr->length();
if (msgLength == sizeof(Header)) {
postMessage(this, &message_);
if (socket_.is_open()) {
asyncReadHeader();
} else {
// Rare: postMessage() closed the socket forcefully.
channelDown();
}
} else {
asyncReadMessage(msgLength);
}
} else {
// The header failed our rudimentary validation checks.
log::debug("asyncReadHeader header validation failed");
channelDown();
}
} else {
if (err != asio::error::eof) {
log::debug("asyncReadHeader error ", err);
}
channelDown();
}
updateLatestActivity();
});
}
template <class SocketType>
void TCP_Connection<SocketType>::asyncReadMessage(size_t msgLength) {
assert(msgLength > sizeof(Header));
assert(socket_.is_open());
auto self(this->shared_from_this());
asio::async_read(
socket_, asio::buffer(message_.mutableData(msgLength) + sizeof(Header),
msgLength - sizeof(Header)),
[this, self](const asio::error_code &err, size_t bytes_transferred) {
if (!err) {
assert(bytes_transferred == message_.size() - sizeof(Header));
postMessage(this, &message_);
if (socket_.is_open()) {
asyncReadHeader();
} else {
// Rare: postMessage() closed the socket forcefully.
channelDown();
}
} else {
if (err != asio::error::eof) {
log::info("asyncReadMessage error ", err);
}
channelDown();
}
updateLatestActivity();
});
}
template <class SocketType>
void TCP_Connection<SocketType>::asyncHandshake() {
// Start async handshake.
auto mode = isOutgoing() ? asio::ssl::stream_base::client : asio::ssl::stream_base::server;
auto self(this->shared_from_this());
socket_.async_handshake(mode, [this, self](const asio::error_code &err) {
if (!err) {
channelUp();
} else {
log::debug("async_handshake failed", err.message());
}
});
}
template <class SocketType>
void TCP_Connection<SocketType>::asyncConnect() {
auto self(this->shared_from_this());
socket_.lowest_layer().async_connect(
endpoint_, [this, self](const asio::error_code &err) {
// `async_connect` may not report an error when the connection attempt
// fails. We need to double-check that we are connected.
if (!err) {
socket_.lowest_layer().set_option(tcp::no_delay(true));
asyncHandshake();
} else if (wantsReconnect()) {
reconnect();
}
deferredExc_->done(err);
deferredExc_ = nullptr;
});
}
template <class SocketType>
void TCP_Connection<SocketType>::asyncDelayConnect(Milliseconds delay) {
auto self(this->shared_from_this());
asio::error_code error;
idleTimer_.expires_from_now(delay, error);
if (error)
return;
idleTimer_.async_wait([this, self](const asio::error_code &err) {
if (err != asio::error::operation_aborted) {
asyncConnect();
} else {
assert(deferredExc_ != nullptr);
deferredExc_->done(err);
deferredExc_ = nullptr;
}
});
}
template <class SocketType>
void TCP_Connection<SocketType>::asyncIdleCheck() {
std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
auto interval =
std::chrono::duration_cast<Milliseconds>(now - latestActivity_);
Milliseconds delay;
if (interval >= 5000_ms) {
postIdle();
delay = 5000_ms;
} else {
delay = 5000_ms - interval;
}
asio::error_code error;
idleTimer_.expires_from_now(delay, error);
if (error)
return;
idleTimer_.async_wait([this](const asio::error_code &err) {
if (err != asio::error::operation_aborted) {
asyncIdleCheck();
}
});
}
template <class SocketType>
void TCP_Connection<SocketType>::reconnect() {
DefaultHandshake *hs = handshake();
assert(hs);
hs->setStartingVersion(version());
hs->setStartingXid(nextXid());
log::debug("reconnecting...", remoteEndpoint());
engine()->reconnect(hs, remoteEndpoint(), 750_ms);
setHandshake(nullptr);
if (channelListener() == hs) {
setChannelListener(nullptr);
}
assert(channelListener() != hs);
}
} // namespace sys
} // namespace ofp
<|endoftext|> |
<commit_before>/*************************************************************************************
**
* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @file g_socket.cpp
* @version
* @brief
* @author duye
* @date 2014-2-16
* @note
*
* 2. 2014-06-21 duye move to gohoop
* 1. 2014-02-16 duye Created this file
*
*/
#include <g_socket.h>
using namespace gsys;
// the max request number, system default value it's 20
static const GUint32 G_DEF_MAX_REQ = 20;
Socket::Socket() : m_sockfd(-1), m_addrLen(0)
{
}
Socket::Socket(const GUint32 ip, const GUint16 port)
: m_sockfd(-1), m_addrLen(0)
{
setAddr(ip, port);
}
Socket::Socket(const Socket& Socket)
{
m_sockfd = Socket.m_sockfd;
m_addr = Socket.m_addr;
}
Socket::~Socket()
{
closeSocket(m_sockfd);
}
GResult Socket::openSocket(const GInt32 domain, const GInt32 type)
{
if ((m_sockfd = socket(domain, type, 0)) == -1)
{
//G_LOG_ERROR(G_LOG_PREFIX, "open GSocket() failed");
return G_NO;
}
// init GSocket option
if (!initOption())
{
//G_LOG_ERROR(G_LOG_PREFIX, "init GSocket option failed");
}
return G_YES;
}
GInt64 Socket::sendData(const GUint8* data, const GUint64 length, const GInt32 flags)
{
return send(m_sockfd, data, length, flags);
}
GInt64 Socket::recvData(GUint8* buffer, const GUint64 size, const GInt32 flags)
{
return recv(m_sockfd, buffer, size, flags);
}
GResult Socket::closeSocket(const GInt32 how)
{
// how = 0 : stop receive data
// how = 1 : stop send data
// how = 2 : both above way
if (m_sockfd == -1)
{
//G_LOG_ERROR(G_LOG_PREFIX, "GSocket hasn't open");
return G_YES;
}
return (shutdown(m_sockfd, how) == 0 ? G_YES : G_NO);
}
void Socket::setAddr(const GUint32 ip, const GUint16 port)
{
m_addr.sin_family = AF_INET; // RF_INET
m_addr.sin_port = htons(port); // port
m_addr.sin_addr.s_addr = ip; // IP
memset(&(m_addr.sin_zero),'\0', 8); // set 0
m_addrLen = sizeof(struct sockaddr);
}
GUint32 Socket::getIP() const
{
return ntohl(m_addr.sin_addr.s_addr);
}
GUint16 Socket::getPort() const
{
return ntohs(m_addr.sin_port);
}
GResult Socket::initOption()
{
GResult ret = G_YES;
// address reuse flag, 1 reuse
GInt32 reuse = 1;
// send time limit, unit ms
//int stime = 1000;
// receive time limit, unit ms
//int rtime = 1000;
// receive and send data buffer size
GInt32 bufsize = 0xFFFF;
// don't copy data from system buffer to GSocket buffer
GInt32 nosize = 0;
// set address reuse
if (setsockopt(m_sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(GInt32)) == -1)
{
//G_LOG_WARN(G_LOG_PREFIX, "set address reuse failed");
ret = false;
}
// set send data time limit
//if (setsockopt(m_sockfd, SOL_GSocket, SO_SNDTIMEO, (const char*)&stime, sizeof(int)) == -1)
//{
// ret = false;
//}
// set receive data time limit
//if (setsockopt(m_sockfd, SOL_GSocket, SO_RCVTIMEO, (const char*)&rtime, sizeof(int)) == -1)
//{
// ret = false;
//}
// set send data buffer size
if (setsockopt(m_sockfd, SOL_SOCKET, SO_SNDBUF, (const char*)&bufsize, sizeof(GInt32)) == -1)
{
ret = false;
}
// set receive data buffer size
if (setsockopt(m_sockfd, SOL_SOCKET, SO_RCVBUF, (const char*)&bufsize, sizeof(GInt32)) == -1)
{
ret = false;
}
// don't copy data from system buffer to GSocket buffer when send data
if (setsockopt(m_sockfd, SOL_SOCKET, SO_SNDBUF, (const char*)&nosize, sizeof(GInt32)) == -1)
{
ret = false;
}
// don't copy data from system buffer to GSocket buffer when receive data
if (setsockopt(m_sockfd, SOL_SOCKET, SO_RCVBUF, (const char*)&nosize, sizeof(GInt32)) == -1)
{
ret = false;
}
// let data send completly after execute close GSocket
struct STR_Linger
{
GInt16 l_onoff;
GInt16 l_linger;
};
/*
STR_Linger linger;
linger.l_onoff = 1; // 1. allow wait; 0. force close
linger.l_linger = 1; // the time of waiting unit s
if (setsockopt(m_sockfd, SOL_GSocket, SO_LINGER, (const char*)&linger, sizeof(STR_Linger)) == -1)
{
ret = false;
}
*/
return ret;
}
<commit_msg>Update g_socket.cpp<commit_after>/*************************************************************************************
**
* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @file g_socket.cpp
* @version
* @brief
* @author duye
* @date 2014-2-16
* @note
*
* 2. 2014-06-21 duye move to gohoop
* 1. 2014-02-16 duye Created this file
*
*/
#include <g_socket.h>
namespace gsys {
SockEntity::SockEntity() : m_ip(0), m_port(0), m_sockfd(-1), m_sockLen(0)
{
bzero(m_sockAddr, sizeof(sockaddr_in));
}
SockEntity::~SockEntity()
{
}
void SockEntity::setIP(const GUint32 ip)
{
m_ip = ip;
}
GUint32 SockEntity::getIP() const
{
return m_ip;
}
void SockEntity::setPort(const GUint32 port) const
{
m_port = port;
}
GUint32 SockEntity::getPort() const
{
return m_port;
}
void SockEntity::setSockfd(const GInt32 sockfd) const
{
m_sockfd = sockfd;
}
GInt32 SockEntity::getSockfd() const
{
return m_sockfd;
}
void SockEntity::setSockAddr(const sockaddr_in sockaddr) const
{
m_sockAddr = sockAddr;
}
sockaddr_in SockEntity::getSockAddr() const
{
return m_sockAddr;
}
void SockEntity::setSockLen(const socklen_t sockLen) const
{
m_sockLen = sockLen;
}
socklen_t SockEntity::getSockLen() const
{
return m_sockLen;
}
SockTransfer::SockTransfer() {}
SockTransfer~SockTransfer() {}
GInt64 SockTransfer::send(const SockEntity& sockEntity,
const GUint8* data,
const GUint64 len,
const GInt32 flags)
{
return ::send(sockEntity.getSockfd(), data, len, flags);
}
GInt64 SockTransfer::recv(const SockEntity& sockEntity,
GUint8* buffer,
const GUint64 size,
const GInt32 flags)
{
return ::recv(sockEntity.getSockfd(), buffer, size, flags);
}
ServerSocket::ServerSocket() : ServerSocket(0, 0) {}
ServerSocket::ServerSocket(const GUint32 ip, const GUint16 port)
{
m_sockEntity.setIP(ip);
m_sockEntity.setPort(ip);
}
ServerSocket::~ServerSocket() {}
void ServerSocket::setIP(const GUint32 ip)
{
m_sockEntity.setIP(ip);
}
GUint32 ServerSocket::getIP() const
{
return m_sockEntity.getIP();
}
void ServerSocket::setPort(const GUint32 port) const
{
m_sockEntity.setPort(port);
}
GUint32 ServerSocket::getPort() const
{
m_sockEntity.getPort();
}
GResult ServerSocket::init(const GInt32 domain/*AF_INET*/, const GInt32 type/*SOCK_STREAM*/)
{
return G_YES;
}
GResult ServerSocket::uninit(const GInt32 how/*0*/)
{
return G_YES;
}
GResult ServerSocket::bind()
{
return G_YES;
}
GResult ServerSocket::listen()
{
return G_YES;
}
GResult ServerSocket::accept()
{
return G_YES;
}
ClientSocket::ClientSocket() : ClientSocket(0, 0) {}
ClientSocket::ClientSocket(const GUint32 ip, const GUint16 port)
{
m_sockEntity.setIP(ip);
m_sockEntity.setPort(ip);
}
ClientSocket::~ClientSocket() {}
void ClientSocket::setIP(const GUint32 ip)
{
m_sockEntity.setIP(ip);
}
GUint32 ClientSocket::getIP() const
{
return m_sockEntity.getIP();
}
void ClientSocket::setPort(const GUint32 port) const
{
m_sockEntity.setPort(port);
}
GUint32 ClientSocket::getPort() const
{
m_sockEntity.getPort();
}
GResult ClientSocket::init(const GInt32 domain/*AF_INET*/, const GInt32 type/*SOCK_STREAM*/)
{
return G_YES;
}
GResult ClientSocket::uninit(const GInt32 how/*0*/)
{
return G_YES;
}
GResult ClientSocket::connect()
{
return G_YES;
}
GInt64 ClientSocket::send(const GUint8* data, const GUint64 len, const GInt32 flags/*MSG_NOSIGNAL*/)
{
return SockTransfer::send(m_sockEntify.getSockfd(), data, len, flags);
}
GInt64 ClientSocket::recv(GUint8* buffer, const GUint64 size, const GInt32 flags/*0*/)
{
return SockTransfer::recv(m_sockEntify.getSockfd(), buffer, size, flags);
}
Socket::Socket() : m_sockfd(-1), m_addrLen(0)
{
}
Socket::Socket(const GUint32 ip, const GUint16 port)
: m_sockfd(-1), m_addrLen(0)
{
setAddr(ip, port);
}
Socket::Socket(const Socket& Socket)
{
m_sockfd = Socket.m_sockfd;
m_addr = Socket.m_addr;
}
Socket::~Socket()
{
closeSocket(m_sockfd);
}
GResult Socket::openSocket(const GInt32 domain, const GInt32 type)
{
if ((m_sockfd = socket(domain, type, 0)) == -1)
{
//G_LOG_ERROR(G_LOG_PREFIX, "open GSocket() failed");
return G_NO;
}
// init GSocket option
if (!initOption())
{
//G_LOG_ERROR(G_LOG_PREFIX, "init GSocket option failed");
}
return G_YES;
}
GInt64 Socket::sendData(const GUint8* data, const GUint64 length, const GInt32 flags)
{
return send(m_sockfd, data, length, flags);
}
GInt64 Socket::recvData(GUint8* buffer, const GUint64 size, const GInt32 flags)
{
return recv(m_sockfd, buffer, size, flags);
}
GResult Socket::closeSocket(const GInt32 how)
{
// how = 0 : stop receive data
// how = 1 : stop send data
// how = 2 : both above way
if (m_sockfd == -1)
{
//G_LOG_ERROR(G_LOG_PREFIX, "GSocket hasn't open");
return G_YES;
}
return (shutdown(m_sockfd, how) == 0 ? G_YES : G_NO);
}
void Socket::setAddr(const GUint32 ip, const GUint16 port)
{
m_addr.sin_family = AF_INET; // RF_INET
m_addr.sin_port = htons(port); // port
m_addr.sin_addr.s_addr = ip; // IP
memset(&(m_addr.sin_zero),'\0', 8); // set 0
m_addrLen = sizeof(struct sockaddr);
}
GUint32 Socket::getIP() const
{
return ntohl(m_addr.sin_addr.s_addr);
}
GUint16 Socket::getPort() const
{
return ntohs(m_addr.sin_port);
}
GResult Socket::initOption()
{
GResult ret = G_YES;
// address reuse flag, 1 reuse
GInt32 reuse = 1;
// send time limit, unit ms
//int stime = 1000;
// receive time limit, unit ms
//int rtime = 1000;
// receive and send data buffer size
GInt32 bufsize = 0xFFFF;
// don't copy data from system buffer to GSocket buffer
GInt32 nosize = 0;
// set address reuse
if (setsockopt(m_sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(GInt32)) == -1)
{
//G_LOG_WARN(G_LOG_PREFIX, "set address reuse failed");
ret = false;
}
// set send data time limit
//if (setsockopt(m_sockfd, SOL_GSocket, SO_SNDTIMEO, (const char*)&stime, sizeof(int)) == -1)
//{
// ret = false;
//}
// set receive data time limit
//if (setsockopt(m_sockfd, SOL_GSocket, SO_RCVTIMEO, (const char*)&rtime, sizeof(int)) == -1)
//{
// ret = false;
//}
// set send data buffer size
if (setsockopt(m_sockfd, SOL_SOCKET, SO_SNDBUF, (const char*)&bufsize, sizeof(GInt32)) == -1)
{
ret = false;
}
// set receive data buffer size
if (setsockopt(m_sockfd, SOL_SOCKET, SO_RCVBUF, (const char*)&bufsize, sizeof(GInt32)) == -1)
{
ret = false;
}
// don't copy data from system buffer to GSocket buffer when send data
if (setsockopt(m_sockfd, SOL_SOCKET, SO_SNDBUF, (const char*)&nosize, sizeof(GInt32)) == -1)
{
ret = false;
}
// don't copy data from system buffer to GSocket buffer when receive data
if (setsockopt(m_sockfd, SOL_SOCKET, SO_RCVBUF, (const char*)&nosize, sizeof(GInt32)) == -1)
{
ret = false;
}
// let data send completly after execute close GSocket
struct STR_Linger
{
GInt16 l_onoff;
GInt16 l_linger;
};
/*
STR_Linger linger;
linger.l_onoff = 1; // 1. allow wait; 0. force close
linger.l_linger = 1; // the time of waiting unit s
if (setsockopt(m_sockfd, SOL_GSocket, SO_LINGER, (const char*)&linger, sizeof(STR_Linger)) == -1)
{
ret = false;
}
*/
return ret;
}
}
<|endoftext|> |
<commit_before>/*
MEGA SDK POSIX filesystem/directory access/notification
(c) 2013 by Mega Limited, Wellsford, New Zealand
Author: mo
Applications using the MEGA API must present a valid application key
and comply with the the rules set forth in the Terms of Service.
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.
*/
// FIXME: add other directory change notification providers (currently supported: Linux inotify)
#define _POSIX_SOURCE
#define _LARGE_FILES
#define _LARGEFILE64_SOURCE
#define _GNU_SOURCE 1
#define _FILE_OFFSET_BITS 64
#define _DARWIN_C_SOURCE
#include <stdio.h>
#include <stdarg.h>
#include <fcntl.h>
#include <sys/un.h>
#include <termios.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <utime.h>
#ifndef USE_FDOPENDIR
#include <sys/dirent.h>
#endif
#include <curl/curl.h>
#include "megaclient.h"
#include "wait.h"
#include "fs.h"
#ifdef __MACH__
ssize_t pread(int, void *, size_t, off_t) __DARWIN_ALIAS_C(pread);
ssize_t pwrite(int, const void *, size_t, off_t) __DARWIN_ALIAS_C(pwrite);
#endif
PosixFileAccess::PosixFileAccess()
{
fd = -1;
#ifndef USE_FDOPENDIR
dp = NULL;
#endif
}
PosixFileAccess::~PosixFileAccess()
{
if (fd >= 0) close(fd);
}
bool PosixFileAccess::fread(string* dst, unsigned len, unsigned pad, m_off_t pos)
{
dst->resize(len+pad);
if (pread(fd,(char*)dst->data(),len,pos) == len)
{
memset((char*)dst->data()+len,0,pad);
return true;
}
return false;
}
bool PosixFileAccess::frawread(byte* dst, unsigned len, m_off_t pos)
{
return pread(fd,(char*)dst,len,pos) == len;
}
bool PosixFileAccess::fwrite(const byte* data, unsigned len, m_off_t pos)
{
return pwrite(fd,data,len,pos) == len;
}
bool PosixFileAccess::fopen(string* f, bool read, bool write)
{
#ifndef USE_FDOPENDIR
if (dp = opendir(f->c_str())) return true;
#endif
if ((fd = open(f->c_str(),write ? (read ? O_RDWR : O_WRONLY|O_CREAT|O_TRUNC) : O_RDONLY,0600)) >= 0)
{
struct stat statbuf;
if (!fstat(fd,&statbuf))
{
size = statbuf.st_size;
mtime = statbuf.st_mtime;
type = S_ISDIR(statbuf.st_mode) ? FOLDERNODE : FILENODE;
return true;
}
close(fd);
}
return false;
}
PosixFileSystemAccess::PosixFileSystemAccess()
{
localseparator = "/";
#ifdef USE_INOTIFY
notifyfd = inotify_init1(IN_NONBLOCK);
notifyerr = false;
notifyleft = 0;
#endif
}
PosixFileSystemAccess::~PosixFileSystemAccess()
{
#ifdef USE_INOTIFY
if (notifyfd >= 0) close(notifyfd);
#endif
}
// wake up from filesystem updates
void PosixFileSystemAccess::addevents(Waiter* w)
{
#ifdef USE_INOTIFY
PosixWaiter* pw = (PosixWaiter*)w;
FD_SET(notifyfd,&pw->rfds);
pw->bumpmaxfd(notifyfd);
#endif
}
// generate unique local filename in the same fs as relatedpath
void PosixFileSystemAccess::tmpnamelocal(string* filename, string* relatedpath)
{
*filename = tmpnam(NULL);
}
void PosixFileSystemAccess::path2local(string* local, string* path)
{
*path = *local;
}
void PosixFileSystemAccess::local2path(string* local, string* path)
{
*path = *local;
}
// use UTF-8 filenames directly, but escape forbidden characters
void PosixFileSystemAccess::name2local(string* filename, const char* badchars)
{
char buf[4];
if (!badchars) badchars = "\\/:?\"<>|*\1\2\3\4\5\6\7\10\11\12\13\14\15\16\17\20\21\22\23\24\25\26\27\30\31\32\33\34\35\36\37";
// replace all occurrences of a badchar with %xx
for (int i = filename->size(); i--; )
{
if ((unsigned char)(*filename)[i] < ' ' || strchr(badchars,(*filename)[i]))
{
sprintf(buf,"%%%02x",(unsigned char)(*filename)[i]);
filename->replace(i,1,buf);
}
}
}
// use UTF-8 filenames directly, but unescape escaped forbidden characters
// by replacing occurrences of %xx (x being a lowercase hex digit) with the encoded character
void PosixFileSystemAccess::local2name(string* filename)
{
char c;
for (int i = filename->size()-2; i-- > 0; )
{
if ((*filename)[i] == '%' && islchex((*filename)[i+1]) && islchex((*filename)[i+2]))
{
c = (MegaClient::hexval((*filename)[i+1])<<4)+MegaClient::hexval((*filename)[i+2]);
filename->replace(i,3,&c,1);
}
}
}
bool PosixFileSystemAccess::renamelocal(string* oldname, string* newname)
{
return !rename(oldname->c_str(),newname->c_str());
}
bool PosixFileSystemAccess::copylocal(string* oldname, string* newname)
{
int sfd, tfd;
ssize_t t = -1;
#ifdef USE_INOTIFY
#include <sys/sendfile.h>
// Linux-specific - kernel 2.6.33+ required
if ((sfd = open(oldname->c_str(),O_RDONLY|O_DIRECT)) >= 0)
{
if ((tfd = open(newname->c_str(),O_WRONLY|O_CREAT|O_TRUNC|O_DIRECT,0600)) >= 0)
{
while ((t = sendfile(tfd,sfd,NULL,1024*1024*1024)) > 0);
#else
char buf[16384];
if ((sfd = open(oldname->c_str(),O_RDONLY)) >= 0)
{
if ((tfd = open(newname->c_str(),O_WRONLY|O_CREAT|O_TRUNC,0600)) >= 0)
{
while (((t = read(sfd,buf,sizeof buf)) > 0) && write(tfd,buf,t) == t);
#endif
close(tfd);
}
close(sfd);
}
return !t;
}
// FIXME: move file or subtree to rubbish bin
bool PosixFileSystemAccess::rubbishlocal(string* name)
{
return !rmdir(name->c_str());
}
bool PosixFileSystemAccess::unlinklocal(string* name)
{
return !unlink(name->c_str());
}
// FIXME: *** must delete subtree recursively ***
bool PosixFileSystemAccess::rmdirlocal(string* name)
{
return !rmdir(name->c_str());
}
bool PosixFileSystemAccess::mkdirlocal(string* name)
{
return !mkdir(name->c_str(),0700);
}
bool PosixFileSystemAccess::setmtimelocal(string* name, time_t mtime)
{
struct utimbuf times = { mtime, mtime };
return !utime(name->c_str(),×);
}
bool PosixFileSystemAccess::chdirlocal(string* name)
{
return !chdir(name->c_str());
}
void PosixFileSystemAccess::addnotify(LocalNode* l, string* path)
{
#ifdef USE_INOTIFY
int wd;
wd = inotify_add_watch(notifyfd,path->c_str(),IN_CREATE|IN_DELETE|IN_MOVED_FROM|IN_MOVED_TO|IN_CLOSE_WRITE|IN_EXCL_UNLINK|IN_ONLYDIR);
if (wd >= 0)
{
l->notifyhandle = (void*)(long)wd;
wdnodes[wd] = l;
}
#endif
}
void PosixFileSystemAccess::delnotify(LocalNode* l)
{
#ifdef USE_INOTIFY
if (wdnodes.erase((int)(long)l->notifyhandle)) inotify_rm_watch(notifyfd,(int)(long)l->notifyhandle);
#endif
}
// return next notified local name and corresponding parent node
bool PosixFileSystemAccess::notifynext(sync_list*, string* localname, LocalNode** localnodep)
{
#ifdef USE_INOTIFY
inotify_event* in;
wdlocalnode_map::iterator it;
for (;;)
{
if (notifyleft <= 0)
{
if ((notifyleft = read(notifyfd,notifybuf,sizeof notifybuf)) <= 0) return false;
notifypos = 0;
}
in = (inotify_event*)(notifybuf+notifypos);
notifyleft += notifypos;
notifypos = in->name-notifybuf+in->len;
notifyleft -= notifypos;
if (in->mask & (IN_Q_OVERFLOW | IN_UNMOUNT)) break;
if (in->mask & (IN_CREATE|IN_DELETE|IN_MOVED_FROM|IN_MOVED_TO|IN_CLOSE_WRITE|IN_EXCL_UNLINK))
{
if ((in->mask & (IN_CREATE|IN_ISDIR)) != IN_CREATE)
{
it = wdnodes.find(in->wd);
if (it != wdnodes.end())
{
*localname = in->name;
*localnodep = it->second;
return true;
}
else cout << "Unknown wd handle" << endl;
}
else cout << "File creation ignored" << endl;
}
else cout << "Unknown mask: " << in->mask << endl;
}
cout << "Notify Overflow" << endl;
#endif
notifyerr = true;
return false;
}
// true if notifications were unreliable and/or a full rescan is required
bool PosixFileSystemAccess::notifyfailed()
{
return notifyerr ? (notifyerr = false) || true : false;
}
bool PosixFileSystemAccess::localhidden(string*, string* filename)
{
char c = *filename->c_str();
return c == '.' || c == '~';
}
FileAccess* PosixFileSystemAccess::newfileaccess()
{
return new PosixFileAccess();
}
DirAccess* PosixFileSystemAccess::newdiraccess()
{
return new PosixDirAccess();
}
bool PosixDirAccess::dopen(string* path, FileAccess* f, bool doglob)
{
if (doglob)
{
if (glob(path->c_str(),GLOB_NOSORT,NULL,&globbuf)) return false;
globbing = true;
globindex = 0;
return true;
}
if (f)
{
#ifdef USE_FDOPENDIR
dp = fdopendir(((PosixFileAccess*)f)->fd);
((PosixFileAccess*)f)->fd = -1;
#else
dp = ((PosixFileAccess*)f)->dp;
((PosixFileAccess*)f)->dp = NULL;
#endif
}
else dp = opendir(path->c_str());
return dp != NULL;
}
bool PosixDirAccess::dnext(string* name, nodetype* type)
{
if (globbing)
{
struct stat statbuf;
while (globindex < globbuf.gl_pathc)
{
if (!stat(globbuf.gl_pathv[globindex++],&statbuf))
{
if (statbuf.st_mode & (S_IFREG | S_IFDIR))
{
*name = globbuf.gl_pathv[globindex-1];
*type = (statbuf.st_mode & S_IFREG) ? FILENODE : FOLDERNODE;
return true;
}
}
}
return false;
}
dirent* d;
while ((d = readdir(dp)))
{
if ((d->d_type == DT_DIR || d->d_type == DT_REG) && (d->d_type != DT_DIR || *d->d_name != '.' || (d->d_name[1] && (d->d_name[1] != '.' || d->d_name[2]))))
{
*name = d->d_name;
if (type) *type = d->d_type == DT_DIR ? FOLDERNODE : FILENODE;
return true;
}
}
return false;
}
PosixDirAccess::PosixDirAccess()
{
dp = NULL;
globbing = false;
}
PosixDirAccess::~PosixDirAccess()
{
if (dp) closedir(dp);
if (globbing) globfree(&globbuf);
}
<commit_msg>Now works under BSD/Darwin<commit_after>/*
MEGA SDK POSIX filesystem/directory access/notification
(c) 2013 by Mega Limited, Wellsford, New Zealand
Author: mo
Applications using the MEGA API must present a valid application key
and comply with the the rules set forth in the Terms of Service.
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.
*/
// FIXME: add other directory change notification providers (currently supported: Linux inotify)
#ifdef __MACH__
#include <sys/dirent.h>
#endif
#define _POSIX_SOURCE
#define _LARGE_FILES
#define _LARGEFILE64_SOURCE
#define _GNU_SOURCE 1
#define _FILE_OFFSET_BITS 64
#include <stdio.h>
#include <stdarg.h>
#include <fcntl.h>
#include <sys/un.h>
#include <termios.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <utime.h>
#include <curl/curl.h>
#include "megaclient.h"
#include "wait.h"
#include "fs.h"
/*#ifdef __MACH__
#define _DARWIN_C_SOURCE
ssize_t pread(int, void *, size_t, off_t) __DARWIN_ALIAS_C(pread);
ssize_t pwrite(int, const void *, size_t, off_t) __DARWIN_ALIAS_C(pwrite);
#endif*/
PosixFileAccess::PosixFileAccess()
{
fd = -1;
#ifndef USE_FDOPENDIR
dp = NULL;
#endif
}
PosixFileAccess::~PosixFileAccess()
{
if (fd >= 0) close(fd);
}
bool PosixFileAccess::fread(string* dst, unsigned len, unsigned pad, m_off_t pos)
{
dst->resize(len+pad);
if (pread(fd,(char*)dst->data(),len,pos) == len)
{
memset((char*)dst->data()+len,0,pad);
return true;
}
return false;
}
bool PosixFileAccess::frawread(byte* dst, unsigned len, m_off_t pos)
{
return pread(fd,(char*)dst,len,pos) == len;
}
bool PosixFileAccess::fwrite(const byte* data, unsigned len, m_off_t pos)
{
return pwrite(fd,data,len,pos) == len;
}
bool PosixFileAccess::fopen(string* f, bool read, bool write)
{
#ifndef USE_FDOPENDIR
if ((dp = opendir(f->c_str())))
{
type = FOLDERNODE;
return true;
}
#endif
if ((fd = open(f->c_str(),write ? (read ? O_RDWR : O_WRONLY|O_CREAT|O_TRUNC) : O_RDONLY,0600)) >= 0)
{
struct stat statbuf;
if (!fstat(fd,&statbuf))
{
size = statbuf.st_size;
mtime = statbuf.st_mtime;
type = S_ISDIR(statbuf.st_mode) ? FOLDERNODE : FILENODE;
return true;
}
close(fd);
}
return false;
}
PosixFileSystemAccess::PosixFileSystemAccess()
{
localseparator = "/";
#ifdef USE_INOTIFY
notifyfd = inotify_init1(IN_NONBLOCK);
notifyerr = false;
notifyleft = 0;
#endif
}
PosixFileSystemAccess::~PosixFileSystemAccess()
{
#ifdef USE_INOTIFY
if (notifyfd >= 0) close(notifyfd);
#endif
}
// wake up from filesystem updates
void PosixFileSystemAccess::addevents(Waiter* w)
{
#ifdef USE_INOTIFY
PosixWaiter* pw = (PosixWaiter*)w;
FD_SET(notifyfd,&pw->rfds);
pw->bumpmaxfd(notifyfd);
#endif
}
// generate unique local filename in the same fs as relatedpath
void PosixFileSystemAccess::tmpnamelocal(string* filename, string* relatedpath)
{
*filename = tmpnam(NULL);
}
void PosixFileSystemAccess::path2local(string* local, string* path)
{
*path = *local;
}
void PosixFileSystemAccess::local2path(string* local, string* path)
{
*path = *local;
}
// use UTF-8 filenames directly, but escape forbidden characters
void PosixFileSystemAccess::name2local(string* filename, const char* badchars)
{
char buf[4];
if (!badchars) badchars = "\\/:?\"<>|*\1\2\3\4\5\6\7\10\11\12\13\14\15\16\17\20\21\22\23\24\25\26\27\30\31\32\33\34\35\36\37";
// replace all occurrences of a badchar with %xx
for (int i = filename->size(); i--; )
{
if ((unsigned char)(*filename)[i] < ' ' || strchr(badchars,(*filename)[i]))
{
sprintf(buf,"%%%02x",(unsigned char)(*filename)[i]);
filename->replace(i,1,buf);
}
}
}
// use UTF-8 filenames directly, but unescape escaped forbidden characters
// by replacing occurrences of %xx (x being a lowercase hex digit) with the encoded character
void PosixFileSystemAccess::local2name(string* filename)
{
char c;
for (int i = filename->size()-2; i-- > 0; )
{
if ((*filename)[i] == '%' && islchex((*filename)[i+1]) && islchex((*filename)[i+2]))
{
c = (MegaClient::hexval((*filename)[i+1])<<4)+MegaClient::hexval((*filename)[i+2]);
filename->replace(i,3,&c,1);
}
}
}
bool PosixFileSystemAccess::renamelocal(string* oldname, string* newname)
{
return !rename(oldname->c_str(),newname->c_str());
}
bool PosixFileSystemAccess::copylocal(string* oldname, string* newname)
{
int sfd, tfd;
ssize_t t = -1;
#ifdef USE_INOTIFY
#include <sys/sendfile.h>
// Linux-specific - kernel 2.6.33+ required
if ((sfd = open(oldname->c_str(),O_RDONLY|O_DIRECT)) >= 0)
{
if ((tfd = open(newname->c_str(),O_WRONLY|O_CREAT|O_TRUNC|O_DIRECT,0600)) >= 0)
{
while ((t = sendfile(tfd,sfd,NULL,1024*1024*1024)) > 0);
#else
char buf[16384];
if ((sfd = open(oldname->c_str(),O_RDONLY)) >= 0)
{
if ((tfd = open(newname->c_str(),O_WRONLY|O_CREAT|O_TRUNC,0600)) >= 0)
{
while (((t = read(sfd,buf,sizeof buf)) > 0) && write(tfd,buf,t) == t);
#endif
close(tfd);
}
close(sfd);
}
return !t;
}
// FIXME: move file or subtree to rubbish bin
bool PosixFileSystemAccess::rubbishlocal(string* name)
{
return !rmdir(name->c_str());
}
bool PosixFileSystemAccess::unlinklocal(string* name)
{
return !unlink(name->c_str());
}
// FIXME: *** must delete subtree recursively ***
bool PosixFileSystemAccess::rmdirlocal(string* name)
{
return !rmdir(name->c_str());
}
bool PosixFileSystemAccess::mkdirlocal(string* name)
{
return !mkdir(name->c_str(),0700);
}
bool PosixFileSystemAccess::setmtimelocal(string* name, time_t mtime)
{
struct utimbuf times = { mtime, mtime };
return !utime(name->c_str(),×);
}
bool PosixFileSystemAccess::chdirlocal(string* name)
{
return !chdir(name->c_str());
}
void PosixFileSystemAccess::addnotify(LocalNode* l, string* path)
{
#ifdef USE_INOTIFY
int wd;
wd = inotify_add_watch(notifyfd,path->c_str(),IN_CREATE|IN_DELETE|IN_MOVED_FROM|IN_MOVED_TO|IN_CLOSE_WRITE|IN_EXCL_UNLINK|IN_ONLYDIR);
if (wd >= 0)
{
l->notifyhandle = (void*)(long)wd;
wdnodes[wd] = l;
}
#endif
}
void PosixFileSystemAccess::delnotify(LocalNode* l)
{
#ifdef USE_INOTIFY
if (wdnodes.erase((int)(long)l->notifyhandle)) inotify_rm_watch(notifyfd,(int)(long)l->notifyhandle);
#endif
}
// return next notified local name and corresponding parent node
bool PosixFileSystemAccess::notifynext(sync_list*, string* localname, LocalNode** localnodep)
{
#ifdef USE_INOTIFY
inotify_event* in;
wdlocalnode_map::iterator it;
for (;;)
{
if (notifyleft <= 0)
{
if ((notifyleft = read(notifyfd,notifybuf,sizeof notifybuf)) <= 0) return false;
notifypos = 0;
}
in = (inotify_event*)(notifybuf+notifypos);
notifyleft += notifypos;
notifypos = in->name-notifybuf+in->len;
notifyleft -= notifypos;
if (in->mask & (IN_Q_OVERFLOW | IN_UNMOUNT)) break;
if (in->mask & (IN_CREATE|IN_DELETE|IN_MOVED_FROM|IN_MOVED_TO|IN_CLOSE_WRITE|IN_EXCL_UNLINK))
{
if ((in->mask & (IN_CREATE|IN_ISDIR)) != IN_CREATE)
{
it = wdnodes.find(in->wd);
if (it != wdnodes.end())
{
*localname = in->name;
*localnodep = it->second;
return true;
}
else cout << "Unknown wd handle" << endl;
}
else cout << "File creation ignored" << endl;
}
else cout << "Unknown mask: " << in->mask << endl;
}
cout << "Notify Overflow" << endl;
#endif
notifyerr = true;
return false;
}
// true if notifications were unreliable and/or a full rescan is required
bool PosixFileSystemAccess::notifyfailed()
{
return notifyerr ? (notifyerr = false) || true : false;
}
bool PosixFileSystemAccess::localhidden(string*, string* filename)
{
char c = *filename->c_str();
return c == '.' || c == '~';
}
FileAccess* PosixFileSystemAccess::newfileaccess()
{
return new PosixFileAccess();
}
DirAccess* PosixFileSystemAccess::newdiraccess()
{
return new PosixDirAccess();
}
bool PosixDirAccess::dopen(string* path, FileAccess* f, bool doglob)
{
if (doglob)
{
if (glob(path->c_str(),GLOB_NOSORT,NULL,&globbuf)) return false;
globbing = true;
globindex = 0;
return true;
}
if (f)
{
#ifdef USE_FDOPENDIR
dp = fdopendir(((PosixFileAccess*)f)->fd);
((PosixFileAccess*)f)->fd = -1;
#else
dp = ((PosixFileAccess*)f)->dp;
((PosixFileAccess*)f)->dp = NULL;
#endif
}
else dp = opendir(path->c_str());
return dp != NULL;
}
bool PosixDirAccess::dnext(string* name, nodetype* type)
{
if (globbing)
{
struct stat statbuf;
while (globindex < globbuf.gl_pathc)
{
if (!stat(globbuf.gl_pathv[globindex++],&statbuf))
{
if (statbuf.st_mode & (S_IFREG | S_IFDIR))
{
*name = globbuf.gl_pathv[globindex-1];
*type = (statbuf.st_mode & S_IFREG) ? FILENODE : FOLDERNODE;
return true;
}
}
}
return false;
}
dirent* d;
while ((d = readdir(dp)))
{
if ((d->d_type == DT_DIR || d->d_type == DT_REG) && (d->d_type != DT_DIR || *d->d_name != '.' || (d->d_name[1] && (d->d_name[1] != '.' || d->d_name[2]))))
{
*name = d->d_name;
if (type) *type = d->d_type == DT_DIR ? FOLDERNODE : FILENODE;
return true;
}
}
return false;
}
PosixDirAccess::PosixDirAccess()
{
dp = NULL;
globbing = false;
}
PosixDirAccess::~PosixDirAccess()
{
if (dp) closedir(dp);
if (globbing) globfree(&globbuf);
}
<|endoftext|> |
<commit_before>#ifndef PQXX_H_CALLGATE
#define PQXX_H_CALLGATE
namespace pqxx
{
namespace internal
{
template<typename HOME> class PQXX_PRIVATE callgate
{
protected:
typedef callgate<HOME> super;
typedef HOME &reference;
callgate(reference x) : m_home(x) {}
const reference home() const throw () { return m_home; }
reference home() throw () { return m_home; }
private:
reference m_home;
};
} // namespace pqxx::internal
} // namespace pqxx
#endif
<commit_msg>Documentation for callgate.<commit_after>#ifndef PQXX_H_CALLGATE
#define PQXX_H_CALLGATE
namespace pqxx
{
namespace internal
{
/// Base class for call gates.
/**
* A call gate defines a limited, private interface on the host class that
* specified client classes can access.
*
* The metaphor works as follows: the gate stands in front of a "home," which is
* really a class, and only lets specific friends in.
*
* To implement a call gate that gives client C access to host H,
* - derive a gate class from callgate<H>;
* - make the gate class a friend of H;
* - make C a friend of the gate class; and
* - implement "stuff C can do with H" inside the gate class.
*
* This special kind of "gated" friendship gives C private access to H, but only
* through an expressly limited interface.
*/
template<typename HOME> class PQXX_PRIVATE callgate
{
protected:
/// This class, to keep constructors easy.
typedef callgate<HOME> super;
/// A reference to the host class. Helps keep constructors easy.
typedef HOME &reference;
callgate(reference x) : m_home(x) {}
/// The home object. The gate class has full "private" access.
const reference home() const throw () { return m_home; }
/// The home object. The gate class has full "private" access.
reference home() throw () { return m_home; }
private:
reference m_home;
};
} // namespace pqxx::internal
} // namespace pqxx
#endif
<|endoftext|> |
<commit_before>#include "blas.hpp"
#include "lapack_wrap.hpp"
#include "linalg.hpp"
#include "mkl.h"
#include "strassen.hpp"
#include "timing.hpp"
#include <stdexcept>
#include <vector>
template <typename Scalar>
void QR(Matrix<Scalar>& A, std::vector<Scalar>& tau, int pos=0) {
int m = A.m();
int n = A.n();
int lda = A.stride();
Scalar *A_data = A.data();
Scalar *curr_tau = &tau[pos];
lapack::Geqrf(m, n, A_data, lda, curr_tau);
}
template <typename Scalar>
Matrix<Scalar> TriangFactor(Matrix<Scalar>& A, std::vector<Scalar>& tau,
int pos) {
char direct = 'F'; // Forward direction of householder reflectors.
char storev = 'C'; // Columns of V are stored columnwise.
Scalar *A_data = A.data();
int M = A.m();
int N = A.n();
int lda = A.stride();
Scalar *curr_tau = &tau[pos];
// Triangular matrix for storing data.
int ldt = N;
Matrix<Scalar> T(ldt, N);
Scalar *T_data = T.data();
lapack::Larft(direct, storev, M, N, A_data, lda, curr_tau, T_data, ldt);
return T;
}
// B <- T * B
template <typename Scalar>
void TriangMatmul(char side, char uplo, char transt, char diag,
Scalar alpha, Matrix<Scalar>& T, Matrix<Scalar>& B) {
int m = B.m();
int n = B.n();
Scalar *T_data = T.data();
int ldt = T.stride();
Scalar *B_data = B.data();
int ldb = B.stride();
lapack::Trmm(side, uplo, transt, diag, m, n, alpha, T_data, ldt, B_data, ldb);
}
template <typename Scalar>
void UpdateTrailing(Matrix<Scalar>& V, Matrix<Scalar>& T, Matrix<Scalar>& A2) {
// W := V^T
Matrix<Scalar> Vt = TransposedCopy(V);
// W := Vt * A2
Matrix<Scalar> W(Vt.m(), A2.n());
int num_steps = 1;
strassen::FastMatmul(Vt, A2, W, num_steps);
// W := T^T * W
TriangMatmul('L', 'U', 'T', 'N', Scalar(1.0), T, W);
// A2 := A2 - VW
//strassen::FastMatmul(V, W, A2, num_steps, 0.0, -1.0, 1.0);
}
template<typename Scalar>
void FastQR(Matrix<Scalar>& A, std::vector<Scalar>& tau, int blocksize) {
if (A.m() < A.n()) {
throw std::logic_error("Only supporting m >= n for now.");
}
tau.resize(A.n());
int i;
for (i = 0; i + blocksize <= std::min(A.m(), A.n()); i += blocksize) {
// Split A as A = (A1 A2) and compute QR on A1.
Matrix<Scalar> A1 = A.Submatrix(i, i, A.m() - i, blocksize);
Matrix<Scalar> A2 = A.Submatrix(i, i + blocksize, A.m() - i, A.n() - i - blocksize);
QR(A1, tau, i);
if (i + blocksize < A.m()) {
// Form the triangular factor of the reflectors
Matrix<Scalar> T = TriangFactor(A1, tau, i);
// A2 := (I - VT'V')A2
UpdateTrailing(A1, T, A2);
}
}
// Now deal with any leftovers
if (i != std::min(A.m(), A.n())) {
Matrix<Scalar> A_end = A.Submatrix(i, i, A.m() - i, A.n() - i);
QR(A_end, tau, i);
}
}
<commit_msg>Fast QR needs a re-working.<commit_after>#include "blas.hpp"
#include "lapack_wrap.hpp"
#include "linalg.hpp"
#include "mkl.h"
#include "strassen.hpp"
#include "timing.hpp"
#include <stdexcept>
#include <vector>
template <typename Scalar>
void QR(Matrix<Scalar>& A, std::vector<Scalar>& tau, int pos=0) {
int m = A.m();
int n = A.n();
int lda = A.stride();
Scalar *A_data = A.data();
Scalar *curr_tau = &tau[pos];
lapack::Geqrf(m, n, A_data, lda, curr_tau);
}
template <typename Scalar>
Matrix<Scalar> TriangFactor(Matrix<Scalar>& A, std::vector<Scalar>& tau,
int pos) {
char direct = 'F'; // Forward direction of householder reflectors.
char storev = 'C'; // Columns of V are stored columnwise.
Scalar *A_data = A.data();
int M = A.m();
int N = A.n();
int lda = A.stride();
Scalar *curr_tau = &tau[pos];
// Triangular matrix for storing data.
int ldt = N;
Matrix<Scalar> T(ldt, N);
Scalar *T_data = T.data();
lapack::Larft(direct, storev, M, N, A_data, lda, curr_tau, T_data, ldt);
return T;
}
// B <- T * B
template <typename Scalar>
void TriangMatmul(char side, char uplo, char transt, char diag,
Scalar alpha, Matrix<Scalar>& T, Matrix<Scalar>& B) {
int m = B.m();
int n = B.n();
Scalar *T_data = T.data();
int ldt = T.stride();
Scalar *B_data = B.data();
int ldb = B.stride();
lapack::Trmm(side, uplo, transt, diag, m, n, alpha, T_data, ldt, B_data, ldb);
}
template <typename Scalar>
void UpdateTrailing(Matrix<Scalar>& V, Matrix<Scalar>& T, Matrix<Scalar>& A2) {
Matrix<Scalar> Vt = TransposedCopy(V);
// W := Vt * A2
Matrix<Scalar> W(Vt.m(), A2.n());
int num_steps = 1;
strassen::FastMatmul(Vt, A2, W, num_steps);
// W := T^T * W
TriangMatmul('L', 'U', 'T', 'N', Scalar(1.0), T, W);
// A2 := A2 - VW
strassen::FastMatmul(V, W, A2, num_steps, 0.0, -1.0, 1.0);
}
template<typename Scalar>
void FastQR(Matrix<Scalar>& A, std::vector<Scalar>& tau, int blocksize) {
if (A.m() < A.n()) {
throw std::logic_error("Only supporting m >= n for now.");
}
tau.resize(A.n());
int i;
for (i = 0; i + blocksize <= std::min(A.m(), A.n()); i += blocksize) {
// Split A as A = (A1 A2) and compute QR on A1.
Matrix<Scalar> A1 = A.Submatrix(i, i, A.m() - i, blocksize);
Matrix<Scalar> A2 = A.Submatrix(i, i + blocksize, A.m() - i, A.n() - i - blocksize);
QR(A1, tau, i);
if (i + blocksize < A.m()) {
// Form the triangular factor of the reflectors
Matrix<Scalar> T = TriangFactor(A1, tau, i);
// A2 := (I - VT'V')A2
UpdateTrailing(A1, T, A2);
}
}
// Now deal with any leftovers
if (i != std::min(A.m(), A.n())) {
Matrix<Scalar> A_end = A.Submatrix(i, i, A.m() - i, A.n() - i);
QR(A_end, tau, i);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_MEMORY_INPUT_HPP
#define TAO_PEGTL_MEMORY_INPUT_HPP
#include <cstddef>
#include <cstring>
#include <string>
#include <type_traits>
#include <utility>
#include "config.hpp"
#include "eol.hpp"
#include "position.hpp"
#include "tracking_mode.hpp"
#include "internal/action_input.hpp"
#include "internal/bump_impl.hpp"
#include "internal/iterator.hpp"
#include "internal/marker.hpp"
namespace tao
{
namespace TAO_PEGTL_NAMESPACE
{
namespace internal
{
template< tracking_mode, typename Eol, typename Source >
class memory_input_base;
template< typename Eol, typename Source >
class memory_input_base< tracking_mode::IMMEDIATE, Eol, Source >
{
public:
using iterator_t = internal::iterator;
template< typename T >
memory_input_base( const iterator_t& in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: m_current( in_begin ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{
}
template< typename T >
memory_input_base( const char* in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: m_current( in_begin ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{
}
memory_input_base( const memory_input_base& ) = delete;
memory_input_base( memory_input_base&& ) = delete;
~memory_input_base() = default;
memory_input_base operator=( const memory_input_base& ) = delete;
memory_input_base operator=( memory_input_base&& ) = delete;
const char* current() const noexcept
{
return m_current.data;
}
const char* end( const std::size_t /*unused*/ = 0 ) const noexcept
{
return m_end;
}
std::size_t byte() const noexcept
{
return m_current.byte;
}
std::size_t line() const noexcept
{
return m_current.line;
}
std::size_t byte_in_line() const noexcept
{
return m_current.byte_in_line;
}
void bump( const std::size_t in_count = 1 ) noexcept
{
internal::bump( m_current, in_count, Eol::ch );
}
void bump_in_this_line( const std::size_t in_count = 1 ) noexcept
{
internal::bump_in_this_line( m_current, in_count );
}
void bump_to_next_line( const std::size_t in_count = 1 ) noexcept
{
internal::bump_to_next_line( m_current, in_count );
}
TAO_PEGTL_NAMESPACE::position position( const iterator_t& it ) const
{
return TAO_PEGTL_NAMESPACE::position( it, m_source );
}
protected:
iterator_t m_current;
const char* const m_end;
const Source m_source;
};
template< typename Eol, typename Source >
class memory_input_base< tracking_mode::LAZY, Eol, Source >
{
public:
using iterator_t = const char*;
template< typename T >
memory_input_base( const internal::iterator& in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: m_begin( in_begin ),
m_current( in_begin.data ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{
}
template< typename T >
memory_input_base( const char* in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: m_begin( in_begin ),
m_current( in_begin ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{
}
memory_input_base( const memory_input_base& ) = delete;
memory_input_base( memory_input_base&& ) = delete;
~memory_input_base() = default;
memory_input_base operator=( const memory_input_base& ) = delete;
memory_input_base operator=( memory_input_base&& ) = delete;
const char* current() const noexcept
{
return m_current;
}
const char* end( const std::size_t /*unused*/ = 0 ) const noexcept
{
return m_end;
}
std::size_t byte() const noexcept
{
return std::size_t( current() - m_begin.data );
}
void bump( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
void bump_in_this_line( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
void bump_to_next_line( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
TAO_PEGTL_NAMESPACE::position position( const iterator_t it ) const
{
internal::iterator c( m_begin );
internal::bump( c, std::size_t( it - m_begin.data ), Eol::ch );
return TAO_PEGTL_NAMESPACE::position( c, m_source );
}
protected:
const internal::iterator m_begin;
iterator_t m_current;
const char* const m_end;
const Source m_source;
};
} // namespace internal
template< tracking_mode P = tracking_mode::IMMEDIATE, typename Eol = eol::lf_crlf, typename Source = std::string >
class memory_input
: public internal::memory_input_base< P, Eol, Source >
{
public:
static constexpr tracking_mode tracking_mode_v = P;
using eol_t = Eol;
using source_t = Source;
using typename internal::memory_input_base< P, Eol, Source >::iterator_t;
using action_t = internal::action_input< memory_input >;
using internal::memory_input_base< P, Eol, Source >::memory_input_base;
template< typename T >
memory_input( const char* in_begin, const std::size_t in_size, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: memory_input( in_begin, in_begin + in_size, std::forward< T >( in_source ) )
{
}
template< typename T >
memory_input( const std::string& in_string, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: memory_input( in_string.data(), in_string.size(), std::forward< T >( in_source ) )
{
}
template< typename T >
memory_input( const char* in_begin, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: memory_input( in_begin, std::strlen( in_begin ), std::forward< T >( in_source ) )
{
}
template< typename T >
memory_input( const char* in_begin, const char* in_end, T&& in_source, const std::size_t in_byte, const std::size_t in_line, const std::size_t in_byte_in_line ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: memory_input( { in_begin, in_byte, in_line, in_byte_in_line }, in_end, std::forward< T >( in_source ) )
{
}
memory_input( const memory_input& ) = delete;
memory_input( memory_input&& ) = delete;
~memory_input() = default;
memory_input operator=( const memory_input& ) = delete;
memory_input operator=( memory_input&& ) = delete;
const Source& source() const noexcept
{
return this->m_source;
}
bool empty() const noexcept
{
return this->current() == this->end();
}
std::size_t size( const std::size_t /*unused*/ = 0 ) const noexcept
{
return std::size_t( this->end() - this->current() );
}
char peek_char( const std::size_t offset = 0 ) const noexcept
{
return this->current()[ offset ];
}
unsigned char peek_byte( const std::size_t offset = 0 ) const noexcept
{
return static_cast< unsigned char >( peek_char( offset ) );
}
iterator_t& iterator() noexcept
{
return this->m_current;
}
const iterator_t& iterator() const noexcept
{
return this->m_current;
}
using internal::memory_input_base< P, Eol, Source >::position;
TAO_PEGTL_NAMESPACE::position position() const
{
return position( iterator() );
}
void discard() const noexcept
{
}
void require( const std::size_t /*unused*/ ) const noexcept
{
}
template< rewind_mode M >
internal::marker< iterator_t, M > mark() noexcept
{
return internal::marker< iterator_t, M >( iterator() );
}
};
} // namespace TAO_PEGTL_NAMESPACE
} // namespace tao
#endif
<commit_msg>Prevent creating a memory_input from a temporary std::string<commit_after>// Copyright (c) 2014-2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_MEMORY_INPUT_HPP
#define TAO_PEGTL_MEMORY_INPUT_HPP
#include <cstddef>
#include <cstring>
#include <string>
#include <type_traits>
#include <utility>
#include "config.hpp"
#include "eol.hpp"
#include "position.hpp"
#include "tracking_mode.hpp"
#include "internal/action_input.hpp"
#include "internal/bump_impl.hpp"
#include "internal/iterator.hpp"
#include "internal/marker.hpp"
namespace tao
{
namespace TAO_PEGTL_NAMESPACE
{
namespace internal
{
template< tracking_mode, typename Eol, typename Source >
class memory_input_base;
template< typename Eol, typename Source >
class memory_input_base< tracking_mode::IMMEDIATE, Eol, Source >
{
public:
using iterator_t = internal::iterator;
template< typename T >
memory_input_base( const iterator_t& in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: m_current( in_begin ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{
}
template< typename T >
memory_input_base( const char* in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: m_current( in_begin ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{
}
memory_input_base( const memory_input_base& ) = delete;
memory_input_base( memory_input_base&& ) = delete;
~memory_input_base() = default;
memory_input_base operator=( const memory_input_base& ) = delete;
memory_input_base operator=( memory_input_base&& ) = delete;
const char* current() const noexcept
{
return m_current.data;
}
const char* end( const std::size_t /*unused*/ = 0 ) const noexcept
{
return m_end;
}
std::size_t byte() const noexcept
{
return m_current.byte;
}
std::size_t line() const noexcept
{
return m_current.line;
}
std::size_t byte_in_line() const noexcept
{
return m_current.byte_in_line;
}
void bump( const std::size_t in_count = 1 ) noexcept
{
internal::bump( m_current, in_count, Eol::ch );
}
void bump_in_this_line( const std::size_t in_count = 1 ) noexcept
{
internal::bump_in_this_line( m_current, in_count );
}
void bump_to_next_line( const std::size_t in_count = 1 ) noexcept
{
internal::bump_to_next_line( m_current, in_count );
}
TAO_PEGTL_NAMESPACE::position position( const iterator_t& it ) const
{
return TAO_PEGTL_NAMESPACE::position( it, m_source );
}
protected:
iterator_t m_current;
const char* const m_end;
const Source m_source;
};
template< typename Eol, typename Source >
class memory_input_base< tracking_mode::LAZY, Eol, Source >
{
public:
using iterator_t = const char*;
template< typename T >
memory_input_base( const internal::iterator& in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: m_begin( in_begin ),
m_current( in_begin.data ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{
}
template< typename T >
memory_input_base( const char* in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: m_begin( in_begin ),
m_current( in_begin ),
m_end( in_end ),
m_source( std::forward< T >( in_source ) )
{
}
memory_input_base( const memory_input_base& ) = delete;
memory_input_base( memory_input_base&& ) = delete;
~memory_input_base() = default;
memory_input_base operator=( const memory_input_base& ) = delete;
memory_input_base operator=( memory_input_base&& ) = delete;
const char* current() const noexcept
{
return m_current;
}
const char* end( const std::size_t /*unused*/ = 0 ) const noexcept
{
return m_end;
}
std::size_t byte() const noexcept
{
return std::size_t( current() - m_begin.data );
}
void bump( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
void bump_in_this_line( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
void bump_to_next_line( const std::size_t in_count = 1 ) noexcept
{
m_current += in_count;
}
TAO_PEGTL_NAMESPACE::position position( const iterator_t it ) const
{
internal::iterator c( m_begin );
internal::bump( c, std::size_t( it - m_begin.data ), Eol::ch );
return TAO_PEGTL_NAMESPACE::position( c, m_source );
}
protected:
const internal::iterator m_begin;
iterator_t m_current;
const char* const m_end;
const Source m_source;
};
} // namespace internal
template< tracking_mode P = tracking_mode::IMMEDIATE, typename Eol = eol::lf_crlf, typename Source = std::string >
class memory_input
: public internal::memory_input_base< P, Eol, Source >
{
public:
static constexpr tracking_mode tracking_mode_v = P;
using eol_t = Eol;
using source_t = Source;
using typename internal::memory_input_base< P, Eol, Source >::iterator_t;
using action_t = internal::action_input< memory_input >;
using internal::memory_input_base< P, Eol, Source >::memory_input_base;
template< typename T >
memory_input( const char* in_begin, const std::size_t in_size, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: memory_input( in_begin, in_begin + in_size, std::forward< T >( in_source ) )
{
}
template< typename T >
memory_input( const std::string& in_string, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: memory_input( in_string.data(), in_string.size(), std::forward< T >( in_source ) )
{
}
template< typename T >
memory_input( std::string&&, T&& ) = delete;
template< typename T >
memory_input( const char* in_begin, T&& in_source ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: memory_input( in_begin, std::strlen( in_begin ), std::forward< T >( in_source ) )
{
}
template< typename T >
memory_input( const char* in_begin, const char* in_end, T&& in_source, const std::size_t in_byte, const std::size_t in_line, const std::size_t in_byte_in_line ) noexcept( std::is_nothrow_constructible< Source, T&& >::value )
: memory_input( { in_begin, in_byte, in_line, in_byte_in_line }, in_end, std::forward< T >( in_source ) )
{
}
memory_input( const memory_input& ) = delete;
memory_input( memory_input&& ) = delete;
~memory_input() = default;
memory_input operator=( const memory_input& ) = delete;
memory_input operator=( memory_input&& ) = delete;
const Source& source() const noexcept
{
return this->m_source;
}
bool empty() const noexcept
{
return this->current() == this->end();
}
std::size_t size( const std::size_t /*unused*/ = 0 ) const noexcept
{
return std::size_t( this->end() - this->current() );
}
char peek_char( const std::size_t offset = 0 ) const noexcept
{
return this->current()[ offset ];
}
unsigned char peek_byte( const std::size_t offset = 0 ) const noexcept
{
return static_cast< unsigned char >( peek_char( offset ) );
}
iterator_t& iterator() noexcept
{
return this->m_current;
}
const iterator_t& iterator() const noexcept
{
return this->m_current;
}
using internal::memory_input_base< P, Eol, Source >::position;
TAO_PEGTL_NAMESPACE::position position() const
{
return position( iterator() );
}
void discard() const noexcept
{
}
void require( const std::size_t /*unused*/ ) const noexcept
{
}
template< rewind_mode M >
internal::marker< iterator_t, M > mark() noexcept
{
return internal::marker< iterator_t, M >( iterator() );
}
};
} // namespace TAO_PEGTL_NAMESPACE
} // namespace tao
#endif
<|endoftext|> |
<commit_before>#include <sys/types.h>
#include <sys/errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <unistd.h>
#include <map>
#include <vector>
#include <common/buffer.h>
#include <common/endian.h>
#include <common/limits.h>
#include <common/timer/timer.h>
#include <xcodec/xcodec.h>
#include <xcodec/xcodec_cache.h>
#include <xcodec/xcodec_decoder.h>
#include <xcodec/xcodec_encoder.h>
enum FileAction {
None, Compress, Decompress
};
static void compress(int, int, XCodec *, bool, Timer *);
static void decompress(int, int, XCodec *, bool, Timer *);
static bool fill(int, Buffer *);
static void flush(int, Buffer *);
static void process_file(int, int, FileAction, XCodec *, bool, Timer *);
static void process_files(int, char *[], FileAction, XCodec *, bool, bool, Timer *);
static void time_samples(Timer *);
static void time_stats(Timer *);
static void usage(void);
int
main(int argc, char *argv[])
{
UUID uuid;
uuid.generate();
XCodecCache *cache = XCodecCache::lookup(uuid);
XCodec codec(cache);
bool codec_timing, quiet_output, samples, verbose;
FileAction action;
int ch;
action = None;
codec_timing = false;
quiet_output = false;
samples = false;
verbose = false;
while ((ch = getopt(argc, argv, "?cdvQST")) != -1) {
switch (ch) {
case 'c':
action = Compress;
break;
case 'd':
action = Decompress;
break;
case 'v':
verbose = true;
break;
case 'Q':
quiet_output = true;
break;
case 'S':
samples = true;
break;
case 'T':
codec_timing = true;
break;
case '?':
default:
usage();
}
}
argc -= optind;
argv += optind;
if (verbose) {
Log::mask(".?", Log::Debug);
} else {
Log::mask(".?", Log::Info);
}
Timer codec_timer;
switch (action) {
case None:
usage();
case Compress:
case Decompress:
process_files(argc, argv, action, &codec, quiet_output, codec_timing, &codec_timer);
if (samples)
time_samples(&codec_timer);
if (codec_timing)
time_stats(&codec_timer);
break;
default:
NOTREACHED();
}
return (0);
}
static void
compress(int ifd, int ofd, XCodec *codec, bool timing, Timer *timer)
{
XCodecEncoder encoder(codec->cache());
Buffer input, output;
while (fill(ifd, &input)) {
if (timing)
timer->start();
encoder.encode(&output, &input);
if (timing)
timer->stop();
flush(ofd, &output);
}
ASSERT(input.empty());
ASSERT(output.empty());
}
static void
decompress(int ifd, int ofd, XCodec *codec, bool timing, Timer *timer)
{
std::set<uint64_t> unknown_hashes;
XCodecDecoder decoder(codec->cache());
Buffer input, output;
(void)codec;
while (fill(ifd, &input)) {
if (timing)
timer->start();
if (!decoder.decode(&output, &input, unknown_hashes)) {
ERROR("/decompress") << "Decode failed.";
return;
}
if (timing)
timer->stop();
if (!unknown_hashes.empty()) {
ERROR("/decompress") << "Cannot decode stream with unknown hashes.";
return;
}
flush(ofd, &output);
}
ASSERT(input.empty());
ASSERT(output.empty());
}
static bool
fill(int fd, Buffer *input)
{
uint8_t data[65536];
ssize_t len;
len = read(fd, data, sizeof data);
if (len == -1)
HALT("/fill") << "read failed.";
if (len == 0)
return (false);
input->append(data, len);
return (true);
}
static void
flush(int fd, Buffer *output)
{
ssize_t len;
if (fd == -1) {
output->clear();
return;
}
for (;;) {
Buffer::SegmentIterator iter = output->segments();
if (iter.end())
break;
const BufferSegment *seg = *iter;
len = write(fd, seg->data(), seg->length());
if (len != (ssize_t)seg->length())
HALT("/output") << "write failed.";
output->skip((size_t)len);
}
ASSERT(output->empty());
}
static void
process_file(int ifd, int ofd, FileAction action, XCodec *codec, bool timing, Timer *timer)
{
switch (action) {
case Compress:
compress(ifd, ofd, codec, timing, timer);
break;
case Decompress:
decompress(ifd, ofd, codec, timing, timer);
break;
default:
NOTREACHED();
}
}
static void
process_files(int argc, char *argv[], FileAction action, XCodec *codec, bool quiet, bool timing, Timer *timer)
{
int ifd, ofd;
if (argc == 0) {
ifd = STDIN_FILENO;
if (quiet)
ofd = -1;
else
ofd = STDOUT_FILENO;
process_file(ifd, ofd, action, codec, timing, timer);
} else {
while (argc--) {
const char *file = *argv++;
ifd = open(file, O_RDONLY);
ASSERT(ifd != -1);
if (quiet)
ofd = -1;
else
ofd = STDOUT_FILENO;
process_file(ifd, ofd, action, codec, timing, timer);
}
}
}
static void
time_samples(Timer *timer)
{
std::vector<uintmax_t> samples = timer->samples();
std::vector<uintmax_t>::iterator it;
for (it = samples.begin(); it != samples.end(); ++it)
fprintf(stderr, "%ju\n", *it);
}
static void
time_stats(Timer *timer)
{
std::vector<uintmax_t> samples = timer->samples();
std::vector<uintmax_t>::iterator it;
LogHandle log("/codec_timer");
uintmax_t microseconds;
INFO(log) << samples.size() << " timer samples.";
microseconds = 0;
for (it = samples.begin(); it != samples.end(); ++it)
microseconds += *it;
INFO(log) << microseconds << " total runtime.";
INFO(log) << (microseconds / samples.size()) << " mean microseconds/call.";
}
static void
usage(void)
{
fprintf(stderr,
"usage: tack [-vQST] -c [file ...]\n"
" tack [-vQST] -d [file ...]\n");
exit(1);
}
<commit_msg>Add stats.<commit_after>#include <sys/types.h>
#include <sys/errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <unistd.h>
#include <map>
#include <vector>
#include <common/buffer.h>
#include <common/endian.h>
#include <common/limits.h>
#include <common/timer/timer.h>
#include <xcodec/xcodec.h>
#include <xcodec/xcodec_cache.h>
#include <xcodec/xcodec_decoder.h>
#include <xcodec/xcodec_encoder.h>
enum FileAction {
None, Compress, Decompress
};
static void compress(const std::string&, int, int, XCodec *, bool, Timer *, bool);
static void decompress(const std::string&, int, int, XCodec *, bool, Timer *, bool);
static bool fill(int, Buffer *);
static void flush(int, Buffer *);
static void print_ratio(const std::string&, uint64_t, uint64_t);
static void process_file(const std::string&, int, int, FileAction, XCodec *, bool, Timer *, bool);
static void process_files(int, char *[], FileAction, XCodec *, bool, bool, Timer *, bool);
static void time_samples(Timer *);
static void time_stats(Timer *);
static void usage(void);
int
main(int argc, char *argv[])
{
UUID uuid;
uuid.generate();
XCodecCache *cache = XCodecCache::lookup(uuid);
XCodec codec(cache);
bool codec_timing, quiet_output, samples, stats, verbose;
FileAction action;
int ch;
action = None;
codec_timing = false;
quiet_output = false;
samples = false;
stats = false;
verbose = false;
while ((ch = getopt(argc, argv, "?cdsvQST")) != -1) {
switch (ch) {
case 'c':
action = Compress;
break;
case 'd':
action = Decompress;
break;
case 's':
stats = true;
break;
case 'v':
verbose = true;
break;
case 'Q':
quiet_output = true;
break;
case 'S':
samples = true;
break;
case 'T':
codec_timing = true;
break;
case '?':
default:
usage();
}
}
argc -= optind;
argv += optind;
if (verbose) {
Log::mask(".?", Log::Debug);
} else {
Log::mask(".?", Log::Info);
}
Timer codec_timer;
switch (action) {
case None:
usage();
case Compress:
case Decompress:
process_files(argc, argv, action, &codec, quiet_output, codec_timing, &codec_timer, stats);
if (samples)
time_samples(&codec_timer);
if (codec_timing)
time_stats(&codec_timer);
break;
default:
NOTREACHED();
}
return (0);
}
static void
compress(const std::string& name, int ifd, int ofd, XCodec *codec, bool timing, Timer *timer, bool stats)
{
XCodecEncoder encoder(codec->cache());
Buffer input, output;
uint64_t inbytes, outbytes;
if (stats)
inbytes = outbytes = 0;
while (fill(ifd, &input)) {
if (stats)
inbytes += input.length();
if (timing)
timer->start();
encoder.encode(&output, &input);
if (timing)
timer->stop();
if (stats) {
inbytes -= input.length();
outbytes += output.length();
}
flush(ofd, &output);
}
ASSERT(input.empty());
ASSERT(output.empty());
if (stats)
print_ratio(name, inbytes, outbytes);
}
static void
decompress(const std::string& name, int ifd, int ofd, XCodec *codec, bool timing, Timer *timer, bool stats)
{
std::set<uint64_t> unknown_hashes;
XCodecDecoder decoder(codec->cache());
Buffer input, output;
uint64_t inbytes, outbytes;
(void)codec;
if (stats)
inbytes = outbytes = 0;
while (fill(ifd, &input)) {
if (stats)
inbytes += input.length();
if (timing)
timer->start();
if (!decoder.decode(&output, &input, unknown_hashes)) {
ERROR("/decompress") << "Decode failed.";
return;
}
if (timing)
timer->stop();
if (!unknown_hashes.empty()) {
ERROR("/decompress") << "Cannot decode stream with unknown hashes.";
return;
}
if (stats) {
inbytes -= input.length();
outbytes += output.length();
}
flush(ofd, &output);
}
ASSERT(input.empty());
ASSERT(output.empty());
if (stats)
print_ratio(name, inbytes, outbytes);
}
static bool
fill(int fd, Buffer *input)
{
uint8_t data[65536];
ssize_t len;
len = read(fd, data, sizeof data);
if (len == -1)
HALT("/fill") << "read failed.";
if (len == 0)
return (false);
input->append(data, len);
return (true);
}
static void
flush(int fd, Buffer *output)
{
ssize_t len;
if (fd == -1) {
output->clear();
return;
}
for (;;) {
Buffer::SegmentIterator iter = output->segments();
if (iter.end())
break;
const BufferSegment *seg = *iter;
len = write(fd, seg->data(), seg->length());
if (len != (ssize_t)seg->length())
HALT("/output") << "write failed.";
output->skip((size_t)len);
}
ASSERT(output->empty());
}
static void
print_ratio(const std::string& name, uint64_t inbytes, uint64_t outbytes)
{
INFO("/codec_stats") << name << ": " << inbytes << " bytes in, " << outbytes << " bytes out.";
}
static void
process_file(const std::string& name, int ifd, int ofd, FileAction action, XCodec *codec, bool timing, Timer *timer, bool stats)
{
switch (action) {
case Compress:
compress(name, ifd, ofd, codec, timing, timer, stats);
break;
case Decompress:
decompress(name, ifd, ofd, codec, timing, timer, stats);
break;
default:
NOTREACHED();
}
}
static void
process_files(int argc, char *argv[], FileAction action, XCodec *codec, bool quiet, bool timing, Timer *timer, bool stats)
{
int ifd, ofd;
if (argc == 0) {
ifd = STDIN_FILENO;
if (quiet)
ofd = -1;
else
ofd = STDOUT_FILENO;
process_file("<stdin>", ifd, ofd, action, codec, timing, timer, stats);
} else {
while (argc--) {
const char *file = *argv++;
ifd = open(file, O_RDONLY);
ASSERT(ifd != -1);
if (quiet)
ofd = -1;
else
ofd = STDOUT_FILENO;
process_file(file, ifd, ofd, action, codec, timing, timer, stats);
close(ifd);
}
}
}
static void
time_samples(Timer *timer)
{
std::vector<uintmax_t> samples = timer->samples();
std::vector<uintmax_t>::iterator it;
for (it = samples.begin(); it != samples.end(); ++it)
fprintf(stderr, "%ju\n", *it);
}
static void
time_stats(Timer *timer)
{
std::vector<uintmax_t> samples = timer->samples();
std::vector<uintmax_t>::iterator it;
LogHandle log("/codec_timer");
uintmax_t microseconds;
INFO(log) << samples.size() << " timer samples.";
microseconds = 0;
for (it = samples.begin(); it != samples.end(); ++it)
microseconds += *it;
INFO(log) << microseconds << " total runtime.";
INFO(log) << (microseconds / samples.size()) << " mean microseconds/call.";
}
static void
usage(void)
{
fprintf(stderr,
"usage: tack [-svQST] -c [file ...]\n"
" tack [-svQST] -d [file ...]\n");
exit(1);
}
<|endoftext|> |
<commit_before>#ifndef ITER_POWERSET_HPP_
#define ITER_POWERSET_HPP_
#include "iterbase.hpp"
#include "combinations.hpp"
#include <cassert>
#include <memory>
#include <initializer_list>
#include <utility>
#include <iterator>
#include <type_traits>
namespace iter {
template <typename Container>
class Powersetter {
private:
Container container;
using CombinatorType =
decltype(combinations(std::declval<Container&>(), 0));
public:
Powersetter(Container&& in_container)
: container(std::forward<Container>(in_container))
{ }
class Iterator
: public std::iterator<
std::input_iterator_tag, CombinatorType>
{
private:
typename std::remove_reference<Container>::type *container_p;
std::size_t set_size;
std::unique_ptr<CombinatorType> comb;
iterator_type<CombinatorType> comb_iter;
iterator_type<CombinatorType> comb_end;
public:
Iterator(Container& in_container, std::size_t sz)
: container_p{&in_container},
set_size{sz},
comb{new CombinatorType(combinations(in_container, sz))},
comb_iter{std::begin(*comb)},
comb_end{std::end(*comb)}
{ }
Iterator& operator++() {
++this->comb_iter;
if (this->comb_iter == this->comb_end) {
++this->set_size;
this->comb.reset(new CombinatorType(combinations(
*this->container_p, this->set_size)));
this->comb_iter = std::begin(*this->comb);
this->comb_end = std::end(*this->comb);
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
iterator_deref<CombinatorType> operator*() {
return *this->comb_iter;
}
bool operator != (const Iterator& other) const {
return !(*this == other);
}
bool operator==(const Iterator& other) const {
return this->set_size == other.set_size
&& this->comb_iter == other.comb_iter;
}
};
Iterator begin() {
return {this->container, 0};
}
Iterator end() {
return {this->container, dumb_size(this->container) + 1};
}
};
template <typename Container>
Powersetter<Container> powerset(Container&& container) {
return {std::forward<Container>(container)};
}
template <typename T>
Powersetter<std::initializer_list<T>> powerset(
std::initializer_list<T> il) {
return {std::move(il)};
}
}
#endif
<commit_msg>makes powerset iterator copyable<commit_after>#ifndef ITER_POWERSET_HPP_
#define ITER_POWERSET_HPP_
#include "iterbase.hpp"
#include "combinations.hpp"
#include <cassert>
#include <memory>
#include <initializer_list>
#include <utility>
#include <iterator>
#include <type_traits>
namespace iter {
template <typename Container>
class Powersetter {
private:
Container container;
using CombinatorType =
decltype(combinations(std::declval<Container&>(), 0));
public:
Powersetter(Container&& in_container)
: container(std::forward<Container>(in_container))
{ }
class Iterator
: public std::iterator<
std::input_iterator_tag, CombinatorType>
{
private:
typename std::remove_reference<Container>::type *container_p;
std::size_t set_size;
std::shared_ptr<CombinatorType> comb;
iterator_type<CombinatorType> comb_iter;
iterator_type<CombinatorType> comb_end;
public:
Iterator(Container& in_container, std::size_t sz)
: container_p{&in_container},
set_size{sz},
comb{new CombinatorType(combinations(in_container, sz))},
comb_iter{std::begin(*comb)},
comb_end{std::end(*comb)}
{ }
Iterator& operator++() {
++this->comb_iter;
if (this->comb_iter == this->comb_end) {
++this->set_size;
this->comb.reset(new CombinatorType(combinations(
*this->container_p, this->set_size)));
this->comb_iter = std::begin(*this->comb);
this->comb_end = std::end(*this->comb);
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
iterator_deref<CombinatorType> operator*() {
return *this->comb_iter;
}
bool operator != (const Iterator& other) const {
return !(*this == other);
}
bool operator==(const Iterator& other) const {
return this->set_size == other.set_size
&& this->comb_iter == other.comb_iter;
}
};
Iterator begin() {
return {this->container, 0};
}
Iterator end() {
return {this->container, dumb_size(this->container) + 1};
}
};
template <typename Container>
Powersetter<Container> powerset(Container&& container) {
return {std::forward<Container>(container)};
}
template <typename T>
Powersetter<std::initializer_list<T>> powerset(
std::initializer_list<T> il) {
return {std::move(il)};
}
}
#endif
<|endoftext|> |
<commit_before>#include "Interceptor.h"
#include "hookzz_internal.h"
#include "InterceptRouting.h"
PUBLIC RetStatus ZzWrap(void *function_address, PRECALL pre_call, POSTCALL post_call) {
DLOG("[*] Initialize 'ZzWrap' hook at %p\n", function_address);
Interceptor *intercepter = Interceptor::SharedInstance();
HookEntry *entry = new HookEntry();
entry->id = intercepter->entries.size();
entry->pre_call = pre_call;
entry->post_call = post_call;
entry->type = kFunctionWrapper;
entry->function_address = function_address;
InterceptRouting *route = InterceptRouting::New(entry);
route->Dispatch();
intercepter->AddHookEntry(entry);
route->Commit();
DLOG("[*] Finalize %p\n", function_address);
return RS_SUCCESS;
}
PUBLIC RetStatus ZzReplace(void *function_address, void *replace_call, void **origin_call) {
DLOG("[*] Initialize 'ZzReplace' hook at %p\n", function_address);
Interceptor *intercepter = Interceptor::SharedInstance();
HookEntry *entry = new HookEntry();
entry->id = intercepter->entries.size();
entry->replace_call = replace_call;
entry->type = kFunctionInlineHook;
entry->function_address = function_address;
InterceptRouting *route = InterceptRouting::New(entry);
route->Dispatch();
intercepter->AddHookEntry(entry);
route->Commit();
// set origin call with relocated function
*origin_call = entry->relocated_origin_function;
DLOG("[*] Finalize %p\n", function_address);
return RS_SUCCESS;
}
PUBLIC RetStatus ZzDynamicBinaryInstrumentation(void *inst_address, DBICALL dbi_call) {
DLOG("[*] Initialize 'ZzDynamicBinaryInstrumentation' hook at %p\n", inst_address);
Interceptor *intercepter = Interceptor::SharedInstance();
HookEntry *entry = new HookEntry();
entry->id = intercepter->entries.size();
entry->dbi_call = dbi_call;
entry->type = kDynamicBinaryInstrumentation;
entry->instruction_address = inst_address;
InterceptRouting *route = InterceptRouting::New(entry);
route->Dispatch();
intercepter->AddHookEntry(entry);
route->Commit();
DLOG("[*] Finalize %p\n", inst_address);
return RS_SUCCESS;
}
PUBLIC RetStatus zz_enable_arm_arm64_b_branch() {
DLOG("%s", "[*] Enable Intercepter ARM/ARM64 B Branch\n");
Interceptor *intercepter = Interceptor::SharedInstance();
// TODO: replace with getter or setter
intercepter->enable_arm_arm64_b_branch();
return RS_SUCCESS;
}
PUBLIC RetStatus zz_disable_arm_arm64_b_branch() {
DLOG("%s", "[*] Disable Intercepter ARM/ARM64 B Branch\n");
Interceptor *intercepter = Interceptor::SharedInstance();
// TODO: replace with getter or setter
intercepter->disable_arm_arm64_b_branch();
return RS_SUCCESS;
}
<commit_msg>[bug-fix] the relocated functioin assign must before Commit<commit_after>#include "Interceptor.h"
#include "hookzz_internal.h"
#include "InterceptRouting.h"
PUBLIC RetStatus ZzWrap(void *function_address, PRECALL pre_call, POSTCALL post_call) {
DLOG("[*] Initialize 'ZzWrap' hook at %p\n", function_address);
Interceptor *intercepter = Interceptor::SharedInstance();
HookEntry *entry = new HookEntry();
entry->id = intercepter->entries.size();
entry->pre_call = pre_call;
entry->post_call = post_call;
entry->type = kFunctionWrapper;
entry->function_address = function_address;
InterceptRouting *route = InterceptRouting::New(entry);
route->Dispatch();
intercepter->AddHookEntry(entry);
route->Commit();
DLOG("[*] Finalize %p\n", function_address);
return RS_SUCCESS;
}
PUBLIC RetStatus ZzReplace(void *function_address, void *replace_call, void **origin_call) {
DLOG("[*] Initialize 'ZzReplace' hook at %p\n", function_address);
Interceptor *intercepter = Interceptor::SharedInstance();
HookEntry *entry = new HookEntry();
entry->id = intercepter->entries.size();
entry->replace_call = replace_call;
entry->type = kFunctionInlineHook;
entry->function_address = function_address;
InterceptRouting *route = InterceptRouting::New(entry);
route->Dispatch();
intercepter->AddHookEntry(entry);
// SET BEFORE `route->Commit()` !!!
// set origin call with relocated function
*origin_call = entry->relocated_origin_function;
route->Commit();
DLOG("[*] Finalize %p\n", function_address);
return RS_SUCCESS;
}
PUBLIC RetStatus ZzDynamicBinaryInstrumentation(void *inst_address, DBICALL dbi_call) {
DLOG("[*] Initialize 'ZzDynamicBinaryInstrumentation' hook at %p\n", inst_address);
Interceptor *intercepter = Interceptor::SharedInstance();
HookEntry *entry = new HookEntry();
entry->id = intercepter->entries.size();
entry->dbi_call = dbi_call;
entry->type = kDynamicBinaryInstrumentation;
entry->instruction_address = inst_address;
InterceptRouting *route = InterceptRouting::New(entry);
route->Dispatch();
intercepter->AddHookEntry(entry);
route->Commit();
DLOG("[*] Finalize %p\n", inst_address);
return RS_SUCCESS;
}
PUBLIC RetStatus zz_enable_arm_arm64_b_branch() {
DLOG("%s", "[*] Enable Intercepter ARM/ARM64 B Branch\n");
Interceptor *intercepter = Interceptor::SharedInstance();
// TODO: replace with getter or setter
intercepter->enable_arm_arm64_b_branch();
return RS_SUCCESS;
}
PUBLIC RetStatus zz_disable_arm_arm64_b_branch() {
DLOG("%s", "[*] Disable Intercepter ARM/ARM64 B Branch\n");
Interceptor *intercepter = Interceptor::SharedInstance();
// TODO: replace with getter or setter
intercepter->disable_arm_arm64_b_branch();
return RS_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "vast/search.h"
#include "vast/exception.h"
#include "vast/optional.h"
#include "vast/query.h"
#include "vast/util/make_unique.h"
namespace vast {
namespace {
// Extracts all (leaf) predicates from an AST.
class predicator : public expr::default_const_visitor
{
public:
predicator(std::vector<expr::ast>& predicates)
: predicates_{predicates}
{
}
virtual void visit(expr::conjunction const& conj)
{
for (auto& op : conj.operands)
op->accept(*this);
}
virtual void visit(expr::disjunction const& disj)
{
for (auto& op : disj.operands)
op->accept(*this);
}
virtual void visit(expr::predicate const& pred)
{
predicates_.emplace_back(pred);
}
private:
std::vector<expr::ast>& predicates_;
};
// Computes the result of a conjunction by ANDing the results of all of its
// child nodes.
struct conjunction_evaluator : public expr::default_const_visitor
{
conjunction_evaluator(std::map<expr::ast, search::state>& state)
: state{state}
{
}
virtual void visit(expr::conjunction const& conj)
{
for (auto& operand : conj.operands)
if (complete)
operand->accept(*this);
}
virtual void visit(expr::disjunction const& disj)
{
if (complete)
update(disj);
}
virtual void visit(expr::predicate const& pred)
{
if (complete)
update(pred);
}
void update(expr::ast const& child)
{
auto i = state.find(child);
assert(i != state.end());
auto& child_result = i->second.result;
if (! child_result)
{
complete = false;
return;
}
result &= child_result;
}
bool complete = true;
search_result result;
std::map<expr::ast, search::state> const& state;
};
// Computes the result of a disjunction by ORing the results of all of its
// child nodes.
struct disjunction_evaluator : public expr::default_const_visitor
{
disjunction_evaluator(std::map<expr::ast, search::state>& state)
: state{state}
{
}
virtual void visit(expr::conjunction const& conj)
{
update(conj);
}
virtual void visit(expr::disjunction const& disj)
{
for (auto& operand : disj.operands)
operand->accept(*this);
}
virtual void visit(expr::predicate const& pred)
{
update(pred);
}
void update(expr::ast const& child)
{
auto i = state.find(child);
assert(i != state.end());
auto& child_result = i->second.result;
if (child_result)
result |= child_result;
}
search_result result;
std::map<expr::ast, search::state> const& state;
};
// Deconstructs an entire query AST into its individual sub-trees and adds
// each sub-tree to the state map.
class dissector : public expr::default_const_visitor
{
public:
dissector(std::map<expr::ast, search::state>& state, expr::ast const& base)
: state_{state},
base_{base}
{
}
virtual void visit(expr::conjunction const& conj)
{
expr::ast ast{conj};
if (parent_)
state_[ast].parents.insert(parent_);
else if (ast == base_)
state_.emplace(ast, search::state{});
parent_ = std::move(ast);
for (auto& clause : conj.operands)
clause->accept(*this);
conjunction_evaluator ce{state_};
ast.accept(ce);
if (ce.complete)
state_[ast].result = std::move(ce.result);
}
virtual void visit(expr::disjunction const& disj)
{
expr::ast ast{disj};
if (parent_)
state_[ast].parents.insert(parent_);
else if (ast == base_)
state_.emplace(ast, search::state{});
parent_ = std::move(ast);
for (auto& term : disj.operands)
term->accept(*this);
disjunction_evaluator de{state_};
ast.accept(de);
state_[ast].result = std::move(de.result);
}
virtual void visit(expr::predicate const& pred)
{
assert(parent_);
expr::ast ast{pred};
state_[ast].parents.insert(parent_);
}
private:
expr::ast parent_;
std::map<expr::ast, search::state>& state_;
expr::ast const& base_;
};
} // namespace <anonymous>
expr::ast search::add_query(std::string const& str)
{
expr::ast ast{str};
if (! ast)
return ast;
dissector d{state_, ast};
ast.accept(d);
return ast;
}
std::vector<expr::ast> search::update(expr::ast const& ast,
search_result const& result)
{
assert(state_.count(ast));
if (! result)
{
VAST_LOG_DEBUG("aborting ast propagation due to empty result");
return {};
}
// Phase 1: Update result of AST node (and potentially its direct children).
auto& ast_state = state_[ast];
if (ast.is_conjunction())
{
VAST_LOG_DEBUG("evaluating conjunction " << ast);
conjunction_evaluator ce{state_};
ast.accept(ce);
if (ce.complete)
ast_state.result = std::move(ce.result);
}
else if (ast.is_disjunction())
{
VAST_LOG_DEBUG("evaluating disjunction " << ast);
disjunction_evaluator de{state_};
ast.accept(de);
if (! ast_state.result || (de.result && de.result != ast_state.result))
ast_state.result = std::move(de.result);
}
else if (! ast_state.result)
{
VAST_LOG_DEBUG("assigning result to " << ast);
ast_state.result = std::move(result);
}
else if (ast_state.result == result)
{
VAST_LOG_DEBUG("ignoring unchanged result for " << ast);
}
else
{
VAST_LOG_DEBUG("computing new result for " << ast);
ast_state.result |= result;
}
// Phase 2: Propagate the result to the parents recursively.
std::vector<expr::ast> path;
for (auto& parent : ast_state.parents)
{
auto pp = update(parent, ast_state.result);
std::move(pp.begin(), pp.end(), std::back_inserter(path));
}
path.push_back(ast);
std::sort(path.begin(), path.end());
path.erase(std::unique(path.begin(), path.end()), path.end());
return path;
}
search_result const* search::result(expr::ast const& ast) const
{
auto i = state_.find(ast);
return i != state_.end() ? &i->second.result : nullptr;
}
using namespace cppa;
search_actor::query_state::query_state(actor_ptr q, actor_ptr c)
: query{q},
client{c}
{
}
search_actor::search_actor(actor_ptr archive,
actor_ptr index,
actor_ptr schema_manager)
: archive_{std::move(archive)},
index_{std::move(index)},
schema_manager_{std::move(schema_manager)}
{
}
void search_actor::act()
{
trap_exit(true);
become(
on(atom("EXIT"), arg_match) >> [=](uint32_t reason)
{
std::set<actor_ptr> doomed;
for (auto& p : query_state_)
{
doomed.insert(p.second.query);
doomed.insert(p.second.client);
}
for (auto& d : doomed)
send_exit(d, exit::stop);
quit(reason);
},
on(atom("DOWN"), arg_match) >> [=](uint32_t)
{
VAST_LOG_ACTOR_DEBUG(
"received DOWN from client " << VAST_ACTOR_ID(last_sender()));
std::set<actor_ptr> doomed;
for (auto& p : query_state_)
{
if (p.second.client == last_sender())
{
doomed.insert(p.second.query);
doomed.insert(p.second.client);
}
}
for (auto& d : doomed)
send_exit(d, exit::stop);
},
on(atom("query"), atom("create"), arg_match) >> [=](std::string const& q)
{
auto ast = search_.add_query(q);
if (! ast)
{
reply(actor_ptr{}, ast);
return;
}
VAST_LOG_ACTOR_DEBUG("received new query: " << ast);
monitor(last_sender());
auto qry = spawn<query_actor>(archive_, last_sender(), ast);
auto i = query_state_.emplace(ast, query_state{qry, last_sender()});
// Deconstruct the AST into its predicates and ask the index for those
// we have no results for.
std::vector<expr::ast> predicates;
predicator visitor{predicates};
ast.accept(visitor);
for (auto& pred : predicates)
{
auto r = search_.result(pred);
if (! r || ! *r)
{
VAST_LOG_ACTOR_DEBUG("hits index with " << pred);
send(index_, pred);
}
else
{
VAST_LOG_ACTOR_DEBUG("reuses existing result for " << pred);
}
}
auto r = search_.result(ast);
if (r && *r)
{
VAST_LOG_ACTOR_DEBUG("could answer query from existing predicates");
i->second.result = *r;
send(i->second.query, r->hits());
}
reply(qry, ast);
},
on_arg_match >> [=](expr::ast const& ast, search_result const& result)
{
if (! result)
{
VAST_LOG_ACTOR_DEBUG(
"ignores empty result from " << VAST_ACTOR_ID(last_sender()) <<
" for: " << ast);
return;
}
for (auto& node : search_.update(ast, result))
{
auto er = query_state_.equal_range(node);
for (auto i = er.first; i != er.second; ++i)
{
auto r = search_.result(node);
if (r && *r && *r != i->second.result)
{
VAST_LOG_ACTOR_DEBUG(
"propagates updated result to query " <<
VAST_ACTOR_ID(i->second.query) << " from " << i->first);
i->second.result = *r;
send(i->second.query, r->hits());
}
}
}
},
others() >> [=]
{
VAST_LOG_ACTOR_ERROR("got unexpected message from " <<
VAST_ACTOR_ID(last_sender()) << ": " <<
to_string(last_dequeued()));
});
}
char const* search_actor::description() const
{
return "search";
}
} // namespace vast
<commit_msg>Fix use-after-move bug.<commit_after>#include "vast/search.h"
#include "vast/exception.h"
#include "vast/optional.h"
#include "vast/query.h"
#include "vast/util/make_unique.h"
namespace vast {
namespace {
// Extracts all (leaf) predicates from an AST.
class predicator : public expr::default_const_visitor
{
public:
predicator(std::vector<expr::ast>& predicates)
: predicates_{predicates}
{
}
virtual void visit(expr::conjunction const& conj)
{
for (auto& op : conj.operands)
op->accept(*this);
}
virtual void visit(expr::disjunction const& disj)
{
for (auto& op : disj.operands)
op->accept(*this);
}
virtual void visit(expr::predicate const& pred)
{
predicates_.emplace_back(pred);
}
private:
std::vector<expr::ast>& predicates_;
};
// Computes the result of a conjunction by ANDing the results of all of its
// child nodes.
struct conjunction_evaluator : public expr::default_const_visitor
{
conjunction_evaluator(std::map<expr::ast, search::state>& state)
: state{state}
{
}
virtual void visit(expr::conjunction const& conj)
{
for (auto& operand : conj.operands)
if (complete)
operand->accept(*this);
}
virtual void visit(expr::disjunction const& disj)
{
if (complete)
update(disj);
}
virtual void visit(expr::predicate const& pred)
{
if (complete)
update(pred);
}
void update(expr::ast const& child)
{
auto i = state.find(child);
assert(i != state.end());
auto& child_result = i->second.result;
if (! child_result)
{
complete = false;
return;
}
result &= child_result;
}
bool complete = true;
search_result result;
std::map<expr::ast, search::state> const& state;
};
// Computes the result of a disjunction by ORing the results of all of its
// child nodes.
struct disjunction_evaluator : public expr::default_const_visitor
{
disjunction_evaluator(std::map<expr::ast, search::state>& state)
: state{state}
{
}
virtual void visit(expr::conjunction const& conj)
{
update(conj);
}
virtual void visit(expr::disjunction const& disj)
{
for (auto& operand : disj.operands)
operand->accept(*this);
}
virtual void visit(expr::predicate const& pred)
{
update(pred);
}
void update(expr::ast const& child)
{
auto i = state.find(child);
assert(i != state.end());
auto& child_result = i->second.result;
if (child_result)
result |= child_result;
}
search_result result;
std::map<expr::ast, search::state> const& state;
};
// Deconstructs an entire query AST into its individual sub-trees and adds
// each sub-tree to the state map.
class dissector : public expr::default_const_visitor
{
public:
dissector(std::map<expr::ast, search::state>& state, expr::ast const& base)
: state_{state},
base_{base}
{
}
virtual void visit(expr::conjunction const& conj)
{
expr::ast ast{conj};
if (parent_)
state_[ast].parents.insert(parent_);
else if (ast == base_)
state_.emplace(ast, search::state{});
assert(state_.find(ast) != state_.end());
parent_ = ast;
for (auto& clause : conj.operands)
clause->accept(*this);
conjunction_evaluator ce{state_};
ast.accept(ce);
if (ce.complete)
state_[ast].result = std::move(ce.result);
}
virtual void visit(expr::disjunction const& disj)
{
expr::ast ast{disj};
if (parent_)
state_[ast].parents.insert(parent_);
else if (ast == base_)
state_.emplace(ast, search::state{});
assert(state_.find(ast) != state_.end());
parent_ = ast;
for (auto& term : disj.operands)
term->accept(*this);
disjunction_evaluator de{state_};
ast.accept(de);
state_[ast].result = std::move(de.result);
}
virtual void visit(expr::predicate const& pred)
{
assert(parent_);
expr::ast ast{pred};
state_[ast].parents.insert(parent_);
}
private:
expr::ast parent_;
std::map<expr::ast, search::state>& state_;
expr::ast const& base_;
};
} // namespace <anonymous>
expr::ast search::add_query(std::string const& str)
{
expr::ast ast{str};
if (! ast)
return ast;
dissector d{state_, ast};
ast.accept(d);
return ast;
}
std::vector<expr::ast> search::update(expr::ast const& ast,
search_result const& result)
{
assert(state_.count(ast));
if (! result)
{
VAST_LOG_DEBUG("aborting ast propagation due to empty result");
return {};
}
// Phase 1: Update result of AST node (and potentially its direct children).
auto& ast_state = state_[ast];
if (ast.is_conjunction())
{
VAST_LOG_DEBUG("evaluating conjunction " << ast);
conjunction_evaluator ce{state_};
ast.accept(ce);
if (ce.complete)
ast_state.result = std::move(ce.result);
}
else if (ast.is_disjunction())
{
VAST_LOG_DEBUG("evaluating disjunction " << ast);
disjunction_evaluator de{state_};
ast.accept(de);
if (! ast_state.result || (de.result && de.result != ast_state.result))
ast_state.result = std::move(de.result);
}
else if (! ast_state.result)
{
VAST_LOG_DEBUG("assigning result to " << ast);
ast_state.result = std::move(result);
}
else if (ast_state.result == result)
{
VAST_LOG_DEBUG("ignoring unchanged result for " << ast);
}
else
{
VAST_LOG_DEBUG("computing new result for " << ast);
ast_state.result |= result;
}
// Phase 2: Propagate the result to the parents recursively.
std::vector<expr::ast> path;
for (auto& parent : ast_state.parents)
{
auto pp = update(parent, ast_state.result);
std::move(pp.begin(), pp.end(), std::back_inserter(path));
}
path.push_back(ast);
std::sort(path.begin(), path.end());
path.erase(std::unique(path.begin(), path.end()), path.end());
return path;
}
search_result const* search::result(expr::ast const& ast) const
{
auto i = state_.find(ast);
return i != state_.end() ? &i->second.result : nullptr;
}
using namespace cppa;
search_actor::query_state::query_state(actor_ptr q, actor_ptr c)
: query{q},
client{c}
{
}
search_actor::search_actor(actor_ptr archive,
actor_ptr index,
actor_ptr schema_manager)
: archive_{std::move(archive)},
index_{std::move(index)},
schema_manager_{std::move(schema_manager)}
{
}
void search_actor::act()
{
trap_exit(true);
become(
on(atom("EXIT"), arg_match) >> [=](uint32_t reason)
{
std::set<actor_ptr> doomed;
for (auto& p : query_state_)
{
doomed.insert(p.second.query);
doomed.insert(p.second.client);
}
for (auto& d : doomed)
send_exit(d, exit::stop);
quit(reason);
},
on(atom("DOWN"), arg_match) >> [=](uint32_t)
{
VAST_LOG_ACTOR_DEBUG(
"received DOWN from client " << VAST_ACTOR_ID(last_sender()));
std::set<actor_ptr> doomed;
for (auto& p : query_state_)
{
if (p.second.client == last_sender())
{
doomed.insert(p.second.query);
doomed.insert(p.second.client);
}
}
for (auto& d : doomed)
send_exit(d, exit::stop);
},
on(atom("query"), atom("create"), arg_match) >> [=](std::string const& q)
{
auto ast = search_.add_query(q);
if (! ast)
{
reply(actor_ptr{}, ast);
return;
}
VAST_LOG_ACTOR_DEBUG("received new query: " << ast);
monitor(last_sender());
auto qry = spawn<query_actor>(archive_, last_sender(), ast);
auto i = query_state_.emplace(ast, query_state{qry, last_sender()});
// Deconstruct the AST into its predicates and ask the index for those
// we have no results for.
std::vector<expr::ast> predicates;
predicator visitor{predicates};
ast.accept(visitor);
for (auto& pred : predicates)
{
auto r = search_.result(pred);
if (! r || ! *r)
{
VAST_LOG_ACTOR_DEBUG("hits index with " << pred);
send(index_, pred);
}
else
{
VAST_LOG_ACTOR_DEBUG("reuses existing result for " << pred);
}
}
auto r = search_.result(ast);
if (r && *r)
{
VAST_LOG_ACTOR_DEBUG("could answer query from existing predicates");
i->second.result = *r;
send(i->second.query, r->hits());
}
reply(qry, ast);
},
on_arg_match >> [=](expr::ast const& ast, search_result const& result)
{
if (! result)
{
VAST_LOG_ACTOR_DEBUG(
"ignores empty result from " << VAST_ACTOR_ID(last_sender()) <<
" for: " << ast);
return;
}
for (auto& node : search_.update(ast, result))
{
auto er = query_state_.equal_range(node);
for (auto i = er.first; i != er.second; ++i)
{
auto r = search_.result(node);
if (r && *r && *r != i->second.result)
{
VAST_LOG_ACTOR_DEBUG(
"propagates updated result to query " <<
VAST_ACTOR_ID(i->second.query) << " from " << i->first);
i->second.result = *r;
send(i->second.query, r->hits());
}
}
}
},
others() >> [=]
{
VAST_LOG_ACTOR_ERROR("got unexpected message from " <<
VAST_ACTOR_ID(last_sender()) << ": " <<
to_string(last_dequeued()));
});
}
char const* search_actor::description() const
{
return "search";
}
} // namespace vast
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XTENSOR_CONFIG_HPP
#define XTENSOR_CONFIG_HPP
#define XTENSOR_VERSION_MAJOR 0
#define XTENSOR_VERSION_MINOR 4
#define XTENSOR_VERSION_PATCH 1
// DETECT 3.6 <= clang < 3.8 for compiler bug workaround.
#ifdef __clang__
#if __clang_major__ == 3 && __clang_minor__ < 8
#define X_OLD_CLANG
#include <initializer_list>
#include <vector>
#endif
#endif
#endif
<commit_msg>Release 0.5.0<commit_after>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XTENSOR_CONFIG_HPP
#define XTENSOR_CONFIG_HPP
#define XTENSOR_VERSION_MAJOR 0
#define XTENSOR_VERSION_MINOR 5
#define XTENSOR_VERSION_PATCH 0
// DETECT 3.6 <= clang < 3.8 for compiler bug workaround.
#ifdef __clang__
#if __clang_major__ == 3 && __clang_minor__ < 8
#define X_OLD_CLANG
#include <initializer_list>
#include <vector>
#endif
#endif
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <Sequence/SimData.hpp>
#include <Sequence/PolySIM.hpp>
#include <Sequence/FST.hpp>
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cerr.tie(nullptr);
std::cout.setf(std::ios::fixed);
std::cout.precision(6);
std::string buffer;
unsigned int nsam, nrep;
std::cin >> buffer >> nsam >> nrep;
std::cerr << buffer << " " << nsam << " " << nrep;
std::vector<unsigned int> sample_sizes{nsam};
while (std::cin >> buffer) {
if (buffer == "-I") {
unsigned int npop;
std::cin >> npop;
std::cerr << " -I " << npop;
sample_sizes.resize(npop);
for (auto& n_i: sample_sizes) {
std::cin >> n_i;
std::cerr << " " << n_i;
}
}
if (buffer == "//") break;
}
std::cerr << std::endl;
std::string line;
if (sample_sizes.size() > 1u) {
for (size_t i=1u; i<=sample_sizes.size(); ++i) {
std::cout << "pi_" << i << '\t'
<< "S_" << i << '\t'
<< "D_" << i << '\t'
<< "tH_" << i << '\t';
}
std::cout << "Fst\tKst\n";
} else {
std::cout << "pi\tS\tD\ttH\n";
}
for (unsigned int irep=1u; irep<=nrep; ++irep) {
if (nrep >= 10000u && (irep % 1000u == 0u)) {
std::cerr << "\r" << irep << " / " << nrep << std::flush;
}
unsigned int segsites;
std::cin >> buffer;
std::cin >> segsites;
std::vector<double> positions(segsites);
std::cin >> buffer;
for (unsigned int i=0u; i<segsites; ++i) {
std::cin >> positions[i];
}
std::cin >> std::ws;
std::vector<std::string> samples;
samples.reserve(nsam);
for (unsigned int i=0u; i<nsam; ++i) {
std::getline(std::cin, line);
samples.push_back(line);
}
std::cin >> std::ws;
std::getline(std::cin, buffer);
auto begit = samples.begin();
for (const auto n: sample_sizes) {
auto endit = begit + n;
Sequence::SimData data(positions, {begit, endit});
Sequence::PolySIM poly(&data);
std::cout << poly.ThetaPi() << '\t'
<< poly.NumPoly() << '\t'
<< poly.TajimasD() << '\t'
<< poly.ThetaH();
if (endit != samples.end()) {std::cout << '\t';}
begit = endit;
}
if (sample_sizes.size() > 1u) {
Sequence::SimData data(positions, samples);
Sequence::FST fst(&data, static_cast<unsigned int>(sample_sizes.size()), sample_sizes.data());
std::cout << '\t' << fst.HSM() << '\t' << fst.HBK();
}
std::cout << '\n';
}
std::cout << std::flush;
if (nrep >= 10000u) std::cerr << std::endl;
return 0;
}
<commit_msg>:art: Shrink main()<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <Sequence/SimData.hpp>
#include <Sequence/PolySIM.hpp>
#include <Sequence/FST.hpp>
inline std::vector<double>
read_positions(std::istream& ist) {
std::string buffer;
unsigned segsites;
while (buffer != "segsites:") {
ist >> buffer;
}
ist >> segsites;
ist >> buffer;
std::vector<double> positions(segsites);
for (unsigned i=0u; i<segsites; ++i) {
ist >> positions[i];
}
ist >> std::ws;
return positions;
}
inline std::ostream&
write_header(std::ostream& ost, const unsigned npop) {
if (npop > 1u) {
for (size_t i=1u; i<=npop; ++i) {
ost << "pi_" << i << '\t'
<< "S_" << i << '\t'
<< "D_" << i << '\t'
<< "tH_" << i << '\t';
}
ost << "Fst\n";
} else {
ost << "pi\tS\tD\ttH\n";
}
return ost;
}
struct MsCommand {
MsCommand(std::istream& ist) {
std::string buffer;
ist >> buffer >> nsam >> nrep;
std::cerr << buffer << " " << nsam << " " << nrep;
sample_sizes.push_back(nsam);
while (ist >> buffer) {
if (buffer == "//") break;
std::cerr << ' ' << buffer;
if (buffer == "-I") {
unsigned npop;
ist >> npop;
sample_sizes.resize(npop);
for (auto& n_i: sample_sizes) {
ist >> n_i;
}
}
}
std::cerr << std::endl;
}
size_t npop() const {return sample_sizes.size();}
unsigned nsam;
unsigned nrep;
std::vector<unsigned> sample_sizes;
};
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cerr.tie(nullptr);
std::cout.setf(std::ios::fixed);
std::cout.precision(6);
std::string buffer;
MsCommand ms(std::cin);
write_header(std::cout, ms.npop());
for (unsigned irep=1u; irep<=ms.nrep; ++irep) {
if (ms.nrep >= 10000u && (irep % 1000u == 0u)) {
std::cerr << "\r" << irep << " / " << ms.nrep << std::flush;
}
const auto positions = read_positions(std::cin);
std::cin >> std::ws;
std::vector<std::string> samples;
samples.reserve(ms.nsam);
for (unsigned i=0u; i<ms.nsam; ++i) {
std::getline(std::cin, buffer);
samples.push_back(buffer);
}
std::cin >> std::ws;
std::getline(std::cin, buffer);
auto begit = samples.begin();
for (const auto n: ms.sample_sizes) {
auto endit = begit + n;
Sequence::SimData data(positions, {begit, endit});
Sequence::PolySIM poly(&data);
std::cout << poly.ThetaPi() << '\t'
<< poly.NumPoly() << '\t'
<< poly.TajimasD() << '\t'
<< poly.ThetaH();
if (endit != samples.end()) {std::cout << '\t';}
begit = endit;
}
if (ms.npop() > 1u) {
Sequence::SimData data(positions, samples);
Sequence::FST fst(&data, static_cast<unsigned>(ms.npop()), ms.sample_sizes.data());
std::cout << '\t' << fst.HSM();
}
std::cout << '\n';
}
std::cout << std::flush;
if (ms.nrep >= 10000u) std::cerr << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#include <benchmark/benchmark.h>
#include <blackhole/attributes.hpp>
#include <blackhole/cpp17/string_view.hpp>
#include <blackhole/extensions/writer.hpp>
#include <blackhole/formatter/string.hpp>
#include <blackhole/record.hpp>
namespace blackhole {
namespace benchmark {
static
void
format_literal(::benchmark::State& state) {
formatter::string_t formatter("message: value");
const string_view message("-");
const attribute_pack pack;
record_t record(0, message, pack);
writer_t writer;
while (state.KeepRunning()) {
formatter.format(record, writer);
}
state.SetItemsProcessed(state.iterations());
}
static
void
format_message(::benchmark::State& state) {
formatter::string_t formatter("message: {message}");
const string_view message("value");
const attribute_pack pack;
record_t record(0, message, pack);
writer_t writer;
while (state.KeepRunning()) {
formatter.format(record, writer);
}
state.SetItemsProcessed(state.iterations());
}
BENCHMARK(format_literal);
BENCHMARK(format_message);
} // namespace benchmark
} // namespace blackhole
<commit_msg>perf(bench): add severity format benchmark<commit_after>#include <benchmark/benchmark.h>
#include <blackhole/attributes.hpp>
#include <blackhole/cpp17/string_view.hpp>
#include <blackhole/extensions/writer.hpp>
#include <blackhole/formatter/string.hpp>
#include <blackhole/record.hpp>
namespace blackhole {
namespace benchmark {
static
void
format_literal(::benchmark::State& state) {
formatter::string_t formatter("message: value");
const string_view message("-");
const attribute_pack pack;
record_t record(0, message, pack);
writer_t writer;
while (state.KeepRunning()) {
formatter.format(record, writer);
}
state.SetItemsProcessed(state.iterations());
}
static
void
format_message(::benchmark::State& state) {
formatter::string_t formatter("message: {message}");
const string_view message("value");
const attribute_pack pack;
record_t record(0, message, pack);
writer_t writer;
while (state.KeepRunning()) {
formatter.format(record, writer);
}
state.SetItemsProcessed(state.iterations());
}
static
void
format_severity_with_message(::benchmark::State& state) {
formatter::string_t formatter("{severity:d}: {message}");
const string_view message("value");
const attribute_pack pack;
record_t record(0, message, pack);
writer_t writer;
while (state.KeepRunning()) {
formatter.format(record, writer);
}
state.SetItemsProcessed(state.iterations());
}
BENCHMARK(format_literal);
BENCHMARK(format_message);
BENCHMARK(format_severity_with_message);
} // namespace benchmark
} // namespace blackhole
<|endoftext|> |
<commit_before>// $Id$
///
/// @file downloadCDB.C
/// @brief Download a snapshot of the CDB to another folder
///
/// <pre>
/// Usage: aliroot -b -q -l \
/// downloadCDB.C'(runno, "from", "to", "path")'
///
/// Examples:
/// downloadCDB.C'(144991, "alien://folder=/alice/data/2011/OCDB", "local:///tmp/144991/OCDB")'
///
/// Defaults
/// path="*/*/*" -> download everything
///
/// </pre>
///
///
void downloadCDB(Int_t runnr,
const char* from,
const char* to,
const char* path="*/*/*")
{
AliCDBManager* man=AliCDBManager::Instance();
man->SetDefaultStorage(from);
man->SetDrain(to);
AliCDBPath cdbpath(path);
man->GetAll(path, runnr);
}
void downloadCDB()
{
cout << " Usage:" << endl;
cout << " aliroot -b -q -l \\" << endl;
cout << " downloadCDB.C'(runno, \"from\", \"to\", \"path\")'" << endl;
cout << "" << endl;
cout << " Examples:" << endl;
cout << " aliroot -b -q -l \\" << endl;
cout << " downloadCDB.C'(144991, \"alien://folder=/alice/data/2011/OCDB\", \"local:///tmp/144991/OCDB\")'" << endl;
cout << "" << endl;
cout << " Defaults" << endl;
cout << " path=\"*/*/*\" -> download everything" << endl;
}
<commit_msg>possibility to create an OCDB snapshot<commit_after>// $Id$
///
/// @file downloadCDB.C
/// @brief Download a snapshot of the CDB to another folder
///
/// <pre>
/// Usage: aliroot -b -q -l \
/// downloadCDB.C'(runno, "from", "to", "path")'
///
/// Examples:
/// downloadCDB.C'(144991, "alien://folder=/alice/data/2011/OCDB", "local:///tmp/144991/OCDB")'
///
/// Defaults
/// path="*/*/*" -> download everything
///
/// </pre>
///
///
void downloadCDB(Int_t runnr,
const char* from,
const char* to,
const char* path="*/*/*")
{
AliCDBManager* man=AliCDBManager::Instance();
man->SetDefaultStorage(from);
man->SetRun(runnr);
man->SetDrain(to);
AliCDBPath cdbpath(path);
man->GetAll(path, runnr);
if(TString(getenv("OCDB_SNAPSHOT_CREATE")) == TString("kTRUE"))
{
TString snapshotFile(getenv("OCDB_SNAPSHOT_FILENAME"));
TString snapshotFileOut = "OCDB.root";
if(!(snapshotFile.IsNull() || snapshotFile.IsWhitespace()))
{
snapshotFileOut = snapshotFile;
}
man->DumpToSnapshotFile("OCDB.root",kFALSE);
}
}
void downloadCDB()
{
cout << " Usage:" << endl;
cout << " aliroot -b -q -l \\" << endl;
cout << " downloadCDB.C'(runno, \"from\", \"to\", \"path\")'" << endl;
cout << "" << endl;
cout << " Examples:" << endl;
cout << " aliroot -b -q -l \\" << endl;
cout << " downloadCDB.C'(144991, \"alien://folder=/alice/data/2011/OCDB\", \"local:///tmp/144991/OCDB\")'" << endl;
cout << "" << endl;
cout << " Defaults" << endl;
cout << " path=\"*/*/*\" -> download everything" << endl;
}
<|endoftext|> |
<commit_before>#include "webresponse.h"
using namespace v8;
Persistent<FunctionTemplate> WebResponse::constructor;
WebResponse::WebResponse() {}
WebResponse::~WebResponse() {
if (response != NULL) g_object_unref(response);
g_object_unref(resource);
delete dataCallback;
}
void WebResponse::init(WebKitWebResource* resource, WebKitURIResponse* response) {
this->resource = resource;
g_object_ref(resource);
this->response = response;
// response can be empty
if (response != NULL) g_object_ref(response);
}
void WebResponse::Init(Handle<Object> target) {
NanScope();
Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(WebResponse::New);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->SetClassName(NanNew("WebResponse"));
ATTR(tpl, "uri", get_prop, NULL);
ATTR(tpl, "status", get_prop, NULL);
ATTR(tpl, "mime", get_prop, NULL);
NODE_SET_PROTOTYPE_METHOD(tpl, "data", WebResponse::Data);
target->Set(NanNew("WebResponse"), tpl->GetFunction());
NanAssignPersistent(constructor, tpl);
}
NAN_METHOD(WebResponse::New) {
NanScope();
WebResponse* self = new WebResponse();
self->Wrap(args.This());
NanReturnValue(args.This());
}
NAN_METHOD(WebResponse::Data) {
NanScope();
WebResponse* self = ObjectWrap::Unwrap<WebResponse>(args.This());
if (self->resource == NULL) {
NanThrowError("cannot call data(cb) on a response decision");
NanReturnUndefined();
}
self->dataCallback = new NanCallback(args[0].As<Function>());
webkit_web_resource_get_data(self->resource, NULL, WebResponse::DataFinished, self);
NanReturnUndefined();
}
void WebResponse::DataFinished(GObject* object, GAsyncResult* result, gpointer data) {
WebResponse* self = (WebResponse*)data;
GError* error = NULL;
gsize length;
guchar* buf = webkit_web_resource_get_data_finish(self->resource, result, &length, &error);
if (buf == NULL) { // if NULL, error is defined
Handle<Value> argv[] = {
NanError(error->message)
};
g_error_free(error);
self->dataCallback->Call(1, argv);
delete self->dataCallback;
self->dataCallback = NULL;
return;
}
Handle<Value> argv[] = {
NanNull(),
NanNewBufferHandle(reinterpret_cast<const char*>(buf), length)
};
self->dataCallback->Call(2, argv);
}
NAN_GETTER(WebResponse::get_prop) {
NanScope();
WebResponse* self = node::ObjectWrap::Unwrap<WebResponse>(args.Holder());
std::string propstr = TOSTR(property);
if (propstr == "uri") {
NanReturnValue(NanNew<String>(webkit_web_resource_get_uri(self->resource)));
} else if (propstr == "mime" && self->response != NULL) {
NanReturnValue(NanNew<String>(webkit_uri_response_get_mime_type(self->response)));
} else if (propstr == "status") {
if (self->response != NULL) {
NanReturnValue(NanNew<Integer>(webkit_uri_response_get_status_code(self->response)));
} else {
NanReturnValue(NanNew<Integer>(0));
}
}
NanReturnUndefined();
}
// NAN_SETTER(WebResponse::set_prop) {
// NanScope();
// WebResponse* self = node::ObjectWrap::Unwrap<WebResponse>(args.Holder());
// std::string propstr = TOSTR(property);
// if (propstr == "cancel") {
// self->cancel = value->BooleanValue();
// }
// NanThrowError("Cannot a property on response object");
// }<commit_msg>WebResponse: data can be empty without error. Throw a custom one.<commit_after>#include "webresponse.h"
using namespace v8;
Persistent<FunctionTemplate> WebResponse::constructor;
WebResponse::WebResponse() {}
WebResponse::~WebResponse() {
if (response != NULL) g_object_unref(response);
g_object_unref(resource);
delete dataCallback;
}
void WebResponse::init(WebKitWebResource* resource, WebKitURIResponse* response) {
this->resource = resource;
g_object_ref(resource);
this->response = response;
// response can be empty
if (response != NULL) g_object_ref(response);
}
void WebResponse::Init(Handle<Object> target) {
NanScope();
Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(WebResponse::New);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->SetClassName(NanNew("WebResponse"));
ATTR(tpl, "uri", get_prop, NULL);
ATTR(tpl, "status", get_prop, NULL);
ATTR(tpl, "mime", get_prop, NULL);
NODE_SET_PROTOTYPE_METHOD(tpl, "data", WebResponse::Data);
target->Set(NanNew("WebResponse"), tpl->GetFunction());
NanAssignPersistent(constructor, tpl);
}
NAN_METHOD(WebResponse::New) {
NanScope();
WebResponse* self = new WebResponse();
self->Wrap(args.This());
NanReturnValue(args.This());
}
NAN_METHOD(WebResponse::Data) {
NanScope();
WebResponse* self = ObjectWrap::Unwrap<WebResponse>(args.This());
if (self->resource == NULL) {
NanThrowError("cannot call data(cb) on a response decision");
NanReturnUndefined();
}
self->dataCallback = new NanCallback(args[0].As<Function>());
webkit_web_resource_get_data(self->resource, NULL, WebResponse::DataFinished, self);
NanReturnUndefined();
}
void WebResponse::DataFinished(GObject* object, GAsyncResult* result, gpointer data) {
WebResponse* self = (WebResponse*)data;
GError* error = NULL;
gsize length;
guchar* buf = webkit_web_resource_get_data_finish(self->resource, result, &length, &error);
if (buf == NULL) { // if NULL, error is defined
Handle<Value> argv[] = {
NanError(error != NULL ? error->message : "Empty buffer")
};
self->dataCallback->Call(1, argv);
delete self->dataCallback;
if (error != NULL) g_error_free(error);
self->dataCallback = NULL;
return;
}
Handle<Value> argv[] = {
NanNull(),
NanNewBufferHandle(reinterpret_cast<const char*>(buf), length)
};
self->dataCallback->Call(2, argv);
}
NAN_GETTER(WebResponse::get_prop) {
NanScope();
WebResponse* self = node::ObjectWrap::Unwrap<WebResponse>(args.Holder());
std::string propstr = TOSTR(property);
if (propstr == "uri") {
NanReturnValue(NanNew<String>(webkit_web_resource_get_uri(self->resource)));
} else if (propstr == "mime" && self->response != NULL) {
NanReturnValue(NanNew<String>(webkit_uri_response_get_mime_type(self->response)));
} else if (propstr == "status") {
if (self->response != NULL) {
NanReturnValue(NanNew<Integer>(webkit_uri_response_get_status_code(self->response)));
} else {
NanReturnValue(NanNew<Integer>(0));
}
}
NanReturnUndefined();
}
// NAN_SETTER(WebResponse::set_prop) {
// NanScope();
// WebResponse* self = node::ObjectWrap::Unwrap<WebResponse>(args.Holder());
// std::string propstr = TOSTR(property);
// if (propstr == "cancel") {
// self->cancel = value->BooleanValue();
// }
// NanThrowError("Cannot a property on response object");
// }<|endoftext|> |
<commit_before>/*
* Copyright 2013-2014 [email protected]
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "_etc.hpp"
#include "zone.hpp"
namespace wombat {
namespace world {
using common::Point;
using common::Bounds;
using core::Event;
using core::TaskState;
Zone::TileGrid::~TileGrid() {
free();
}
void Zone::TileGrid::setDimensions(int w, int h, int layers) {
m_tilesWide = w;
m_tilesHigh = h;
m_layers = layers;
}
void Zone::TileGrid::allocate() {
m_tiles = (Tile***) malloc(sizeof(Tile**) * m_layers);
for (int l = 0; l < m_layers; l++) {
m_tiles[l] = (Tile**) malloc(sizeof(Tile*) * m_tilesHigh);
for (int y = 0; y < m_tilesHigh; y++) {
m_tiles[l][y] = (Tile*) malloc(sizeof(Tile) * m_tilesWide);
Tile t;
for (int x = 0; x < m_tilesWide; x++) {
m_tiles[l][y][x] = t;
}
}
}
}
void Zone::TileGrid::free() {
if (m_tiles) {
for (int l = 0; l < m_layers; l++) {
for (int y = 0; y < m_tilesHigh; y++) {
::free(m_tiles[l][y]);
}
::free(m_tiles[l]);
}
::free(m_tiles);
m_tiles = nullptr;
}
}
int Zone::TileGrid::tilesWide() {
return m_tilesWide;
}
int Zone::TileGrid::tilesHigh() {
return m_tilesHigh;
}
int Zone::TileGrid::layers() {
return m_layers;
}
Zone::Zone(models::ZoneInstance model) {
models::ZoneHeader header;
core::read(header, model.ZoneHeader);
m_address = model.Address;
m_tiles.setDimensions(header.TilesWide, header.TilesHigh, header.Layers);
m_path = header.Zone;
m_taskProcessor->addTask(this);
m_taskProcessor->start();
}
Zone::~Zone() {
m_taskProcessor->stop();
m_taskProcessor->done();
delete m_taskProcessor;
}
TaskState Zone::run(core::Event e) {
switch (e.type()) {
case Event::Timeout:
if (m_dependents == 0) {
unload();
}
return 10000;
default:
return TaskState::Continue;
}
}
bool Zone::loaded() {
return m_loaded;
}
Bounds Zone::bounds() {
Bounds bnds;
bnds.X = TileWidth * m_address.X;
bnds.Y = TileHeight * m_address.Y;
bnds.Width = TileWidth * m_tiles.tilesWide();
bnds.Height = TileHeight * m_tiles.tilesHigh();
return bnds;
}
void Zone::draw(Bounds bnds,
Point translation, std::pair<Sprite*, common::Point> focus) {
auto loc = pt(bounds().pt1()) + translation;
for (auto l = 0; l < m_tiles.layers(); l++) {
for (auto y = bnds.Y; y < bnds.y2(); y += TileHeight) {
for (auto x = bnds.X; x < bnds.x2(); x += TileWidth) {
auto tile = m_tiles.at(x / TileWidth, y / TileHeight, l);
tile->draw(pt(addr(Point(x, y))) + loc);
}
}
}
for (auto l = 0; l < m_tiles.layers(); l++) {
for (auto y = bnds.Y; y < bnds.y2(); y += TileHeight) {
for (auto x = bnds.X; x < bnds.x2(); x += TileWidth) {
auto tile = m_tiles.at(x / TileWidth, y / TileHeight, l);
auto oc = tile->getOccupant();
if (oc) {
common::Point pt;
if (oc != focus.first) {
pt = world::pt(addr(Point(x, y))) + loc;
} else {
pt = focus.second;
}
oc->draw(tile, pt);
}
}
}
}
}
Point Zone::loc() {
return Point(TileWidth * m_address.X, TileHeight * m_address.Y);
}
void Zone::incDeps() {
m_mutex.lock();
m_dependents++;
if (m_dependents == 1 && !m_loaded) {
load();
}
m_mutex.unlock();
}
void Zone::decDeps() {
m_mutex.lock();
if (m_dependents > 0) {
m_dependents--;
}
m_mutex.unlock();
}
void Zone::add(Sprite *sprite) {
sprite->setZone(this);
if (sprite->id() != "") {
m_sprites[sprite->id()] = sprite;
}
auto task = dynamic_cast<Task*>(sprite);
if (task) {
task->post(Event::FinishTask);
m_taskProcessor->addTask(task);
}
}
void Zone::remove(Sprite *sprite) {
for (auto v : m_sprites) {
if (v.second == sprite) {
m_sprites.erase(v.first);
}
}
}
Sprite *Zone::getSprite(std::string id) {
return m_sprites[id];
}
Tile *Zone::getTile(int x, int y, int layer) {
return m_tiles.safeAt(x, y, layer);
}
void Zone::load() {
models::Zone zone;
core::read(zone, m_path);
m_tiles.allocate();
for (int l = 0; l < m_tiles.layers(); l++) {
for (int y = 0; y < m_tiles.tilesHigh(); y++) {
for (int x = 0; x < m_tiles.tilesWide(); x++) {
auto tile = m_tiles.at(x, y, l);
auto model = zone.Tiles[l][y][x];
tile->load(model);
auto oc = tile->getOccupant();
if (oc) {
oc->setAddress(Point(x, y));
add(oc);
}
}
}
}
m_loaded = true;
}
void Zone::unload() {
for (auto s : m_sprites) {
m_sprites.erase(s.first);
}
m_tiles.free();
m_loaded = false;
}
}
}
<commit_msg>Fixed not to crash if Zone and ZoneHeaders do not match up.<commit_after>/*
* Copyright 2013-2014 [email protected]
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "_etc.hpp"
#include "zone.hpp"
namespace wombat {
namespace world {
using common::Point;
using common::Bounds;
using core::Event;
using core::TaskState;
Zone::TileGrid::~TileGrid() {
free();
}
void Zone::TileGrid::setDimensions(int w, int h, int layers) {
m_tilesWide = w;
m_tilesHigh = h;
m_layers = layers;
}
void Zone::TileGrid::allocate() {
m_tiles = (Tile***) malloc(sizeof(Tile**) * m_layers);
for (int l = 0; l < m_layers; l++) {
m_tiles[l] = (Tile**) malloc(sizeof(Tile*) * m_tilesHigh);
for (int y = 0; y < m_tilesHigh; y++) {
m_tiles[l][y] = (Tile*) malloc(sizeof(Tile) * m_tilesWide);
Tile t;
for (int x = 0; x < m_tilesWide; x++) {
m_tiles[l][y][x] = t;
}
}
}
}
void Zone::TileGrid::free() {
if (m_tiles) {
for (int l = 0; l < m_layers; l++) {
for (int y = 0; y < m_tilesHigh; y++) {
::free(m_tiles[l][y]);
}
::free(m_tiles[l]);
}
::free(m_tiles);
m_tiles = nullptr;
}
}
int Zone::TileGrid::tilesWide() {
return m_tilesWide;
}
int Zone::TileGrid::tilesHigh() {
return m_tilesHigh;
}
int Zone::TileGrid::layers() {
return m_layers;
}
Zone::Zone(models::ZoneInstance model) {
models::ZoneHeader header;
core::read(header, model.ZoneHeader);
m_address = model.Address;
m_tiles.setDimensions(header.TilesWide, header.TilesHigh, header.Layers);
m_path = header.Zone;
m_taskProcessor->addTask(this);
m_taskProcessor->start();
}
Zone::~Zone() {
m_taskProcessor->stop();
m_taskProcessor->done();
delete m_taskProcessor;
}
TaskState Zone::run(core::Event e) {
switch (e.type()) {
case Event::Timeout:
if (m_dependents == 0) {
unload();
}
return 10000;
default:
return TaskState::Continue;
}
}
bool Zone::loaded() {
return m_loaded;
}
Bounds Zone::bounds() {
Bounds bnds;
bnds.X = TileWidth * m_address.X;
bnds.Y = TileHeight * m_address.Y;
bnds.Width = TileWidth * m_tiles.tilesWide();
bnds.Height = TileHeight * m_tiles.tilesHigh();
return bnds;
}
void Zone::draw(Bounds bnds,
Point translation, std::pair<Sprite*, common::Point> focus) {
auto loc = pt(bounds().pt1()) + translation;
for (auto l = 0; l < m_tiles.layers(); l++) {
for (auto y = bnds.Y; y < bnds.y2(); y += TileHeight) {
for (auto x = bnds.X; x < bnds.x2(); x += TileWidth) {
auto tile = m_tiles.at(x / TileWidth, y / TileHeight, l);
tile->draw(pt(addr(Point(x, y))) + loc);
}
}
}
for (auto l = 0; l < m_tiles.layers(); l++) {
for (auto y = bnds.Y; y < bnds.y2(); y += TileHeight) {
for (auto x = bnds.X; x < bnds.x2(); x += TileWidth) {
auto tile = m_tiles.at(x / TileWidth, y / TileHeight, l);
auto oc = tile->getOccupant();
if (oc) {
common::Point pt;
if (oc != focus.first) {
pt = world::pt(addr(Point(x, y))) + loc;
} else {
pt = focus.second;
}
oc->draw(tile, pt);
}
}
}
}
}
Point Zone::loc() {
return Point(TileWidth * m_address.X, TileHeight * m_address.Y);
}
void Zone::incDeps() {
m_mutex.lock();
m_dependents++;
if (m_dependents == 1 && !m_loaded) {
load();
}
m_mutex.unlock();
}
void Zone::decDeps() {
m_mutex.lock();
if (m_dependents > 0) {
m_dependents--;
}
m_mutex.unlock();
}
void Zone::add(Sprite *sprite) {
sprite->setZone(this);
if (sprite->id() != "") {
m_sprites[sprite->id()] = sprite;
}
auto task = dynamic_cast<Task*>(sprite);
if (task) {
task->post(Event::FinishTask);
m_taskProcessor->addTask(task);
}
}
void Zone::remove(Sprite *sprite) {
for (auto v : m_sprites) {
if (v.second == sprite) {
m_sprites.erase(v.first);
}
}
}
Sprite *Zone::getSprite(std::string id) {
return m_sprites[id];
}
Tile *Zone::getTile(int x, int y, int layer) {
return m_tiles.safeAt(x, y, layer);
}
void Zone::load() {
models::Zone zone;
core::read(zone, m_path);
m_tiles.allocate();
zone.Tiles.resize(m_tiles.layers());
for (int l = 0; l < m_tiles.layers(); l++) {
zone.Tiles[l].resize(m_tiles.tilesHigh());
for (int y = 0; y < m_tiles.tilesHigh(); y++) {
zone.Tiles[l][y].resize(m_tiles.tilesWide());
for (int x = 0; x < m_tiles.tilesWide(); x++) {
auto tile = m_tiles.at(x, y, l);
auto model = zone.Tiles[l][y][x];
tile->load(model);
auto oc = tile->getOccupant();
if (oc) {
oc->setAddress(Point(x, y));
add(oc);
}
}
}
}
m_loaded = true;
}
void Zone::unload() {
for (auto s : m_sprites) {
m_sprites.erase(s.first);
}
m_tiles.free();
m_loaded = false;
}
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <unotools/textsearch.hxx>
#include "chgviset.hxx"
#include "rechead.hxx"
#include "chgtrack.hxx"
#include "document.hxx"
// -----------------------------------------------------------------------
ScChangeViewSettings::~ScChangeViewSettings()
{
if(pCommentSearcher!=NULL)
delete pCommentSearcher;
}
ScChangeViewSettings::ScChangeViewSettings( const ScChangeViewSettings& r )
:
aFirstDateTime( DateTime::EMPTY ),
aLastDateTime( DateTime::EMPTY )
{
SetTheComment(r.aComment);
aFirstDateTime =r.aFirstDateTime;
aLastDateTime =r.aLastDateTime;
aAuthorToShow =r.aAuthorToShow;
aRangeList =r.aRangeList;
eDateMode =r.eDateMode;
bShowIt =r.bShowIt;
bIsDate =r.bIsDate;
bIsAuthor =r.bIsAuthor;
bIsComment =r.bIsComment;
bIsRange =r.bIsRange;
bEveryoneButMe =r.bEveryoneButMe;
bShowAccepted =r.bShowAccepted;
bShowRejected =r.bShowRejected;
mbIsActionRange = r.mbIsActionRange;
mnFirstAction = r.mnFirstAction;
mnLastAction = r.mnLastAction;
}
ScChangeViewSettings& ScChangeViewSettings::operator=( const ScChangeViewSettings& r )
{
SetTheComment(r.aComment);
aFirstDateTime =r.aFirstDateTime;
aLastDateTime =r.aLastDateTime;
aAuthorToShow =r.aAuthorToShow;
aRangeList =r.aRangeList;
eDateMode =r.eDateMode;
bShowIt =r.bShowIt;
bIsDate =r.bIsDate;
bIsAuthor =r.bIsAuthor;
bIsComment =r.bIsComment;
bIsRange =r.bIsRange;
bEveryoneButMe =r.bEveryoneButMe;
bShowAccepted =r.bShowAccepted;
bShowRejected =r.bShowRejected;
mbIsActionRange = r.mbIsActionRange;
mnFirstAction = r.mnFirstAction;
mnLastAction = r.mnLastAction;
return *this;
}
sal_Bool ScChangeViewSettings::IsValidComment(const OUString* pCommentStr) const
{
sal_Bool nTheFlag=sal_True;
if(pCommentSearcher!=NULL)
{
sal_Int32 nStartPos = 0;
sal_Int32 nEndPos = pCommentStr->getLength();
nTheFlag=pCommentSearcher->SearchForward(*pCommentStr, &nStartPos, &nEndPos);
}
return nTheFlag;
}
void ScChangeViewSettings::SetTheComment(const OUString& rString)
{
aComment=rString;
if(pCommentSearcher!=NULL)
{
delete pCommentSearcher;
pCommentSearcher=NULL;
}
if(!rString.isEmpty())
{
utl::SearchParam aSearchParam( rString,
utl::SearchParam::SRCH_REGEXP,false,false,false );
pCommentSearcher = new utl::TextSearch( aSearchParam, *ScGlobal::pCharClass );
}
}
void ScChangeViewSettings::AdjustDateMode( const ScDocument& rDoc )
{
switch ( eDateMode )
{ // corresponds with ScViewUtil::IsActionShown
case SCDM_DATE_EQUAL :
case SCDM_DATE_NOTEQUAL :
aFirstDateTime.SetTime( 0 );
aLastDateTime = aFirstDateTime;
aLastDateTime.SetTime( 23595999 );
break;
case SCDM_DATE_SAVE:
{
const ScChangeAction* pLast = 0;
ScChangeTrack* pTrack = rDoc.GetChangeTrack();
if ( pTrack )
{
pLast = pTrack->GetLastSaved();
if ( pLast )
{
aFirstDateTime = pLast->GetDateTime();
// Set the next minute as the start time and assume that
// the document isn't saved, reloaded, edited and filter set
// all together during the gap between those two times.
aFirstDateTime += Time( 0, 1 );
aFirstDateTime.SetSec(0);
aFirstDateTime.SetNanoSec(0);
}
}
if ( !pLast )
{
aFirstDateTime.SetDate( 18990101 );
aFirstDateTime.SetTime( 0 );
}
aLastDateTime = Date( Date::SYSTEM );
aLastDateTime.SetYear( aLastDateTime.GetYear() + 100 );
}
break;
default:
{
// added to avoid warnings
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>CID#1079183: unitialized pointer value<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <unotools/textsearch.hxx>
#include "chgviset.hxx"
#include "rechead.hxx"
#include "chgtrack.hxx"
#include "document.hxx"
// -----------------------------------------------------------------------
ScChangeViewSettings::~ScChangeViewSettings()
{
delete pCommentSearcher;
}
ScChangeViewSettings::ScChangeViewSettings( const ScChangeViewSettings& r ):
pCommentSearcher(NULL),
aFirstDateTime( DateTime::EMPTY ),
aLastDateTime( DateTime::EMPTY )
{
SetTheComment(r.aComment);
aFirstDateTime =r.aFirstDateTime;
aLastDateTime =r.aLastDateTime;
aAuthorToShow =r.aAuthorToShow;
aRangeList =r.aRangeList;
eDateMode =r.eDateMode;
bShowIt =r.bShowIt;
bIsDate =r.bIsDate;
bIsAuthor =r.bIsAuthor;
bIsComment =r.bIsComment;
bIsRange =r.bIsRange;
bEveryoneButMe =r.bEveryoneButMe;
bShowAccepted =r.bShowAccepted;
bShowRejected =r.bShowRejected;
mbIsActionRange = r.mbIsActionRange;
mnFirstAction = r.mnFirstAction;
mnLastAction = r.mnLastAction;
}
ScChangeViewSettings& ScChangeViewSettings::operator=( const ScChangeViewSettings& r )
{
pCommentSearcher = NULL;
SetTheComment(r.aComment);
aFirstDateTime =r.aFirstDateTime;
aLastDateTime =r.aLastDateTime;
aAuthorToShow =r.aAuthorToShow;
aRangeList =r.aRangeList;
eDateMode =r.eDateMode;
bShowIt =r.bShowIt;
bIsDate =r.bIsDate;
bIsAuthor =r.bIsAuthor;
bIsComment =r.bIsComment;
bIsRange =r.bIsRange;
bEveryoneButMe =r.bEveryoneButMe;
bShowAccepted =r.bShowAccepted;
bShowRejected =r.bShowRejected;
mbIsActionRange = r.mbIsActionRange;
mnFirstAction = r.mnFirstAction;
mnLastAction = r.mnLastAction;
return *this;
}
sal_Bool ScChangeViewSettings::IsValidComment(const OUString* pCommentStr) const
{
bool nTheFlag = true;
if(pCommentSearcher)
{
sal_Int32 nStartPos = 0;
sal_Int32 nEndPos = pCommentStr->getLength();
nTheFlag = pCommentSearcher->SearchForward(*pCommentStr, &nStartPos, &nEndPos);
}
return nTheFlag;
}
void ScChangeViewSettings::SetTheComment(const OUString& rString)
{
aComment = rString;
if(pCommentSearcher)
{
delete pCommentSearcher;
pCommentSearcher=NULL;
}
if(!rString.isEmpty())
{
utl::SearchParam aSearchParam( rString,
utl::SearchParam::SRCH_REGEXP,false,false,false );
pCommentSearcher = new utl::TextSearch( aSearchParam, *ScGlobal::pCharClass );
}
}
void ScChangeViewSettings::AdjustDateMode( const ScDocument& rDoc )
{
switch ( eDateMode )
{ // corresponds with ScViewUtil::IsActionShown
case SCDM_DATE_EQUAL :
case SCDM_DATE_NOTEQUAL :
aFirstDateTime.SetTime( 0 );
aLastDateTime = aFirstDateTime;
aLastDateTime.SetTime( 23595999 );
break;
case SCDM_DATE_SAVE:
{
const ScChangeAction* pLast = 0;
ScChangeTrack* pTrack = rDoc.GetChangeTrack();
if ( pTrack )
{
pLast = pTrack->GetLastSaved();
if ( pLast )
{
aFirstDateTime = pLast->GetDateTime();
// Set the next minute as the start time and assume that
// the document isn't saved, reloaded, edited and filter set
// all together during the gap between those two times.
aFirstDateTime += Time( 0, 1 );
aFirstDateTime.SetSec(0);
aFirstDateTime.SetNanoSec(0);
}
}
if ( !pLast )
{
aFirstDateTime.SetDate( 18990101 );
aFirstDateTime.SetTime( 0 );
}
aLastDateTime = Date( Date::SYSTEM );
aLastDateTime.SetYear( aLastDateTime.GetYear() + 100 );
}
break;
default:
{
// added to avoid warnings
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2007 Sebastian Sauer <[email protected]>
*
* This file is part of SuperKaramba.
*
* SuperKaramba is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* SuperKaramba is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SuperKaramba; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "plasmaengine.h"
#include <plasma/dataenginemanager.h>
#if 0
#include <QFile>
#include <QTextStream>
#endif
/// \internal helper function that translates plasma data into a QVariantMap.
QVariantMap dataToMap(Plasma::DataEngine::Data data)
{
QVariantMap map;
Plasma::DataEngine::DataIterator it(data);
while( it.hasNext() ) {
it.next();
map.insert(it.key(), it.value());
}
return map;
}
/*
/// \internal helper function that translates a QVariantMap into plasma data.
Plasma::DataEngine::Data mapToData(QVariantMap map)
{
Plasma::DataEngine::Data data;
for(QVariantMap::Iterator it = map.begin(); it != map.end(); ++it)
data.insert(it.key(), it.value());
return data;
}
*/
/*****************************************************************************************
* PlasmaSensorConnector
*/
/// \internal d-pointer class.
class PlasmaSensorConnector::Private
{
public:
Meter* meter;
QString source;
QString format;
};
PlasmaSensorConnector::PlasmaSensorConnector(Meter *meter, const QString& source) : QObject(meter), d(new Private)
{
//kDebug()<<"PlasmaSensorConnector Ctor"<<endl;
setObjectName(source);
d->meter = meter;
d->source = source;
}
PlasmaSensorConnector::~PlasmaSensorConnector()
{
//kDebug()<<"PlasmaSensorConnector Dtor"<<endl;
delete d;
}
Meter* PlasmaSensorConnector::meter() const
{
return d->meter;
}
QString PlasmaSensorConnector::source() const
{
return d->source;
}
void PlasmaSensorConnector::setSource(const QString& source)
{
d->source = source;
}
QString PlasmaSensorConnector::format() const
{
return d->format;
}
void PlasmaSensorConnector::setFormat(const QString& format)
{
d->format = format;
}
void PlasmaSensorConnector::dataUpdated(const QString& source, const Plasma::DataEngine::Data &data)
{
//kDebug()<<"PlasmaSensorConnector::dataUpdated d->source="<<d->source<<" source="<<source<<endl;
if( d->source.isEmpty() ) {
emit sourceUpdated(source, dataToMap(data));
return;
}
if( source != d->source ) {
return;
}
QString v = d->format;
Plasma::DataEngine::DataIterator it(data);
while( it.hasNext() ) {
it.next();
QString s = QString("%%1").arg( it.key() );
v.replace(s,it.value().toString());
}
d->meter->setValue(v);
}
/*****************************************************************************************
* PlasmaSensor
*/
/// \internal d-pointer class.
class PlasmaSensor::Private
{
public:
Plasma::DataEngine* engine;
QString engineName;
explicit Private() : engine(0) {}
};
PlasmaSensor::PlasmaSensor(int msec) : Sensor(msec), d(new Private)
{
kDebug()<<"PlasmaSensor Ctor"<<endl;
}
PlasmaSensor::~PlasmaSensor()
{
kDebug()<<"PlasmaSensor Dtor"<<endl;
delete d;
}
Plasma::DataEngine* PlasmaSensor::engineImpl() const
{
return d->engine;
}
void PlasmaSensor::setEngineImpl(Plasma::DataEngine* engine, const QString& engineName)
{
d->engine = engine;
d->engineName = engineName;
}
QString PlasmaSensor::engine()
{
return d->engine ? d->engineName : QString();
}
void PlasmaSensor::setEngine(const QString& name)
{
//kDebug()<<"PlasmaSensor::setEngine name="<<name<<endl;
if( d->engine ) {
disconnect(d->engine, SIGNAL(newSource(QString)), this, SIGNAL(sourceAdded(QString)));
disconnect(d->engine, SIGNAL(sourceRemoved(QString)), this, SIGNAL(sourceRemoved(QString)));
Plasma::DataEngineManager::self()->unloadDataEngine(d->engineName);
}
d->engineName = QString();
d->engine = Plasma::DataEngineManager::self()->dataEngine(name);
if( ! d->engine || ! d->engine->isValid() ) {
d->engine = Plasma::DataEngineManager::self()->loadDataEngine(name);
if( ! d->engine || ! d->engine->isValid() ) {
kWarning()<<"PlasmaSensor::setEngine: No such engine: "<<name<<endl;
return;
}
}
d->engineName = name;
connect(d->engine, SIGNAL(newSource(QString)), this, SIGNAL(sourceAdded(QString)));
connect(d->engine, SIGNAL(sourceRemoved(QString)), this, SIGNAL(sourceRemoved(QString)));
//d->engine->setProperty("reportSeconds", true);
}
bool PlasmaSensor::isValid() const
{
return d->engine && d->engine->isValid();
}
QStringList PlasmaSensor::sources() const
{
return d->engine ? d->engine->sources() : QStringList();
}
QVariant PlasmaSensor::property(const QByteArray& name) const
{
return d->engine ? d->engine->property(name) : QVariant();
}
void PlasmaSensor::setProperty(const QByteArray& name, const QVariant& value)
{
if( d->engine )
d->engine->setProperty(name, value);
}
QVariantMap PlasmaSensor::query(const QString& source)
{
//kDebug()<<"PlasmaSensor::query"<<endl;
return d->engine ? dataToMap(d->engine->query(source)) : QVariantMap();
}
QObject* PlasmaSensor::connectSource(const QString& source, QObject* visualization)
{
//kDebug()<<"PlasmaSensor::connectSource source="<<source<<endl;
if( ! d->engine ) {
kWarning()<<"PlasmaSensor::connectSource: No engine"<<endl;
return 0;
}
if( Meter* m = dynamic_cast<Meter*>(visualization) ) {
PlasmaSensorConnector* c = new PlasmaSensorConnector(m, source);
d->engine->connectSource(source, c);
kDebug()<<"PlasmaSensor::connectSource meter, engine isValid="<<d->engine->isValid()<<" isUsed="<<d->engine->isUsed()<<endl;
return c;
}
d->engine->connectSource(source, visualization ? visualization : this);
return 0;
}
void PlasmaSensor::disconnectSource(const QString& source, QObject* visualization)
{
//kDebug()<<"PlasmaSensor::disconnectSource"<<endl;
if( Meter* m = dynamic_cast<Meter*>(visualization) ) {
foreach(PlasmaSensorConnector* c, m->findChildren<PlasmaSensorConnector*>(source))
if( c->meter() == m )
delete c;
}
else if( d->engine ) {
d->engine->disconnectSource(source, visualization ? visualization : this);
}
else
kWarning()<<"PlasmaSensor::disconnectSource: No engine"<<endl;
}
void PlasmaSensor::update()
{
kDebug()<<"PlasmaSensor::update"<<endl;
/*TODO
foreach(QObject *it, *objList) {
SensorParams *sp = qobject_cast<SensorParams*>(it);
Meter *meter = sp->getMeter();
const QString format = sp->getParam("FORMAT");
//if (format.length() == 0) format = "%um";
//format.replace(QRegExp("%fmb", Qt::CaseInsensitive),QString::number((int)((totalMem - usedMemNoBuffers) / 1024.0 + 0.5)));
//meter->setValue(format);
}
*/
}
void PlasmaSensor::dataUpdated(const QString& source, Plasma::DataEngine::Data data)
{
//kDebug()<<"PlasmaSensor::dataUpdated source="<<source<<endl;
emit sourceUpdated(source, dataToMap(data));
}
#include "plasmaengine.moc"
<commit_msg>Adapt to new api<commit_after>/*
* Copyright (C) 2007 Sebastian Sauer <[email protected]>
*
* This file is part of SuperKaramba.
*
* SuperKaramba is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* SuperKaramba is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SuperKaramba; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "plasmaengine.h"
#include <plasma/dataenginemanager.h>
#if 0
#include <QFile>
#include <QTextStream>
#endif
/// \internal helper function that translates plasma data into a QVariantMap.
QVariantMap dataToMap(Plasma::DataEngine::Data data)
{
QVariantMap map;
Plasma::DataEngine::DataIterator it(data);
while( it.hasNext() ) {
it.next();
map.insert(it.key(), it.value());
}
return map;
}
/*
/// \internal helper function that translates a QVariantMap into plasma data.
Plasma::DataEngine::Data mapToData(QVariantMap map)
{
Plasma::DataEngine::Data data;
for(QVariantMap::Iterator it = map.begin(); it != map.end(); ++it)
data.insert(it.key(), it.value());
return data;
}
*/
/*****************************************************************************************
* PlasmaSensorConnector
*/
/// \internal d-pointer class.
class PlasmaSensorConnector::Private
{
public:
Meter* meter;
QString source;
QString format;
};
PlasmaSensorConnector::PlasmaSensorConnector(Meter *meter, const QString& source) : QObject(meter), d(new Private)
{
//kDebug()<<"PlasmaSensorConnector Ctor"<<endl;
setObjectName(source);
d->meter = meter;
d->source = source;
}
PlasmaSensorConnector::~PlasmaSensorConnector()
{
//kDebug()<<"PlasmaSensorConnector Dtor"<<endl;
delete d;
}
Meter* PlasmaSensorConnector::meter() const
{
return d->meter;
}
QString PlasmaSensorConnector::source() const
{
return d->source;
}
void PlasmaSensorConnector::setSource(const QString& source)
{
d->source = source;
}
QString PlasmaSensorConnector::format() const
{
return d->format;
}
void PlasmaSensorConnector::setFormat(const QString& format)
{
d->format = format;
}
void PlasmaSensorConnector::dataUpdated(const QString& source, const Plasma::DataEngine::Data &data)
{
//kDebug()<<"PlasmaSensorConnector::dataUpdated d->source="<<d->source<<" source="<<source<<endl;
if( d->source.isEmpty() ) {
emit sourceUpdated(source, dataToMap(data));
return;
}
if( source != d->source ) {
return;
}
QString v = d->format;
Plasma::DataEngine::DataIterator it(data);
while( it.hasNext() ) {
it.next();
QString s = QString("%%1").arg( it.key() );
v.replace(s,it.value().toString());
}
d->meter->setValue(v);
}
/*****************************************************************************************
* PlasmaSensor
*/
/// \internal d-pointer class.
class PlasmaSensor::Private
{
public:
Plasma::DataEngine* engine;
QString engineName;
explicit Private() : engine(0) {}
};
PlasmaSensor::PlasmaSensor(int msec) : Sensor(msec), d(new Private)
{
kDebug()<<"PlasmaSensor Ctor"<<endl;
}
PlasmaSensor::~PlasmaSensor()
{
kDebug()<<"PlasmaSensor Dtor"<<endl;
delete d;
}
Plasma::DataEngine* PlasmaSensor::engineImpl() const
{
return d->engine;
}
void PlasmaSensor::setEngineImpl(Plasma::DataEngine* engine, const QString& engineName)
{
d->engine = engine;
d->engineName = engineName;
}
QString PlasmaSensor::engine()
{
return d->engine ? d->engineName : QString();
}
void PlasmaSensor::setEngine(const QString& name)
{
//kDebug()<<"PlasmaSensor::setEngine name="<<name<<endl;
if( d->engine ) {
disconnect(d->engine, SIGNAL(newSource(QString)), this, SIGNAL(sourceAdded(QString)));
disconnect(d->engine, SIGNAL(sourceRemoved(QString)), this, SIGNAL(sourceRemoved(QString)));
Plasma::DataEngineManager::self()->unload(d->engineName);
}
d->engineName = QString();
d->engine = Plasma::DataEngineManager::self()->get(name);
if( ! d->engine || ! d->engine->isValid() ) {
d->engine = Plasma::DataEngineManager::self()->load(name);
if( ! d->engine || ! d->engine->isValid() ) {
kWarning()<<"PlasmaSensor::setEngine: No such engine: "<<name<<endl;
return;
}
}
d->engineName = name;
connect(d->engine, SIGNAL(newSource(QString)), this, SIGNAL(sourceAdded(QString)));
connect(d->engine, SIGNAL(sourceRemoved(QString)), this, SIGNAL(sourceRemoved(QString)));
//d->engine->setProperty("reportSeconds", true);
}
bool PlasmaSensor::isValid() const
{
return d->engine && d->engine->isValid();
}
QStringList PlasmaSensor::sources() const
{
return d->engine ? d->engine->sources() : QStringList();
}
QVariant PlasmaSensor::property(const QByteArray& name) const
{
return d->engine ? d->engine->property(name) : QVariant();
}
void PlasmaSensor::setProperty(const QByteArray& name, const QVariant& value)
{
if( d->engine )
d->engine->setProperty(name, value);
}
QVariantMap PlasmaSensor::query(const QString& source)
{
//kDebug()<<"PlasmaSensor::query"<<endl;
return d->engine ? dataToMap(d->engine->query(source)) : QVariantMap();
}
QObject* PlasmaSensor::connectSource(const QString& source, QObject* visualization)
{
//kDebug()<<"PlasmaSensor::connectSource source="<<source<<endl;
if( ! d->engine ) {
kWarning()<<"PlasmaSensor::connectSource: No engine"<<endl;
return 0;
}
if( Meter* m = dynamic_cast<Meter*>(visualization) ) {
PlasmaSensorConnector* c = new PlasmaSensorConnector(m, source);
d->engine->connectSource(source, c);
kDebug()<<"PlasmaSensor::connectSource meter, engine isValid="<<d->engine->isValid()<<" isUsed="<<d->engine->isUsed()<<endl;
return c;
}
d->engine->connectSource(source, visualization ? visualization : this);
return 0;
}
void PlasmaSensor::disconnectSource(const QString& source, QObject* visualization)
{
//kDebug()<<"PlasmaSensor::disconnectSource"<<endl;
if( Meter* m = dynamic_cast<Meter*>(visualization) ) {
foreach(PlasmaSensorConnector* c, m->findChildren<PlasmaSensorConnector*>(source))
if( c->meter() == m )
delete c;
}
else if( d->engine ) {
d->engine->disconnectSource(source, visualization ? visualization : this);
}
else
kWarning()<<"PlasmaSensor::disconnectSource: No engine"<<endl;
}
void PlasmaSensor::update()
{
kDebug()<<"PlasmaSensor::update"<<endl;
/*TODO
foreach(QObject *it, *objList) {
SensorParams *sp = qobject_cast<SensorParams*>(it);
Meter *meter = sp->getMeter();
const QString format = sp->getParam("FORMAT");
//if (format.length() == 0) format = "%um";
//format.replace(QRegExp("%fmb", Qt::CaseInsensitive),QString::number((int)((totalMem - usedMemNoBuffers) / 1024.0 + 0.5)));
//meter->setValue(format);
}
*/
}
void PlasmaSensor::dataUpdated(const QString& source, Plasma::DataEngine::Data data)
{
//kDebug()<<"PlasmaSensor::dataUpdated source="<<source<<endl;
emit sourceUpdated(source, dataToMap(data));
}
#include "plasmaengine.moc"
<|endoftext|> |
<commit_before>#include <boost/bind.hpp>
#include "serializer/serializer.hpp"
#include "arch/coroutines.hpp"
serializer_t::index_write_op_t::index_write_op_t(
block_id_t block_id,
boost::optional<boost::shared_ptr<block_token_t> > token,
boost::optional<repli_timestamp_t> recency,
boost::optional<bool> delete_bit)
: block_id(block_id), token(token), recency(recency), delete_bit(delete_bit) {}
void serializer_t::index_write(const index_write_op_t &op, file_t::account_t *io_account) {
std::vector<index_write_op_t> ops;
ops.push_back(op);
return index_write(ops, io_account);
}
// Blocking block_write implementation
boost::shared_ptr<serializer_t::block_token_t>
serializer_t::block_write(const void *buf, file_t::account_t *io_account) {
// Default implementation: Wrap around non-blocking variant
struct : public cond_t, public iocallback_t {
void on_io_complete() { pulse(); }
} cb;
boost::shared_ptr<block_token_t> result = block_write(buf, io_account, &cb);
cb.wait();
return result;
}
boost::shared_ptr<serializer_t::block_token_t>
serializer_t::block_write(const void *buf, block_id_t block_id, file_t::account_t *io_account) {
// Default implementation: Wrap around non-blocking variant
struct : public cond_t, public iocallback_t {
void on_io_complete() { pulse(); }
} cb;
boost::shared_ptr<block_token_t> result = block_write(buf, block_id, io_account, &cb);
cb.wait();
return result;
}
boost::shared_ptr<serializer_t::block_token_t>
serializer_t::block_write(const void *buf, file_t::account_t *io_account, iocallback_t *cb) {
return block_write(buf, NULL_BLOCK_ID, io_account, cb);
}
// do_read implementation
static void do_read_wrapper(serializer_t *serializer, block_id_t block_id, void *buf,
file_t::account_t *io_account, serializer_t::read_callback_t *callback) {
serializer->block_read(serializer->index_read(block_id), buf, io_account);
callback->on_serializer_read();
}
bool serializer_t::do_read(block_id_t block_id, void *buf, file_t::account_t *io_account, read_callback_t *callback) {
// Just a wrapper around the new interface. TODO: Get rid of this eventually
coro_t::spawn(boost::bind(&do_read_wrapper, this, block_id, buf, io_account, callback));
return false;
}
// do_write implementation
struct block_write_cond_t : public cond_t, public iocallback_t {
block_write_cond_t(serializer_t::write_block_callback_t *cb) : callback(cb) { }
void on_io_complete() {
if (callback) callback->on_serializer_write_block();
pulse();
}
serializer_t::write_block_callback_t *callback;
};
static void do_write_wrapper(serializer_t *serializer,
serializer_t::write_t *writes,
int num_writes,
file_t::account_t *io_account,
serializer_t::write_txn_callback_t *callback,
serializer_t::write_tid_callback_t *tid_callback)
{
std::vector<block_write_cond_t*> block_write_conds;
block_write_conds.reserve(num_writes);
std::vector<serializer_t::index_write_op_t> index_write_ops;
// Prepare a zero buf for deletions
void *zerobuf = serializer->malloc();
bzero(zerobuf, serializer->get_block_size().value());
memcpy(zerobuf, "zero", 4); // TODO: This constant should be part of the serializer implementation or something like that or we should get rid of zero blocks completely...
// Step 1: Write buffers to disk and assemble index operations
for (size_t i = 0; i < (size_t)num_writes; ++i) {
const serializer_t::write_t& write = writes[i];
serializer_t::index_write_op_t op(write.block_id);
if (write.recency_specified) op.recency = write.recency;
// Buffer writes:
if (write.buf_specified) {
if (write.buf) {
block_write_conds.push_back(new block_write_cond_t(write.callback));
boost::shared_ptr<serializer_t::block_token_t> token = serializer->block_write(
write.buf, write.block_id, io_account, block_write_conds.back());
// also generate the corresponding index op
op.token = token;
op.delete_bit = false;
if (write.recency_specified) op.recency = write.recency;
} else {
// Deletion:
boost::shared_ptr<serializer_t::block_token_t> token;
if (write.write_empty_deleted_block) {
/* Extract might get confused if we delete a block, because it doesn't
* search the LBA for deletion entries. We clear things up for extract by
* writing a block with the block ID of the block to be deleted but zero
* contents. All that matters is that this block is on disk somewhere. */
block_write_conds.push_back(new block_write_cond_t(write.callback));
token = serializer->block_write(zerobuf, write.block_id, io_account, block_write_conds.back());
}
op.token = token;
op.delete_bit = true;
}
} else { // Recency update
rassert(write.recency_specified);
}
index_write_ops.push_back(op);
}
// Step 2: At the point where all writes have been started, we can call tid_callback
if (tid_callback) {
tid_callback->on_serializer_write_tid();
}
// Step 3: Wait on all writes to finish
for (size_t i = 0; i < block_write_conds.size(); ++i) {
block_write_conds[i]->wait();
delete block_write_conds[i];
}
// (free the zerobuf)
serializer->free(zerobuf);
// Step 4: Commit the transaction to the serializer
serializer->index_write(index_write_ops, io_account);
index_write_ops.clear(); // clean up index_write_ops; not strictly necessary
// Step 5: Call callback
callback->on_serializer_write_txn();
}
bool serializer_t::do_write(write_t *writes, int num_writes, file_t::account_t *io_account,
write_txn_callback_t *callback, write_tid_callback_t *tid_callback)
{
// Just a wrapper around the new interface.
coro_t::spawn(boost::bind(&do_write_wrapper, this, writes, num_writes, io_account, callback, tid_callback));
return false;
}
<commit_msg>check that no callback is specified for recency updates<commit_after>#include <boost/bind.hpp>
#include "serializer/serializer.hpp"
#include "arch/coroutines.hpp"
serializer_t::index_write_op_t::index_write_op_t(
block_id_t block_id,
boost::optional<boost::shared_ptr<block_token_t> > token,
boost::optional<repli_timestamp_t> recency,
boost::optional<bool> delete_bit)
: block_id(block_id), token(token), recency(recency), delete_bit(delete_bit) {}
void serializer_t::index_write(const index_write_op_t &op, file_t::account_t *io_account) {
std::vector<index_write_op_t> ops;
ops.push_back(op);
return index_write(ops, io_account);
}
// Blocking block_write implementation
boost::shared_ptr<serializer_t::block_token_t>
serializer_t::block_write(const void *buf, file_t::account_t *io_account) {
// Default implementation: Wrap around non-blocking variant
struct : public cond_t, public iocallback_t {
void on_io_complete() { pulse(); }
} cb;
boost::shared_ptr<block_token_t> result = block_write(buf, io_account, &cb);
cb.wait();
return result;
}
boost::shared_ptr<serializer_t::block_token_t>
serializer_t::block_write(const void *buf, block_id_t block_id, file_t::account_t *io_account) {
// Default implementation: Wrap around non-blocking variant
struct : public cond_t, public iocallback_t {
void on_io_complete() { pulse(); }
} cb;
boost::shared_ptr<block_token_t> result = block_write(buf, block_id, io_account, &cb);
cb.wait();
return result;
}
boost::shared_ptr<serializer_t::block_token_t>
serializer_t::block_write(const void *buf, file_t::account_t *io_account, iocallback_t *cb) {
return block_write(buf, NULL_BLOCK_ID, io_account, cb);
}
// do_read implementation
static void do_read_wrapper(serializer_t *serializer, block_id_t block_id, void *buf,
file_t::account_t *io_account, serializer_t::read_callback_t *callback) {
serializer->block_read(serializer->index_read(block_id), buf, io_account);
callback->on_serializer_read();
}
bool serializer_t::do_read(block_id_t block_id, void *buf, file_t::account_t *io_account, read_callback_t *callback) {
// Just a wrapper around the new interface. TODO: Get rid of this eventually
coro_t::spawn(boost::bind(&do_read_wrapper, this, block_id, buf, io_account, callback));
return false;
}
// do_write implementation
struct block_write_cond_t : public cond_t, public iocallback_t {
block_write_cond_t(serializer_t::write_block_callback_t *cb) : callback(cb) { }
void on_io_complete() {
if (callback) callback->on_serializer_write_block();
pulse();
}
serializer_t::write_block_callback_t *callback;
};
static void do_write_wrapper(serializer_t *serializer,
serializer_t::write_t *writes,
int num_writes,
file_t::account_t *io_account,
serializer_t::write_txn_callback_t *callback,
serializer_t::write_tid_callback_t *tid_callback)
{
std::vector<block_write_cond_t*> block_write_conds;
block_write_conds.reserve(num_writes);
std::vector<serializer_t::index_write_op_t> index_write_ops;
// Prepare a zero buf for deletions
void *zerobuf = serializer->malloc();
bzero(zerobuf, serializer->get_block_size().value());
memcpy(zerobuf, "zero", 4); // TODO: This constant should be part of the serializer implementation or something like that or we should get rid of zero blocks completely...
// Step 1: Write buffers to disk and assemble index operations
for (size_t i = 0; i < (size_t)num_writes; ++i) {
const serializer_t::write_t& write = writes[i];
serializer_t::index_write_op_t op(write.block_id);
if (write.recency_specified) op.recency = write.recency;
// Buffer writes:
if (write.buf_specified) {
if (write.buf) {
block_write_conds.push_back(new block_write_cond_t(write.callback));
boost::shared_ptr<serializer_t::block_token_t> token = serializer->block_write(
write.buf, write.block_id, io_account, block_write_conds.back());
// also generate the corresponding index op
op.token = token;
op.delete_bit = false;
if (write.recency_specified) op.recency = write.recency;
} else {
// Deletion:
boost::shared_ptr<serializer_t::block_token_t> token;
if (write.write_empty_deleted_block) {
/* Extract might get confused if we delete a block, because it doesn't
* search the LBA for deletion entries. We clear things up for extract by
* writing a block with the block ID of the block to be deleted but zero
* contents. All that matters is that this block is on disk somewhere. */
block_write_conds.push_back(new block_write_cond_t(write.callback));
token = serializer->block_write(zerobuf, write.block_id, io_account, block_write_conds.back());
}
op.token = token;
op.delete_bit = true;
}
} else { // Recency update
rassert(write.recency_specified);
rassert(!write.callback);
}
index_write_ops.push_back(op);
}
// Step 2: At the point where all writes have been started, we can call tid_callback
if (tid_callback) {
tid_callback->on_serializer_write_tid();
}
// Step 3: Wait on all writes to finish
for (size_t i = 0; i < block_write_conds.size(); ++i) {
block_write_conds[i]->wait();
delete block_write_conds[i];
}
// (free the zerobuf)
serializer->free(zerobuf);
// Step 4: Commit the transaction to the serializer
serializer->index_write(index_write_ops, io_account);
index_write_ops.clear(); // clean up index_write_ops; not strictly necessary
// Step 5: Call callback
callback->on_serializer_write_txn();
}
bool serializer_t::do_write(write_t *writes, int num_writes, file_t::account_t *io_account,
write_txn_callback_t *callback, write_tid_callback_t *tid_callback)
{
// Just a wrapper around the new interface.
coro_t::spawn(boost::bind(&do_write_wrapper, this, writes, num_writes, io_account, callback, tid_callback));
return false;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/audio_coding/codecs/red/audio_encoder_copy_red.h"
#include <string.h>
#include "webrtc/base/checks.h"
namespace webrtc {
AudioEncoderCopyRed::AudioEncoderCopyRed(const Config& config)
: speech_encoder_(config.speech_encoder),
red_payload_type_(config.payload_type),
secondary_allocated_(0) {
CHECK(speech_encoder_) << "Speech encoder not provided.";
}
AudioEncoderCopyRed::~AudioEncoderCopyRed() {
}
int AudioEncoderCopyRed::SampleRateHz() const {
return speech_encoder_->SampleRateHz();
}
int AudioEncoderCopyRed::RtpTimestampRateHz() const {
return speech_encoder_->RtpTimestampRateHz();
}
int AudioEncoderCopyRed::NumChannels() const {
return speech_encoder_->NumChannels();
}
int AudioEncoderCopyRed::Num10MsFramesInNextPacket() const {
return speech_encoder_->Num10MsFramesInNextPacket();
}
int AudioEncoderCopyRed::Max10MsFramesInAPacket() const {
return speech_encoder_->Max10MsFramesInAPacket();
}
void AudioEncoderCopyRed::SetTargetBitrate(int bits_per_second) {
speech_encoder_->SetTargetBitrate(bits_per_second);
}
void AudioEncoderCopyRed::SetProjectedPacketLossRate(double fraction) {
DCHECK_GE(fraction, 0.0);
DCHECK_LE(fraction, 1.0);
speech_encoder_->SetProjectedPacketLossRate(fraction);
}
bool AudioEncoderCopyRed::EncodeInternal(uint32_t rtp_timestamp,
const int16_t* audio,
size_t max_encoded_bytes,
uint8_t* encoded,
EncodedInfo* info) {
if (!speech_encoder_->Encode(rtp_timestamp, audio,
static_cast<size_t>(SampleRateHz() / 100),
max_encoded_bytes, encoded, info))
return false;
if (max_encoded_bytes < info->encoded_bytes + secondary_info_.encoded_bytes)
return false;
CHECK(info->redundant.empty()) << "Cannot use nested redundant encoders.";
if (info->encoded_bytes > 0) {
// |info| will be implicitly cast to an EncodedInfoLeaf struct, effectively
// discarding the (empty) vector of redundant information. This is
// intentional.
info->redundant.push_back(*info);
DCHECK_EQ(info->redundant.size(), 1u);
if (secondary_info_.encoded_bytes > 0) {
memcpy(&encoded[info->encoded_bytes], secondary_encoded_.get(),
secondary_info_.encoded_bytes);
info->redundant.push_back(secondary_info_);
DCHECK_EQ(info->redundant.size(), 2u);
}
// Save primary to secondary.
if (secondary_allocated_ < info->encoded_bytes) {
secondary_encoded_.reset(new uint8_t[info->encoded_bytes]);
secondary_allocated_ = info->encoded_bytes;
}
CHECK(secondary_encoded_);
memcpy(secondary_encoded_.get(), encoded, info->encoded_bytes);
secondary_info_ = *info;
}
// Update main EncodedInfo.
info->payload_type = red_payload_type_;
info->encoded_bytes = 0;
for (std::vector<EncodedInfoLeaf>::const_iterator it =
info->redundant.begin();
it != info->redundant.end(); ++it) {
info->encoded_bytes += it->encoded_bytes;
}
return true;
}
} // namespace webrtc
<commit_msg>AudioEncoderCopyRed: CHECK that encode call doesn't fail<commit_after>/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/audio_coding/codecs/red/audio_encoder_copy_red.h"
#include <string.h>
#include "webrtc/base/checks.h"
namespace webrtc {
AudioEncoderCopyRed::AudioEncoderCopyRed(const Config& config)
: speech_encoder_(config.speech_encoder),
red_payload_type_(config.payload_type),
secondary_allocated_(0) {
CHECK(speech_encoder_) << "Speech encoder not provided.";
}
AudioEncoderCopyRed::~AudioEncoderCopyRed() {
}
int AudioEncoderCopyRed::SampleRateHz() const {
return speech_encoder_->SampleRateHz();
}
int AudioEncoderCopyRed::RtpTimestampRateHz() const {
return speech_encoder_->RtpTimestampRateHz();
}
int AudioEncoderCopyRed::NumChannels() const {
return speech_encoder_->NumChannels();
}
int AudioEncoderCopyRed::Num10MsFramesInNextPacket() const {
return speech_encoder_->Num10MsFramesInNextPacket();
}
int AudioEncoderCopyRed::Max10MsFramesInAPacket() const {
return speech_encoder_->Max10MsFramesInAPacket();
}
void AudioEncoderCopyRed::SetTargetBitrate(int bits_per_second) {
speech_encoder_->SetTargetBitrate(bits_per_second);
}
void AudioEncoderCopyRed::SetProjectedPacketLossRate(double fraction) {
DCHECK_GE(fraction, 0.0);
DCHECK_LE(fraction, 1.0);
speech_encoder_->SetProjectedPacketLossRate(fraction);
}
bool AudioEncoderCopyRed::EncodeInternal(uint32_t rtp_timestamp,
const int16_t* audio,
size_t max_encoded_bytes,
uint8_t* encoded,
EncodedInfo* info) {
CHECK(speech_encoder_->Encode(rtp_timestamp, audio,
static_cast<size_t>(SampleRateHz() / 100),
max_encoded_bytes, encoded, info));
CHECK_GE(max_encoded_bytes,
info->encoded_bytes + secondary_info_.encoded_bytes);
CHECK(info->redundant.empty()) << "Cannot use nested redundant encoders.";
if (info->encoded_bytes > 0) {
// |info| will be implicitly cast to an EncodedInfoLeaf struct, effectively
// discarding the (empty) vector of redundant information. This is
// intentional.
info->redundant.push_back(*info);
DCHECK_EQ(info->redundant.size(), 1u);
if (secondary_info_.encoded_bytes > 0) {
memcpy(&encoded[info->encoded_bytes], secondary_encoded_.get(),
secondary_info_.encoded_bytes);
info->redundant.push_back(secondary_info_);
DCHECK_EQ(info->redundant.size(), 2u);
}
// Save primary to secondary.
if (secondary_allocated_ < info->encoded_bytes) {
secondary_encoded_.reset(new uint8_t[info->encoded_bytes]);
secondary_allocated_ = info->encoded_bytes;
}
CHECK(secondary_encoded_);
memcpy(secondary_encoded_.get(), encoded, info->encoded_bytes);
secondary_info_ = *info;
}
// Update main EncodedInfo.
info->payload_type = red_payload_type_;
info->encoded_bytes = 0;
for (std::vector<EncodedInfoLeaf>::const_iterator it =
info->redundant.begin();
it != info->redundant.end(); ++it) {
info->encoded_bytes += it->encoded_bytes;
}
return true;
}
} // namespace webrtc
<|endoftext|> |
<commit_before>/*
* This File is part of Davix, The IO library for HTTP based protocols
* Copyright (C) CERN 2017
* Author: Georgios Bitzes <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "S3IO.hpp"
#include <utils/davix_logger_internal.hpp>
#include <xml/S3MultiPartInitiationParser.hpp>
#define SSTR(message) static_cast<std::ostringstream&>(std::ostringstream().flush() << message).str()
namespace Davix{
static bool is_s3_operation(IOChainContext & context){
if(context._reqparams->getProtocol() == RequestProtocol::AwsS3) {
return true;
}
return false;
}
static bool should_use_s3_multipart(IOChainContext & context, dav_size_t size) {
bool is_s3 = is_s3_operation(context);
if(!is_s3) return false;
if(context._uri.fragmentParamExists("forceMultiPart")) {
return true;
}
return size > (1024 * 1024 * 512); // 512 MB
}
S3IO::S3IO() {
}
S3IO::~S3IO() {
}
std::string S3IO::initiateMultipart(IOChainContext & iocontext) {
Uri url(iocontext._uri);
url.addQueryParam("uploads", "");
return initiateMultipart(iocontext, url);
}
std::string S3IO::initiateMultipart(IOChainContext & iocontext, const Uri &url) {
DavixError * tmp_err=NULL;
PostRequest req(iocontext._context, url, &tmp_err);
checkDavixError(&tmp_err);
req.setParameters(iocontext._reqparams);
req.setRequestBody("");
req.executeRequest(&tmp_err);
if(!tmp_err && httpcodeIsValid(req.getRequestCode()) == false){
httpcodeToDavixError(req.getRequestCode(), davix_scope_io_buff(),
"write error: ", &tmp_err);
}
checkDavixError(&tmp_err);
std::string response = req.getAnswerContent();
S3MultiPartInitiationParser parser;
if(parser.parseChunk(response) != 0) {
DavixError::setupError(&tmp_err, "S3::MultiPart", StatusCode::InvalidServerResponse, "Unable to parse server response for multi-part initiation");
}
checkDavixError(&tmp_err);
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "Obtained multi-part upload id {} for {}", parser.getUploadId(), iocontext._uri);
return parser.getUploadId();
}
std::string S3IO::writeChunk(IOChainContext & iocontext, const char* buff, dav_size_t size, const std::string &uploadId, int partNumber) {
Uri url(iocontext._uri);
url.addQueryParam("uploadId", uploadId);
url.addQueryParam("partNumber", SSTR(partNumber));
return writeChunk(iocontext, buff, size, url, partNumber);
}
std::string S3IO::writeChunk(IOChainContext & iocontext, const char* buff, dav_size_t size, const Uri &url, int partNumber) {
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "writing chunk #{} with size {}", partNumber, size);
DavixError * tmp_err=NULL;
PutRequest req(iocontext._context, url, &tmp_err);
checkDavixError(&tmp_err);
req.setParameters(iocontext._reqparams);
req.setRequestBody(buff, size);
req.executeRequest(&tmp_err);
if(!tmp_err && httpcodeIsValid(req.getRequestCode()) == false){
httpcodeToDavixError(req.getRequestCode(), davix_scope_io_buff(),
"write error: ", &tmp_err);
}
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "write result size {}", size);
checkDavixError(&tmp_err);
std::string etag;
if(!req.getAnswerHeader("Etag", etag)) {
DavixError::setupError(&tmp_err, "S3::MultiPart", StatusCode::InvalidServerResponse, "Unable to retrieve chunk Etag, necessary when committing chunks");
}
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "chunk #{} written successfully, etag: {}", partNumber, etag);
return etag;
}
void S3IO::commitChunks(IOChainContext & iocontext, const std::string &uploadId, const std::vector<std::string> &etags) {
Uri url(iocontext._uri);
url.addQueryParam("uploadId", uploadId);
return commitChunks(iocontext, url, etags);
}
void S3IO::commitChunks(IOChainContext & iocontext, const Uri &url, const std::vector<std::string> &etags) {
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "committing {} chunks", etags.size());
std::ostringstream payload;
payload << "<CompleteMultipartUpload>";
for(size_t i = 1; i <= etags.size(); i++) {
payload << "<Part>";
payload << "<PartNumber>" << i << "</PartNumber>";
payload << "<ETag>" << etags[i-1] << "</ETag>";
payload << "</Part>";
}
payload << "</CompleteMultipartUpload>";
DavixError * tmp_err=NULL;
PostRequest req(iocontext._context, url, &tmp_err);
req.setParameters(iocontext._reqparams);
req.setRequestBody(payload.str());
req.executeRequest(&tmp_err);
if(!tmp_err && httpcodeIsValid(req.getRequestCode()) == false){
httpcodeToDavixError(req.getRequestCode(), davix_scope_io_buff(),
"write error: ", &tmp_err);
}
checkDavixError(&tmp_err);
}
static dav_ssize_t readFunction(int fd, void* buffer, dav_size_t size) {
dav_ssize_t ret = ::read(fd, buffer, size);
if(ret < 0) {
int myerr = errno;
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "Error in readFunction when attempting to read from fd {}: Return code {}, errno: {}", fd, ret, myerr);
}
return ret;
}
dav_ssize_t S3IO::writeFromFd(IOChainContext & iocontext, int fd, dav_size_t size) {
if(!should_use_s3_multipart(iocontext, size)) {
CHAIN_FORWARD(writeFromFd(iocontext, fd, size));
}
using std::placeholders::_1;
using std::placeholders::_2;
DataProviderFun providerFunc = std::bind(readFunction, fd, _1, _2);
return this->writeFromCb(iocontext, providerFunc, size);
}
static dav_size_t fillBufferWithProviderData(std::vector<char> &buffer, const dav_size_t maxChunkSize, const DataProviderFun &func) {
dav_size_t written = 0u;
dav_size_t remaining = maxChunkSize;
while(true) {
dav_ssize_t bytesRead = func(buffer.data(), remaining);
if(bytesRead < 0) {
throw DavixException(davix_scope_io_buff(), StatusCode::InvalidFileHandle, fmt::format("Error when reading from callback: {}", bytesRead));
}
remaining -= bytesRead;
written += bytesRead;
if(bytesRead == 0) break; // EOF
}
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "Retrieved {} bytes from data provider", written);
return written;
}
dav_ssize_t S3IO::writeFromCb(IOChainContext & iocontext, const DataProviderFun & func, dav_size_t size) {
if(!should_use_s3_multipart(iocontext, size)) {
CHAIN_FORWARD(writeFromCb(iocontext, func, size));
}
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "Initiating multi-part upload towards {} to upload file with size {}", iocontext._uri, size);
std::string uploadId = initiateMultipart(iocontext);
size_t remaining = size;
const dav_size_t MAX_CHUNK_SIZE = 1024 * 1024 * 256; // 256 MB
std::vector<char> buffer;
buffer.resize(std::min(MAX_CHUNK_SIZE, size) + 10);
std::vector<std::string> etags;
size_t partNumber = 0;
while(remaining > 0) {
size_t toRead = std::min(size, MAX_CHUNK_SIZE);
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "S3IO write: toRead from cb {}", toRead);
dav_size_t bytesRead = fillBufferWithProviderData(buffer, MAX_CHUNK_SIZE, func);
if(bytesRead == 0) break; // EOF
partNumber++;
etags.emplace_back(writeChunk(iocontext, buffer.data(), bytesRead, uploadId, partNumber));
}
commitChunks(iocontext, uploadId, etags);
}
DynafedUris S3IO::retrieveDynafedUris(IOChainContext & iocontext, const std::string &uploadId, const std::string &pluginId, size_t nchunks) {
DynafedUris retval;
DavixError *tmp_err = NULL;
PutRequest req(iocontext._context, iocontext._uri, &tmp_err);
checkDavixError(&tmp_err);
req.setParameters(iocontext._reqparams);
req.addHeaderField("x-s3-uploadid", uploadId);
req.addHeaderField("x-ugrpluginid", pluginId);
req.addHeaderField("x-s3-upload-nchunks", SSTR(nchunks));
req.executeRequest(&tmp_err);
if(!tmp_err && httpcodeIsValid(req.getRequestCode()) == false){
httpcodeToDavixError(req.getRequestCode(), davix_scope_io_buff(),
"write error: ", &tmp_err);
}
checkDavixError(&tmp_err);
// We have a response, parse it into lines
retval.chunks = StrUtil::tokenSplit(req.getAnswerContent(), "\n");
if(!retval.chunks.empty()) {
retval.post = retval.chunks.back();
retval.chunks.pop_back();
}
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "retrieveDynafedUris: Obtained list with {} chunk URIs in total", retval.chunks.size());
return retval;
}
void S3IO::performUgrS3MultiPart(IOChainContext & iocontext, const std::string &posturl, const std::string &pluginId, const DataProviderFun &func, dav_size_t size, DavixError **err) {
try {
Uri uri(posturl);
std::string uploadId = initiateMultipart(iocontext, posturl);
const dav_size_t MAX_CHUNK_SIZE = 1024 * 1024 * 256; // 256 MB
std::vector<char> buffer;
buffer.resize(std::min(MAX_CHUNK_SIZE, size) + 10);
size_t nchunks = (size / MAX_CHUNK_SIZE) + 2;
DynafedUris uris = retrieveDynafedUris(iocontext, uploadId, pluginId, nchunks);
if(uris.chunks.size() != nchunks) {
DAVIX_SLOG(DAVIX_LOG_WARNING, DAVIX_LOG_CHAIN, "Dynafed returned different number of URIs than expected: {} vs {]", "} retrieveDynafedUris: Obtained list with {} chunk URIs in total", uris.chunks.size(), nchunks);
throw DavixException("S3::MultiPart", StatusCode::InvalidServerResponse, "Dynafed returned different number of URIs than expected");
}
std::vector<std::string> etags;
size_t partNumber = 1;
uint64_t remaining = size;
while(remaining > 0) {
dav_size_t bytesRetrieved = fillBufferWithProviderData(buffer, MAX_CHUNK_SIZE, func);
if(bytesRetrieved == 0) {
break; // EOF
}
etags.emplace_back(writeChunk(iocontext, buffer.data(), bytesRetrieved, Uri(uris.chunks[partNumber-1]), partNumber));
partNumber++;
remaining -= bytesRetrieved;
}
commitChunks(iocontext, Uri(uris.post), etags);
}
CATCH_DAVIX(err);
}
}
<commit_msg>DMC-1135 Fix data provider usage in s3 multi-part<commit_after>/*
* This File is part of Davix, The IO library for HTTP based protocols
* Copyright (C) CERN 2017
* Author: Georgios Bitzes <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "S3IO.hpp"
#include <utils/davix_logger_internal.hpp>
#include <xml/S3MultiPartInitiationParser.hpp>
#define SSTR(message) static_cast<std::ostringstream&>(std::ostringstream().flush() << message).str()
namespace Davix{
static bool is_s3_operation(IOChainContext & context){
if(context._reqparams->getProtocol() == RequestProtocol::AwsS3) {
return true;
}
return false;
}
static bool should_use_s3_multipart(IOChainContext & context, dav_size_t size) {
bool is_s3 = is_s3_operation(context);
if(!is_s3) return false;
if(context._uri.fragmentParamExists("forceMultiPart")) {
return true;
}
return size > (1024 * 1024 * 512); // 512 MB
}
S3IO::S3IO() {
}
S3IO::~S3IO() {
}
std::string S3IO::initiateMultipart(IOChainContext & iocontext) {
Uri url(iocontext._uri);
url.addQueryParam("uploads", "");
return initiateMultipart(iocontext, url);
}
std::string S3IO::initiateMultipart(IOChainContext & iocontext, const Uri &url) {
DavixError * tmp_err=NULL;
PostRequest req(iocontext._context, url, &tmp_err);
checkDavixError(&tmp_err);
req.setParameters(iocontext._reqparams);
req.setRequestBody("");
req.executeRequest(&tmp_err);
if(!tmp_err && httpcodeIsValid(req.getRequestCode()) == false){
httpcodeToDavixError(req.getRequestCode(), davix_scope_io_buff(),
"write error: ", &tmp_err);
}
checkDavixError(&tmp_err);
std::string response = req.getAnswerContent();
S3MultiPartInitiationParser parser;
if(parser.parseChunk(response) != 0) {
DavixError::setupError(&tmp_err, "S3::MultiPart", StatusCode::InvalidServerResponse, "Unable to parse server response for multi-part initiation");
}
checkDavixError(&tmp_err);
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "Obtained multi-part upload id {} for {}", parser.getUploadId(), iocontext._uri);
return parser.getUploadId();
}
std::string S3IO::writeChunk(IOChainContext & iocontext, const char* buff, dav_size_t size, const std::string &uploadId, int partNumber) {
Uri url(iocontext._uri);
url.addQueryParam("uploadId", uploadId);
url.addQueryParam("partNumber", SSTR(partNumber));
return writeChunk(iocontext, buff, size, url, partNumber);
}
std::string S3IO::writeChunk(IOChainContext & iocontext, const char* buff, dav_size_t size, const Uri &url, int partNumber) {
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "writing chunk #{} with size {}", partNumber, size);
DavixError * tmp_err=NULL;
PutRequest req(iocontext._context, url, &tmp_err);
checkDavixError(&tmp_err);
req.setParameters(iocontext._reqparams);
req.setRequestBody(buff, size);
req.executeRequest(&tmp_err);
if(!tmp_err && httpcodeIsValid(req.getRequestCode()) == false){
httpcodeToDavixError(req.getRequestCode(), davix_scope_io_buff(),
"write error: ", &tmp_err);
}
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "write result size {}", size);
checkDavixError(&tmp_err);
std::string etag;
if(!req.getAnswerHeader("Etag", etag)) {
DavixError::setupError(&tmp_err, "S3::MultiPart", StatusCode::InvalidServerResponse, "Unable to retrieve chunk Etag, necessary when committing chunks");
}
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "chunk #{} written successfully, etag: {}", partNumber, etag);
return etag;
}
void S3IO::commitChunks(IOChainContext & iocontext, const std::string &uploadId, const std::vector<std::string> &etags) {
Uri url(iocontext._uri);
url.addQueryParam("uploadId", uploadId);
return commitChunks(iocontext, url, etags);
}
void S3IO::commitChunks(IOChainContext & iocontext, const Uri &url, const std::vector<std::string> &etags) {
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "committing {} chunks", etags.size());
std::ostringstream payload;
payload << "<CompleteMultipartUpload>";
for(size_t i = 1; i <= etags.size(); i++) {
payload << "<Part>";
payload << "<PartNumber>" << i << "</PartNumber>";
payload << "<ETag>" << etags[i-1] << "</ETag>";
payload << "</Part>";
}
payload << "</CompleteMultipartUpload>";
DavixError * tmp_err=NULL;
PostRequest req(iocontext._context, url, &tmp_err);
req.setParameters(iocontext._reqparams);
req.setRequestBody(payload.str());
req.executeRequest(&tmp_err);
if(!tmp_err && httpcodeIsValid(req.getRequestCode()) == false){
httpcodeToDavixError(req.getRequestCode(), davix_scope_io_buff(),
"write error: ", &tmp_err);
}
checkDavixError(&tmp_err);
}
static dav_ssize_t readFunction(int fd, void* buffer, dav_size_t size) {
dav_ssize_t ret = ::read(fd, buffer, size);
if(ret < 0) {
int myerr = errno;
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "Error in readFunction when attempting to read from fd {}: Return code {}, errno: {}", fd, ret, myerr);
}
return ret;
}
dav_ssize_t S3IO::writeFromFd(IOChainContext & iocontext, int fd, dav_size_t size) {
if(!should_use_s3_multipart(iocontext, size)) {
CHAIN_FORWARD(writeFromFd(iocontext, fd, size));
}
using std::placeholders::_1;
using std::placeholders::_2;
DataProviderFun providerFunc = std::bind(readFunction, fd, _1, _2);
return this->writeFromCb(iocontext, providerFunc, size);
}
static dav_size_t fillBufferWithProviderData(std::vector<char> &buffer, const dav_size_t maxChunkSize, const DataProviderFun &func) {
dav_size_t written = 0u;
dav_size_t remaining = maxChunkSize;
while(true) {
dav_ssize_t bytesRead = func(buffer.data(), remaining);
if(bytesRead < 0) {
throw DavixException(davix_scope_io_buff(), StatusCode::InvalidFileHandle, fmt::format("Error when reading from callback: {}", bytesRead));
}
remaining -= bytesRead;
written += bytesRead;
if(bytesRead == 0) {
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "Reached data provider EOF, received 0 bytes, even though asked for {}", remaining);
break; // EOF
}
if(remaining == 0) {
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "Data provider buffer has been filled");
break; // buffer is full
}
}
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "Retrieved {} bytes from data provider", written);
return written;
}
dav_ssize_t S3IO::writeFromCb(IOChainContext & iocontext, const DataProviderFun & func, dav_size_t size) {
if(!should_use_s3_multipart(iocontext, size)) {
CHAIN_FORWARD(writeFromCb(iocontext, func, size));
}
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "Initiating multi-part upload towards {} to upload file with size {}", iocontext._uri, size);
std::string uploadId = initiateMultipart(iocontext);
size_t remaining = size;
const dav_size_t MAX_CHUNK_SIZE = 1024 * 1024 * 256; // 256 MB
std::vector<char> buffer;
buffer.resize(std::min(MAX_CHUNK_SIZE, size) + 10);
std::vector<std::string> etags;
size_t partNumber = 0;
while(remaining > 0) {
size_t toRead = std::min(size, MAX_CHUNK_SIZE);
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "S3IO write: toRead from cb {}", toRead);
dav_size_t bytesRead = fillBufferWithProviderData(buffer, MAX_CHUNK_SIZE, func);
if(bytesRead == 0) break; // EOF
partNumber++;
etags.emplace_back(writeChunk(iocontext, buffer.data(), bytesRead, uploadId, partNumber));
}
commitChunks(iocontext, uploadId, etags);
}
DynafedUris S3IO::retrieveDynafedUris(IOChainContext & iocontext, const std::string &uploadId, const std::string &pluginId, size_t nchunks) {
DynafedUris retval;
DavixError *tmp_err = NULL;
PutRequest req(iocontext._context, iocontext._uri, &tmp_err);
checkDavixError(&tmp_err);
req.setParameters(iocontext._reqparams);
req.addHeaderField("x-s3-uploadid", uploadId);
req.addHeaderField("x-ugrpluginid", pluginId);
req.addHeaderField("x-s3-upload-nchunks", SSTR(nchunks));
req.executeRequest(&tmp_err);
if(!tmp_err && httpcodeIsValid(req.getRequestCode()) == false){
httpcodeToDavixError(req.getRequestCode(), davix_scope_io_buff(),
"write error: ", &tmp_err);
}
checkDavixError(&tmp_err);
// We have a response, parse it into lines
retval.chunks = StrUtil::tokenSplit(req.getAnswerContent(), "\n");
if(!retval.chunks.empty()) {
retval.post = retval.chunks.back();
retval.chunks.pop_back();
}
DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_CHAIN, "retrieveDynafedUris: Obtained list with {} chunk URIs in total", retval.chunks.size());
return retval;
}
void S3IO::performUgrS3MultiPart(IOChainContext & iocontext, const std::string &posturl, const std::string &pluginId, const DataProviderFun &func, dav_size_t size, DavixError **err) {
try {
Uri uri(posturl);
std::string uploadId = initiateMultipart(iocontext, posturl);
const dav_size_t MAX_CHUNK_SIZE = 1024 * 1024 * 256; // 256 MB
std::vector<char> buffer;
buffer.resize(std::min(MAX_CHUNK_SIZE, size) + 10);
size_t nchunks = (size / MAX_CHUNK_SIZE) + 2;
DynafedUris uris = retrieveDynafedUris(iocontext, uploadId, pluginId, nchunks);
if(uris.chunks.size() != nchunks) {
DAVIX_SLOG(DAVIX_LOG_WARNING, DAVIX_LOG_CHAIN, "Dynafed returned different number of URIs than expected: {} vs {]", "} retrieveDynafedUris: Obtained list with {} chunk URIs in total", uris.chunks.size(), nchunks);
throw DavixException("S3::MultiPart", StatusCode::InvalidServerResponse, "Dynafed returned different number of URIs than expected");
}
std::vector<std::string> etags;
size_t partNumber = 1;
uint64_t remaining = size;
while(remaining > 0) {
dav_size_t bytesRetrieved = fillBufferWithProviderData(buffer, MAX_CHUNK_SIZE, func);
if(bytesRetrieved == 0) {
break; // EOF
}
etags.emplace_back(writeChunk(iocontext, buffer.data(), bytesRetrieved, Uri(uris.chunks[partNumber-1]), partNumber));
partNumber++;
remaining -= bytesRetrieved;
}
commitChunks(iocontext, Uri(uris.post), etags);
}
CATCH_DAVIX(err);
}
}
<|endoftext|> |
<commit_before>#include "GenericIO.h"
#include <memory>
#include "MatrixIO.h"
#include "TensorIO.h"
#include "DataWriter.h"
#include <SmurffCpp/Utils/Error.h>
using namespace smurff;
std::shared_ptr<TensorConfig> generic_io::read_data_config(const std::string& filename, bool isScarce)
{
try
{
if(matrix_io::ExtensionToMatrixType(filename) == matrix_io::MatrixType::csv)
{
THROWERROR("csv input is not allowed for matrix data");
}
//read will throw exception if file extension is not correct
return matrix_io::read_matrix(filename, isScarce);
}
catch(std::runtime_error& ex1)
{
try
{
if(tensor_io::ExtensionToTensorType(filename) == tensor_io::TensorType::csv)
{
THROWERROR("csv input is not allowed for tensor data");
}
//read will throw exception if file extension is not correct
return tensor_io::read_tensor(filename, isScarce);
}
catch(std::runtime_error& ex2)
{
THROWERROR("Wrong file format " + filename + ". " + ex2.what());
}
}
}
void generic_io::write_data_config(const std::string& filename, std::shared_ptr<TensorConfig> tensorConfig)
{
tensorConfig->write(std::make_shared<DataWriter>(filename));
}
bool generic_io::file_exists(const std::string& filepath)
{
std::ifstream infile(filepath.c_str());
return infile.good();
}
<commit_msg>Better error message when a file does not exist<commit_after>#include "GenericIO.h"
#include <memory>
#include "MatrixIO.h"
#include "TensorIO.h"
#include "DataWriter.h"
#include <SmurffCpp/Utils/Error.h>
using namespace smurff;
std::shared_ptr<TensorConfig> generic_io::read_data_config(const std::string& filename, bool isScarce)
{
THROWERROR_FILE_NOT_EXIST(filename);
try
{
if(matrix_io::ExtensionToMatrixType(filename) == matrix_io::MatrixType::csv)
{
THROWERROR("csv input is not allowed for matrix data");
}
//read will throw exception if file extension is not correct
return matrix_io::read_matrix(filename, isScarce);
}
catch(std::runtime_error& ex1)
{
try
{
if(tensor_io::ExtensionToTensorType(filename) == tensor_io::TensorType::csv)
{
THROWERROR("csv input is not allowed for tensor data");
}
//read will throw exception if file extension is not correct
return tensor_io::read_tensor(filename, isScarce);
}
catch(std::runtime_error& ex2)
{
THROWERROR("Could not read tensor/matrix file: " + filename +
"\n Both Matrix and Tensor file formats tried. Both gave an error.\n " +
ex2.what() + "\n " +
ex1.what());
}
}
}
void generic_io::write_data_config(const std::string& filename, std::shared_ptr<TensorConfig> tensorConfig)
{
tensorConfig->write(std::make_shared<DataWriter>(filename));
}
bool generic_io::file_exists(const std::string& filepath)
{
std::ifstream infile(filepath.c_str());
return infile.good();
}
<|endoftext|> |
<commit_before>
#include "swganh/simulation/scene.h"
#include <algorithm>
#include "swganh/object/object.h"
using namespace std;
using namespace swganh::object;
using namespace swganh::simulation;
class Scene::SceneImpl
{
public:
SceneImpl(SceneDescription description)
: description_(move(description))
{}
const SceneDescription& GetDescription() const
{
return description_;
}
void AddObject(const shared_ptr<Object>& object)
{
InsertObject(object);
for_each(begin(object_map_), end(object_map_),
[&object] (const ObjectMap::value_type& object_entry)
{
auto& stored_object = object_entry.second;
stored_object->AddAwareObject(object);
object->AddAwareObject(stored_object);
});
}
void RemoveObject(const shared_ptr<Object>& object)
{
EraseObject(object);
for_each(begin(object_map_), end(object_map_),
[&object] (const ObjectMap::value_type& object_entry)
{
auto& stored_object = object_entry.second;
stored_object->RemoveContainedObject(object);
stored_object->RemoveAwareObject(object);
});
}
void InsertObject(const shared_ptr<Object>& object)
{
// make sure it's not already there
auto find_iter = objects_.find(object);
if (find_iter == end(objects_))
objects_.insert(find_iter, object);
auto find_map = object_map_.find(object->GetObjectId());
if (find_map == end(object_map_))
object_map_.insert(find_map, ObjectPair(object->GetObjectId(), object));
}
void EraseObject(const shared_ptr<Object>& object)
{
objects_.erase(object);
object_map_.erase(object->GetObjectId());
}
private:
typedef std::map<
uint64_t,
shared_ptr<Object>
> ObjectMap;
typedef std::pair<
uint64_t,
shared_ptr<Object>
> ObjectPair;
typedef std::set<std::shared_ptr<Object>> ObjectSet;
ObjectSet objects_;
ObjectMap object_map_;
SceneDescription description_;
};
Scene::Scene(SceneDescription description)
: impl_(new SceneImpl(move(description)))
{}
Scene::Scene(uint32_t scene_id, string name, string label, string description, string terrain)
{
SceneDescription scene_description;
scene_description.id = scene_id;
scene_description.name = move(name);
scene_description.label = move(label);
scene_description.description = move(description);
scene_description.terrain = move(terrain);
impl_.reset(new SceneImpl(move(scene_description)));
}
uint32_t Scene::GetSceneId() const
{
return impl_->GetDescription().id;
}
const std::string& Scene::GetName() const
{
return impl_->GetDescription().name;
}
const std::string& Scene::GetLabel() const
{
return impl_->GetDescription().label;
}
const std::string& Scene::GetDescription() const
{
return impl_->GetDescription().description;
}
const std::string& Scene::GetTerrainMap() const
{
return impl_->GetDescription().terrain;
}
void Scene::AddObject(const std::shared_ptr<swganh::object::Object>& object)
{
impl_->AddObject(object);
}
void Scene::RemoveObject(const std::shared_ptr<swganh::object::Object>& object)
{
impl_->RemoveObject(object);
}
<commit_msg>Send destroy messages to all objects with controllers that were observing the now removed object.<commit_after>
#include "swganh/simulation/scene.h"
#include <algorithm>
#include "swganh/object/object.h"
#include "swganh/object/object_controller.h"
#include "swganh/messages/scene_destroy_object.h"
using namespace std;
using namespace swganh::messages;
using namespace swganh::object;
using namespace swganh::simulation;
class Scene::SceneImpl
{
public:
SceneImpl(SceneDescription description)
: description_(move(description))
{}
const SceneDescription& GetDescription() const
{
return description_;
}
void AddObject(const shared_ptr<Object>& object)
{
InsertObject(object);
for_each(begin(object_map_), end(object_map_),
[&object] (const ObjectMap::value_type& object_entry)
{
auto& stored_object = object_entry.second;
stored_object->AddAwareObject(object);
object->AddAwareObject(stored_object);
});
}
void RemoveObject(const shared_ptr<Object>& object)
{
EraseObject(object);
SceneDestroyObject destroy_message;
destroy_message.object_id = object->GetObjectId();
for_each(begin(object_map_), end(object_map_),
[&object, &destroy_message] (const ObjectMap::value_type& object_entry)
{
auto& stored_object = object_entry.second;
stored_object->RemoveContainedObject(object);
stored_object->RemoveAwareObject(object);
if (stored_object->HasController())
{
stored_object->GetController()->Notify(destroy_message);
}
});
}
void InsertObject(const shared_ptr<Object>& object)
{
// make sure it's not already there
auto find_iter = objects_.find(object);
if (find_iter == end(objects_))
objects_.insert(find_iter, object);
auto find_map = object_map_.find(object->GetObjectId());
if (find_map == end(object_map_))
object_map_.insert(find_map, ObjectPair(object->GetObjectId(), object));
}
void EraseObject(const shared_ptr<Object>& object)
{
objects_.erase(object);
object_map_.erase(object->GetObjectId());
}
private:
typedef std::map<
uint64_t,
shared_ptr<Object>
> ObjectMap;
typedef std::pair<
uint64_t,
shared_ptr<Object>
> ObjectPair;
typedef std::set<std::shared_ptr<Object>> ObjectSet;
ObjectSet objects_;
ObjectMap object_map_;
SceneDescription description_;
};
Scene::Scene(SceneDescription description)
: impl_(new SceneImpl(move(description)))
{}
Scene::Scene(uint32_t scene_id, string name, string label, string description, string terrain)
{
SceneDescription scene_description;
scene_description.id = scene_id;
scene_description.name = move(name);
scene_description.label = move(label);
scene_description.description = move(description);
scene_description.terrain = move(terrain);
impl_.reset(new SceneImpl(move(scene_description)));
}
uint32_t Scene::GetSceneId() const
{
return impl_->GetDescription().id;
}
const std::string& Scene::GetName() const
{
return impl_->GetDescription().name;
}
const std::string& Scene::GetLabel() const
{
return impl_->GetDescription().label;
}
const std::string& Scene::GetDescription() const
{
return impl_->GetDescription().description;
}
const std::string& Scene::GetTerrainMap() const
{
return impl_->GetDescription().terrain;
}
void Scene::AddObject(const std::shared_ptr<swganh::object::Object>& object)
{
impl_->AddObject(object);
}
void Scene::RemoveObject(const std::shared_ptr<swganh::object::Object>& object)
{
impl_->RemoveObject(object);
}
<|endoftext|> |
<commit_before>/*
* VelocitySystem.cpp
*
* Created on: 11/07/2014
* Author: vitor
*/
#include "VelocitySystem.h"
VelocitySystem::VelocitySystem() :
System() {
add_aspect(new AllOfAspect<PositionComponent, VelocityComponent>());
}
VelocitySystem::~VelocitySystem() {
}
void VelocitySystem::process_entity(Entity& entity, double dt) {
auto p = entity.get_component<PositionComponent>();
auto v = entity.get_component<VelocityComponent>();
p->x += v->x;
p->y += v->y;
}
<commit_msg>Used dt parameter on VelocitySystem.<commit_after>/*
* VelocitySystem.cpp
*
* Created on: 11/07/2014
* Author: vitor
*/
#include "VelocitySystem.h"
VelocitySystem::VelocitySystem() :
System() {
add_aspect(new AllOfAspect<PositionComponent, VelocityComponent>());
}
VelocitySystem::~VelocitySystem() {
}
void VelocitySystem::process_entity(Entity& entity, double dt) {
auto p = entity.get_component<PositionComponent>();
auto v = entity.get_component<VelocityComponent>();
p->x += v->x * dt;
p->y += v->y * dt;
}
<|endoftext|> |
<commit_before>/*++
Copyright (c) 2012 Microsoft Corporation
Module Name:
qffpa_tactic.cpp
Abstract:
Tactic for QF_FP benchmarks.
Author:
Christoph (cwinter) 2012-01-16
Notes:
--*/
#include"tactical.h"
#include"simplify_tactic.h"
#include"bit_blaster_tactic.h"
#include"sat_tactic.h"
#include"fpa2bv_tactic.h"
#include"smt_tactic.h"
#include"propagate_values_tactic.h"
#include"probe_arith.h"
#include"qfnra_tactic.h"
#include"qffp_tactic.h"
struct has_fp_to_real_predicate {
struct found {};
ast_manager & m;
bv_util bu;
fpa_util fu;
arith_util au;
has_fp_to_real_predicate(ast_manager & _m) : m(_m), bu(m), fu(m), au(m) {}
void operator()(var *) { throw found(); }
void operator()(quantifier *) { throw found(); }
void operator()(app * n) {
sort * s = get_sort(n);
if (au.is_real(s) && n->get_family_id() == fu.get_family_id() &&
is_app(n) && to_app(n)->get_kind() == OP_FPA_TO_REAL)
throw found();
}
};
class has_fp_to_real_probe : public probe {
public:
virtual result operator()(goal const & g) {
return !test<has_fp_to_real_predicate>(g);
}
virtual ~has_fp_to_real_probe() {}
};
probe * mk_has_fp_to_real_probe() {
return alloc(has_fp_to_real_probe);
}
tactic * mk_qffp_tactic(ast_manager & m, params_ref const & p) {
params_ref simp_p = p;
simp_p.set_bool("arith_lhs", true);
simp_p.set_bool("elim_and", true);
tactic * st = and_then(mk_simplify_tactic(m, simp_p),
mk_propagate_values_tactic(m, p),
cond(mk_or(mk_produce_proofs_probe(), mk_produce_unsat_cores_probe()),
mk_smt_tactic(),
and_then(
mk_fpa2bv_tactic(m, p),
mk_propagate_values_tactic(m, p),
using_params(mk_simplify_tactic(m, p), simp_p),
mk_bit_blaster_tactic(m, p),
using_params(mk_simplify_tactic(m, p), simp_p),
cond(mk_is_propositional_probe(),
mk_sat_tactic(m, p),
cond(mk_has_fp_to_real_probe(),
mk_qfnra_tactic(m, p),
mk_smt_tactic(p))
),
mk_fail_if_undecided_tactic())));
st->updt_params(p);
return st;
}
tactic * mk_qffpbv_tactic(ast_manager & m, params_ref const & p) {
return mk_qffp_tactic(m, p);
}
struct is_non_qffp_predicate {
struct found {};
ast_manager & m;
bv_util bu;
fpa_util fu;
arith_util au;
is_non_qffp_predicate(ast_manager & _m) : m(_m), bu(m), fu(m), au(m) {}
void operator()(var *) { throw found(); }
void operator()(quantifier *) { throw found(); }
void operator()(app * n) {
sort * s = get_sort(n);
if (!m.is_bool(s) && !fu.is_float(s) && !fu.is_rm(s) && !bu.is_bv_sort(s) && !au.is_real(s))
throw found();
family_id fid = n->get_family_id();
if (fid == m.get_basic_family_id())
return;
if (fid == fu.get_family_id() || fid == bu.get_family_id())
return;
if (is_uninterp_const(n))
return;
if (au.is_real(s) && au.is_numeral(n))
return;
throw found();
}
};
class is_qffp_probe : public probe {
public:
virtual result operator()(goal const & g) {
return !test<is_non_qffp_predicate>(g);
}
virtual ~is_qffp_probe() {}
};
probe * mk_is_qffp_probe() {
return alloc(is_qffp_probe);
}
probe * mk_is_qffpbv_probe() {
return alloc(is_qffp_probe);
}
<commit_msg>Bugfix for QF_FP default tactic.<commit_after>/*++
Copyright (c) 2012 Microsoft Corporation
Module Name:
qffpa_tactic.cpp
Abstract:
Tactic for QF_FP benchmarks.
Author:
Christoph (cwinter) 2012-01-16
Notes:
--*/
#include"tactical.h"
#include"simplify_tactic.h"
#include"bit_blaster_tactic.h"
#include"sat_tactic.h"
#include"fpa2bv_tactic.h"
#include"smt_tactic.h"
#include"propagate_values_tactic.h"
#include"probe_arith.h"
#include"qfnra_tactic.h"
#include"qffp_tactic.h"
struct has_fp_to_real_predicate {
struct found {};
ast_manager & m;
bv_util bu;
fpa_util fu;
arith_util au;
has_fp_to_real_predicate(ast_manager & _m) : m(_m), bu(m), fu(m), au(m) {}
void operator()(var *) { throw found(); }
void operator()(quantifier *) { throw found(); }
void operator()(app * n) {
sort * s = get_sort(n);
if (au.is_real(s) && n->get_family_id() == fu.get_family_id() &&
is_app(n) && to_app(n)->get_decl_kind() == OP_FPA_TO_REAL)
throw found();
}
};
class has_fp_to_real_probe : public probe {
public:
virtual result operator()(goal const & g) {
return !test<has_fp_to_real_predicate>(g);
}
virtual ~has_fp_to_real_probe() {}
};
probe * mk_has_fp_to_real_probe() {
return alloc(has_fp_to_real_probe);
}
tactic * mk_qffp_tactic(ast_manager & m, params_ref const & p) {
params_ref simp_p = p;
simp_p.set_bool("arith_lhs", true);
simp_p.set_bool("elim_and", true);
tactic * st = and_then(mk_simplify_tactic(m, simp_p),
mk_propagate_values_tactic(m, p),
cond(mk_or(mk_produce_proofs_probe(), mk_produce_unsat_cores_probe()),
mk_smt_tactic(),
and_then(
mk_fpa2bv_tactic(m, p),
mk_propagate_values_tactic(m, p),
using_params(mk_simplify_tactic(m, p), simp_p),
mk_bit_blaster_tactic(m, p),
using_params(mk_simplify_tactic(m, p), simp_p),
cond(mk_is_propositional_probe(),
mk_sat_tactic(m, p),
cond(mk_has_fp_to_real_probe(),
mk_qfnra_tactic(m, p),
mk_smt_tactic(p))
),
mk_fail_if_undecided_tactic())));
st->updt_params(p);
return st;
}
tactic * mk_qffpbv_tactic(ast_manager & m, params_ref const & p) {
return mk_qffp_tactic(m, p);
}
struct is_non_qffp_predicate {
struct found {};
ast_manager & m;
bv_util bu;
fpa_util fu;
arith_util au;
is_non_qffp_predicate(ast_manager & _m) : m(_m), bu(m), fu(m), au(m) {}
void operator()(var *) { throw found(); }
void operator()(quantifier *) { throw found(); }
void operator()(app * n) {
sort * s = get_sort(n);
if (!m.is_bool(s) && !fu.is_float(s) && !fu.is_rm(s) && !bu.is_bv_sort(s) && !au.is_real(s))
throw found();
family_id fid = n->get_family_id();
if (fid == m.get_basic_family_id())
return;
if (fid == fu.get_family_id() || fid == bu.get_family_id())
return;
if (is_uninterp_const(n))
return;
if (au.is_real(s) && au.is_numeral(n))
return;
throw found();
}
};
class is_qffp_probe : public probe {
public:
virtual result operator()(goal const & g) {
return !test<is_non_qffp_predicate>(g);
}
virtual ~is_qffp_probe() {}
};
probe * mk_is_qffp_probe() {
return alloc(is_qffp_probe);
}
probe * mk_is_qffpbv_probe() {
return alloc(is_qffp_probe);
}
<|endoftext|> |
<commit_before>#include "Groups.h"
UserGroup::UserGroup(int id,unsigned char def)
{
this->id = id;
this->defaultPerm = def;
}
<commit_msg>lorde<commit_after>#include "Groups.h"
UserGroup::UserGroup(int id,unsigned char def)
{
this->id = id;
this->defaultPerm = def;
}
void UserGroup::AddRule(PermRule newRule)
{
Forum_Board * board = forum.getBoardById(newRule.f_id);
//Add the rule to our list.
this->prules.push_back(newRule);
//Increment the scope
newRule.scope++;
//Loop through the board's children and add it with the updaeted scope.
for(auto i=board->children.begin();i != board->children.end();i++){
newRule.f_id = (*i)->id;
//Set the new ID, then recursively call the function.
this->AddRule(newRule);
}
}
<|endoftext|> |
<commit_before>#include "tmfs.hh"
static std::string _get_real_path(const std::string & str)
{
const auto clean_path = fs::path(str);
fs::path real_path(tmfs::instance().hfs_root());
real_path /= "Backups.backupdb"; // ${hfs_root}/Backups.backupdb/
// ok let's copy the 4 first part of the virtual path
// (/, ${comp_name}, ${date}, ${disk_name})
auto it = clean_path.begin();
for (int i = 0; i < 4 && it != clean_path.end(); ++i, ++it)
real_path /= *it;
// let's resolv all the parts of the path
struct stat stbuf;
for (; it != clean_path.end(); ++it)
{
real_path /= *it;
// Does the file exists ?
if (stat(real_path.string().c_str(), &stbuf))
return real_path.string();
// Is the file a dir_id ?
if (S_ISREG(stbuf.st_mode) && stbuf.st_size == 0 && stbuf.st_nlink > 0)
{
// build the real path
std::ostringstream os;
os << tmfs::instance().hfs_root() << "/.HFS+ Private Directory Data\r/dir_" << stbuf.st_nlink;
// check if it's really a ${dir_id}
if (stat(os.str().c_str(), &stbuf))
continue; // it's not
real_path = os.str(); // it is
}
}
return real_path.string();
}
std::string get_real_path(const std::string & str)
{
auto result = _get_real_path(str);
std::cout << "get_real_path(\"" << str << "\") -> " << result << std::endl;
return result;
}<commit_msg>Use relative path since absolute path will replace the real_path<commit_after>#include "tmfs.hh"
static std::string _get_real_path(const std::string & str)
{
// use the relative path so that the real_path doesn't get replaced
const auto clean_path = fs::path(str).relative_path();
fs::path real_path(tmfs::instance().hfs_root());
real_path /= "Backups.backupdb"; // ${hfs_root}/Backups.backupdb/
// ok let's copy the 3 first part of the virtual path
// (${comp_name}, ${date}, ${disk_name})
auto it = clean_path.begin();
for (int i = 0; i < 3 && it != clean_path.end(); ++i, ++it)
{
real_path /= *it;
}
// let's resolv all the parts of the path
struct stat stbuf;
for (; it != clean_path.end(); ++it)
{
real_path /= *it;
// Does the file exists ?
if (stat(real_path.string().c_str(), &stbuf))
return real_path.string();
// Is the file a dir_id ?
if (S_ISREG(stbuf.st_mode) && stbuf.st_size == 0 && stbuf.st_nlink > 0)
{
// build the real path
std::ostringstream os;
os << tmfs::instance().hfs_root() << "/.HFS+ Private Directory Data\r/dir_" << stbuf.st_nlink;
// check if it's really a ${dir_id}
if (stat(os.str().c_str(), &stbuf))
continue; // it's not
real_path = os.str(); // it is
}
}
return real_path.string();
}
std::string get_real_path(const std::string & str)
{
auto result = _get_real_path(str);
std::cout << "get_real_path(\"" << str << "\") -> " << result << std::endl;
return result;
}<|endoftext|> |
<commit_before>// Copyright (c) 2014-2022 The Gridcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or https://opensource.org/licenses/mit-license.php.
#include "amount.h"
#include "key.h"
#include "main.h"
#include "gridcoin/mrc.h"
#include "gridcoin/account.h"
#include "gridcoin/tally.h"
#include "gridcoin/beacon.h"
#include "util.h"
using namespace GRC;
namespace {
//!
//! \brief Get the hash of a subset of the data in the mrc object used as
//! input to sign or verify a research reward claim.
//!
//! \param mrc MRC to generate a hash for.
//! \param last_block_hash Hash of the block at the head of the chain.
//! \param mrc mrc transaction of the block that contains
//! the claim.
//!
//! \return Hash of the CPID and last block hash contained in the claim.
//!
uint256 GetMRCHash(
const MRC& mrc,
const uint256& last_block_hash)
{
const CpidOption cpid = mrc.m_mining_id.TryCpid();
if (!cpid) {
return uint256();
}
CHashWriter hasher(SER_NETWORK, PROTOCOL_VERSION);
hasher << *cpid << last_block_hash;
return hasher.GetHash();
}
} // anonymous namespace
// -----------------------------------------------------------------------------
// Class: MRC
// -----------------------------------------------------------------------------
MRC::MRC() : MRC(CURRENT_VERSION)
{
}
MRC::MRC(uint32_t version)
: m_version(version)
, m_research_subsidy(0)
, m_magnitude(0)
, m_magnitude_unit(0)
{
}
bool MRC::WellFormed() const
{
if (m_version <= 0 || m_version > MRC::CURRENT_VERSION) {
return false;
}
if (m_version == 1) {
return true;
}
if (!m_mining_id.Valid()) {
return false;
}
if (m_client_version.empty()) {
return false;
}
if (m_mining_id.Which() == MiningId::Kind::CPID) {
if (m_research_subsidy <= 0 || m_signature.empty()) {
return false;
}
}
return true;
}
bool MRC::HasResearchReward() const
{
return m_mining_id.Which() == MiningId::Kind::CPID;
}
CAmount MRC::ComputeMRCFee() const
{
CAmount fee = 0;
// This is the 14 days where fees will be 100% if someone tries to slip an MRC through.
const int64_t zero_payout_interval = 14 * 24 * 60 * 60;
// Initial fee fraction at end of zero_payout_interval (beginning of valid MRC interval). This is expressed as
// separate numerator and denominator for integer math. This is equivalent to 40% fees at the end of the
// zero_payout_interval
int64_t fee_fraction_numerator = 2;
int64_t fee_fraction_denominator = 5;
const CpidOption cpid = m_mining_id.TryCpid();
if (!cpid) return fee;
const ResearchAccount& account = Tally::GetAccount(*cpid);
const int64_t last_reward_time = account.LastRewardTime();
// Get the block index of the head of the chain at the time the MRC was filled out.
CBlockIndex* prev_block_pindex = mapBlockIndex[m_last_block_hash];
int64_t payment_time = prev_block_pindex->nTime;
int64_t mrc_payment_interval = 0;
// If there is a last reward recorded in the accrual system, then the payment interval for the MRC request starts
// there and goes to the head of the chain for the MRC in the mempool. If not, we use the age of the beacon.
if (!last_reward_time) {
const BeaconOption beacon = GetBeaconRegistry().Try(*cpid);;
if (beacon) {
mrc_payment_interval = beacon->Age(prev_block_pindex->nTime);
} else {
// This should not happen, because we should have an active beacon, but just in case return fee of zero.
return fee;
}
} else {
mrc_payment_interval = payment_time - last_reward_time;
}
// If the payment interval for the MRC is less than the zero payout interval, then set the fees equal to the entire
// m_research_subsidy, which means the entire accrual will be forfeited. This should not happen because the sending
// node will use the same rules to validate and not allow sends within zero_payout_interval; however, this implements
// a serious penalty for someone trying to abuse MRC with a modified client. If a rogue node operator sends an MRC
// where they payment interval is smaller than zero_payout_interval, and it makes it through, the entire rewards will
// be taken as fees.
if (mrc_payment_interval < zero_payout_interval) return m_research_subsidy;
// TODO: do overflow check analysis.
// This is a simple model that is very deterministic and should not cause consensus problems. It is essentially
// The straight line estimate of the m_research_subsidy at mrc_payment_interval * the fee fraction, which is (pure math)
// m_research_subsidy * (zero_payout_interval / mrc_payment_interval) * fee_fraction.
//
// If the magnitude of the cpid with the MRC is constant, this has the effect of holding fees constant at
// the value they would have been at the zero_payout_interval and keeping them there as the mrc_payment_interval gets
// larger. From the point of view of the actual MRC, the payment fees as a percentage of the m_research_subsidty
// decline as c/t where c is a constant and t is elapsed time.
//
// If the MRC is exactly at the end of the zero_payout_interval, the fees are effectively
// fee_fraction * m_research_subsidy.
fee = m_research_subsidy * zero_payout_interval * fee_fraction_numerator /
(mrc_payment_interval * fee_fraction_denominator);
return fee;
}
bool MRC::Sign(CKey& private_key)
{
const CpidOption cpid = m_mining_id.TryCpid();
if (!cpid) {
return false;
}
const uint256 hash = GetMRCHash(*this, m_last_block_hash);
if (!private_key.Sign(hash, m_signature)) {
m_signature.clear();
return false;
}
return true;
}
bool MRC::VerifySignature(
const CPubKey& public_key,
const uint256& last_block_hash) const
{
CKey key;
if (!key.SetPubKey(public_key)) {
return false;
}
const uint256 hash = GetMRCHash(*this, last_block_hash);
return key.Verify(hash, m_signature);
}
uint256 MRC::GetHash() const
{
CHashWriter hasher(SER_NETWORK, PROTOCOL_VERSION);
// MRC contracts do not use the contract action specifier:
Serialize(hasher, ContractAction::UNKNOWN);
return hasher.GetHash();
}
bool GRC::MRCContractHandler::Validate(const Contract& contract, const CTransaction& tx) const
{
// Check that the burn in the contract is equal or greater than the required burn.
CAmount burn_amount = 0;
for (const auto& output : tx.vout) {
if (output.scriptPubKey == (CScript() << OP_RETURN)) {
burn_amount += output.nValue;
}
}
GRC::MRC mrc = contract.CopyPayloadAs<GRC::MRC>();
if (burn_amount < mrc.RequiredBurnAmount()) return false;
// MRC transactions are only valid if the MRC contracts that they contain refer to the current head of the chain as
// m_last_block_hash.
return ValidateMRC(pindexBest, mrc);
}
namespace {
//!
//! \brief Sign the mrc.
//!
//! \param pwallet Supplies beacon private keys for signing.
//! \param pindex Block index of last block.
//! \param mrc An initialized mrc to sign.
//! \param mrc_tx The transaction for the mrc.
//!
//! \return \c true if the miner holds active beacon keys used to successfully
//! sign the claim.
//!
bool TrySignMRC(
CWallet* pwallet,
CBlockIndex* pindex,
GRC::MRC& mrc) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{
AssertLockHeld(cs_main);
// lock needs to be taken on pwallet here.
LOCK(pwallet->cs_wallet);
const GRC::CpidOption cpid = mrc.m_mining_id.TryCpid();
if (!cpid) {
return false; // Skip beacon signature for investors.
}
const GRC::BeaconOption beacon = GRC::GetBeaconRegistry().Try(*cpid);
if (!beacon) {
return error("%s: No active beacon", __func__);
}
// We use pindex->nTime here because the ending interval of the payment is aligned to the last block
// (the head of the chain), not the MRC transaction time.
if (beacon->Expired(pindex->nTime)) {
return error("%s: Beacon expired", __func__);
}
CKey beacon_key;
if (!pwallet->GetKey(beacon->m_public_key.GetID(), beacon_key)) {
return error("%s: Missing beacon private key", __func__);
}
if (!beacon_key.IsValid()) {
return error("%s: Invalid beacon key", __func__);
}
// Note that the last block hash has already been recorded in mrc for binding into the signature.
if (!mrc.Sign(beacon_key)) {
return error("%s: Signature failed. Check beacon key", __func__);
}
LogPrint(BCLog::LogFlags::MINER,
"%s: Signed for CPID %s and block hash %s with signature %s",
__func__,
cpid->ToString(),
pindex->GetBlockHash().ToString(),
HexStr(mrc.m_signature));
return true;
}
} // anonymous namespace
//!
//! \brief This is patterned after the CreatGridcoinReward, except that it is attached as a contract
//! to a regular transaction by a requesting node rather than bound to the block by the staker.
//! Note that the Researcher::Get() here is the requesting node, not the staker node.
//!
//! TODO: This arguably should be put somewhere else besides the miner.
//! The nTime of the pindex (head of the chain) is used as the time for the accrual calculations.
bool CreateMRC(CBlockIndex* pindex,
CTransaction &mrc_tx,
CAmount &nReward,
CAmount &fee,
CWallet* pwallet) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{
const GRC::ResearcherPtr researcher = GRC::Researcher::Get();
GRC::MRC mrc;
mrc.m_mining_id = researcher->Id();
if (researcher->Status() == GRC::ResearcherStatus::NO_BEACON) {
error("%s: CPID eligible but no active beacon key so MRC cannot be formed.", __func__);
return false;
}
if (const GRC::CpidOption cpid = mrc.m_mining_id.TryCpid()) {
mrc.m_research_subsidy = GRC::Tally::GetAccrual(*cpid, pindex->nTime, pindex);
// If no pending research subsidy value exists, bail.
if (mrc.m_research_subsidy <= 0) {
error("%s: No positive research reward pending at time of mrc.", __func__);
return false;
} else {
nReward = mrc.m_research_subsidy;
mrc.m_magnitude = GRC::Quorum::GetMagnitude(*cpid).Floating();
}
}
mrc.m_client_version = FormatFullVersion().substr(0, GRC::Claim::MAX_VERSION_SIZE);
mrc.m_organization = gArgs.GetArg("-org", "").substr(0, GRC::Claim::MAX_ORGANIZATION_SIZE);
mrc.m_fee = mrc.ComputeMRCFee();
fee = mrc.m_fee;
mrc.m_last_block_hash = pindex->GetBlockHash();
if (!TrySignMRC(pwallet, pindex, mrc)) {
error("%s: Failed to sign mrc.", __func__);
return false;
}
LogPrintf(
"INFO: %s: for %s mrc %s magnitude %d Research %s",
__func__,
mrc.m_mining_id.ToString(),
FormatMoney(nReward),
mrc.m_magnitude,
FormatMoney(mrc.m_research_subsidy));
mrc_tx.vContracts.emplace_back(GRC::MakeContract<GRC::MRC>(GRC::ContractAction::ADD, std::move(mrc)));
return true;
}
<commit_msg>mrc: CreateMRC: fix typo in doc<commit_after>// Copyright (c) 2014-2022 The Gridcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or https://opensource.org/licenses/mit-license.php.
#include "amount.h"
#include "key.h"
#include "main.h"
#include "gridcoin/mrc.h"
#include "gridcoin/account.h"
#include "gridcoin/tally.h"
#include "gridcoin/beacon.h"
#include "util.h"
using namespace GRC;
namespace {
//!
//! \brief Get the hash of a subset of the data in the mrc object used as
//! input to sign or verify a research reward claim.
//!
//! \param mrc MRC to generate a hash for.
//! \param last_block_hash Hash of the block at the head of the chain.
//! \param mrc mrc transaction of the block that contains
//! the claim.
//!
//! \return Hash of the CPID and last block hash contained in the claim.
//!
uint256 GetMRCHash(
const MRC& mrc,
const uint256& last_block_hash)
{
const CpidOption cpid = mrc.m_mining_id.TryCpid();
if (!cpid) {
return uint256();
}
CHashWriter hasher(SER_NETWORK, PROTOCOL_VERSION);
hasher << *cpid << last_block_hash;
return hasher.GetHash();
}
} // anonymous namespace
// -----------------------------------------------------------------------------
// Class: MRC
// -----------------------------------------------------------------------------
MRC::MRC() : MRC(CURRENT_VERSION)
{
}
MRC::MRC(uint32_t version)
: m_version(version)
, m_research_subsidy(0)
, m_magnitude(0)
, m_magnitude_unit(0)
{
}
bool MRC::WellFormed() const
{
if (m_version <= 0 || m_version > MRC::CURRENT_VERSION) {
return false;
}
if (m_version == 1) {
return true;
}
if (!m_mining_id.Valid()) {
return false;
}
if (m_client_version.empty()) {
return false;
}
if (m_mining_id.Which() == MiningId::Kind::CPID) {
if (m_research_subsidy <= 0 || m_signature.empty()) {
return false;
}
}
return true;
}
bool MRC::HasResearchReward() const
{
return m_mining_id.Which() == MiningId::Kind::CPID;
}
CAmount MRC::ComputeMRCFee() const
{
CAmount fee = 0;
// This is the 14 days where fees will be 100% if someone tries to slip an MRC through.
const int64_t zero_payout_interval = 14 * 24 * 60 * 60;
// Initial fee fraction at end of zero_payout_interval (beginning of valid MRC interval). This is expressed as
// separate numerator and denominator for integer math. This is equivalent to 40% fees at the end of the
// zero_payout_interval
int64_t fee_fraction_numerator = 2;
int64_t fee_fraction_denominator = 5;
const CpidOption cpid = m_mining_id.TryCpid();
if (!cpid) return fee;
const ResearchAccount& account = Tally::GetAccount(*cpid);
const int64_t last_reward_time = account.LastRewardTime();
// Get the block index of the head of the chain at the time the MRC was filled out.
CBlockIndex* prev_block_pindex = mapBlockIndex[m_last_block_hash];
int64_t payment_time = prev_block_pindex->nTime;
int64_t mrc_payment_interval = 0;
// If there is a last reward recorded in the accrual system, then the payment interval for the MRC request starts
// there and goes to the head of the chain for the MRC in the mempool. If not, we use the age of the beacon.
if (!last_reward_time) {
const BeaconOption beacon = GetBeaconRegistry().Try(*cpid);;
if (beacon) {
mrc_payment_interval = beacon->Age(prev_block_pindex->nTime);
} else {
// This should not happen, because we should have an active beacon, but just in case return fee of zero.
return fee;
}
} else {
mrc_payment_interval = payment_time - last_reward_time;
}
// If the payment interval for the MRC is less than the zero payout interval, then set the fees equal to the entire
// m_research_subsidy, which means the entire accrual will be forfeited. This should not happen because the sending
// node will use the same rules to validate and not allow sends within zero_payout_interval; however, this implements
// a serious penalty for someone trying to abuse MRC with a modified client. If a rogue node operator sends an MRC
// where they payment interval is smaller than zero_payout_interval, and it makes it through, the entire rewards will
// be taken as fees.
if (mrc_payment_interval < zero_payout_interval) return m_research_subsidy;
// TODO: do overflow check analysis.
// This is a simple model that is very deterministic and should not cause consensus problems. It is essentially
// The straight line estimate of the m_research_subsidy at mrc_payment_interval * the fee fraction, which is (pure math)
// m_research_subsidy * (zero_payout_interval / mrc_payment_interval) * fee_fraction.
//
// If the magnitude of the cpid with the MRC is constant, this has the effect of holding fees constant at
// the value they would have been at the zero_payout_interval and keeping them there as the mrc_payment_interval gets
// larger. From the point of view of the actual MRC, the payment fees as a percentage of the m_research_subsidty
// decline as c/t where c is a constant and t is elapsed time.
//
// If the MRC is exactly at the end of the zero_payout_interval, the fees are effectively
// fee_fraction * m_research_subsidy.
fee = m_research_subsidy * zero_payout_interval * fee_fraction_numerator /
(mrc_payment_interval * fee_fraction_denominator);
return fee;
}
bool MRC::Sign(CKey& private_key)
{
const CpidOption cpid = m_mining_id.TryCpid();
if (!cpid) {
return false;
}
const uint256 hash = GetMRCHash(*this, m_last_block_hash);
if (!private_key.Sign(hash, m_signature)) {
m_signature.clear();
return false;
}
return true;
}
bool MRC::VerifySignature(
const CPubKey& public_key,
const uint256& last_block_hash) const
{
CKey key;
if (!key.SetPubKey(public_key)) {
return false;
}
const uint256 hash = GetMRCHash(*this, last_block_hash);
return key.Verify(hash, m_signature);
}
uint256 MRC::GetHash() const
{
CHashWriter hasher(SER_NETWORK, PROTOCOL_VERSION);
// MRC contracts do not use the contract action specifier:
Serialize(hasher, ContractAction::UNKNOWN);
return hasher.GetHash();
}
bool GRC::MRCContractHandler::Validate(const Contract& contract, const CTransaction& tx) const
{
// Check that the burn in the contract is equal or greater than the required burn.
CAmount burn_amount = 0;
for (const auto& output : tx.vout) {
if (output.scriptPubKey == (CScript() << OP_RETURN)) {
burn_amount += output.nValue;
}
}
GRC::MRC mrc = contract.CopyPayloadAs<GRC::MRC>();
if (burn_amount < mrc.RequiredBurnAmount()) return false;
// MRC transactions are only valid if the MRC contracts that they contain refer to the current head of the chain as
// m_last_block_hash.
return ValidateMRC(pindexBest, mrc);
}
namespace {
//!
//! \brief Sign the mrc.
//!
//! \param pwallet Supplies beacon private keys for signing.
//! \param pindex Block index of last block.
//! \param mrc An initialized mrc to sign.
//! \param mrc_tx The transaction for the mrc.
//!
//! \return \c true if the miner holds active beacon keys used to successfully
//! sign the claim.
//!
bool TrySignMRC(
CWallet* pwallet,
CBlockIndex* pindex,
GRC::MRC& mrc) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{
AssertLockHeld(cs_main);
// lock needs to be taken on pwallet here.
LOCK(pwallet->cs_wallet);
const GRC::CpidOption cpid = mrc.m_mining_id.TryCpid();
if (!cpid) {
return false; // Skip beacon signature for investors.
}
const GRC::BeaconOption beacon = GRC::GetBeaconRegistry().Try(*cpid);
if (!beacon) {
return error("%s: No active beacon", __func__);
}
// We use pindex->nTime here because the ending interval of the payment is aligned to the last block
// (the head of the chain), not the MRC transaction time.
if (beacon->Expired(pindex->nTime)) {
return error("%s: Beacon expired", __func__);
}
CKey beacon_key;
if (!pwallet->GetKey(beacon->m_public_key.GetID(), beacon_key)) {
return error("%s: Missing beacon private key", __func__);
}
if (!beacon_key.IsValid()) {
return error("%s: Invalid beacon key", __func__);
}
// Note that the last block hash has already been recorded in mrc for binding into the signature.
if (!mrc.Sign(beacon_key)) {
return error("%s: Signature failed. Check beacon key", __func__);
}
LogPrint(BCLog::LogFlags::MINER,
"%s: Signed for CPID %s and block hash %s with signature %s",
__func__,
cpid->ToString(),
pindex->GetBlockHash().ToString(),
HexStr(mrc.m_signature));
return true;
}
} // anonymous namespace
//!
//! \brief This is patterned after the CreateGridcoinReward, except that it is attached as a contract
//! to a regular transaction by a requesting node rather than bound to the block by the staker.
//! Note that the Researcher::Get() here is the requesting node, not the staker node.
//!
//! TODO: This arguably should be put somewhere else besides the miner.
//! The nTime of the pindex (head of the chain) is used as the time for the accrual calculations.
bool CreateMRC(CBlockIndex* pindex,
CTransaction &mrc_tx,
CAmount &nReward,
CAmount &fee,
CWallet* pwallet) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{
const GRC::ResearcherPtr researcher = GRC::Researcher::Get();
GRC::MRC mrc;
mrc.m_mining_id = researcher->Id();
if (researcher->Status() == GRC::ResearcherStatus::NO_BEACON) {
error("%s: CPID eligible but no active beacon key so MRC cannot be formed.", __func__);
return false;
}
if (const GRC::CpidOption cpid = mrc.m_mining_id.TryCpid()) {
mrc.m_research_subsidy = GRC::Tally::GetAccrual(*cpid, pindex->nTime, pindex);
// If no pending research subsidy value exists, bail.
if (mrc.m_research_subsidy <= 0) {
error("%s: No positive research reward pending at time of mrc.", __func__);
return false;
} else {
nReward = mrc.m_research_subsidy;
mrc.m_magnitude = GRC::Quorum::GetMagnitude(*cpid).Floating();
}
}
mrc.m_client_version = FormatFullVersion().substr(0, GRC::Claim::MAX_VERSION_SIZE);
mrc.m_organization = gArgs.GetArg("-org", "").substr(0, GRC::Claim::MAX_ORGANIZATION_SIZE);
mrc.m_fee = mrc.ComputeMRCFee();
fee = mrc.m_fee;
mrc.m_last_block_hash = pindex->GetBlockHash();
if (!TrySignMRC(pwallet, pindex, mrc)) {
error("%s: Failed to sign mrc.", __func__);
return false;
}
LogPrintf(
"INFO: %s: for %s mrc %s magnitude %d Research %s",
__func__,
mrc.m_mining_id.ToString(),
FormatMoney(nReward),
mrc.m_magnitude,
FormatMoney(mrc.m_research_subsidy));
mrc_tx.vContracts.emplace_back(GRC::MakeContract<GRC::MRC>(GRC::ContractAction::ADD, std::move(mrc)));
return true;
}
<|endoftext|> |
<commit_before>#include "hext/matcher.h"
namespace hext {
matcher::match_error::match_error(const char * msg)
: std::runtime_error(msg)
{
}
matcher::matcher(const char * path)
: g_outp(nullptr),
buffer()
{
assert(path != nullptr);
{
std::ifstream file;
// force exception on error
file.exceptions(std::ios::failbit | std::ios::badbit);
file.open(path);
std::stringstream stream;
stream << file.rdbuf();
this->buffer = stream.str();
file.close();
}
this->g_outp = gumbo_parse(this->buffer.c_str());
if( this->g_outp == nullptr )
throw match_error("gumbo_parse returned nullptr");
}
std::unique_ptr<match_tree>
matcher::capture_node(const rule * r, const GumboNode * node) const
{
typedef rule::const_attribute_iterator r_attr_iter;
std::unique_ptr<match_tree> m_node = make_unique<match_tree>();
if( r == nullptr )
return m_node;
if( node == nullptr )
return m_node;
if( node->type != GUMBO_NODE_ELEMENT )
return m_node;
for(r_attr_iter it = r->attributes_begin(); it != r->attributes_end(); ++it)
{
if( it->get_is_capture() )
{
m_node->append_match(
this->capture_attribute(&(*it), node)
);
}
}
return m_node;
}
match_tree::name_value_pair
matcher::capture_attribute(const attribute * a, const GumboNode * node) const
{
assert(a != nullptr);
assert(node != nullptr);
assert(node->type == GUMBO_NODE_ELEMENT);
if( a == nullptr )
return match_tree::name_value_pair("", "");
if( node == nullptr )
return match_tree::name_value_pair("", "");
if( node->type != GUMBO_NODE_ELEMENT )
return match_tree::name_value_pair("", "");
if( a->get_name() == "hext-inner-text" )
{
return match_tree::name_value_pair(
/* name */ a->get_value(),
/* value */ bc::capture_inner_text(node)
);
}
else
{
GumboAttribute * g_attr = gumbo_get_attribute(
&node->v.element.attributes,
a->get_name().c_str()
);
return match_tree::name_value_pair(
/* name */ a->get_value(),
/* value */ ( g_attr && g_attr->value ? g_attr->value : "" )
);
}
}
bool matcher::node_matches_rule(const GumboNode * node, const rule * r) const
{
typedef rule::const_attribute_iterator r_attr_iter;
if( node == nullptr )
return false;
if( r == nullptr )
return false;
if( node->type != GUMBO_NODE_ELEMENT )
return false;
std::string tag_name = r->get_tag_name();
if( !tag_name.empty() &&
node->v.element.tag != gumbo_tag_enum(tag_name.c_str()) )
return false;
for(r_attr_iter it = r->attributes_begin(); it != r->attributes_end(); ++it)
{
std::string attr_name = it->get_name();
GumboAttribute * g_attr =
gumbo_get_attribute(&node->v.element.attributes, attr_name.c_str());
if( !g_attr && !it->get_is_builtin() )
return false;
std::string attr_value = it->get_value();
if( !it->get_is_capture() && !attr_value.empty() )
{
if( attr_value.compare(g_attr->value) != 0 )
return false;
}
}
return true;
}
std::unique_ptr<match_tree> matcher::match(const rule * r) const
{
assert(this->g_outp != nullptr);
assert(r != nullptr);
std::unique_ptr<match_tree> m = make_unique<match_tree>();
if( r )
this->match_node(r, this->g_outp->root, m.get());
return m;
}
void matcher::match_node(
const rule * r,
const GumboNode * node,
match_tree * m
) const
{
typedef rule::const_child_iterator r_child_iter;
if( r == nullptr )
return;
if( node == nullptr )
return;
if( m == nullptr )
return;
if( node->type != GUMBO_NODE_ELEMENT )
return;
if( this->node_matches_rule(node, r) )
{
m = m->append_child_and_own(this->capture_node(r, node));
for(r_child_iter it = r->children_begin(); it != r->children_end(); ++it)
{
this->match_node_children(&(*it), node, m);
}
}
else
{
this->match_node_children(r, node, m);
}
}
void matcher::match_node_children(
const rule * r,
const GumboNode * node,
match_tree * m
) const
{
if( r == nullptr )
return;
if( node == nullptr )
return;
if( m == nullptr )
return;
if( node->type != GUMBO_NODE_ELEMENT )
return;
const GumboVector * children = &node->v.element.children;
for(unsigned int i = 0; i < children->length; ++i)
{
this->match_node(r, static_cast<const GumboNode *>(children->data[i]), m);
}
}
matcher::~matcher()
{
assert(this->g_outp != nullptr);
gumbo_destroy_output(&kGumboDefaultOptions, this->g_outp);
}
} // namespace hext
<commit_msg>removed redundant assert<commit_after>#include "hext/matcher.h"
namespace hext {
matcher::match_error::match_error(const char * msg)
: std::runtime_error(msg)
{
}
matcher::matcher(const char * path)
: g_outp(nullptr),
buffer()
{
assert(path != nullptr);
{
std::ifstream file;
// force exception on error
file.exceptions(std::ios::failbit | std::ios::badbit);
file.open(path);
std::stringstream stream;
stream << file.rdbuf();
this->buffer = stream.str();
file.close();
}
this->g_outp = gumbo_parse(this->buffer.c_str());
if( this->g_outp == nullptr )
throw match_error("gumbo_parse returned nullptr");
}
std::unique_ptr<match_tree>
matcher::capture_node(const rule * r, const GumboNode * node) const
{
typedef rule::const_attribute_iterator r_attr_iter;
std::unique_ptr<match_tree> m_node = make_unique<match_tree>();
if( r == nullptr )
return m_node;
if( node == nullptr )
return m_node;
if( node->type != GUMBO_NODE_ELEMENT )
return m_node;
for(r_attr_iter it = r->attributes_begin(); it != r->attributes_end(); ++it)
{
if( it->get_is_capture() )
{
m_node->append_match(
this->capture_attribute(&(*it), node)
);
}
}
return m_node;
}
match_tree::name_value_pair
matcher::capture_attribute(const attribute * a, const GumboNode * node) const
{
if( a == nullptr )
return match_tree::name_value_pair("", "");
if( node == nullptr )
return match_tree::name_value_pair("", "");
if( node->type != GUMBO_NODE_ELEMENT )
return match_tree::name_value_pair("", "");
if( a->get_name() == "hext-inner-text" )
{
return match_tree::name_value_pair(
/* name */ a->get_value(),
/* value */ bc::capture_inner_text(node)
);
}
else
{
GumboAttribute * g_attr = gumbo_get_attribute(
&node->v.element.attributes,
a->get_name().c_str()
);
return match_tree::name_value_pair(
/* name */ a->get_value(),
/* value */ ( g_attr && g_attr->value ? g_attr->value : "" )
);
}
}
bool matcher::node_matches_rule(const GumboNode * node, const rule * r) const
{
typedef rule::const_attribute_iterator r_attr_iter;
if( node == nullptr )
return false;
if( r == nullptr )
return false;
if( node->type != GUMBO_NODE_ELEMENT )
return false;
std::string tag_name = r->get_tag_name();
if( !tag_name.empty() &&
node->v.element.tag != gumbo_tag_enum(tag_name.c_str()) )
return false;
for(r_attr_iter it = r->attributes_begin(); it != r->attributes_end(); ++it)
{
std::string attr_name = it->get_name();
GumboAttribute * g_attr =
gumbo_get_attribute(&node->v.element.attributes, attr_name.c_str());
if( !g_attr && !it->get_is_builtin() )
return false;
std::string attr_value = it->get_value();
if( !it->get_is_capture() && !attr_value.empty() )
{
if( attr_value.compare(g_attr->value) != 0 )
return false;
}
}
return true;
}
std::unique_ptr<match_tree> matcher::match(const rule * r) const
{
assert(this->g_outp != nullptr);
assert(r != nullptr);
std::unique_ptr<match_tree> m = make_unique<match_tree>();
if( r )
this->match_node(r, this->g_outp->root, m.get());
return m;
}
void matcher::match_node(
const rule * r,
const GumboNode * node,
match_tree * m
) const
{
typedef rule::const_child_iterator r_child_iter;
if( r == nullptr )
return;
if( node == nullptr )
return;
if( m == nullptr )
return;
if( node->type != GUMBO_NODE_ELEMENT )
return;
if( this->node_matches_rule(node, r) )
{
m = m->append_child_and_own(this->capture_node(r, node));
for(r_child_iter it = r->children_begin(); it != r->children_end(); ++it)
{
this->match_node_children(&(*it), node, m);
}
}
else
{
this->match_node_children(r, node, m);
}
}
void matcher::match_node_children(
const rule * r,
const GumboNode * node,
match_tree * m
) const
{
if( r == nullptr )
return;
if( node == nullptr )
return;
if( m == nullptr )
return;
if( node->type != GUMBO_NODE_ELEMENT )
return;
const GumboVector * children = &node->v.element.children;
for(unsigned int i = 0; i < children->length; ++i)
{
this->match_node(r, static_cast<const GumboNode *>(children->data[i]), m);
}
}
matcher::~matcher()
{
assert(this->g_outp != nullptr);
gumbo_destroy_output(&kGumboDefaultOptions, this->g_outp);
}
} // namespace hext
<|endoftext|> |
<commit_before>/*
* hq_sound.c
*
* Created on: 05.01.2009
* Author: gerstrong
*/
#include <SDL.h>
#include "../hqp/hq_sound.h"
#include "../keen.h"
#include "../sdl/CVideoDriver.h"
#include "../include/vorbis/oggsupport.h"
#include "../CLogFile.h"
short HQSndDrv_Load(SDL_AudioSpec *AudioSpec, stHQSound *psound, const std::string& soundfile)
{
SDL_AudioSpec AudioFileSpec;
SDL_AudioCVT Audio_cvt;
psound->sound_buffer = NULL;
std::string buf;
FILE *fp;
buf = "data/hqp/snd/" + soundfile + ".OGG"; // Start with OGG
if((fp = fopen(buf.c_str(),"rb")) != NULL)
{
#ifdef BUILD_WITH_OGG
if(openOGGSound(fp, &AudioFileSpec, AudioSpec->format, psound) != 0)
{
g_pLogFile->ftextOut(PURPLE,"OGG file could not be opened: \"%s\". The file was detected, but appears to be damaged. Trying to load the classical sound<br>", soundfile);
return 1;
}
psound->enabled = true;
#endif
#ifndef BUILD_WITH_OGG
g_pLogFile->textOut(PURPLE,"Sorry, OGG-Support is disabled!<br>");
buf = "data/hqp/snd/"+ soundfile + ".WAV";
// Check, if it is a wav file or go back to classic sounds
if (SDL_LoadWAV (buf.c_str(), &AudioFileSpec, &(psound->sound_buffer), &(psound->sound_len)) == NULL)
{
g_pLogFile->textOut(PURPLE,"Wave file could not be opened: \"%s\". Trying to load the classical sound<br>", buf.c_str());
return 1;
}
#endif
}
else
{
buf = "data/hqp/snd/" + soundfile + ".WAV";
// Check, if it is a wav file or go back to classic sounds
if (SDL_LoadWAV (buf.c_str(), &AudioFileSpec, &(psound->sound_buffer), &(psound->sound_len)) == NULL)
{
g_pLogFile->textOut(PURPLE,"Wave file could not be opened: \"%s\". Trying to load the classical sounds<br>", buf.c_str());
return 1;
}
}
psound->sound_pos = 0;
g_pLogFile->textOut(PURPLE,"File \"%s\" opened successfully!<br>", buf.c_str());
int ret;
/* Build AudioCVT (This is needed for the conversion from one format to the one used in the game)*/
ret = SDL_BuildAudioCVT(&Audio_cvt,
AudioFileSpec.format, AudioFileSpec.channels, AudioFileSpec.freq,
AudioSpec->format, AudioSpec->channels, AudioSpec->freq);
/* Check that the convert was built */
if(ret == -1){
g_pLogFile->textOut(PURPLE,"Couldn't build converter!<br>");
SDL_FreeWAV(psound->sound_buffer);
return 1;
}
/* Setup for conversion, copy original data to new buffer*/
Audio_cvt.buf = (Uint8*) malloc(psound->sound_len * Audio_cvt.len_mult);
Audio_cvt.len = psound->sound_len;
memcpy(Audio_cvt.buf, psound->sound_buffer, psound->sound_len);
/* We can delete to original WAV data now */
SDL_FreeWAV(psound->sound_buffer);
/* And now we're ready to convert */
SDL_ConvertAudio(&Audio_cvt);
/* copy the converted stuff to the original music buffer*/
psound->sound_len = Audio_cvt.len_cvt;
psound->sound_buffer = (Uint8*) malloc(psound->sound_len);
memcpy(psound->sound_buffer, Audio_cvt.buf, psound->sound_len);
// Structure Audio_cvt must be freed!
free(Audio_cvt.buf);
return 0;
}
void HQSndDrv_Unload(stHQSound *psound)
{
if(psound->sound_buffer){ free(psound->sound_buffer); psound->sound_buffer = NULL;}
}
<commit_msg>Changed hq_sound fixing problem when loading. (Still not finished)<commit_after>/*
* hq_sound.c
*
* Created on: 05.01.2009
* Author: gerstrong
*/
#include <SDL.h>
#include "../hqp/hq_sound.h"
#include "../keen.h"
#include "../sdl/CVideoDriver.h"
#include "../include/vorbis/oggsupport.h"
#include "../CLogFile.h"
short HQSndDrv_Load(SDL_AudioSpec *AudioSpec, stHQSound *psound, const std::string& soundfile)
{
SDL_AudioSpec AudioFileSpec;
SDL_AudioCVT Audio_cvt;
psound->sound_buffer = NULL;
std::string buf;
FILE *fp;
buf = "data/hqp/snd/" + soundfile + ".OGG"; // Start with OGG
if((fp = fopen(buf.c_str(),"rb")) != NULL)
{
#ifdef BUILD_WITH_OGG
if(openOGGSound(fp, &AudioFileSpec, AudioSpec->format, psound) != 0)
{
char *buf2;
buf2 = (char*) soundfile.c_str();
g_pLogFile->ftextOut(PURPLE,"OGG file could not be opened: \"%s\". The file was detected, but appears to be damaged. Trying to load the classical sound<br>", (const char*)buf2);
return 1;
}
psound->enabled = true;
#endif
#ifndef BUILD_WITH_OGG
g_pLogFile->textOut(PURPLE,"Sorry, OGG-Support is disabled!<br>");
buf = "data/hqp/snd/"+ soundfile + ".WAV";
// Check, if it is a wav file or go back to classic sounds
if (SDL_LoadWAV (buf.c_str(), &AudioFileSpec, &(psound->sound_buffer), &(psound->sound_len)) == NULL)
{
g_pLogFile->textOut(PURPLE,"Wave file could not be opened: \"%s\". Trying to load the classical sound<br>", buf.c_str());
return 1;
}
#endif
}
else
{
buf = "data/hqp/snd/" + soundfile + ".WAV";
// Check, if it is a wav file or go back to classic sounds
if (SDL_LoadWAV (buf.c_str(), &AudioFileSpec, &(psound->sound_buffer), &(psound->sound_len)) == NULL)
{
g_pLogFile->textOut(PURPLE,"Wave file could not be opened: \"%s\". Trying to load the classical sounds<br>", buf.c_str());
return 1;
}
}
psound->sound_pos = 0;
g_pLogFile->textOut(PURPLE,"File \"%s\" opened successfully!<br>", buf.c_str());
int ret;
/* Build AudioCVT (This is needed for the conversion from one format to the one used in the game)*/
ret = SDL_BuildAudioCVT(&Audio_cvt,
AudioFileSpec.format, AudioFileSpec.channels, AudioFileSpec.freq,
AudioSpec->format, AudioSpec->channels, AudioSpec->freq);
/* Check that the convert was built */
if(ret == -1){
g_pLogFile->textOut(PURPLE,"Couldn't build converter!<br>");
SDL_FreeWAV(psound->sound_buffer);
return 1;
}
/* Setup for conversion, copy original data to new buffer*/
Audio_cvt.buf = (Uint8*) malloc(psound->sound_len * Audio_cvt.len_mult);
Audio_cvt.len = psound->sound_len;
memcpy(Audio_cvt.buf, psound->sound_buffer, psound->sound_len);
/* We can delete to original WAV data now */
SDL_FreeWAV(psound->sound_buffer);
/* And now we're ready to convert */
SDL_ConvertAudio(&Audio_cvt);
/* copy the converted stuff to the original music buffer*/
psound->sound_len = Audio_cvt.len_cvt;
psound->sound_buffer = (Uint8*) malloc(psound->sound_len);
memcpy(psound->sound_buffer, Audio_cvt.buf, psound->sound_len);
// Structure Audio_cvt must be freed!
free(Audio_cvt.buf);
return 0;
}
void HQSndDrv_Unload(stHQSound *psound)
{
if(psound->sound_buffer){ free(psound->sound_buffer); psound->sound_buffer = NULL;}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011, Cornell University
// 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 HyperDex 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.
#define __STDC_LIMIT_MACROS
// POSIX
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
// Google Log
#include <glog/logging.h>
// po6
#include <po6/io/fd.h>
// HyperDex
#include <hyperdex/disk.h>
#include <hyperdex/hyperspace.h>
// XXX It might be a good idea to add bounds checking in here to prevent
// corrupted files from causing us to access out-of-bounds memory.
// Where possible, we use pointers instead of memmove, but if alignment is not
// guaranteed, memmove is preferred.
#define HASH_TABLE_ENTRIES 262144
#define HASH_TABLE_SIZE (HASH_TABLE_ENTRIES * 8)
#define SEARCH_INDEX_ENTRIES (HASH_TABLE_ENTRIES * 4)
#define SEARCH_INDEX_SIZE (SEARCH_INDEX_ENTRIES * 12)
#define INDEX_SEGMENT_SIZE (HASH_TABLE_SIZE + SEARCH_INDEX_SIZE)
#define DATA_SEGMENT_SIZE 1073741824
#define TOTAL_FILE_SIZE (INDEX_SEGMENT_SIZE + DATA_SEGMENT_SIZE)
#define INIT_BLOCK_SIZE 16384
#define INIT_ITERATIONS (TOTAL_FILE_SIZE / INIT_BLOCK_SIZE)
hyperdex :: disk :: disk(const char* filename)
: m_base(NULL)
, m_offset(INDEX_SEGMENT_SIZE)
, m_search(0)
{
po6::io::fd fd(open(filename, O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR));
if (fd.get() < 0)
{
throw po6::error(errno);
}
char buf[INIT_BLOCK_SIZE];
memset(buf, 0, sizeof(buf));
for (uint64_t i = 0; i < INIT_ITERATIONS; ++i)
{
fd.xwrite(buf, sizeof(buf));
}
if (fsync(fd.get()) < 0)
{
throw po6::error(errno);
}
m_base = static_cast<char*>(mmap(NULL, TOTAL_FILE_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd.get(), 0));
if (m_base == MAP_FAILED
|| madvise(m_base, INDEX_SEGMENT_SIZE, MADV_WILLNEED) < 0
|| madvise(m_base + INDEX_SEGMENT_SIZE, DATA_SEGMENT_SIZE, MADV_RANDOM) < 0)
{
int saved = errno;
if (m_base != MAP_FAILED)
{
if (munmap(m_base, TOTAL_FILE_SIZE) < 0)
{
PLOG(WARNING) << "Could not mmap disk";
}
}
throw po6::error(saved);
}
}
hyperdex :: disk :: ~disk()
throw ()
{
try
{
if (munmap(m_base, TOTAL_FILE_SIZE) < 0)
{
PLOG(WARNING) << "Could not munmap disk";
}
}
catch (...)
{
}
}
hyperdex :: result_t
hyperdex :: disk :: get(const e::buffer& key,
uint64_t key_hash,
std::vector<e::buffer>* value,
uint64_t* version)
{
uint32_t* hash;
uint32_t* offset;
if (!find_bucket_for_key(key, key_hash, &hash, &offset))
{
return NOTFOUND;
}
if (!offset || *offset == 0 || *offset == UINT32_MAX)
{
return NOTFOUND;
}
// Load the version.
uint32_t curr_offset = *offset;
*version = *reinterpret_cast<uint64_t*>(m_base + curr_offset);
// Fast-forward past the key (checked by find_bucket_for_key).
curr_offset += sizeof(*version) + sizeof(uint32_t) + key.size();
// Load the value.
value->clear();
uint16_t num_values;
memmove(&num_values, m_base + curr_offset, sizeof(num_values));
curr_offset += sizeof(num_values);
for (uint16_t i = 0; i < num_values; ++i)
{
uint32_t size;
memmove(&size, m_base + curr_offset, sizeof(size));
curr_offset += sizeof(size);
value->push_back(e::buffer());
e::buffer buf(m_base + curr_offset, size);
value->back().swap(buf);
curr_offset += size;
}
return SUCCESS;
}
hyperdex :: result_t
hyperdex :: disk :: put(const e::buffer& key,
uint64_t key_hash,
const std::vector<e::buffer>& value,
const std::vector<uint64_t>& value_hashes,
uint64_t version)
{
// Figure out if the PUT will fit in memory.
uint64_t hypothetical_size = sizeof(uint64_t) + sizeof(uint32_t) + sizeof(uint16_t) + key.size();
for (size_t i = 0; i < value.size(); ++i)
{
hypothetical_size += sizeof(uint32_t) + value[i].size();
}
if (hypothetical_size + m_offset > TOTAL_FILE_SIZE)
{
LOG(INFO) << "Put failed because disk is full.";
return ERROR;
}
if (m_search == SEARCH_INDEX_ENTRIES - 1)
{
LOG(INFO) << "Put failed because disk is full.";
return ERROR;
}
// Find the bucket.
uint32_t* hash;
uint32_t* offset;
if (!find_bucket_for_key(key, key_hash, &hash, &offset))
{
LOG(INFO) << "Put failed because index is full.";
return ERROR;
}
// We have our index position.
uint32_t curr_offset = m_offset;
*reinterpret_cast<uint64_t*>(m_base + curr_offset) = version;
curr_offset += sizeof(version);
uint32_t key_size = key.size();
*reinterpret_cast<uint32_t*>(m_base + curr_offset) = key_size;
curr_offset += sizeof(key_size);
memmove(m_base + curr_offset, key.get(), key_size);
curr_offset += key_size;
for (size_t i = 0; i < value.size(); ++i)
{
uint32_t size = value[i].size();
memmove(m_base + curr_offset, &size, sizeof(size));
curr_offset += sizeof(size);
memmove(m_base + curr_offset, value[i].get(), size);
curr_offset += size;
}
// Invalidate anything point to the old version. Update the offset to point
// to the new version. Update the search index.
invalidate_search_index(*offset);
*reinterpret_cast<uint32_t*>(m_base + m_search * 12) =
0xffffffff & interlace(value_hashes);
*reinterpret_cast<uint32_t*>(m_base + m_search * 12 + sizeof(uint32_t)) = m_offset;
*reinterpret_cast<uint32_t*>(m_base + m_search * 12 + sizeof(uint32_t) * 2) = 0;
++m_search;
*offset = m_offset;
m_offset = curr_offset;
return SUCCESS;
}
hyperdex :: result_t
hyperdex :: disk :: del(const e::buffer& key,
uint64_t key_hash)
{
// Find the bucket.
uint32_t* hash;
uint32_t* offset;
if (!find_bucket_for_key(key, key_hash, &hash, &offset))
{
LOG(INFO) << "Put failed because index is full.";
return ERROR;
}
if (*offset != 0 && *offset != UINT32_MAX)
{
invalidate_search_index(*offset);
*offset = UINT32_MAX;
m_offset += sizeof(uint64_t);
return SUCCESS;
}
return NOTFOUND;
}
void
hyperdex :: disk :: sync()
{
if (msync(m_base, TOTAL_FILE_SIZE, MS_SYNC) < 0)
{
PLOG(INFO) << "Could not sync disk";
}
}
bool
hyperdex :: disk :: find_bucket_for_key(const e::buffer& key,
uint64_t key_hash,
uint32_t** hash,
uint32_t** offset)
{
// First "dead" bucket.
uint32_t* dead_hash = NULL;
uint32_t* dead_offset = NULL;
// Figure out the bucket.
uint64_t bucket = key_hash % HASH_TABLE_ENTRIES;
uint32_t short_key_hash = 0xffffffff & key_hash;
for (uint64_t entry = 0; entry < HASH_TABLE_ENTRIES; ++entry)
{
uint32_t* tmp_hash = reinterpret_cast<uint32_t*>(m_base + (bucket + entry % HASH_TABLE_ENTRIES) * 8);
uint32_t* tmp_offset = reinterpret_cast<uint32_t*>(m_base + (bucket + entry % HASH_TABLE_ENTRIES) * 8 + 4);
// If we've found an empty bucket.
if (*tmp_offset == 0)
{
*hash = tmp_hash;
*offset = tmp_offset;
return true;
}
// If we've found our first dead bucket.
if (*tmp_offset == UINT32_MAX && dead_hash == NULL)
{
dead_hash = tmp_hash;
dead_offset = tmp_offset;
continue;
}
if (*tmp_hash == short_key_hash)
{
uint64_t curr_offset = *tmp_offset + sizeof(uint64_t);
uint32_t key_size = *reinterpret_cast<uint32_t*>(m_base + curr_offset);
curr_offset += sizeof(key_size);
// If the key doesn't match because of a hash collision.
if (key_size != key.size() || memcmp(m_base + curr_offset, key.get(), key_size) != 0)
{
continue;
}
*hash = tmp_hash;
*offset = tmp_offset;
return true;
}
}
*hash = dead_hash;
*offset = dead_offset;
return hash != NULL;
}
void
hyperdex :: disk :: invalidate_search_index(uint32_t to_invalidate)
{
for (uint64_t entry = 0; entry < SEARCH_INDEX_ENTRIES; ++entry)
{
uint32_t* offset = reinterpret_cast<uint32_t*>(m_base + entry * 12 + sizeof(uint32_t));
uint32_t* invalidator = reinterpret_cast<uint32_t*>(m_base + entry * 12 + sizeof(uint32_t));
if (*offset == 0)
{
return;
}
else if (*offset == to_invalidate)
{
*invalidator = m_offset;
}
}
}
<commit_msg>Do not create disks at construction.<commit_after>// Copyright (c) 2011, Cornell University
// 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 HyperDex 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.
#define __STDC_LIMIT_MACROS
// POSIX
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
// Google Log
#include <glog/logging.h>
// po6
#include <po6/io/fd.h>
// HyperDex
#include <hyperdex/disk.h>
#include <hyperdex/hyperspace.h>
// XXX It might be a good idea to add bounds checking in here to prevent
// corrupted files from causing us to access out-of-bounds memory.
// Where possible, we use pointers instead of memmove, but if alignment is not
// guaranteed, memmove is preferred.
#define HASH_TABLE_ENTRIES 262144
#define HASH_TABLE_SIZE (HASH_TABLE_ENTRIES * 8)
#define SEARCH_INDEX_ENTRIES (HASH_TABLE_ENTRIES * 4)
#define SEARCH_INDEX_SIZE (SEARCH_INDEX_ENTRIES * 12)
#define INDEX_SEGMENT_SIZE (HASH_TABLE_SIZE + SEARCH_INDEX_SIZE)
#define DATA_SEGMENT_SIZE 1073741824
#define TOTAL_FILE_SIZE (INDEX_SEGMENT_SIZE + DATA_SEGMENT_SIZE)
#define INIT_BLOCK_SIZE 16384
#define INIT_ITERATIONS (TOTAL_FILE_SIZE / INIT_BLOCK_SIZE)
hyperdex :: disk :: disk(const char* filename)
: m_base(NULL)
, m_offset(INDEX_SEGMENT_SIZE)
, m_search(0)
{
po6::io::fd fd(open(filename, O_RDWR, S_IRUSR|S_IWUSR));
if (fd.get() < 0)
{
throw po6::error(errno);
}
struct stat buf;
if (fstat(fd.get(), &buf) < 0)
{
throw po6::error(errno);
}
if (buf.st_size < TOTAL_FILE_SIZE)
{
throw std::runtime_error("File is too small.");
}
m_base = static_cast<char*>(mmap(NULL, TOTAL_FILE_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd.get(), 0));
if (m_base == MAP_FAILED
|| madvise(m_base, HASH_TABLE_SIZE, MADV_WILLNEED) < 0
|| madvise(m_base + HASH_TABLE_SIZE, SEARCH_INDEX_SIZE, MADV_SEQUENTIAL) < 0
|| madvise(m_base + INDEX_SEGMENT_SIZE, DATA_SEGMENT_SIZE, MADV_RANDOM) < 0)
{
int saved = errno;
if (m_base != MAP_FAILED)
{
if (munmap(m_base, TOTAL_FILE_SIZE) < 0)
{
PLOG(WARNING) << "Could not mmap disk";
}
}
throw po6::error(saved);
}
}
hyperdex :: disk :: ~disk()
throw ()
{
try
{
if (munmap(m_base, TOTAL_FILE_SIZE) < 0)
{
PLOG(WARNING) << "Could not munmap disk";
}
}
catch (...)
{
}
}
hyperdex :: result_t
hyperdex :: disk :: get(const e::buffer& key,
uint64_t key_hash,
std::vector<e::buffer>* value,
uint64_t* version)
{
uint32_t* hash;
uint32_t* offset;
if (!find_bucket_for_key(key, key_hash, &hash, &offset))
{
return NOTFOUND;
}
if (!offset || *offset == 0 || *offset == UINT32_MAX)
{
return NOTFOUND;
}
// Load the version.
uint32_t curr_offset = *offset;
*version = *reinterpret_cast<uint64_t*>(m_base + curr_offset);
// Fast-forward past the key (checked by find_bucket_for_key).
curr_offset += sizeof(*version) + sizeof(uint32_t) + key.size();
// Load the value.
value->clear();
uint16_t num_values;
memmove(&num_values, m_base + curr_offset, sizeof(num_values));
curr_offset += sizeof(num_values);
for (uint16_t i = 0; i < num_values; ++i)
{
uint32_t size;
memmove(&size, m_base + curr_offset, sizeof(size));
curr_offset += sizeof(size);
value->push_back(e::buffer());
e::buffer buf(m_base + curr_offset, size);
value->back().swap(buf);
curr_offset += size;
}
return SUCCESS;
}
hyperdex :: result_t
hyperdex :: disk :: put(const e::buffer& key,
uint64_t key_hash,
const std::vector<e::buffer>& value,
const std::vector<uint64_t>& value_hashes,
uint64_t version)
{
// Figure out if the PUT will fit in memory.
uint64_t hypothetical_size = sizeof(uint64_t) + sizeof(uint32_t) + sizeof(uint16_t) + key.size();
for (size_t i = 0; i < value.size(); ++i)
{
hypothetical_size += sizeof(uint32_t) + value[i].size();
}
if (hypothetical_size + m_offset > TOTAL_FILE_SIZE)
{
LOG(INFO) << "Put failed because disk is full.";
return ERROR;
}
if (m_search == SEARCH_INDEX_ENTRIES - 1)
{
LOG(INFO) << "Put failed because disk is full.";
return ERROR;
}
// Find the bucket.
uint32_t* hash;
uint32_t* offset;
if (!find_bucket_for_key(key, key_hash, &hash, &offset))
{
LOG(INFO) << "Put failed because index is full.";
return ERROR;
}
// We have our index position.
uint32_t curr_offset = m_offset;
*reinterpret_cast<uint64_t*>(m_base + curr_offset) = version;
curr_offset += sizeof(version);
uint32_t key_size = key.size();
*reinterpret_cast<uint32_t*>(m_base + curr_offset) = key_size;
curr_offset += sizeof(key_size);
memmove(m_base + curr_offset, key.get(), key_size);
curr_offset += key_size;
for (size_t i = 0; i < value.size(); ++i)
{
uint32_t size = value[i].size();
memmove(m_base + curr_offset, &size, sizeof(size));
curr_offset += sizeof(size);
memmove(m_base + curr_offset, value[i].get(), size);
curr_offset += size;
}
// Invalidate anything point to the old version. Update the offset to point
// to the new version. Update the search index.
invalidate_search_index(*offset);
*reinterpret_cast<uint32_t*>(m_base + m_search * 12) =
0xffffffff & interlace(value_hashes);
*reinterpret_cast<uint32_t*>(m_base + m_search * 12 + sizeof(uint32_t)) = m_offset;
*reinterpret_cast<uint32_t*>(m_base + m_search * 12 + sizeof(uint32_t) * 2) = 0;
++m_search;
*offset = m_offset;
m_offset = curr_offset;
return SUCCESS;
}
hyperdex :: result_t
hyperdex :: disk :: del(const e::buffer& key,
uint64_t key_hash)
{
// Find the bucket.
uint32_t* hash;
uint32_t* offset;
if (!find_bucket_for_key(key, key_hash, &hash, &offset))
{
LOG(INFO) << "Put failed because index is full.";
return ERROR;
}
if (*offset != 0 && *offset != UINT32_MAX)
{
invalidate_search_index(*offset);
*offset = UINT32_MAX;
m_offset += sizeof(uint64_t);
return SUCCESS;
}
return NOTFOUND;
}
void
hyperdex :: disk :: sync()
{
if (msync(m_base, TOTAL_FILE_SIZE, MS_SYNC) < 0)
{
PLOG(INFO) << "Could not sync disk";
}
}
bool
hyperdex :: disk :: find_bucket_for_key(const e::buffer& key,
uint64_t key_hash,
uint32_t** hash,
uint32_t** offset)
{
// First "dead" bucket.
uint32_t* dead_hash = NULL;
uint32_t* dead_offset = NULL;
// Figure out the bucket.
uint64_t bucket = key_hash % HASH_TABLE_ENTRIES;
uint32_t short_key_hash = 0xffffffff & key_hash;
for (uint64_t entry = 0; entry < HASH_TABLE_ENTRIES; ++entry)
{
uint32_t* tmp_hash = reinterpret_cast<uint32_t*>(m_base + (bucket + entry % HASH_TABLE_ENTRIES) * 8);
uint32_t* tmp_offset = reinterpret_cast<uint32_t*>(m_base + (bucket + entry % HASH_TABLE_ENTRIES) * 8 + 4);
// If we've found an empty bucket.
if (*tmp_offset == 0)
{
*hash = tmp_hash;
*offset = tmp_offset;
return true;
}
// If we've found our first dead bucket.
if (*tmp_offset == UINT32_MAX && dead_hash == NULL)
{
dead_hash = tmp_hash;
dead_offset = tmp_offset;
continue;
}
if (*tmp_hash == short_key_hash)
{
uint64_t curr_offset = *tmp_offset + sizeof(uint64_t);
uint32_t key_size = *reinterpret_cast<uint32_t*>(m_base + curr_offset);
curr_offset += sizeof(key_size);
// If the key doesn't match because of a hash collision.
if (key_size != key.size() || memcmp(m_base + curr_offset, key.get(), key_size) != 0)
{
continue;
}
*hash = tmp_hash;
*offset = tmp_offset;
return true;
}
}
*hash = dead_hash;
*offset = dead_offset;
return hash != NULL;
}
void
hyperdex :: disk :: invalidate_search_index(uint32_t to_invalidate)
{
for (uint64_t entry = 0; entry < SEARCH_INDEX_ENTRIES; ++entry)
{
uint32_t* offset = reinterpret_cast<uint32_t*>(m_base + entry * 12 + sizeof(uint32_t));
uint32_t* invalidator = reinterpret_cast<uint32_t*>(m_base + entry * 12 + sizeof(uint32_t));
if (*offset == 0)
{
return;
}
else if (*offset == to_invalidate)
{
*invalidator = m_offset;
}
}
}
<|endoftext|> |
<commit_before>
//===----------------------------------------------------------------------===//
//
// Peloton
//
// bwtree.cpp
//
// Identification: src/index/bwtree.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "index/bwtree.h"
#ifdef BWTREE_PELOTON
namespace peloton {
namespace index {
#endif
bool print_flag = true;
#ifdef BWTREE_PELOTON
} // End index namespace
} // End peloton namespace
#endif
<commit_msg>Removing print_flag<commit_after>
//===----------------------------------------------------------------------===//
//
// Peloton
//
// bwtree.cpp
//
// Identification: src/index/bwtree.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "index/bwtree.h"
#ifdef BWTREE_PELOTON
namespace peloton {
namespace index {
#endif
#ifdef BWTREE_PELOTON
} // End index namespace
} // End peloton namespace
#endif
<|endoftext|> |
<commit_before>// Best-first Utility-Guided Search Yes! From:
// "Best-first Utility-Guided Search," Wheeler Ruml and Minh B. Do,
// Proceedings of the Twentieth International Joint Conference on
// Artificial Intelligence (IJCAI-07), 2007
#include "../search/search.hpp"
#include "../structs/binheap.hpp"
#include "../utils/pool.hpp"
template <class D> struct Bugsy : public SearchAlgorithm<D> {
typedef typename D::State State;
typedef typename D::PackedState PackedState;
typedef typename D::Cost Cost;
typedef typename D::Oper Oper;
struct Node : SearchNode<D> {
typename D::Cost f, h, d;
double u, t;
// The expansion count when this node was
// generated.
unsigned long expct;
static bool pred(Node *a, Node *b) {
if (a->u != b->u)
return a->u > b->u;
if (a->t != b->t)
return a->t < b->t;
if (a->f != b->f)
return a->f < b->f;
return a->g > b->g;
}
};
enum {
// Resort1 is the number of expansions to perform
// before the 1st open list resort.
Resort1 = 128,
};
Bugsy(int argc, const char *argv[]) :
SearchAlgorithm<D>(argc, argv), usehhat(false),
usedhat(false), navg(0), herror(0), derror(0),
useexpdelay(false), avgdelay(0), dropdups(false),
timeper(0.0), nextresort(Resort1), nresort(0),
closed(30000001) {
wf = wt = -1;
for (int i = 0; i < argc; i++) {
if (i < argc - 1 && strcmp(argv[i], "-wf") == 0)
wf = strtod(argv[++i], NULL);
else if (i < argc - 1 && strcmp(argv[i], "-wt") == 0)
wt = strtod(argv[++i], NULL);
else if (i < argc - 1 && strcmp(argv[i], "-expdelay") == 0)
useexpdelay = true;
else if (i < argc - 1 && strcmp(argv[i], "-hhat") == 0)
usehhat = true;
else if (i < argc - 1 && strcmp(argv[i], "-dhat") == 0)
usedhat = true;
else if (i < argc - 1 && strcmp(argv[i], "-dropdups") == 0)
dropdups = true;
}
if (wf < 0)
fatal("Must specify non-negative f-weight using -wf");
if (wt < 0)
fatal("Must specify non-negative t-weight using -wt");
nodes = new Pool<Node>();
}
~Bugsy() {
delete nodes;
}
void search(D &d, typename D::State &s0) {
this->start();
last = walltime();
closed.init(d);
Node *n0 = init(d, s0);
closed.add(n0);
open.push(n0);
while (!open.empty() && !SearchAlgorithm<D>::limit()) {
Node* n = *open.pop();
State buf, &state = d.unpack(buf, n->packed);
if (d.isgoal(state)) {
SearchAlgorithm<D>::res.goal(d, n);
break;
}
expand(d, n, state);
updatetime();
updateopen();
}
this->finish();
}
virtual void reset() {
SearchAlgorithm<D>::reset();
open.clear();
closed.clear();
delete nodes;
timeper = 0.0;
nresort = 0;
nextresort = Resort1;
navg = 0;
herror = derror = 0;
nodes = new Pool<Node>();
}
virtual void output(FILE *out) {
SearchAlgorithm<D>::output(out);
closed.prstats(stdout, "closed ");
dfpair(stdout, "open list type", "%s", "binary heap");
dfpair(stdout, "node size", "%u", sizeof(Node));
dfpair(stdout, "cost weight", "%g", wf);
dfpair(stdout, "time weight", "%g", wt);
dfpair(stdout, "final time per expand", "%g", timeper);
dfpair(stdout, "number of resorts", "%lu", nresort);
if (usehhat)
dfpair(stdout, "mean single-step h error", "%g", herror);
if (usedhat)
dfpair(stdout, "mean single-step d error", "%g", derror);
if (useexpdelay)
dfpair(stdout, "mean expansion delay", "%g", avgdelay);
}
private:
// Kidinfo holds information about a node used for
// correcting the heuristic estimates.
struct Kidinfo {
Kidinfo() : f(-1), h(-1), d(-1) { }
Kidinfo(Cost gval, Cost hval, Cost dval) : f(gval + hval), h(hval), d(dval) { }
Cost f, h, d;
};
// expand expands the node, adding its children to the
// open and closed lists as appropriate.
void expand(D &d, Node *n, State &state) {
this->res.expd++;
if (useexpdelay) {
unsigned long delay = this->res.expd - n->expct;
avgdelay = avgdelay + (delay - avgdelay)/this->res.expd;
}
Kidinfo bestinfo;
typename D::Operators ops(d, state);
for (unsigned int i = 0; i < ops.size(); i++) {
if (ops[i] == n->pop)
continue;
this->res.gend++;
Kidinfo kinfo = considerkid(d, n, state, ops[i]);
if (bestinfo.f < Cost(0) || kinfo.f < bestinfo.f)
bestinfo = kinfo;
}
if (bestinfo.f < Cost(0))
return;
navg++;
if (usehhat) {
double herr = bestinfo.f - n->f;
assert (herr >= 0);
herror = herror + (herr - herror)/navg;
}
if (usedhat) {
double derr = bestinfo.d + 1 - n->d;
assert (derr >= 0);
derror = derror + (derr - derror)/navg;
}
}
// considers adding the child to the open and closed lists.
Kidinfo considerkid(D &d, Node *parent, State &state, Oper op) {
Node *kid = nodes->construct();
typename D::Edge e(d, state, op);
kid->g = parent->g + e.cost;
// single step path-max on d
kid->d = d.d(e.state);
if (kid->d < parent->d - Cost(1))
kid->d = parent->d - Cost(1);
// single step path-max on h
kid->h = d.h(e.state);
if (kid->h < parent->h - e.cost)
kid->h = parent->h - e.cost;
kid->f = kid->g + kid->h;
if (useexpdelay)
kid->expct = this->res.expd;
Kidinfo kinfo(kid->g, kid->h, kid->d);
d.pack(kid->packed, e.state);
unsigned long hash = d.hash(kid->packed);
Node *dup = static_cast<Node*>(closed.find(kid->packed, hash));
if (dup) {
this->res.dups++;
if (!dropdups && kid->g < dup->g) {
this->res.reopnd++;
dup->f = dup->f - dup->g + kid->g;
dup->update(kid->g, parent, op, e.revop);
computeutil(dup);
open.pushupdate(dup, dup->ind);
}
nodes->destruct(kid);
} else {
kid->update(kid->g, parent, op, e.revop);
computeutil(kid);
closed.add(kid, hash);
open.push(kid);
}
return kinfo;
}
Node *init(D &d, State &s0) {
Node *n0 = nodes->construct();
d.pack(n0->packed, s0);
n0->g = Cost(0);
n0->h = n0->f = d.h(s0);
n0->d = d.d(s0);
computeutil(n0);
n0->op = n0->pop = D::Nop;
n0->parent = NULL;
n0->expct = 0;
return n0;
}
// compututil computes the utility value of the given node
// using corrected estimates of d and h.
void computeutil(Node *n) {
double d = n->d;
if (usedhat)
d /= (1 - derror);
double h = n->h;
if (usehhat)
h += d * herror;
if (useexpdelay && avgdelay > 0)
d *= avgdelay;
double f = h + n->g;
n->t = timeper * d;
n->u = -(wf * f + wt * n->t);
}
// updatetime runs a simple state machine (from Wheeler's BUGSY
// implementation) that estimates the node expansion rate.
void updatetime() {
double t = walltime() - last;
timeper = timeper + (t - timeper)/this->res.expd;
last = walltime();
}
// updateopen updates the utilities of all nodes on open and
// reinitializes the heap every 2^i expansions.
void updateopen() {
if (this->res.expd < nextresort)
return;
nextresort *= 2;
nresort++;
for (int i = 0; i < open.size(); i++)
computeutil(open.at(i));
open.reinit();
}
// wf and wt are the cost and time weight respectively.
double wf, wt;
// heuristic correction
bool usehhat, usedhat;
unsigned long navg;
double herror, derror;
// expansion delay
bool useexpdelay;
double avgdelay;
bool dropdups;
// for nodes-per-second estimation
double timeper, last;
// for resorting the open list
unsigned long nextresort;
unsigned int nresort;
BinHeap<Node, Node*> open;
ClosedList<SearchNode<D>, SearchNode<D>, D> closed;
Pool<Node> *nodes;
};
<commit_msg>Path-based expansion delay.<commit_after>// Best-first Utility-Guided Search Yes! From:
// "Best-first Utility-Guided Search," Wheeler Ruml and Minh B. Do,
// Proceedings of the Twentieth International Joint Conference on
// Artificial Intelligence (IJCAI-07), 2007
#include "../search/search.hpp"
#include "../structs/binheap.hpp"
#include "../utils/pool.hpp"
template <class D> struct Bugsy : public SearchAlgorithm<D> {
typedef typename D::State State;
typedef typename D::PackedState PackedState;
typedef typename D::Cost Cost;
typedef typename D::Oper Oper;
struct Node : SearchNode<D> {
typename D::Cost f, h, d;
double u, t;
// The expansion count when this node was
// generated.
unsigned long expct;
// path-based mean expansion delay.
double avgdelay;
unsigned long depth;
static bool pred(Node *a, Node *b) {
if (a->u != b->u)
return a->u > b->u;
if (a->t != b->t)
return a->t < b->t;
if (a->f != b->f)
return a->f < b->f;
return a->g > b->g;
}
};
enum {
// Resort1 is the number of expansions to perform
// before the 1st open list resort.
Resort1 = 128,
};
Bugsy(int argc, const char *argv[]) :
SearchAlgorithm<D>(argc, argv), usehhat(false),
usedhat(false), navg(0), herror(0), derror(0),
useexpdelay(false), avgdelay(0), dropdups(false),
timeper(0.0), nextresort(Resort1), nresort(0),
closed(30000001) {
wf = wt = -1;
for (int i = 0; i < argc; i++) {
if (i < argc - 1 && strcmp(argv[i], "-wf") == 0)
wf = strtod(argv[++i], NULL);
else if (i < argc - 1 && strcmp(argv[i], "-wt") == 0)
wt = strtod(argv[++i], NULL);
else if (i < argc - 1 && strcmp(argv[i], "-expdelay") == 0)
useexpdelay = true;
else if (i < argc - 1 && strcmp(argv[i], "-expdelay-path") == 0)
useexpdelay = delaypath = true;
else if (i < argc - 1 && strcmp(argv[i], "-hhat") == 0)
usehhat = true;
else if (i < argc - 1 && strcmp(argv[i], "-dhat") == 0)
usedhat = true;
else if (i < argc - 1 && strcmp(argv[i], "-dropdups") == 0)
dropdups = true;
}
if (wf < 0)
fatal("Must specify non-negative f-weight using -wf");
if (wt < 0)
fatal("Must specify non-negative t-weight using -wt");
nodes = new Pool<Node>();
}
~Bugsy() {
delete nodes;
}
void search(D &d, typename D::State &s0) {
this->start();
last = walltime();
closed.init(d);
Node *n0 = init(d, s0);
closed.add(n0);
open.push(n0);
while (!open.empty() && !SearchAlgorithm<D>::limit()) {
Node* n = *open.pop();
State buf, &state = d.unpack(buf, n->packed);
if (d.isgoal(state)) {
SearchAlgorithm<D>::res.goal(d, n);
break;
}
expand(d, n, state);
updatetime();
updateopen();
}
this->finish();
}
virtual void reset() {
SearchAlgorithm<D>::reset();
open.clear();
closed.clear();
delete nodes;
timeper = 0.0;
nresort = 0;
nextresort = Resort1;
navg = 0;
herror = derror = 0;
nodes = new Pool<Node>();
}
virtual void output(FILE *out) {
SearchAlgorithm<D>::output(out);
closed.prstats(stdout, "closed ");
dfpair(stdout, "open list type", "%s", "binary heap");
dfpair(stdout, "node size", "%u", sizeof(Node));
dfpair(stdout, "cost weight", "%g", wf);
dfpair(stdout, "time weight", "%g", wt);
dfpair(stdout, "final time per expand", "%g", timeper);
dfpair(stdout, "number of resorts", "%lu", nresort);
if (usehhat)
dfpair(stdout, "mean single-step h error", "%g", herror);
if (usedhat)
dfpair(stdout, "mean single-step d error", "%g", derror);
if (useexpdelay && !delaypath)
dfpair(stdout, "mean expansion delay", "%g", avgdelay);
}
private:
// Kidinfo holds information about a node used for
// correcting the heuristic estimates.
struct Kidinfo {
Kidinfo() : f(-1), h(-1), d(-1) { }
Kidinfo(Cost gval, Cost hval, Cost dval) : f(gval + hval), h(hval), d(dval) { }
Cost f, h, d;
};
// expand expands the node, adding its children to the
// open and closed lists as appropriate.
void expand(D &d, Node *n, State &state) {
this->res.expd++;
if (useexpdelay) {
unsigned long delay = this->res.expd - n->expct;
if (delaypath)
n->avgdelay = n->avgdelay + (delay - n->avgdelay)/n->depth;
else
avgdelay = avgdelay + (delay - avgdelay)/this->res.expd;
}
Kidinfo bestinfo;
typename D::Operators ops(d, state);
for (unsigned int i = 0; i < ops.size(); i++) {
if (ops[i] == n->pop)
continue;
this->res.gend++;
Kidinfo kinfo = considerkid(d, n, state, ops[i]);
if (bestinfo.f < Cost(0) || kinfo.f < bestinfo.f)
bestinfo = kinfo;
}
if (bestinfo.f < Cost(0))
return;
navg++;
if (usehhat) {
double herr = bestinfo.f - n->f;
assert (herr >= 0);
herror = herror + (herr - herror)/navg;
}
if (usedhat) {
double derr = bestinfo.d + 1 - n->d;
assert (derr >= 0);
derror = derror + (derr - derror)/navg;
}
}
// considers adding the child to the open and closed lists.
Kidinfo considerkid(D &d, Node *parent, State &state, Oper op) {
Node *kid = nodes->construct();
typename D::Edge e(d, state, op);
kid->g = parent->g + e.cost;
kid->depth = parent->depth + 1;
kid->avgdelay = parent->avgdelay;
// single step path-max on d
kid->d = d.d(e.state);
if (kid->d < parent->d - Cost(1))
kid->d = parent->d - Cost(1);
// single step path-max on h
kid->h = d.h(e.state);
if (kid->h < parent->h - e.cost)
kid->h = parent->h - e.cost;
kid->f = kid->g + kid->h;
if (useexpdelay)
kid->expct = this->res.expd;
Kidinfo kinfo(kid->g, kid->h, kid->d);
d.pack(kid->packed, e.state);
unsigned long hash = d.hash(kid->packed);
Node *dup = static_cast<Node*>(closed.find(kid->packed, hash));
if (dup) {
this->res.dups++;
if (!dropdups && kid->g < dup->g) {
this->res.reopnd++;
dup->f = dup->f - dup->g + kid->g;
dup->update(kid->g, parent, op, e.revop);
computeutil(dup);
open.pushupdate(dup, dup->ind);
}
nodes->destruct(kid);
} else {
kid->update(kid->g, parent, op, e.revop);
computeutil(kid);
closed.add(kid, hash);
open.push(kid);
}
return kinfo;
}
Node *init(D &d, State &s0) {
Node *n0 = nodes->construct();
d.pack(n0->packed, s0);
n0->g = Cost(0);
n0->h = n0->f = d.h(s0);
n0->d = d.d(s0);
n0->depth = 0;
n0->avgdelay = 0;
computeutil(n0);
n0->op = n0->pop = D::Nop;
n0->parent = NULL;
n0->expct = 0;
return n0;
}
// compututil computes the utility value of the given node
// using corrected estimates of d and h.
void computeutil(Node *n) {
double d = n->d;
if (usedhat)
d /= (1 - derror);
double h = n->h;
if (usehhat)
h += d * herror;
if (useexpdelay) {
double avg = delaypath ? n->avgdelay : avgdelay;
if (avg > 0)
d *= avg;
}
double f = h + n->g;
n->t = timeper * d;
n->u = -(wf * f + wt * n->t);
}
// updatetime runs a simple state machine (from Wheeler's BUGSY
// implementation) that estimates the node expansion rate.
void updatetime() {
double t = walltime() - last;
timeper = timeper + (t - timeper)/this->res.expd;
last = walltime();
}
// updateopen updates the utilities of all nodes on open and
// reinitializes the heap every 2^i expansions.
void updateopen() {
if (this->res.expd < nextresort)
return;
nextresort *= 2;
nresort++;
for (int i = 0; i < open.size(); i++)
computeutil(open.at(i));
open.reinit();
}
// wf and wt are the cost and time weight respectively.
double wf, wt;
// heuristic correction
bool usehhat, usedhat;
unsigned long navg;
double herror, derror;
// expansion delay
bool useexpdelay, delaypath;
double avgdelay;
bool dropdups;
// for nodes-per-second estimation
double timeper, last;
// for resorting the open list
unsigned long nextresort;
unsigned int nresort;
BinHeap<Node, Node*> open;
ClosedList<SearchNode<D>, SearchNode<D>, D> closed;
Pool<Node> *nodes;
};
<|endoftext|> |
<commit_before>#include "query.hpp"
#include "delimiters.hpp"
#include "keyword_matcher.hpp"
#include "string_match.hpp"
namespace search
{
namespace impl
{
uint32_t KeywordMatch(strings::UniChar const * sA, uint32_t sizeA,
strings::UniChar const * sB, uint32_t sizeB,
uint32_t maxCost)
{
return StringMatchCost(sA, sizeA, sB, sizeB, DefaultMatchCost(), maxCost, false);
}
uint32_t PrefixMatch(strings::UniChar const * sA, uint32_t sizeA,
strings::UniChar const * sB, uint32_t sizeB,
uint32_t maxCost)
{
return StringMatchCost(sA, sizeA, sB, sizeB, DefaultMatchCost(), maxCost, true);
}
Query::Query(string const & query, m2::RectD const & rect, IndexType const * pIndex)
: m_queryText(query), m_rect(rect), m_pIndex(pIndex)
{
search::Delimiters delims;
for (strings::TokenizeIterator<search::Delimiters> iter(query, delims); iter; ++iter)
{
if (iter.IsLast() && !delims(strings::LastUniChar(query)))
m_prefix = iter.GetUniString();
else
m_keywords.push_back(strings::MakeLowerCase(iter.GetUniString()));
}
}
struct FeatureProcessor
{
Query & m_query;
explicit FeatureProcessor(Query & query) : m_query(query) {}
void operator () (FeatureType const & feature) const
{
KeywordMatcher matcher(&m_query.m_keywords[0], m_query.m_keywords.size(),
m_query.m_prefix, 1000, 1000,
&KeywordMatch, &PrefixMatch);
feature.ForEachNameRef(matcher);
m_query.AddResult(Result(feature.GetPreferredDrawableName(), feature.GetLimitRect(-1),
matcher.GetMatchScore()));
}
};
void Query::Search(function<void (Result const &)> const & f)
{
FeatureProcessor featureProcessor(*this);
m_pIndex->ForEachInViewport(featureProcessor, m_rect);
vector<Result> results;
results.reserve(m_resuts.size());
while (!m_resuts.empty())
{
results.push_back(m_resuts.top());
m_resuts.pop();
}
for (vector<Result>::const_reverse_iterator it = results.rbegin(); it != results.rend(); ++it)
f(*it);
}
void Query::AddResult(Result const & result)
{
m_resuts.push(result);
while (m_resuts.size() > 10)
m_resuts.pop();
}
bool Query::ResultBetter::operator ()(Result const & r1, Result const & r2) const
{
return r1.GetPenalty() < r2.GetPenalty();
}
} // namespace search::impl
} // namespace search
<commit_msg>[search] Make prefix lower case as well.<commit_after>#include "query.hpp"
#include "delimiters.hpp"
#include "keyword_matcher.hpp"
#include "string_match.hpp"
namespace search
{
namespace impl
{
uint32_t KeywordMatch(strings::UniChar const * sA, uint32_t sizeA,
strings::UniChar const * sB, uint32_t sizeB,
uint32_t maxCost)
{
return StringMatchCost(sA, sizeA, sB, sizeB, DefaultMatchCost(), maxCost, false);
}
uint32_t PrefixMatch(strings::UniChar const * sA, uint32_t sizeA,
strings::UniChar const * sB, uint32_t sizeB,
uint32_t maxCost)
{
return StringMatchCost(sA, sizeA, sB, sizeB, DefaultMatchCost(), maxCost, true);
}
Query::Query(string const & query, m2::RectD const & rect, IndexType const * pIndex)
: m_queryText(query), m_rect(rect), m_pIndex(pIndex)
{
search::Delimiters delims;
for (strings::TokenizeIterator<search::Delimiters> iter(query, delims); iter; ++iter)
{
if (iter.IsLast() && !delims(strings::LastUniChar(query)))
m_prefix = strings::MakeLowerCase(iter.GetUniString());
else
m_keywords.push_back(strings::MakeLowerCase(iter.GetUniString()));
}
}
struct FeatureProcessor
{
Query & m_query;
explicit FeatureProcessor(Query & query) : m_query(query) {}
void operator () (FeatureType const & feature) const
{
KeywordMatcher matcher(&m_query.m_keywords[0], m_query.m_keywords.size(),
m_query.m_prefix, 1000, 1000,
&KeywordMatch, &PrefixMatch);
feature.ForEachNameRef(matcher);
m_query.AddResult(Result(feature.GetPreferredDrawableName(), feature.GetLimitRect(-1),
matcher.GetMatchScore()));
}
};
void Query::Search(function<void (Result const &)> const & f)
{
FeatureProcessor featureProcessor(*this);
m_pIndex->ForEachInViewport(featureProcessor, m_rect);
vector<Result> results;
results.reserve(m_resuts.size());
while (!m_resuts.empty())
{
results.push_back(m_resuts.top());
m_resuts.pop();
}
for (vector<Result>::const_reverse_iterator it = results.rbegin(); it != results.rend(); ++it)
f(*it);
}
void Query::AddResult(Result const & result)
{
m_resuts.push(result);
while (m_resuts.size() > 10)
m_resuts.pop();
}
bool Query::ResultBetter::operator ()(Result const & r1, Result const & r2) const
{
return r1.GetPenalty() < r2.GetPenalty();
}
} // namespace search::impl
} // namespace search
<|endoftext|> |
<commit_before>#include "inoreaderapi.h"
#include <cstring>
#include <curl/curl.h>
#include <json.h>
#include <vector>
#include "config.h"
#include "strprintf.h"
#include "utils.h"
#define INOREADER_LOGIN "https://inoreader.com/accounts/ClientLogin"
#define INOREADER_API_PREFIX "https://inoreader.com/reader/api/0/"
#define INOREADER_FEED_PREFIX "https://inoreader.com/reader/atom/"
#define INOREADER_SUBSCRIPTION_LIST INOREADER_API_PREFIX "subscription/list"
#define INOREADER_API_MARK_ALL_READ_URL INOREADER_API_PREFIX "mark-all-as-read"
#define INOREADER_API_EDIT_TAG_URL INOREADER_API_PREFIX "edit-tag"
#define INOREADER_API_TOKEN_URL INOREADER_API_PREFIX "token"
#define INOREADER_APP_ID "AppId: 1000000394"
#define INOREADER_APP_KEY "AppKey: CWcdJdSDcuxHYoqGa3RsPh7X2DZ2MmO7"
// for reference, see https://inoreader.com/developers
namespace newsboat {
InoreaderApi::InoreaderApi(ConfigContainer* c)
: RemoteApi(c)
{
// TODO
}
InoreaderApi::~InoreaderApi()
{
// TODO
}
bool InoreaderApi::authenticate()
{
auth = retrieve_auth();
LOG(Level::DEBUG, "InoreaderApi::authenticate: Auth = %s", auth);
return auth != "";
}
static size_t my_write_data(void* buffer, size_t size, size_t nmemb,
void* userp)
{
std::string* pbuf = static_cast<std::string*>(userp);
pbuf->append(static_cast<const char*>(buffer), size * nmemb);
return size * nmemb;
}
std::string InoreaderApi::retrieve_auth()
{
CURL* handle = curl_easy_init();
Credentials cred = get_credentials("inoreader", "Inoreader");
if (cred.user.empty() || cred.pass.empty()) {
return "";
}
char* username = curl_easy_escape(handle, cred.user.c_str(), 0);
char* password = curl_easy_escape(handle, cred.pass.c_str(), 0);
std::string postcontent =
strprintf::fmt("Email=%s&Passwd=%s", username, password);
curl_free(username);
curl_free(password);
std::string result;
curl_slist* list = NULL;
list = curl_slist_append(list, INOREADER_APP_ID);
list = curl_slist_append(list, INOREADER_APP_KEY);
utils::set_common_curl_options(handle, cfg);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, my_write_data);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &result);
curl_easy_setopt(handle, CURLOPT_POSTFIELDS, postcontent.c_str());
curl_easy_setopt(handle, CURLOPT_URL, INOREADER_LOGIN);
curl_easy_perform(handle);
curl_easy_cleanup(handle);
curl_slist_free_all(list);
std::vector<std::string> lines = utils::tokenize(result);
for (const auto& line : lines) {
LOG(Level::DEBUG,
"InoreaderApi::retrieve_auth: line = %s",
line);
const std::string auth_string = "Auth=";
if (line.compare(0, auth_string.length(), auth_string) == 0) {
std::string auth = line.substr(auth_string.length());
return auth;
}
}
return "";
}
std::vector<TaggedFeedUrl> InoreaderApi::get_subscribed_urls()
{
std::vector<TaggedFeedUrl> urls;
curl_slist* custom_headers{};
CURL* handle = curl_easy_init();
std::string result;
add_custom_headers(&custom_headers);
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, custom_headers);
utils::set_common_curl_options(handle, cfg);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, my_write_data);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &result);
curl_easy_setopt(handle, CURLOPT_URL, INOREADER_SUBSCRIPTION_LIST);
curl_easy_perform(handle);
curl_easy_cleanup(handle);
curl_slist_free_all(custom_headers);
LOG(Level::DEBUG,
"InoreaderApi::get_subscribed_urls: document = %s",
result);
json_object* reply = json_tokener_parse(result.c_str());
if (reply == nullptr) {
LOG(Level::ERROR,
"InoreaderApi::get_subscribed_urls: failed to parse "
"response as JSON.");
return urls;
}
json_object* subscription_obj{};
json_object_object_get_ex(reply, "subscriptions", &subscription_obj);
struct array_list* subscriptions =
json_object_get_array(subscription_obj);
int len = array_list_length(subscriptions);
for (int i = 0; i < len; i++) {
std::vector<std::string> tags;
json_object* sub =
json_object_array_get_idx(subscription_obj, i);
json_object* node{};
json_object_object_get_ex(sub, "id", &node);
const char* id = json_object_get_string(node);
char* id_uenc = curl_easy_escape(handle, id, 0);
json_object_object_get_ex(sub, "title", &node);
const char* title = json_object_get_string(node);
tags.push_back(std::string("~") + title);
json_object_object_get_ex(sub, "categories", &node);
struct array_list* categories = json_object_get_array(node);
#if JSON_C_MAJOR_VERSION == 0 && JSON_C_MINOR_VERSION < 13
for (int i = 0; i < array_list_length(categories); i++) {
#else
for (size_t i = 0; i < array_list_length(categories); i++) {
#endif
json_object* cat = json_object_array_get_idx(node, i);
json_object* label_node{};
json_object_object_get_ex(cat, "label", &label_node);
const char* label = json_object_get_string(label_node);
tags.push_back(std::string(label));
}
auto url = strprintf::fmt("%s%s?n=%u",
INOREADER_FEED_PREFIX,
id_uenc,
cfg->get_configvalue_as_int("inoreader-min-items"));
urls.push_back(TaggedFeedUrl(url, tags));
curl_free(id_uenc);
}
json_object_put(reply);
return urls;
}
void InoreaderApi::add_custom_headers(curl_slist** custom_headers)
{
if (auth_header.empty()) {
auth_header = strprintf::fmt(
"Authorization: GoogleLogin auth=%s", auth);
}
LOG(Level::DEBUG,
"InoreaderApi::add_custom_headers header = %s",
auth_header);
*custom_headers =
curl_slist_append(*custom_headers, auth_header.c_str());
*custom_headers = curl_slist_append(*custom_headers, INOREADER_APP_ID);
*custom_headers = curl_slist_append(*custom_headers, INOREADER_APP_KEY);
}
bool InoreaderApi::mark_all_read(const std::string& feedurl)
{
std::string real_feedurl =
feedurl.substr(strlen(INOREADER_FEED_PREFIX));
std::vector<std::string> elems = utils::tokenize(real_feedurl, "?");
real_feedurl = utils::unescape_url(elems[0]);
std::string token = get_new_token();
std::string postcontent =
strprintf::fmt("s=%s&T=%s", real_feedurl, token);
std::string result =
post_content(INOREADER_API_MARK_ALL_READ_URL, postcontent);
return result == "OK";
}
bool InoreaderApi::mark_article_read(const std::string& guid, bool read)
{
std::string token = get_new_token();
return mark_article_read_with_token(guid, read, token);
}
bool InoreaderApi::mark_article_read_with_token(const std::string& guid,
bool read,
const std::string& token)
{
std::string postcontent;
if (read) {
postcontent = strprintf::fmt(
"i=%s&a=user/-/state/com.google/read&r=user/-/state/"
"com.google/kept-unread&ac=edit&T=%s",
guid,
token);
} else {
postcontent = strprintf::fmt(
"i=%s&r=user/-/state/com.google/read&a=user/-/state/"
"com.google/kept-unread&a=user/-/state/com.google/"
"tracking-kept-unread&ac=edit&T=%s",
guid,
token);
}
std::string result =
post_content(INOREADER_API_EDIT_TAG_URL, postcontent);
LOG(Level::DEBUG,
"InoreaderApi::mark_article_read_with_token: postcontent = %s "
"result = %s",
postcontent,
result);
return result == "OK";
}
std::string InoreaderApi::get_new_token()
{
CURL* handle = curl_easy_init();
std::string result;
curl_slist* custom_headers{};
utils::set_common_curl_options(handle, cfg);
add_custom_headers(&custom_headers);
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, custom_headers);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, my_write_data);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &result);
curl_easy_setopt(handle, CURLOPT_URL, INOREADER_API_TOKEN_URL);
curl_easy_perform(handle);
curl_easy_cleanup(handle);
curl_slist_free_all(custom_headers);
LOG(Level::DEBUG, "InoreaderApi::get_new_token: token = %s", result);
return result;
}
bool InoreaderApi::update_article_flags(const std::string& inoflags,
const std::string& newflags,
const std::string& guid)
{
std::string star_flag = cfg->get_configvalue("inoreader-flag-star");
std::string share_flag = cfg->get_configvalue("inoreader-flag-share");
bool success = true;
if (star_flag.length() > 0) {
if (strchr(inoflags.c_str(), star_flag[0]) == nullptr &&
strchr(newflags.c_str(), star_flag[0]) != nullptr) {
success = star_article(guid, true);
} else if (strchr(inoflags.c_str(), star_flag[0]) != nullptr &&
strchr(newflags.c_str(), star_flag[0]) == nullptr) {
success = star_article(guid, false);
}
}
if (share_flag.length() > 0) {
if (strchr(inoflags.c_str(), share_flag[0]) == nullptr &&
strchr(newflags.c_str(), share_flag[0]) != nullptr) {
success = share_article(guid, true);
} else if (strchr(inoflags.c_str(), share_flag[0]) != nullptr &&
strchr(newflags.c_str(), share_flag[0]) == nullptr) {
success = share_article(guid, false);
}
}
return success;
}
bool InoreaderApi::star_article(const std::string& guid, bool star)
{
std::string token = get_new_token();
std::string postcontent;
if (star) {
postcontent = strprintf::fmt(
"i=%s&a=user/-/state/com.google/starred&ac=edit&T=%s",
guid,
token);
} else {
postcontent = strprintf::fmt(
"i=%s&r=user/-/state/com.google/starred&ac=edit&T=%s",
guid,
token);
}
std::string result =
post_content(INOREADER_API_EDIT_TAG_URL, postcontent);
return result == "OK";
}
bool InoreaderApi::share_article(const std::string& guid, bool share)
{
std::string token = get_new_token();
std::string postcontent;
if (share) {
postcontent = strprintf::fmt(
"i=%s&a=user/-/state/com.google/broadcast&ac=edit&T=%s",
guid,
token);
} else {
postcontent = strprintf::fmt(
"i=%s&r=user/-/state/com.google/broadcast&ac=edit&T=%s",
guid,
token);
}
std::string result =
post_content(INOREADER_API_EDIT_TAG_URL, postcontent);
return result == "OK";
}
std::string InoreaderApi::post_content(const std::string& url,
const std::string& postdata)
{
std::string result;
curl_slist* custom_headers{};
CURL* handle = curl_easy_init();
utils::set_common_curl_options(handle, cfg);
add_custom_headers(&custom_headers);
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, custom_headers);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, my_write_data);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &result);
curl_easy_setopt(handle, CURLOPT_POSTFIELDS, postdata.c_str());
curl_easy_setopt(handle, CURLOPT_URL, url.c_str());
curl_easy_perform(handle);
curl_easy_cleanup(handle);
curl_slist_free_all(custom_headers);
LOG(Level::DEBUG,
"InoreaderApi::post_content: url = %s postdata = %s result = "
"%s",
url,
postdata,
result);
return result;
}
} // namespace newsboat
<commit_msg>speedup Inoreader mark_article_read using thread, code borrowed from ttrssapi.cpp<commit_after>#include "inoreaderapi.h"
#include <cstring>
#include <curl/curl.h>
#include <json.h>
#include <vector>
#include <thread>
#include "config.h"
#include "strprintf.h"
#include "utils.h"
#define INOREADER_LOGIN "https://inoreader.com/accounts/ClientLogin"
#define INOREADER_API_PREFIX "https://inoreader.com/reader/api/0/"
#define INOREADER_FEED_PREFIX "https://inoreader.com/reader/atom/"
#define INOREADER_SUBSCRIPTION_LIST INOREADER_API_PREFIX "subscription/list"
#define INOREADER_API_MARK_ALL_READ_URL INOREADER_API_PREFIX "mark-all-as-read"
#define INOREADER_API_EDIT_TAG_URL INOREADER_API_PREFIX "edit-tag"
#define INOREADER_API_TOKEN_URL INOREADER_API_PREFIX "token"
#define INOREADER_APP_ID "AppId: 1000000394"
#define INOREADER_APP_KEY "AppKey: CWcdJdSDcuxHYoqGa3RsPh7X2DZ2MmO7"
// for reference, see https://inoreader.com/developers
namespace newsboat {
InoreaderApi::InoreaderApi(ConfigContainer* c)
: RemoteApi(c)
{
// TODO
}
InoreaderApi::~InoreaderApi()
{
// TODO
}
bool InoreaderApi::authenticate()
{
auth = retrieve_auth();
LOG(Level::DEBUG, "InoreaderApi::authenticate: Auth = %s", auth);
return auth != "";
}
static size_t my_write_data(void* buffer, size_t size, size_t nmemb,
void* userp)
{
std::string* pbuf = static_cast<std::string*>(userp);
pbuf->append(static_cast<const char*>(buffer), size * nmemb);
return size * nmemb;
}
std::string InoreaderApi::retrieve_auth()
{
CURL* handle = curl_easy_init();
Credentials cred = get_credentials("inoreader", "Inoreader");
if (cred.user.empty() || cred.pass.empty()) {
return "";
}
char* username = curl_easy_escape(handle, cred.user.c_str(), 0);
char* password = curl_easy_escape(handle, cred.pass.c_str(), 0);
std::string postcontent =
strprintf::fmt("Email=%s&Passwd=%s", username, password);
curl_free(username);
curl_free(password);
std::string result;
curl_slist* list = NULL;
list = curl_slist_append(list, INOREADER_APP_ID);
list = curl_slist_append(list, INOREADER_APP_KEY);
utils::set_common_curl_options(handle, cfg);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, my_write_data);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &result);
curl_easy_setopt(handle, CURLOPT_POSTFIELDS, postcontent.c_str());
curl_easy_setopt(handle, CURLOPT_URL, INOREADER_LOGIN);
curl_easy_perform(handle);
curl_easy_cleanup(handle);
curl_slist_free_all(list);
std::vector<std::string> lines = utils::tokenize(result);
for (const auto& line : lines) {
LOG(Level::DEBUG,
"InoreaderApi::retrieve_auth: line = %s",
line);
const std::string auth_string = "Auth=";
if (line.compare(0, auth_string.length(), auth_string) == 0) {
std::string auth = line.substr(auth_string.length());
return auth;
}
}
return "";
}
std::vector<TaggedFeedUrl> InoreaderApi::get_subscribed_urls()
{
std::vector<TaggedFeedUrl> urls;
curl_slist* custom_headers{};
CURL* handle = curl_easy_init();
std::string result;
add_custom_headers(&custom_headers);
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, custom_headers);
utils::set_common_curl_options(handle, cfg);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, my_write_data);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &result);
curl_easy_setopt(handle, CURLOPT_URL, INOREADER_SUBSCRIPTION_LIST);
curl_easy_perform(handle);
curl_easy_cleanup(handle);
curl_slist_free_all(custom_headers);
LOG(Level::DEBUG,
"InoreaderApi::get_subscribed_urls: document = %s",
result);
json_object* reply = json_tokener_parse(result.c_str());
if (reply == nullptr) {
LOG(Level::ERROR,
"InoreaderApi::get_subscribed_urls: failed to parse "
"response as JSON.");
return urls;
}
json_object* subscription_obj{};
json_object_object_get_ex(reply, "subscriptions", &subscription_obj);
struct array_list* subscriptions =
json_object_get_array(subscription_obj);
int len = array_list_length(subscriptions);
for (int i = 0; i < len; i++) {
std::vector<std::string> tags;
json_object* sub =
json_object_array_get_idx(subscription_obj, i);
json_object* node{};
json_object_object_get_ex(sub, "id", &node);
const char* id = json_object_get_string(node);
char* id_uenc = curl_easy_escape(handle, id, 0);
json_object_object_get_ex(sub, "title", &node);
const char* title = json_object_get_string(node);
tags.push_back(std::string("~") + title);
json_object_object_get_ex(sub, "categories", &node);
struct array_list* categories = json_object_get_array(node);
#if JSON_C_MAJOR_VERSION == 0 && JSON_C_MINOR_VERSION < 13
for (int i = 0; i < array_list_length(categories); i++) {
#else
for (size_t i = 0; i < array_list_length(categories); i++) {
#endif
json_object* cat = json_object_array_get_idx(node, i);
json_object* label_node{};
json_object_object_get_ex(cat, "label", &label_node);
const char* label = json_object_get_string(label_node);
tags.push_back(std::string(label));
}
auto url = strprintf::fmt("%s%s?n=%u",
INOREADER_FEED_PREFIX,
id_uenc,
cfg->get_configvalue_as_int("inoreader-min-items"));
urls.push_back(TaggedFeedUrl(url, tags));
curl_free(id_uenc);
}
json_object_put(reply);
return urls;
}
void InoreaderApi::add_custom_headers(curl_slist** custom_headers)
{
if (auth_header.empty()) {
auth_header = strprintf::fmt(
"Authorization: GoogleLogin auth=%s", auth);
}
LOG(Level::DEBUG,
"InoreaderApi::add_custom_headers header = %s",
auth_header);
*custom_headers =
curl_slist_append(*custom_headers, auth_header.c_str());
*custom_headers = curl_slist_append(*custom_headers, INOREADER_APP_ID);
*custom_headers = curl_slist_append(*custom_headers, INOREADER_APP_KEY);
}
bool InoreaderApi::mark_all_read(const std::string& feedurl)
{
std::string real_feedurl =
feedurl.substr(strlen(INOREADER_FEED_PREFIX));
std::vector<std::string> elems = utils::tokenize(real_feedurl, "?");
real_feedurl = utils::unescape_url(elems[0]);
std::string token = get_new_token();
std::string postcontent =
strprintf::fmt("s=%s&T=%s", real_feedurl, token);
std::string result =
post_content(INOREADER_API_MARK_ALL_READ_URL, postcontent);
return result == "OK";
}
bool InoreaderApi::mark_article_read(const std::string& guid, bool read)
{
// Do this in a thread, as we don't care about the result enough to wait
// for it. borrowed from ttrssapi.cpp
std::thread t{[=]()
{
LOG(Level::DEBUG,
"InoreaderApi::mark_article_read: inside thread, marking "
"thread as read...");
std::string token = get_new_token();
mark_article_read_with_token(guid, read, token);
}};
t.detach();
return true;
}
bool InoreaderApi::mark_article_read_with_token(const std::string& guid,
bool read,
const std::string& token)
{
std::string postcontent;
if (read) {
postcontent = strprintf::fmt(
"i=%s&a=user/-/state/com.google/read&r=user/-/state/"
"com.google/kept-unread&ac=edit&T=%s",
guid,
token);
} else {
postcontent = strprintf::fmt(
"i=%s&r=user/-/state/com.google/read&a=user/-/state/"
"com.google/kept-unread&a=user/-/state/com.google/"
"tracking-kept-unread&ac=edit&T=%s",
guid,
token);
}
std::string result =
post_content(INOREADER_API_EDIT_TAG_URL, postcontent);
LOG(Level::DEBUG,
"InoreaderApi::mark_article_read_with_token: postcontent = %s "
"result = %s",
postcontent,
result);
return result == "OK";
}
std::string InoreaderApi::get_new_token()
{
CURL* handle = curl_easy_init();
std::string result;
curl_slist* custom_headers{};
utils::set_common_curl_options(handle, cfg);
add_custom_headers(&custom_headers);
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, custom_headers);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, my_write_data);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &result);
curl_easy_setopt(handle, CURLOPT_URL, INOREADER_API_TOKEN_URL);
curl_easy_perform(handle);
curl_easy_cleanup(handle);
curl_slist_free_all(custom_headers);
LOG(Level::DEBUG, "InoreaderApi::get_new_token: token = %s", result);
return result;
}
bool InoreaderApi::update_article_flags(const std::string& inoflags,
const std::string& newflags,
const std::string& guid)
{
std::string star_flag = cfg->get_configvalue("inoreader-flag-star");
std::string share_flag = cfg->get_configvalue("inoreader-flag-share");
bool success = true;
if (star_flag.length() > 0) {
if (strchr(inoflags.c_str(), star_flag[0]) == nullptr &&
strchr(newflags.c_str(), star_flag[0]) != nullptr) {
success = star_article(guid, true);
} else if (strchr(inoflags.c_str(), star_flag[0]) != nullptr &&
strchr(newflags.c_str(), star_flag[0]) == nullptr) {
success = star_article(guid, false);
}
}
if (share_flag.length() > 0) {
if (strchr(inoflags.c_str(), share_flag[0]) == nullptr &&
strchr(newflags.c_str(), share_flag[0]) != nullptr) {
success = share_article(guid, true);
} else if (strchr(inoflags.c_str(), share_flag[0]) != nullptr &&
strchr(newflags.c_str(), share_flag[0]) == nullptr) {
success = share_article(guid, false);
}
}
return success;
}
bool InoreaderApi::star_article(const std::string& guid, bool star)
{
std::string token = get_new_token();
std::string postcontent;
if (star) {
postcontent = strprintf::fmt(
"i=%s&a=user/-/state/com.google/starred&ac=edit&T=%s",
guid,
token);
} else {
postcontent = strprintf::fmt(
"i=%s&r=user/-/state/com.google/starred&ac=edit&T=%s",
guid,
token);
}
std::string result =
post_content(INOREADER_API_EDIT_TAG_URL, postcontent);
return result == "OK";
}
bool InoreaderApi::share_article(const std::string& guid, bool share)
{
std::string token = get_new_token();
std::string postcontent;
if (share) {
postcontent = strprintf::fmt(
"i=%s&a=user/-/state/com.google/broadcast&ac=edit&T=%s",
guid,
token);
} else {
postcontent = strprintf::fmt(
"i=%s&r=user/-/state/com.google/broadcast&ac=edit&T=%s",
guid,
token);
}
std::string result =
post_content(INOREADER_API_EDIT_TAG_URL, postcontent);
return result == "OK";
}
std::string InoreaderApi::post_content(const std::string& url,
const std::string& postdata)
{
std::string result;
curl_slist* custom_headers{};
CURL* handle = curl_easy_init();
utils::set_common_curl_options(handle, cfg);
add_custom_headers(&custom_headers);
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, custom_headers);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, my_write_data);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &result);
curl_easy_setopt(handle, CURLOPT_POSTFIELDS, postdata.c_str());
curl_easy_setopt(handle, CURLOPT_URL, url.c_str());
curl_easy_perform(handle);
curl_easy_cleanup(handle);
curl_slist_free_all(custom_headers);
LOG(Level::DEBUG,
"InoreaderApi::post_content: url = %s postdata = %s result = "
"%s",
url,
postdata,
result);
return result;
}
} // namespace newsboat
<|endoftext|> |
<commit_before>#include "inputhandler.h"
#include "effects.h"
#include "slog/slog.h"
#include "sdl.h"
#include <utility>
#include "userinput.h"
extern UserInput* user_input;
InputHandler::InputHandler(std::unique_ptr<Image> image)
: curr_effect_(NULL),
image_(image.release())
{
this->RegisterKey(SDLK_q);
this->RegisterKey(SDLK_ESCAPE);
this->RegisterKey(SDLK_LEFT);
this->RegisterKey(SDLK_RIGHT);
}
void InputHandler::OnMessage(SDLKey key, uint8_t type)
{
SLOG_DEBUG("User input: %d %d", key, type);
if (type == SDL_KEYUP)
{
return;
}
if (key == SDLK_ESCAPE)
{
user_input->Stop();
return;
}
if (key == SDLK_q)
{
this->ResetState();
SLOG_DEBUG("Leave the effect")
return;
}
if (this->curr_effect_ == NULL)
{
auto effect = this->effects_.find(key);
if (effect != this->effects_.end())
{
this->curr_effect_ = effect->second;
SLOG_DEBUG("Enter the effect")
return;
}
}
else
{
if (this->image_.get() == NULL)
{
SLOG_DEBUG("Try to execute effect without image");
user_input->Stop();
return;
}
SLOG_DEBUG("Apply effect");
this->curr_effect_(this->image_.get(), key, type);
display_vfb(this->image_->buffer, this->image_->width, this->image_->height);
}
}
void InputHandler::Bind(SDLKey keypress, Effect effect)
{
this->effects_.insert(std::make_pair(keypress, effect));
this->RegisterKey(keypress);
}
void InputHandler::RemoveBind(SDLKey keypress)
{
auto effect = this->effects_.find(keypress);
if (effect != this->effects_.end())
{
this->effects_.erase(effect);
}
}
<commit_msg>* Leave effects to show changes<commit_after>#include "inputhandler.h"
#include "effects.h"
#include "slog/slog.h"
#include "sdl.h"
#include <utility>
#include "userinput.h"
extern UserInput* user_input;
InputHandler::InputHandler(std::unique_ptr<Image> image)
: curr_effect_(NULL),
image_(image.release())
{
this->RegisterKey(SDLK_q);
this->RegisterKey(SDLK_ESCAPE);
this->RegisterKey(SDLK_LEFT);
this->RegisterKey(SDLK_RIGHT);
}
void InputHandler::OnMessage(SDLKey key, uint8_t type)
{
SLOG_DEBUG("User input: %d %d", key, type);
if (type == SDL_KEYUP)
{
return;
}
if (key == SDLK_ESCAPE)
{
user_input->Stop();
return;
}
if (key == SDLK_q)
{
this->ResetState();
SLOG_DEBUG("Leave the effect")
return;
}
if (this->curr_effect_ == NULL)
{
auto effect = this->effects_.find(key);
if (effect != this->effects_.end())
{
this->curr_effect_ = effect->second;
SLOG_DEBUG("Enter the effect")
return;
}
}
else
{
if (this->image_.get() == NULL)
{
SLOG_DEBUG("Try to execute effect without image");
user_input->Stop();
return;
}
SLOG_DEBUG("Apply effect");
this->curr_effect_(this->image_.get(), key, type);
}
}
void InputHandler::Bind(SDLKey keypress, Effect effect)
{
this->effects_.insert(std::make_pair(keypress, effect));
this->RegisterKey(keypress);
}
void InputHandler::RemoveBind(SDLKey keypress)
{
auto effect = this->effects_.find(keypress);
if (effect != this->effects_.end())
{
this->effects_.erase(effect);
}
}
<|endoftext|> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.