<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %cling -Xclang -verify | FileCheck %s

#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/StoredValueRef.h"

cling::StoredValueRef V;
V // CHECK: (cling::StoredValueRef) <<<invalid>>> @0x{{.*}}

gCling->evaluate("return 1;", V);
V // CHECK: (cling::StoredValueRef) boxes [(int) 1]

// Returns must put the result in the StoredValueRef.
bool cond = true;
gCling->evaluate("if (cond) return \"true\"; else return 0;", V);
V // CHECK: (cling::StoredValueRef) boxes [(const char [5]) "true"]
gCling->evaluate("cond = false; if (cond) return \"true\"; else return 0;", V);
V // CHECK: (cling::StoredValueRef) boxes [(int) 0]

gCling->evaluate("auto a = 12.3; a;", V);
V // CHECK: (cling::StoredValueRef) boxes [(double) 1.230000e+01]

long LongV = 17;
gCling->evaluate("LongV;", V);
V // CHECK: (cling::StoredValueRef) boxes [(long) 17]

int* IntP = (int*)0x12;
gCling->evaluate("IntP;", V);
V // CHECK: (cling::StoredValueRef) boxes [(int *) 0x12]

cling::StoredValueRef Result;
gCling->evaluate("V", Result);
// Here we check what happens for record type like cling::StoredValueRef; they are returned by reference.
Result // CHECK: (cling::StoredValueRef) boxes [(cling::StoredValueRef) boxes [(int *) 0x12]]
V // CHECK: (cling::StoredValueRef) boxes [(int *) 0x12]

// Savannah #96277
gCling->evaluate("gCling->declare(\"double sin(double);\"); double one = sin(3.141/2);", V);
V // CHECK: (cling::StoredValueRef) boxes [(double) 1.000000e+00]

gCling->process("double one = sin(3.141/2);", &V);
V // CHECK: (cling::StoredValueRef) boxes [(double) 1.000000e+00]
one // CHECK: (double) 1.000
int one; // expected-error {{redefinition of 'one' with a different type: 'int' vs 'double'}} expected-note {{previous definition is here}}

// Make sure that PR#98434 doesn't get reintroduced.
.rawInput
void f(int) { return; }
.rawInput

gCling->evaluate("f", V);
V.isValid() //CHECK: {{\([_]B|b}}ool) true
// end PR#98434

// Check lifetime of objects in StoredValue
.rawInput 1
struct WithDtor {
   static int fgCount;
   WithDtor() { ++fgCount; }
   WithDtor(const WithDtor&) { ++fgCount; }
   ~WithDtor() { --fgCount; }
};
int WithDtor::fgCount = 0;
WithDtor getWithDtor() { return WithDtor(); }
#include <vector>
std::vector<WithDtor> getWithDtorVec() { std::vector<WithDtor> ret; ret.resize(7); return ret; }
.rawInput 0

cling::StoredValueRef* VOnHeap = new cling::StoredValueRef();
gCling->evaluate("getWithDtor()", *VOnHeap);
*VOnHeap //CHECK: (cling::StoredValueRef) boxes [(WithDtor) @0x{{.*}}]
WithDtor::fgCount //CHECK: (int) 1
delete VOnHeap;
WithDtor::fgCount //CHECK: (int) 0

// Check destructor call for templates
VOnHeap = new cling::StoredValueRef();
gCling->evaluate("getWithDtorVec()", *VOnHeap);
*VOnHeap //CHECK: (cling::StoredValueRef) boxes [(std::vector<WithDtor>) @0x{{.*}}]
WithDtor::fgCount //CHECK: (int) 7
delete VOnHeap;
WithDtor::fgCount //CHECK: (int) 0

// long doubles (tricky for the JIT).
gCling->evaluate("17.42L", V);
V // CHECK: (cling::StoredValueRef) boxes [(long double) 17.4200000{{[0-9]*}}]
<commit_msg>long double has "L" suffix.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %cling -Xclang -verify | FileCheck %s

#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/StoredValueRef.h"

cling::StoredValueRef V;
V // CHECK: (cling::StoredValueRef) <<<invalid>>> @0x{{.*}}

gCling->evaluate("return 1;", V);
V // CHECK: (cling::StoredValueRef) boxes [(int) 1]

// Returns must put the result in the StoredValueRef.
bool cond = true;
gCling->evaluate("if (cond) return \"true\"; else return 0;", V);
V // CHECK: (cling::StoredValueRef) boxes [(const char [5]) "true"]
gCling->evaluate("cond = false; if (cond) return \"true\"; else return 0;", V);
V // CHECK: (cling::StoredValueRef) boxes [(int) 0]

gCling->evaluate("auto a = 12.3; a;", V);
V // CHECK: (cling::StoredValueRef) boxes [(double) 1.230000e+01]

long LongV = 17;
gCling->evaluate("LongV;", V);
V // CHECK: (cling::StoredValueRef) boxes [(long) 17]

int* IntP = (int*)0x12;
gCling->evaluate("IntP;", V);
V // CHECK: (cling::StoredValueRef) boxes [(int *) 0x12]

cling::StoredValueRef Result;
gCling->evaluate("V", Result);
// Here we check what happens for record type like cling::StoredValueRef; they are returned by reference.
Result // CHECK: (cling::StoredValueRef) boxes [(cling::StoredValueRef) boxes [(int *) 0x12]]
V // CHECK: (cling::StoredValueRef) boxes [(int *) 0x12]

// Savannah #96277
gCling->evaluate("gCling->declare(\"double sin(double);\"); double one = sin(3.141/2);", V);
V // CHECK: (cling::StoredValueRef) boxes [(double) 1.000000e+00]

gCling->process("double one = sin(3.141/2);", &V);
V // CHECK: (cling::StoredValueRef) boxes [(double) 1.000000e+00]
one // CHECK: (double) 1.000
int one; // expected-error {{redefinition of 'one' with a different type: 'int' vs 'double'}} expected-note {{previous definition is here}}

// Make sure that PR#98434 doesn't get reintroduced.
.rawInput
void f(int) { return; }
.rawInput

gCling->evaluate("f", V);
V.isValid() //CHECK: {{\([_]B|b}}ool) true
// end PR#98434

// Check lifetime of objects in StoredValue
.rawInput 1
struct WithDtor {
   static int fgCount;
   WithDtor() { ++fgCount; }
   WithDtor(const WithDtor&) { ++fgCount; }
   ~WithDtor() { --fgCount; }
};
int WithDtor::fgCount = 0;
WithDtor getWithDtor() { return WithDtor(); }
#include <vector>
std::vector<WithDtor> getWithDtorVec() { std::vector<WithDtor> ret; ret.resize(7); return ret; }
.rawInput 0

cling::StoredValueRef* VOnHeap = new cling::StoredValueRef();
gCling->evaluate("getWithDtor()", *VOnHeap);
*VOnHeap //CHECK: (cling::StoredValueRef) boxes [(WithDtor) @0x{{.*}}]
WithDtor::fgCount //CHECK: (int) 1
delete VOnHeap;
WithDtor::fgCount //CHECK: (int) 0

// Check destructor call for templates
VOnHeap = new cling::StoredValueRef();
gCling->evaluate("getWithDtorVec()", *VOnHeap);
*VOnHeap //CHECK: (cling::StoredValueRef) boxes [(std::vector<WithDtor>) @0x{{.*}}]
WithDtor::fgCount //CHECK: (int) 7
delete VOnHeap;
WithDtor::fgCount //CHECK: (int) 0

// long doubles (tricky for the JIT).
gCling->evaluate("17.42L", V);
V // CHECK: (cling::StoredValueRef) boxes [(long double) 17.4200000{{[0-9]*}}L]
<|endoftext|>


<commit_before>/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-6-23 21:49:57
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int N, M;
set<int> W[1000];
vector<int> V[1000];

vector<pair<int, int>> res;

int visited[1000];
int cnt[2];

bool nuri(int v, int k)
{
  visited[v] = k;
  for (auto x : V[v])
  {
    if (visited[x] == 0)
    {
      if (!nuri(x, 3 - k))
      {
        return false;
      }
    }
    else if (visited[x] == k)
    {
      return false;
    }
  }
  cnt[k - 1]++;
  return true;
}

bool reach[1000][1000];

int main()
{
  cin >> N >> M;
  for (auto i = 0; i < M; i++)
  {
    int a, b;
    cin >> a >> b;
    a--;
    b--;
    W[a].insert(b);
    W[b].insert(a);
  }
  for (auto i = 0; i < N; i++)
  {
    for (auto j = 0; j < N; j++)
    {
      if (i == j)
        continue;
      if (W[i].find(j) == W[i].end())
      {
        V[i].push_back(j);
        // cerr << "V[" << i << "].push_back(" << j << ")" << endl;
      }
    }
  }
  fill(visited, visited + 1000, 0);
  for (auto k = 0; k < N; k++)
  {
    if (visited[k] != 0)
    {
      continue;
    }
    cnt[0] = cnt[1] = 0;
    if (!nuri(k, 1))
    {
      cout << -1 << endl;
      return 0;
    }
    res.push_back(make_pair(cnt[0], cnt[1]));
  }
  fill(&reach[0][0], &reach[0][0] + 1000 * 1000, false);
  reach[0][0] = true;
  for (int i = 0; i < (int)res.size(); i++)
  {
    auto e = res[i];
    int x = e.first;
    int y = e.second;
    // cerr << "x = " << x << ", y = " << y << endl;
    for (auto j = N; j >= 0; j--)
    {
      if (reach[i][j])
      {
        reach[i + 1][x + j] = true;
        reach[i + 1][y + j] = true;
      }
    }
  }
  int ans = 1000000007;
  for (auto i = 0; i <= N; i++)
  {
    int j = N - i;
    if (reach[i])
    {
      ans = min(ans, i * (i - 1) / 2 + j * (j - 1) / 2);
    }
  }
  cout << ans << endl;
}
<commit_msg>tried E.cpp to 'E'<commit_after>/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-6-23 21:49:57
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int N, M;
set<int> W[1000];
vector<int> V[1000];

vector<pair<int, int>> res;

int visited[1000];
int cnt[2];

bool nuri(int v, int k)
{
  visited[v] = k;
  for (auto x : V[v])
  {
    if (visited[x] == 0)
    {
      if (!nuri(x, 3 - k))
      {
        return false;
      }
    }
    else if (visited[x] == k)
    {
      return false;
    }
  }
  cnt[k - 1]++;
  return true;
}

bool reach[1000][1000];

int main()
{
  cin >> N >> M;
  for (auto i = 0; i < M; i++)
  {
    int a, b;
    cin >> a >> b;
    a--;
    b--;
    W[a].insert(b);
    W[b].insert(a);
  }
  for (auto i = 0; i < N; i++)
  {
    for (auto j = 0; j < N; j++)
    {
      if (i == j)
        continue;
      if (W[i].find(j) == W[i].end())
      {
        V[i].push_back(j);
        // cerr << "V[" << i << "].push_back(" << j << ")" << endl;
      }
    }
  }
  fill(visited, visited + 1000, 0);
  for (auto k = 0; k < N; k++)
  {
    if (visited[k] != 0)
    {
      continue;
    }
    cnt[0] = cnt[1] = 0;
    if (!nuri(k, 1))
    {
      cout << -1 << endl;
      return 0;
    }
    res.push_back(make_pair(cnt[0], cnt[1]));
  }
  fill(&reach[0][0], &reach[0][0] + 1000 * 1000, false);
  reach[0][0] = true;
  for (int i = 0; i < (int)res.size(); i++)
  {
    auto e = res[i];
    int x = e.first;
    int y = e.second;
    // cerr << "x = " << x << ", y = " << y << endl;
    for (auto j = N; j >= 0; j--)
    {
      if (reach[i][j])
      {
        reach[i + 1][x + j] = true;
        reach[i + 1][y + j] = true;
      }
    }
  }
  int ans = 1000000007;
  for (auto i = 0; i <= N; i++)
  {
    int j = N - i;
    if (reach[N][i])
    {
      ans = min(ans, i * (i - 1) / 2 + j * (j - 1) / 2);
    }
  }
  cout << ans << endl;
}
<|endoftext|>


<commit_before>/*-----------------------------------------------------------------------------------------------
The MIT License (MIT)

Copyright (c) 2014-2015 Kim Kulling

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 "gtest/gtest.h"

#include <openddlparser/OpenDDLCommon.h>

BEGIN_ODDLPARSER_NS

static const char TestText[] = "hello";

class OpenDDLCommonTest : public testing::Test {
    Text *m_text;
public:
    virtual void SetUp() {
        m_text = ddl_nullptr;
    }

    virtual void TearDown() {
        delete m_text;
        m_text = ddl_nullptr;
    }

    const char *getTestText() const {
        return &TestText[ 0 ];
    }

    size_t getTestTextLen() {
        return strlen( TestText );
    }

    Text *createTestText() {
        m_text = new Text( getTestText(), getTestTextLen() );
        return m_text;
    }
};

TEST_F( OpenDDLCommonTest, createNameTest ) {
    bool ok( true );
    Name *name( nullptr );
    try {
        name = new Name( GlobalName, nullptr );
    } catch( ... ) {
        ok = false;
    }
    EXPECT_TRUE( ok );
}

TEST_F( OpenDDLCommonTest, createTextTest ) {
    bool ok( true );
    try {
        static_cast<void>( createTestText() );
    } catch( ... ) {
        ok = false;
    }
    EXPECT_TRUE( ok );
}

TEST_F( OpenDDLCommonTest, accessTextTest ) {
    Text *theText = createTestText();
    ASSERT_NE( ddl_nullptr, theText );

    EXPECT_EQ( getTestTextLen(), theText->m_len );
    int res( strncmp( getTestText(), theText->m_buffer, getTestTextLen() ) );
    EXPECT_EQ( 0, res );
}

TEST_F( OpenDDLCommonTest, clearTextTest ) {
    Text *theText = createTestText();
    ASSERT_NE( ddl_nullptr, theText );

    theText->clear();
    EXPECT_EQ( 0, theText->m_len );
    EXPECT_EQ( ddl_nullptr, theText->m_buffer );
}

TEST_F( OpenDDLCommonTest, setTextTest ) {
    Text *theText = createTestText();
    ASSERT_NE( ddl_nullptr, theText );

    static const std::string test2 = "Hello, World!";
    theText->set( test2.c_str(), test2.size() );

    EXPECT_EQ( test2.size(), theText->m_len );
    int res( strncmp( test2.c_str(), theText->m_buffer, test2.size() ) );
    EXPECT_EQ( 0, res );
}

TEST_F( OpenDDLCommonTest, CompareIdentifierTest ) {
    Identifier id1( "test" ), id2( "test" );
    bool equal( id1 == id2 );
    EXPECT_TRUE( equal );
}

END_ODDLPARSER_NS
<commit_msg>Add type size checks.<commit_after>/*-----------------------------------------------------------------------------------------------
The MIT License (MIT)

Copyright (c) 2014-2015 Kim Kulling

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 "gtest/gtest.h"

#include <openddlparser/OpenDDLCommon.h>

BEGIN_ODDLPARSER_NS

static const char TestText[] = "hello";

class OpenDDLCommonTest : public testing::Test {
    Text *m_text;
public:
    virtual void SetUp() {
        m_text = ddl_nullptr;
    }

    virtual void TearDown() {
        delete m_text;
        m_text = ddl_nullptr;
    }

    const char *getTestText() const {
        return &TestText[ 0 ];
    }

    size_t getTestTextLen() {
        return strlen( TestText );
    }

    Text *createTestText() {
        m_text = new Text( getTestText(), getTestTextLen() );
        return m_text;
    }
};

TEST_F( OpenDDLCommonTest, typeSizesTest ) {
    EXPECT_EQ( 1, sizeof( int8 ) );
    EXPECT_EQ( 2, sizeof( int16 ) );
    EXPECT_EQ( 4, sizeof( int32 ) );
    EXPECT_EQ( 8, sizeof( int64 ) );

    EXPECT_EQ( 1, sizeof( uint8 ) );
    EXPECT_EQ( 2, sizeof( uint16 ) );
    EXPECT_EQ( 4, sizeof( uint32 ) );
    EXPECT_EQ( 8, sizeof( uint64 ) );
}

TEST_F( OpenDDLCommonTest, createNameTest ) {
    bool ok( true );
    Name *name( nullptr );
    try {
        name = new Name( GlobalName, nullptr );
    } catch( ... ) {
        ok = false;
    }
    EXPECT_TRUE( ok );
}

TEST_F( OpenDDLCommonTest, createTextTest ) {
    bool ok( true );
    try {
        static_cast<void>( createTestText() );
    } catch( ... ) {
        ok = false;
    }
    EXPECT_TRUE( ok );
}

TEST_F( OpenDDLCommonTest, accessTextTest ) {
    Text *theText = createTestText();
    ASSERT_NE( ddl_nullptr, theText );

    EXPECT_EQ( getTestTextLen(), theText->m_len );
    int res( strncmp( getTestText(), theText->m_buffer, getTestTextLen() ) );
    EXPECT_EQ( 0, res );
}

TEST_F( OpenDDLCommonTest, clearTextTest ) {
    Text *theText = createTestText();
    ASSERT_NE( ddl_nullptr, theText );

    theText->clear();
    EXPECT_EQ( 0, theText->m_len );
    EXPECT_EQ( ddl_nullptr, theText->m_buffer );
}

TEST_F( OpenDDLCommonTest, setTextTest ) {
    Text *theText = createTestText();
    ASSERT_NE( ddl_nullptr, theText );

    static const std::string test2 = "Hello, World!";
    theText->set( test2.c_str(), test2.size() );

    EXPECT_EQ( test2.size(), theText->m_len );
    int res( strncmp( test2.c_str(), theText->m_buffer, test2.size() ) );
    EXPECT_EQ( 0, res );
}

TEST_F( OpenDDLCommonTest, CompareIdentifierTest ) {
    Identifier id1( "test" ), id2( "test" );
    bool equal( id1 == id2 );
    EXPECT_TRUE( equal );
}

END_ODDLPARSER_NS
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef DLL_WATCHER_HPP
#define DLL_WATCHER_HPP

#include <fstream>

#include <sys/stat.h>

#include "cpp_utils/stop_watch.hpp"

#include "trainer/rbm_training_context.hpp"
#include "layer_traits.hpp"
#include "dbn_traits.hpp"

namespace dll {

template <typename R>
struct default_rbm_watcher {
    cpp::stop_watch<std::chrono::seconds> watch;

    template <typename RBM = R>
    void training_begin(const RBM& rbm) {
        std::cout << "Train RBM with \"" << RBM::desc::template trainer_t<RBM, false>::name() << "\"" << std::endl;

        rbm.display();

        std::cout << "With parameters:" << std::endl;
        std::cout << "   learning_rate=" << rbm.learning_rate << std::endl;
        std::cout << "   batch_size=" << get_batch_size(rbm) << std::endl;

        if (layer_traits<RBM>::has_momentum()) {
            std::cout << "   momentum=" << rbm.momentum << std::endl;
        }

        if (w_decay(layer_traits<RBM>::decay()) == decay_type::L1 || w_decay(layer_traits<RBM>::decay()) == decay_type::L1L2) {
            std::cout << "   weight_cost(L1)=" << rbm.l1_weight_cost << std::endl;
        }

        if (w_decay(layer_traits<RBM>::decay()) == decay_type::L2 || w_decay(layer_traits<RBM>::decay()) == decay_type::L1L2) {
            std::cout << "   weight_cost(L2)=" << rbm.l2_weight_cost << std::endl;
        }

        if (layer_traits<RBM>::sparsity_method() == sparsity_method::LEE) {
            std::cout << "   Sparsity (Lee): pbias=" << rbm.pbias << std::endl;
            std::cout << "   Sparsity (Lee): pbias_lambda=" << rbm.pbias_lambda << std::endl;
        } else if (layer_traits<RBM>::sparsity_method() == sparsity_method::GLOBAL_TARGET) {
            std::cout << "   sparsity_target(Global)=" << rbm.sparsity_target << std::endl;
        } else if (layer_traits<RBM>::sparsity_method() == sparsity_method::LOCAL_TARGET) {
            std::cout << "   sparsity_target(Local)=" << rbm.sparsity_target << std::endl;
        }
    }

    template <typename RBM = R>
    void epoch_end(std::size_t epoch, const rbm_training_context& context, const RBM& /*rbm*/) {
        char formatted[1024];
        if (layer_traits<RBM>::free_energy()) {
            snprintf(formatted, 1024, "epoch %ld - Reconstruction error: %.5f - Free energy: %.3f - Sparsity: %.5f", epoch,
                     context.reconstruction_error, context.free_energy, context.sparsity);
        } else {
            snprintf(formatted, 1024, "epoch %ld - Reconstruction error: %.5f - Sparsity: %.5f", epoch, context.reconstruction_error, context.sparsity);
        }
        std::cout << formatted << std::endl;
    }

    template <typename RBM = R>
    void batch_end(const RBM& /* rbm */, const rbm_training_context& context, std::size_t batch, std::size_t batches) {
        char formatted[1024];
        sprintf(formatted, "Batch %ld/%ld - Reconstruction error: %.5f - Sparsity: %.5f", batch, batches,
                context.batch_error, context.batch_sparsity);
        std::cout << formatted << std::endl;
    }

    template <typename RBM = R>
    void training_end(const RBM&) {
        std::cout << "Training took " << watch.elapsed() << "s" << std::endl;
    }
};

template <typename DBN>
struct default_dbn_watcher {
    static constexpr const bool ignore_sub  = false;
    static constexpr const bool replace_sub = false;

    cpp::stop_watch<std::chrono::seconds> watch;

    void pretraining_begin(const DBN& /*dbn*/, std::size_t max_epochs) {
        std::cout << "DBN: Pretraining begin for " << max_epochs << " epochs" << std::endl;
    }

    template <typename RBM>
    void pretrain_layer(const DBN& /*dbn*/, std::size_t I, std::size_t input_size) {
        using rbm_t = RBM;

        if (input_size > 0) {
            std::cout << "DBN: Pretrain layer " << I << " (" << rbm_t::to_short_string() << ") with " << input_size << " entries" << std::endl;
        } else {
            std::cout << "DBN: Pretrain layer " << I << " (" << rbm_t::to_short_string() << ")" << std::endl;
        }
    }

    void pretraining_end(const DBN& /*dbn*/) {
        std::cout << "DBN: Pretraining finished after " << watch.elapsed() << "s" << std::endl;
    }

    void pretraining_batch(const DBN& /*dbn*/, std::size_t batch) {
        std::cout << "DBN: Pretraining batch " << batch << std::endl;
    }

    void fine_tuning_begin(const DBN& dbn) {
        std::cout << "Train DBN with \"" << DBN::desc::template trainer_t<DBN>::name() << "\"" << std::endl;
        std::cout << "With parameters:" << std::endl;
        std::cout << "   learning_rate=" << dbn.learning_rate << std::endl;

        if (dbn_traits<DBN>::has_momentum()) {
            std::cout << "   momentum=" << dbn.momentum << std::endl;
        }

        if (w_decay(dbn_traits<DBN>::decay()) == decay_type::L1 || w_decay(dbn_traits<DBN>::decay()) == decay_type::L1L2) {
            std::cout << "   weight_cost(L1)=" << dbn.l1_weight_cost << std::endl;
        }

        if (w_decay(dbn_traits<DBN>::decay()) == decay_type::L2 || w_decay(dbn_traits<DBN>::decay()) == decay_type::L1L2) {
            std::cout << "   weight_cost(L2)=" << dbn.l2_weight_cost << std::endl;
        }

        if (dbn_traits<DBN>::lr_driver() == lr_driver_type::BOLD) {
            std::cout << "   lr_driver(BOLD)=" << dbn.lr_bold_inc << ":" << dbn.lr_bold_dec << std::endl;
        }

        if (dbn_traits<DBN>::lr_driver() == lr_driver_type::STEP) {
            std::cout << "   lr_driver(STEP)=" << dbn.lr_step_size << ":" << dbn.lr_step_gamma << std::endl;
        }
    }

    void ft_epoch_end(std::size_t epoch, double error, const DBN&) {
        char formatted[1024];
        snprintf(formatted, 1024, "epoch %ld - Classification error: %.5f", epoch, error);
        std::cout << formatted << std::endl;
    }

    void lr_adapt(const DBN& dbn) {
        char formatted[1024];
        snprintf(formatted, 1024, "driver: learning rate adapted to %.5f", dbn.learning_rate);
        std::cout << formatted << std::endl;
    }

    void fine_tuning_end(const DBN&) {
        std::cout << "Training took " << watch.elapsed() << "s" << std::endl;
    }
};

template <typename DBN>
struct silent_dbn_watcher : default_dbn_watcher<DBN> {
    static constexpr const bool ignore_sub  = true;
    static constexpr const bool replace_sub = false;
};

//TODO This is currently useless

template <typename R>
struct histogram_watcher {
    default_rbm_watcher<R> parent;

    template <typename RBM = R>
    void training_begin(const RBM& rbm) {
        parent.training_begin(rbm);
    }

    template <typename RBM = R>
    void epoch_end(std::size_t epoch, double error, double /*free_energy*/, const RBM& rbm) {
        parent.epoch_end(epoch, error, rbm);
    }

    template <typename RBM = R>
    void batch_end(const RBM& rbm, const rbm_training_context& context, std::size_t batch, std::size_t batches) {
        parent.batch_end(rbm, context, batch, batches);
    }

    template <typename RBM = R>
    void training_end(const RBM& rbm) {
        parent.training_end(rbm);
    }

    void generate_hidden_images(std::size_t epoch, const R& rbm) {
        mkdir("reports", 0777);

        auto folder = "reports/epoch_" + std::to_string(epoch);
        mkdir(folder.c_str(), 0777);

        for (std::size_t j = 0; j < R::num_hidden; ++j) {
            auto path = folder + "/h_" + std::to_string(j) + ".dat";
            std::ofstream file(path, std::ios::out);

            if (!file) {
                std::cout << "Could not open file " << path << std::endl;
            } else {
                std::size_t i = R::num_visible;
                while (i > 0) {
                    --i;

                    auto value = rbm.w(i, j);
                    file << static_cast<std::size_t>(value > 0 ? static_cast<std::size_t>(value * 255.0) << 8 : static_cast<std::size_t>(-value * 255.0) << 16) << " ";
                }

                file << std::endl;
                file.close();
            }
        }
    }

    void generate_histograms(std::size_t epoch, const R& rbm) {
        mkdir("reports", 0777);

        auto folder = "reports/epoch_" + std::to_string(epoch);
        mkdir(folder.c_str(), 0777);

        generate_histogram(folder + "/weights.dat", rbm.w);
        generate_histogram(folder + "/visibles.dat", rbm.a);
        generate_histogram(folder + "/hiddens.dat", rbm.b);
    }

    template <typename Container>
    void generate_histogram(const std::string& path, const Container& weights) {
        std::ofstream file(path, std::ios::out);

        if (!file) {
            std::cout << "Could not open file " << path << std::endl;
        } else {
            for (auto& weight : weights) {
                file << weight << std::endl;
            }

            file << std::endl;
            file.close();
        }
    }
};

} //end of dll namespace

#endif
<commit_msg>New watcher : mute_dbn_watcher<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef DLL_WATCHER_HPP
#define DLL_WATCHER_HPP

#include <fstream>

#include <sys/stat.h>

#include "cpp_utils/stop_watch.hpp"

#include "trainer/rbm_training_context.hpp"
#include "layer_traits.hpp"
#include "dbn_traits.hpp"

namespace dll {

template <typename R>
struct default_rbm_watcher {
    cpp::stop_watch<std::chrono::seconds> watch;

    template <typename RBM = R>
    void training_begin(const RBM& rbm) {
        std::cout << "Train RBM with \"" << RBM::desc::template trainer_t<RBM, false>::name() << "\"" << std::endl;

        rbm.display();

        std::cout << "With parameters:" << std::endl;
        std::cout << "   learning_rate=" << rbm.learning_rate << std::endl;
        std::cout << "   batch_size=" << get_batch_size(rbm) << std::endl;

        if (layer_traits<RBM>::has_momentum()) {
            std::cout << "   momentum=" << rbm.momentum << std::endl;
        }

        if (w_decay(layer_traits<RBM>::decay()) == decay_type::L1 || w_decay(layer_traits<RBM>::decay()) == decay_type::L1L2) {
            std::cout << "   weight_cost(L1)=" << rbm.l1_weight_cost << std::endl;
        }

        if (w_decay(layer_traits<RBM>::decay()) == decay_type::L2 || w_decay(layer_traits<RBM>::decay()) == decay_type::L1L2) {
            std::cout << "   weight_cost(L2)=" << rbm.l2_weight_cost << std::endl;
        }

        if (layer_traits<RBM>::sparsity_method() == sparsity_method::LEE) {
            std::cout << "   Sparsity (Lee): pbias=" << rbm.pbias << std::endl;
            std::cout << "   Sparsity (Lee): pbias_lambda=" << rbm.pbias_lambda << std::endl;
        } else if (layer_traits<RBM>::sparsity_method() == sparsity_method::GLOBAL_TARGET) {
            std::cout << "   sparsity_target(Global)=" << rbm.sparsity_target << std::endl;
        } else if (layer_traits<RBM>::sparsity_method() == sparsity_method::LOCAL_TARGET) {
            std::cout << "   sparsity_target(Local)=" << rbm.sparsity_target << std::endl;
        }
    }

    template <typename RBM = R>
    void epoch_end(std::size_t epoch, const rbm_training_context& context, const RBM& /*rbm*/) {
        char formatted[1024];
        if (layer_traits<RBM>::free_energy()) {
            snprintf(formatted, 1024, "epoch %ld - Reconstruction error: %.5f - Free energy: %.3f - Sparsity: %.5f", epoch,
                     context.reconstruction_error, context.free_energy, context.sparsity);
        } else {
            snprintf(formatted, 1024, "epoch %ld - Reconstruction error: %.5f - Sparsity: %.5f", epoch, context.reconstruction_error, context.sparsity);
        }
        std::cout << formatted << std::endl;
    }

    template <typename RBM = R>
    void batch_end(const RBM& /* rbm */, const rbm_training_context& context, std::size_t batch, std::size_t batches) {
        char formatted[1024];
        sprintf(formatted, "Batch %ld/%ld - Reconstruction error: %.5f - Sparsity: %.5f", batch, batches,
                context.batch_error, context.batch_sparsity);
        std::cout << formatted << std::endl;
    }

    template <typename RBM = R>
    void training_end(const RBM&) {
        std::cout << "Training took " << watch.elapsed() << "s" << std::endl;
    }
};

template <typename DBN>
struct default_dbn_watcher {
    static constexpr const bool ignore_sub  = false;
    static constexpr const bool replace_sub = false;

    cpp::stop_watch<std::chrono::seconds> watch;

    void pretraining_begin(const DBN& /*dbn*/, std::size_t max_epochs) {
        std::cout << "DBN: Pretraining begin for " << max_epochs << " epochs" << std::endl;
    }

    template <typename RBM>
    void pretrain_layer(const DBN& /*dbn*/, std::size_t I, std::size_t input_size) {
        using rbm_t = RBM;

        if (input_size > 0) {
            std::cout << "DBN: Pretrain layer " << I << " (" << rbm_t::to_short_string() << ") with " << input_size << " entries" << std::endl;
        } else {
            std::cout << "DBN: Pretrain layer " << I << " (" << rbm_t::to_short_string() << ")" << std::endl;
        }
    }

    void pretraining_end(const DBN& /*dbn*/) {
        std::cout << "DBN: Pretraining finished after " << watch.elapsed() << "s" << std::endl;
    }

    void pretraining_batch(const DBN& /*dbn*/, std::size_t batch) {
        std::cout << "DBN: Pretraining batch " << batch << std::endl;
    }

    void fine_tuning_begin(const DBN& dbn) {
        std::cout << "Train DBN with \"" << DBN::desc::template trainer_t<DBN>::name() << "\"" << std::endl;
        std::cout << "With parameters:" << std::endl;
        std::cout << "   learning_rate=" << dbn.learning_rate << std::endl;

        if (dbn_traits<DBN>::has_momentum()) {
            std::cout << "   momentum=" << dbn.momentum << std::endl;
        }

        if (w_decay(dbn_traits<DBN>::decay()) == decay_type::L1 || w_decay(dbn_traits<DBN>::decay()) == decay_type::L1L2) {
            std::cout << "   weight_cost(L1)=" << dbn.l1_weight_cost << std::endl;
        }

        if (w_decay(dbn_traits<DBN>::decay()) == decay_type::L2 || w_decay(dbn_traits<DBN>::decay()) == decay_type::L1L2) {
            std::cout << "   weight_cost(L2)=" << dbn.l2_weight_cost << std::endl;
        }

        if (dbn_traits<DBN>::lr_driver() == lr_driver_type::BOLD) {
            std::cout << "   lr_driver(BOLD)=" << dbn.lr_bold_inc << ":" << dbn.lr_bold_dec << std::endl;
        }

        if (dbn_traits<DBN>::lr_driver() == lr_driver_type::STEP) {
            std::cout << "   lr_driver(STEP)=" << dbn.lr_step_size << ":" << dbn.lr_step_gamma << std::endl;
        }
    }

    void ft_epoch_end(std::size_t epoch, double error, const DBN&) {
        char formatted[1024];
        snprintf(formatted, 1024, "epoch %ld - Classification error: %.5f", epoch, error);
        std::cout << formatted << std::endl;
    }

    void lr_adapt(const DBN& dbn) {
        char formatted[1024];
        snprintf(formatted, 1024, "driver: learning rate adapted to %.5f", dbn.learning_rate);
        std::cout << formatted << std::endl;
    }

    void fine_tuning_end(const DBN&) {
        std::cout << "Training took " << watch.elapsed() << "s" << std::endl;
    }
};

template <typename DBN>
struct silent_dbn_watcher : default_dbn_watcher<DBN> {
    static constexpr const bool ignore_sub  = true;
    static constexpr const bool replace_sub = false;
};

template <typename DBN>
struct mute_dbn_watcher {
    static constexpr const bool ignore_sub  = true;
    static constexpr const bool replace_sub = false;

    void pretraining_begin(const DBN& /*dbn*/, std::size_t /*max_epochs*/) {}

    template <typename RBM>
    void pretrain_layer(const DBN& /*dbn*/, std::size_t /*I*/, std::size_t /*input_size*/) {}

    void pretraining_end(const DBN& /*dbn*/) {}

    void pretraining_batch(const DBN& /*dbn*/, std::size_t /*batch*/) {}

    void fine_tuning_begin(const DBN& /*dbn*/) {}

    void ft_epoch_end(std::size_t /*epoch*/, double /*error*/, const DBN& /*dbn*/) {}

    void lr_adapt(const DBN& /*dbn*/) {}

    void fine_tuning_end(const DBN& /*dbn*/) {}
};

//TODO This is currently useless

template <typename R>
struct histogram_watcher {
    default_rbm_watcher<R> parent;

    template <typename RBM = R>
    void training_begin(const RBM& rbm) {
        parent.training_begin(rbm);
    }

    template <typename RBM = R>
    void epoch_end(std::size_t epoch, double error, double /*free_energy*/, const RBM& rbm) {
        parent.epoch_end(epoch, error, rbm);
    }

    template <typename RBM = R>
    void batch_end(const RBM& rbm, const rbm_training_context& context, std::size_t batch, std::size_t batches) {
        parent.batch_end(rbm, context, batch, batches);
    }

    template <typename RBM = R>
    void training_end(const RBM& rbm) {
        parent.training_end(rbm);
    }

    void generate_hidden_images(std::size_t epoch, const R& rbm) {
        mkdir("reports", 0777);

        auto folder = "reports/epoch_" + std::to_string(epoch);
        mkdir(folder.c_str(), 0777);

        for (std::size_t j = 0; j < R::num_hidden; ++j) {
            auto path = folder + "/h_" + std::to_string(j) + ".dat";
            std::ofstream file(path, std::ios::out);

            if (!file) {
                std::cout << "Could not open file " << path << std::endl;
            } else {
                std::size_t i = R::num_visible;
                while (i > 0) {
                    --i;

                    auto value = rbm.w(i, j);
                    file << static_cast<std::size_t>(value > 0 ? static_cast<std::size_t>(value * 255.0) << 8 : static_cast<std::size_t>(-value * 255.0) << 16) << " ";
                }

                file << std::endl;
                file.close();
            }
        }
    }

    void generate_histograms(std::size_t epoch, const R& rbm) {
        mkdir("reports", 0777);

        auto folder = "reports/epoch_" + std::to_string(epoch);
        mkdir(folder.c_str(), 0777);

        generate_histogram(folder + "/weights.dat", rbm.w);
        generate_histogram(folder + "/visibles.dat", rbm.a);
        generate_histogram(folder + "/hiddens.dat", rbm.b);
    }

    template <typename Container>
    void generate_histogram(const std::string& path, const Container& weights) {
        std::ofstream file(path, std::ios::out);

        if (!file) {
            std::cout << "Could not open file " << path << std::endl;
        } else {
            for (auto& weight : weights) {
                file << weight << std::endl;
            }

            file << std::endl;
            file.close();
        }
    }
};

} //end of dll namespace

#endif
<|endoftext|>


<commit_before>/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-12-15 21:49:53
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

const int C = 100;
// const ll M = 1000000007;

int N;
int A[200010];
int K[C];

bool solve(int X)
{
  fill(K, K + A[0], 0);
  for (auto i = 0; i < N - 1; i++)
  {
    if (A[i] > A[i + 1])
    {
      continue;
    }
    else if (A[i] == C + 1)
    {
      continue;
    }
    else
    {
      bool ok = false;
      for (auto j = A[i] - 1; j >= 0; j--)
      {
        K[j]++;
        if (K[j] == X)
        {
          K[j] = 0;
        }
        else
        {
          ok = true;
          break;
        }
      }
      if (!ok)
      {
        return false;
      }
      for (auto j = A[i]; j < A[i + 1]; j++)
      {
        K[j] = 0;
      }
    }
  }
  return true;
}

int main()
{
  cin >> N;
  for (auto i = 0; i < N; i++)
  {
    cin >> A[i];
    A[i] = min(C + 1, A[i]);
  }
  reverse(A, A + N);
  int ub = N;
  int lb = 0;
  while (ub - lb > 1)
  {
    int t = (ub + lb) / 2;
    if (solve(t))
    {
      ub = t;
    }
    else
    {
      lb = t;
    }
  }
  cout << ub << endl;
}<commit_msg>submit C.cpp to 'C - Lexicographic constraints' (agc029) [C++14 (GCC 5.4.1)]<commit_after>/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-12-15 21:49:53
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

const int C = 100;
// const ll M = 1000000007;

int N;
int A[200010];
int K[C];

bool solve(int X)
{
  fill(K, K + A[0], 0);
  for (auto i = 0; i < N - 1; i++)
  {
    if (A[i] > A[i + 1])
    {
      continue;
    }
    else if (A[i + 1] == C + 1)
    {
      continue;
    }
    else
    {
      bool ok = false;
      for (auto j = A[i] - 1; j >= 0; j--)
      {
        K[j]++;
        if (K[j] == X)
        {
          K[j] = 0;
        }
        else
        {
          ok = true;
          break;
        }
      }
      if (!ok)
      {
        return false;
      }
      for (auto j = A[i]; j < A[i + 1]; j++)
      {
        K[j] = 0;
      }
    }
  }
  return true;
}

int main()
{
  cin >> N;
  for (auto i = 0; i < N; i++)
  {
    cin >> A[i];
    A[i] = min(C + 1, A[i]);
  }
  reverse(A, A + N);
  int ub = N;
  int lb = 0;
  while (ub - lb > 1)
  {
    int t = (ub + lb) / 2;
    if (solve(t))
    {
      ub = t;
    }
    else
    {
      lb = t;
    }
  }
  cout << ub << endl;
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: impgrf.cxx,v $
 *
 *  $Revision: 1.20 $
 *
 *  last change: $Author: svesik $ $Date: 2004-04-21 12:10:40 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
// include ------------------------------------------------------------------

#include <limits.h>             // USHRT_MAX

#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _BIGINT_HXX
#include <tools/bigint.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif
#ifndef _SFXDISPATCH_HXX
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SV_WAITOBJ_HXX //autogen
#include <vcl/waitobj.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_VIEWOPTIONS_HXX
#include <svtools/viewoptions.hxx>
#endif
#ifndef _UNOTOOLS_LOCALFILEHELPER_HXX
#include <unotools/localfilehelper.hxx>
#endif
#pragma hdrstop

#include <ucbhelper/content.hxx>
#include <osl/file.hxx>

#ifndef _COM_SUN_STAR_UCB_COMMANDABORTEDEXCEPTION_HPP_
#include <com/sun/star/ucb/CommandAbortedException.hpp>
#endif

using namespace ::ucb;
using namespace com::sun::star::uno;

#include "dialogs.hrc"
#include "impgrf.hrc"

#define _SVX_IMPGRF_CXX
#include "impgrf.hxx"

#include "dialmgr.hxx"
#include "svxerr.hxx"
#include "helpid.hrc"

// defines ---------------------------------------------------------------

#define IMPGRF_INIKEY_ASLINK        "ImportGraphicAsLink"
#define IMPGRF_INIKEY_PREVIEW       "ImportGraphicPreview"
#define IMPGRF_CONFIGNAME           String(DEFINE_CONST_UNICODE("ImportGraphicDialog"))

GraphicFilter* GetGrfFilter()
{
    return GraphicFilter::GetGraphicFilter();
}

// -----------------------------------------------------------------------

#pragma optimize( "", off )

int LoadGraphic( const String &rPath, const String &rFilterName,
                 Graphic& rGraphic, GraphicFilter* pFilter,
                 USHORT* pDeterminedFormat )
{
    if ( !pFilter )
        pFilter = ::GetGrfFilter();

    const int nFilter = rFilterName.Len() && pFilter->GetImportFormatCount()
                    ? pFilter->GetImportFormatNumber( rFilterName )
                    : GRFILTER_FORMAT_DONTKNOW;

    SfxMedium* pMed = 0;

    // dann teste mal auf File-Protokoll:
    SvStream* pStream = NULL;
    INetURLObject aURL( rPath );

    if ( aURL.HasError() || INET_PROT_NOT_VALID == aURL.GetProtocol() )
    {
        aURL.SetSmartProtocol( INET_PROT_FILE );
        aURL.SetSmartURL( rPath );
    }
    else if ( INET_PROT_FILE != aURL.GetProtocol() )
    {
        // z.Z. nur auf die aktuelle DocShell
        pMed = new SfxMedium( rPath, STREAM_READ, TRUE );
        pMed->DownLoad();
        pStream = pMed->GetInStream();
    }
    int nRes = GRFILTER_OK;

    if ( !pStream )
        nRes = pFilter->ImportGraphic( rGraphic, aURL, nFilter, pDeterminedFormat );
    else
        nRes = pFilter->ImportGraphic( rGraphic, rPath, *pStream,
                                       nFilter, pDeterminedFormat );

#ifndef PRODUCT
    if( nRes )
    {
        if( pMed )
        {
            DBG_WARNING3( "GrafikFehler [%d] - [%s] URL[%s]",
                            nRes,
                            pMed->GetPhysicalName().GetBuffer(),
                            rPath.GetBuffer() );
        }
        else
        {
            DBG_WARNING2( "GrafikFehler [%d] - [%s]", nRes, rPath.GetBuffer() );
        }
    }
#endif

    if ( pMed )
        delete pMed;
    return nRes;
}

#pragma optimize( "", on )

<commit_msg>INTEGRATION: CWS ooo19126 (1.20.928); FILE MERGED 2005/09/05 14:19:44 rt 1.20.928.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: impgrf.cxx,v $
 *
 *  $Revision: 1.21 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 21:21:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
// include ------------------------------------------------------------------

#include <limits.h>             // USHRT_MAX

#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _BIGINT_HXX
#include <tools/bigint.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif
#ifndef _SFXDISPATCH_HXX
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SV_WAITOBJ_HXX //autogen
#include <vcl/waitobj.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_VIEWOPTIONS_HXX
#include <svtools/viewoptions.hxx>
#endif
#ifndef _UNOTOOLS_LOCALFILEHELPER_HXX
#include <unotools/localfilehelper.hxx>
#endif
#pragma hdrstop

#include <ucbhelper/content.hxx>
#include <osl/file.hxx>

#ifndef _COM_SUN_STAR_UCB_COMMANDABORTEDEXCEPTION_HPP_
#include <com/sun/star/ucb/CommandAbortedException.hpp>
#endif

using namespace ::ucb;
using namespace com::sun::star::uno;

#include "dialogs.hrc"
#include "impgrf.hrc"

#define _SVX_IMPGRF_CXX
#include "impgrf.hxx"

#include "dialmgr.hxx"
#include "svxerr.hxx"
#include "helpid.hrc"

// defines ---------------------------------------------------------------

#define IMPGRF_INIKEY_ASLINK        "ImportGraphicAsLink"
#define IMPGRF_INIKEY_PREVIEW       "ImportGraphicPreview"
#define IMPGRF_CONFIGNAME           String(DEFINE_CONST_UNICODE("ImportGraphicDialog"))

GraphicFilter* GetGrfFilter()
{
    return GraphicFilter::GetGraphicFilter();
}

// -----------------------------------------------------------------------

#pragma optimize( "", off )

int LoadGraphic( const String &rPath, const String &rFilterName,
                 Graphic& rGraphic, GraphicFilter* pFilter,
                 USHORT* pDeterminedFormat )
{
    if ( !pFilter )
        pFilter = ::GetGrfFilter();

    const int nFilter = rFilterName.Len() && pFilter->GetImportFormatCount()
                    ? pFilter->GetImportFormatNumber( rFilterName )
                    : GRFILTER_FORMAT_DONTKNOW;

    SfxMedium* pMed = 0;

    // dann teste mal auf File-Protokoll:
    SvStream* pStream = NULL;
    INetURLObject aURL( rPath );

    if ( aURL.HasError() || INET_PROT_NOT_VALID == aURL.GetProtocol() )
    {
        aURL.SetSmartProtocol( INET_PROT_FILE );
        aURL.SetSmartURL( rPath );
    }
    else if ( INET_PROT_FILE != aURL.GetProtocol() )
    {
        // z.Z. nur auf die aktuelle DocShell
        pMed = new SfxMedium( rPath, STREAM_READ, TRUE );
        pMed->DownLoad();
        pStream = pMed->GetInStream();
    }
    int nRes = GRFILTER_OK;

    if ( !pStream )
        nRes = pFilter->ImportGraphic( rGraphic, aURL, nFilter, pDeterminedFormat );
    else
        nRes = pFilter->ImportGraphic( rGraphic, rPath, *pStream,
                                       nFilter, pDeterminedFormat );

#ifndef PRODUCT
    if( nRes )
    {
        if( pMed )
        {
            DBG_WARNING3( "GrafikFehler [%d] - [%s] URL[%s]",
                            nRes,
                            pMed->GetPhysicalName().GetBuffer(),
                            rPath.GetBuffer() );
        }
        else
        {
            DBG_WARNING2( "GrafikFehler [%d] - [%s]", nRes, rPath.GetBuffer() );
        }
    }
#endif

    if ( pMed )
        delete pMed;
    return nRes;
}

#pragma optimize( "", on )

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: onefuncstarter.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 12:17:31 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <vector>
#include <stdio.h>
#include "registerfunc.h"

#ifndef _OSL_MODULE_HXX_
#include <osl/module.hxx>
#endif
#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif

#include <rtl/string.hxx>
#include <rtl/ustring.hxx>

typedef std::vector<FktPtr> FunctionList;
FunctionList m_Functions;

extern "C" bool SAL_CALL registerFunc(FktPtr _pFunc, const char* _sFuncName)
{
   printf("Function register call for func(%s) successful.\n", _sFuncName);
   m_Functions.push_back(_pFunc);
   // FktPtr pFunc = _pFunc;
   // if (_pFunc)
   // {
   //    (_pFunc)();
   // }

   return true;
}

void callAll()
{
   for(FunctionList::const_iterator it = m_Functions.begin();
       it != m_Functions.end();
       ++it)
   {
      FktPtr pFunc = *it;
      if (pFunc)
      {
         (pFunc)();
      }
   }
}

// void test_link_at_compiletime()
// {
//     FktRegFuncPtr pRegisterFunc = &registerFunc;
//     registerAll(pRegisterFunc);
//     callAll();
// }

// -----------------------------------------------------------------------------
rtl::OUString convertPath( rtl::OString const& sysPth )
{
    // PRE: String should contain a filename, relativ or absolut
    rtl::OUString sysPath( rtl::OUString::createFromAscii( sysPth.getStr() ) );
    rtl::OUString fURL;
    if ( sysPth.indexOf("..") == 0 )
    {
        // filepath contains '..' so it's a relative path make it absolut.
        rtl::OUString curDirPth;
        osl_getProcessWorkingDir( &curDirPth.pData );
        osl::FileBase::getAbsoluteFileURL( curDirPth, sysPath, fURL );
    }
    else
    {
        osl::FileBase::getFileURLFromSystemPath( sysPath, fURL );
    }
    return fURL;
}
// -----------------------------------------------------------------------------

void test_link_at_runtime()
{
    ::osl::Module* pModule;
    pModule = new ::osl::Module();
    // create and load the module (shared library)
    // pModule = new ::osl::Module();
#ifdef WNT
    pModule->load( convertPath( rtl::OString( "onefunc_DLL.dll" ) ) );
#endif
#ifdef UNX
    pModule->load( convertPath( rtl::OString( "libonefunc_DLL.so" ) ) );
#endif

    // get entry pointer
    FktRegAllPtr pFunc = (FktRegAllPtr) pModule->getSymbol( rtl::OUString::createFromAscii( "registerAllTestFunction" ) );

    if (pFunc)
    {
        FktRegFuncPtr pRegisterFunc = &registerFunc;
        pFunc(pRegisterFunc);
        callAll();
    }

    delete pModule;
}

// ----------------------------------- Main -----------------------------------
#if (defined UNX) || (defined OS2)
int main( int argc, char* argv[] )
#else
int _cdecl main( int argc, char* argv[] )
#endif
{
//  test_link_at_compiletime();
    test_link_at_runtime();
    return 0;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.4.24); FILE MERGED 2006/09/01 17:53:51 kaib 1.4.24.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: onefuncstarter.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 03:49:28 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_testshl2.hxx"

#include <vector>
#include <stdio.h>
#include "registerfunc.h"

#ifndef _OSL_MODULE_HXX_
#include <osl/module.hxx>
#endif
#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif

#include <rtl/string.hxx>
#include <rtl/ustring.hxx>

typedef std::vector<FktPtr> FunctionList;
FunctionList m_Functions;

extern "C" bool SAL_CALL registerFunc(FktPtr _pFunc, const char* _sFuncName)
{
   printf("Function register call for func(%s) successful.\n", _sFuncName);
   m_Functions.push_back(_pFunc);
   // FktPtr pFunc = _pFunc;
   // if (_pFunc)
   // {
   //    (_pFunc)();
   // }

   return true;
}

void callAll()
{
   for(FunctionList::const_iterator it = m_Functions.begin();
       it != m_Functions.end();
       ++it)
   {
      FktPtr pFunc = *it;
      if (pFunc)
      {
         (pFunc)();
      }
   }
}

// void test_link_at_compiletime()
// {
//     FktRegFuncPtr pRegisterFunc = &registerFunc;
//     registerAll(pRegisterFunc);
//     callAll();
// }

// -----------------------------------------------------------------------------
rtl::OUString convertPath( rtl::OString const& sysPth )
{
    // PRE: String should contain a filename, relativ or absolut
    rtl::OUString sysPath( rtl::OUString::createFromAscii( sysPth.getStr() ) );
    rtl::OUString fURL;
    if ( sysPth.indexOf("..") == 0 )
    {
        // filepath contains '..' so it's a relative path make it absolut.
        rtl::OUString curDirPth;
        osl_getProcessWorkingDir( &curDirPth.pData );
        osl::FileBase::getAbsoluteFileURL( curDirPth, sysPath, fURL );
    }
    else
    {
        osl::FileBase::getFileURLFromSystemPath( sysPath, fURL );
    }
    return fURL;
}
// -----------------------------------------------------------------------------

void test_link_at_runtime()
{
    ::osl::Module* pModule;
    pModule = new ::osl::Module();
    // create and load the module (shared library)
    // pModule = new ::osl::Module();
#ifdef WNT
    pModule->load( convertPath( rtl::OString( "onefunc_DLL.dll" ) ) );
#endif
#ifdef UNX
    pModule->load( convertPath( rtl::OString( "libonefunc_DLL.so" ) ) );
#endif

    // get entry pointer
    FktRegAllPtr pFunc = (FktRegAllPtr) pModule->getSymbol( rtl::OUString::createFromAscii( "registerAllTestFunction" ) );

    if (pFunc)
    {
        FktRegFuncPtr pRegisterFunc = &registerFunc;
        pFunc(pRegisterFunc);
        callAll();
    }

    delete pModule;
}

// ----------------------------------- Main -----------------------------------
#if (defined UNX) || (defined OS2)
int main( int argc, char* argv[] )
#else
int _cdecl main( int argc, char* argv[] )
#endif
{
//  test_link_at_compiletime();
    test_link_at_runtime();
    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmltxtimp.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 13:29:45 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _COM_SUN_STAR_IO_XACTIVEDATACONTROL_HPP_
#include <com/sun/star/io/XActiveDataControl.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_
#include <com/sun/star/io/XActiveDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _UTL_STREAM_WRAPPER_HXX_
#include <unotools/streamwrap.hxx>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _SVSTOR_HXX
#include <sot/storage.hxx>
#endif

#ifndef _SFX_ITEMPROP_HXX
#include <svtools/itemprop.hxx>
#endif

#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif

#ifndef _XMLOFF_XMLMETAE_HXX
#include "xmloff/xmlmetae.hxx"
#endif
#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_XMLSTYLE_HXX
#include <xmloff/xmlstyle.hxx>
#endif

#ifndef _SVX_EDITSOURCE_HXX
#include "editsource.hxx"
#endif

#ifndef _SVX_UNOTEXT_HXX
#include "unotext.hxx"
#endif

using namespace com::sun::star;
using namespace com::sun::star::document;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::xml::sax;
using namespace com::sun::star::text;
using namespace ::rtl;
using namespace cppu;
using namespace xmloff::token;

///////////////////////////////////////////////////////////////////////

class SvxXMLTextImportContext : public SvXMLImportContext
{
public:
    SvxXMLTextImportContext( SvXMLImport& rImport, USHORT nPrfx, const OUString& rLName, const Reference< XAttributeList >& xAttrList, const Reference< XText >& xText );
    virtual ~SvxXMLTextImportContext();

    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList );

//  SvxXMLXTableImport& getImport() const { return *(SvxXMLXTableImport*)&GetImport(); }

private:
    const Reference< XText > mxText;
};

///////////////////////////////////////////////////////////////////////

SvxXMLTextImportContext::SvxXMLTextImportContext( SvXMLImport& rImport, USHORT nPrfx, const OUString& rLName, const Reference< XAttributeList >&, const Reference< XText >& xText )
: SvXMLImportContext( rImport, nPrfx, rLName ), mxText( xText )
{
}

SvxXMLTextImportContext::~SvxXMLTextImportContext()
{
}

SvXMLImportContext *SvxXMLTextImportContext::CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList )
{
    SvXMLImportContext* pContext = NULL;
    if(XML_NAMESPACE_OFFICE == nPrefix && IsXMLToken( rLocalName, XML_BODY ) )
    {
        pContext = new SvxXMLTextImportContext( GetImport(), nPrefix, rLocalName, xAttrList, mxText );
    }
    else if( XML_NAMESPACE_OFFICE == nPrefix && IsXMLToken( rLocalName, XML_AUTOMATIC_STYLES ) )
    {
        pContext = new SvXMLStylesContext( GetImport(), nPrefix, rLocalName, xAttrList );
        GetImport().GetTextImport()->SetAutoStyles( (SvXMLStylesContext*)pContext );

    }
    else
    {
        pContext = GetImport().GetTextImport()->CreateTextChildContext( GetImport(), nPrefix, rLocalName, xAttrList );
    }

    if( NULL == pContext )
        pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );

    return pContext;
}

///////////////////////////////////////////////////////////////////////

class SvxXMLXTextImportComponent : public SvXMLImport
{
public:
    // #110680#
    SvxXMLXTextImportComponent(
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
        const Reference< XText > & xText );

    virtual ~SvxXMLXTextImportComponent() throw ();

    static sal_Bool load( const rtl::OUString& rUrl, const com::sun::star::uno::Reference< com::sun::star::container::XNameContainer >& xTable ) throw();
protected:
    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList );

private:
    const Reference< XText > mxText;
};

// --------------------------------------------------------------------

// #110680#
SvxXMLXTextImportComponent::SvxXMLXTextImportComponent(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
    const Reference< XText > & xText )
:   SvXMLImport(xServiceFactory),
    mxText( xText )
{
    GetTextImport()->SetCursor( mxText->createTextCursor() );
}

SvxXMLXTextImportComponent::~SvxXMLXTextImportComponent() throw ()
{
}

void SvxReadXML( EditEngine& rEditEngine, SvStream& rStream, const ESelection& rSel )
{
    SvxEditEngineSource aEditSource( &rEditEngine );

    static const SfxItemPropertyMap SvxXMLTextImportComponentPropertyMap[] =
    {
        SVX_UNOEDIT_CHAR_PROPERTIES,
        SVX_UNOEDIT_FONT_PROPERTIES,
//      SVX_UNOEDIT_OUTLINER_PROPERTIES,
        SVX_UNOEDIT_PARA_PROPERTIES,
        {0,0,0,0,0,0}
    };

    uno::Reference<text::XText > xParent;
    SvxUnoText* pUnoText = new SvxUnoText( &aEditSource, SvxXMLTextImportComponentPropertyMap, xParent );
    pUnoText->SetSelection( rSel );
    uno::Reference<text::XText > xText( pUnoText );

    try
    {
        do
        {
            uno::Reference<lang::XMultiServiceFactory> xServiceFactory( ::comphelper::getProcessServiceFactory() );
            if( !xServiceFactory.is() )
            {
                DBG_ERROR( "SvxXMLXTableImport::load: got no service manager" );
                break;
            }

            uno::Reference< xml::sax::XParser > xParser( xServiceFactory->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.sax.Parser" ) ) ), uno::UNO_QUERY );
            if( !xParser.is() )
            {
                DBG_ERROR( "com.sun.star.xml.sax.Parser service missing" );
                break;
            }

            Reference<io::XInputStream> xInputStream = new utl::OInputStreamWrapper( rStream );

/* testcode
            const OUString aURL( RTL_CONSTASCII_USTRINGPARAM( "file:///e:/test.xml" ) );
            SfxMedium aMedium( aURL, STREAM_READ | STREAM_NOCREATE, TRUE );
            aMedium.IsRemote();
            uno::Reference<io::XOutputStream> xOut( new utl::OOutputStreamWrapper( *aMedium.GetOutStream() ) );

            aMedium.GetInStream()->Seek( 0 );
            uno::Reference< io::XActiveDataSource > xSource( aMedium.GetDataSource() );

            if( !xSource.is() )
            {
                DBG_ERROR( "got no data source from medium" );
                break;
            }

            Reference< XInterface > xPipe( xServiceFactory->createInstance(OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.io.Pipe") ) ) );
            if( !xPipe.is() )
            {
                DBG_ERROR( "XMLReader::Read: com.sun.star.io.Pipe service missing" );
                break;
            }

            // connect pipe's output stream to the data source
            xSource->setOutputStream( Reference< io::XOutputStream >::query( xPipe ) );

            xml::sax::InputSource aParserInput;
            aParserInput.aInputStream = uno::Reference< io::XInputStream >::query( xPipe );
            aParserInput.sSystemId = aMedium.GetName();

            if( xSource.is() )
            {
                Reference< io::XActiveDataControl > xSourceControl( xSource, UNO_QUERY );
                xSourceControl->start();
            }

*/

            // #110680#
            // Reference< XDocumentHandler > xHandler( new SvxXMLXTextImportComponent( xText ) );
            Reference< XDocumentHandler > xHandler( new SvxXMLXTextImportComponent( xServiceFactory, xText ) );

            xParser->setDocumentHandler( xHandler );

            xml::sax::InputSource aParserInput;
            aParserInput.aInputStream = xInputStream;
//          aParserInput.sSystemId = aMedium.GetName();
            xParser->parseStream( aParserInput );
        }
        while(0);
    }
    catch( uno::Exception& )
    {
    }
}

SvXMLImportContext *SvxXMLXTextImportComponent::CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList )
{
    SvXMLImportContext* pContext;
    if(XML_NAMESPACE_OFFICE == nPrefix && ( IsXMLToken( rLocalName, XML_DOCUMENT ) || IsXMLToken( rLocalName, XML_DOCUMENT_CONTENT ) ) )
    {
         pContext = new SvxXMLTextImportContext(*this, nPrefix, rLocalName, xAttrList, mxText );
    }
    else
    {
        pContext = SvXMLImport::CreateContext(nPrefix, rLocalName, xAttrList);
    }
    return pContext;
}

<commit_msg>INTEGRATION: CWS bgdlremove (1.8.304); FILE MERGED 2007/05/11 09:12:34 kso 1.8.304.1: #i76911# - ucbhelper lib no longer uses VOS. (vos::ORef => rtl::Reference, vos::OMutex => osl::Mutex, ...)<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmltxtimp.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: ihi $ $Date: 2007-06-05 14:37:30 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _COM_SUN_STAR_IO_XACTIVEDATACONTROL_HPP_
#include <com/sun/star/io/XActiveDataControl.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_
#include <com/sun/star/io/XActiveDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _UTL_STREAM_WRAPPER_HXX_
#include <unotools/streamwrap.hxx>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _SVSTOR_HXX
#include <sot/storage.hxx>
#endif

#ifndef _SFX_ITEMPROP_HXX
#include <svtools/itemprop.hxx>
#endif

#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif

#ifndef _XMLOFF_XMLMETAE_HXX
#include "xmloff/xmlmetae.hxx"
#endif
#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_XMLSTYLE_HXX
#include <xmloff/xmlstyle.hxx>
#endif

#ifndef _SVX_EDITSOURCE_HXX
#include "editsource.hxx"
#endif

#ifndef _SVX_UNOTEXT_HXX
#include "unotext.hxx"
#endif

using namespace com::sun::star;
using namespace com::sun::star::document;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::xml::sax;
using namespace com::sun::star::text;
using namespace ::rtl;
using namespace cppu;
using namespace xmloff::token;

///////////////////////////////////////////////////////////////////////

class SvxXMLTextImportContext : public SvXMLImportContext
{
public:
    SvxXMLTextImportContext( SvXMLImport& rImport, USHORT nPrfx, const OUString& rLName, const uno::Reference< XAttributeList >& xAttrList, const uno::Reference< XText >& xText );
    virtual ~SvxXMLTextImportContext();

    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const uno::Reference< XAttributeList >& xAttrList );

//  SvxXMLXTableImport& getImport() const { return *(SvxXMLXTableImport*)&GetImport(); }

private:
    const uno::Reference< XText > mxText;
};

///////////////////////////////////////////////////////////////////////

SvxXMLTextImportContext::SvxXMLTextImportContext( SvXMLImport& rImport, USHORT nPrfx, const OUString& rLName, const uno::Reference< XAttributeList >&, const uno::Reference< XText >& xText )
: SvXMLImportContext( rImport, nPrfx, rLName ), mxText( xText )
{
}

SvxXMLTextImportContext::~SvxXMLTextImportContext()
{
}

SvXMLImportContext *SvxXMLTextImportContext::CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const uno::Reference< XAttributeList >& xAttrList )
{
    SvXMLImportContext* pContext = NULL;
    if(XML_NAMESPACE_OFFICE == nPrefix && IsXMLToken( rLocalName, XML_BODY ) )
    {
        pContext = new SvxXMLTextImportContext( GetImport(), nPrefix, rLocalName, xAttrList, mxText );
    }
    else if( XML_NAMESPACE_OFFICE == nPrefix && IsXMLToken( rLocalName, XML_AUTOMATIC_STYLES ) )
    {
        pContext = new SvXMLStylesContext( GetImport(), nPrefix, rLocalName, xAttrList );
        GetImport().GetTextImport()->SetAutoStyles( (SvXMLStylesContext*)pContext );

    }
    else
    {
        pContext = GetImport().GetTextImport()->CreateTextChildContext( GetImport(), nPrefix, rLocalName, xAttrList );
    }

    if( NULL == pContext )
        pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );

    return pContext;
}

///////////////////////////////////////////////////////////////////////

class SvxXMLXTextImportComponent : public SvXMLImport
{
public:
    // #110680#
    SvxXMLXTextImportComponent(
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
        const uno::Reference< XText > & xText );

    virtual ~SvxXMLXTextImportComponent() throw ();

    static sal_Bool load( const rtl::OUString& rUrl, const com::sun::star::uno::Reference< com::sun::star::container::XNameContainer >& xTable ) throw();
protected:
    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const uno::Reference< XAttributeList >& xAttrList );

private:
    const uno::Reference< XText > mxText;
};

// --------------------------------------------------------------------

// #110680#
SvxXMLXTextImportComponent::SvxXMLXTextImportComponent(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
    const uno::Reference< XText > & xText )
:   SvXMLImport(xServiceFactory),
    mxText( xText )
{
    GetTextImport()->SetCursor( mxText->createTextCursor() );
}

SvxXMLXTextImportComponent::~SvxXMLXTextImportComponent() throw ()
{
}

void SvxReadXML( EditEngine& rEditEngine, SvStream& rStream, const ESelection& rSel )
{
    SvxEditEngineSource aEditSource( &rEditEngine );

    static const SfxItemPropertyMap SvxXMLTextImportComponentPropertyMap[] =
    {
        SVX_UNOEDIT_CHAR_PROPERTIES,
        SVX_UNOEDIT_FONT_PROPERTIES,
//      SVX_UNOEDIT_OUTLINER_PROPERTIES,
        SVX_UNOEDIT_PARA_PROPERTIES,
        {0,0,0,0,0,0}
    };

    uno::Reference<text::XText > xParent;
    SvxUnoText* pUnoText = new SvxUnoText( &aEditSource, SvxXMLTextImportComponentPropertyMap, xParent );
    pUnoText->SetSelection( rSel );
    uno::Reference<text::XText > xText( pUnoText );

    try
    {
        do
        {
            uno::Reference<lang::XMultiServiceFactory> xServiceFactory( ::comphelper::getProcessServiceFactory() );
            if( !xServiceFactory.is() )
            {
                DBG_ERROR( "SvxXMLXTableImport::load: got no service manager" );
                break;
            }

            uno::Reference< xml::sax::XParser > xParser( xServiceFactory->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.sax.Parser" ) ) ), uno::UNO_QUERY );
            if( !xParser.is() )
            {
                DBG_ERROR( "com.sun.star.xml.sax.Parser service missing" );
                break;
            }

            uno::Reference<io::XInputStream> xInputStream = new utl::OInputStreamWrapper( rStream );

/* testcode
            const OUString aURL( RTL_CONSTASCII_USTRINGPARAM( "file:///e:/test.xml" ) );
            SfxMedium aMedium( aURL, STREAM_READ | STREAM_NOCREATE, TRUE );
            aMedium.IsRemote();
            uno::Reference<io::XOutputStream> xOut( new utl::OOutputStreamWrapper( *aMedium.GetOutStream() ) );

            aMedium.GetInStream()->Seek( 0 );
            uno::Reference< io::XActiveDataSource > xSource( aMedium.GetDataSource() );

            if( !xSource.is() )
            {
                DBG_ERROR( "got no data source from medium" );
                break;
            }

            uno::Reference< XInterface > xPipe( xServiceFactory->createInstance(OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.io.Pipe") ) ) );
            if( !xPipe.is() )
            {
                DBG_ERROR( "XMLReader::Read: com.sun.star.io.Pipe service missing" );
                break;
            }

            // connect pipe's output stream to the data source
            xSource->setOutputStream( uno::Reference< io::XOutputStream >::query( xPipe ) );

            xml::sax::InputSource aParserInput;
            aParserInput.aInputStream = uno::Reference< io::XInputStream >::query( xPipe );
            aParserInput.sSystemId = aMedium.GetName();

            if( xSource.is() )
            {
                uno::Reference< io::XActiveDataControl > xSourceControl( xSource, UNO_QUERY );
                xSourceControl->start();
            }

*/

            // #110680#
            // uno::Reference< XDocumentHandler > xHandler( new SvxXMLXTextImportComponent( xText ) );
            uno::Reference< XDocumentHandler > xHandler( new SvxXMLXTextImportComponent( xServiceFactory, xText ) );

            xParser->setDocumentHandler( xHandler );

            xml::sax::InputSource aParserInput;
            aParserInput.aInputStream = xInputStream;
//          aParserInput.sSystemId = aMedium.GetName();
            xParser->parseStream( aParserInput );
        }
        while(0);
    }
    catch( uno::Exception& )
    {
    }
}

SvXMLImportContext *SvxXMLXTextImportComponent::CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const uno::Reference< XAttributeList >& xAttrList )
{
    SvXMLImportContext* pContext;
    if(XML_NAMESPACE_OFFICE == nPrefix && ( IsXMLToken( rLocalName, XML_DOCUMENT ) || IsXMLToken( rLocalName, XML_DOCUMENT_CONTENT ) ) )
    {
         pContext = new SvxXMLTextImportContext(*this, nPrefix, rLocalName, xAttrList, mxText );
    }
    else
    {
        pContext = SvXMLImport::CreateContext(nPrefix, rLocalName, xAttrList);
    }
    return pContext;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: multmrk.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: fme $ $Date: 2001-05-21 12:25:10 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _MULTMRK_HXX
#define _MULTMRK_HXX

#ifndef _SVX_STDDLG_HXX //autogen
#include <svx/stddlg.hxx>
#endif

#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif

#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif

#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif

class SwTOXMgr;

/*--------------------------------------------------------------------
     Beschreibung:  Markierung fuer Verzeichniseintrag einfuegen
 --------------------------------------------------------------------*/

class SwMultiTOXMarkDlg : public SvxStandardDialog
{
    DECL_LINK( SelectHdl, ListBox * );

    FixedLine           aTOXFL;
    FixedText           aEntryFT;
    FixedInfo           aTextFT;
    FixedText           aTOXFT;
    ListBox             aTOXLB;
    OKButton            aOkBT;
    CancelButton        aCancelBT;

    SwTOXMgr           &rMgr;
    USHORT              nPos;

    void                Apply();
public:
    SwMultiTOXMarkDlg( Window* pParent, SwTOXMgr &rTOXMgr );
    ~SwMultiTOXMarkDlg();
};

#endif // _MULTMRK_HXX

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.1448); FILE MERGED 2005/09/05 13:45:27 rt 1.2.1448.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: multmrk.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 09:51:31 $
 *
 *  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 _MULTMRK_HXX
#define _MULTMRK_HXX

#ifndef _SVX_STDDLG_HXX //autogen
#include <svx/stddlg.hxx>
#endif

#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif

#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif

#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif

class SwTOXMgr;

/*--------------------------------------------------------------------
     Beschreibung:  Markierung fuer Verzeichniseintrag einfuegen
 --------------------------------------------------------------------*/

class SwMultiTOXMarkDlg : public SvxStandardDialog
{
    DECL_LINK( SelectHdl, ListBox * );

    FixedLine           aTOXFL;
    FixedText           aEntryFT;
    FixedInfo           aTextFT;
    FixedText           aTOXFT;
    ListBox             aTOXLB;
    OKButton            aOkBT;
    CancelButton        aCancelBT;

    SwTOXMgr           &rMgr;
    USHORT              nPos;

    void                Apply();
public:
    SwMultiTOXMarkDlg( Window* pParent, SwTOXMgr &rTOXMgr );
    ~SwMultiTOXMarkDlg();
};

#endif // _MULTMRK_HXX

<|endoftext|>


<commit_before>#ifndef _LINKED_LIST_HPP_
#define _LINKED_LIST_HPP_

#ifndef _LINKED_LIST_NODE_HPP
#define _LINKED_LIST_NODE_HPP
#include "linked_list_node.hpp"
#endif // _LINKED_LIST_NODE_HPP

template <typename T>
class LinkedList
{
public:
	// pointer to the head of the list
	LinkedListNode<T>* head;

	LinkedList() { head = nullptr; }

	/** METHODS **/

	// Returns true if the list is empty, false otherwise.
	bool empty()
	{
		if( head == nullptr )
			return true;
		return false;
	}

	// Returns the length of the LinkedList.
	unsigned int length()
	{
		if( empty() )
			return 0;
		LinkedListNode<T>* node = head;
		unsigned int count = 1;
		while( node->next != nullptr ) {
			node = node->next;
			count++;
		}
		return count;
	}

	// Add value to the head of the linked list.
	void prepend( T value )
	{
		LinkedListNode<T>* node = new LinkedListNode<T>( value );
		node->next = head;
		head = node;
	}

	// Add value to the end of the linked list.
	void append( T value )
	{
		LinkedListNode<T>* tmp = new LinkedListNode<T>( value );
		if( empty() ) {
			prepend( value );
		} else {
			LinkedListNode<T>* node = head;
			while( node->next != nullptr ) {
				node = node->next;
			}
			node->next = tmp;
		}
	}

	// Inserts value at given index. If the index is out of range,
	// inserts value at the tail of the list.
	void insertAt( T value, unsigned int index )
	{
		LinkedListNode<T>* node = head;
		LinkedListNode<T>* tmp  = new LinkedListNode<T>( value );
		while( index > 1 && node->next != nullptr ) {
			node = node->next;
			--index;
		}
		tmp->next = node->next;
		node->next = tmp;
	}

	// Remove the node at the head of the list.
	//
	// PRECONDITION: List must not be empty.
	T decapitate()
	{
		// if( empty() )
		// 	return;
		LinkedListNode<T>* node = head;
		head = node->next;
		delete node;
		return node->data;
	}

	// Remove the node at the end of the list.
	//
	// PRECONDITION: List must not be empty.
	T decaudate()
	{
		// if list has length 1, decapitate the list.
		if( length() == 1 )
			return decapitate();

		// else, decaudate the list.
		LinkedListNode<T>* node = head;
		LinkedListNode<T>* prev = node;
		while( node->next != nullptr )
		{
			prev = node;
			node = node->next;
		}
		prev->next = nullptr;
		delete node;
		return node->data;
	}

	// Remove the node at the index.
	//
	// Removes the last item in the list if the index is out of bounds.
	//
	// TODO: Raise exception if index out of bounds.
	T removeAt( unsigned int index )
	{
		LinkedListNode<T>* node = head;
		if( index == 0 ) {
			head = node->next;
			delete node;
			return node->data;
		} else {
			LinkedListNode<T>* prev = head;
			while( index > 0 && node->next != nullptr ) {
				prev = node;
				node = node->next;
				--index;
			}
			prev->next = node->next;
			delete node;
			return node->data;
		}
	}

	// Returns true if the list contains the value.
	// Returns false if the list does not contain the value.
	bool contains( T value )
	{
		LinkedListNode<T>* node = head;
		while( node->next != nullptr ) {
			if( node->data == value )
				return true;
			node = node->next;
		}
		if( node->data == value )
			return true;
		return false;
	}

	// Returns the index of the value if it exists in the list.
	// Returns -1 if value is not in the list.
	//
	// Zero indexed.
	unsigned int indexOf( T value )
	{
		unsigned int index = 0;
		LinkedListNode<T>* node = head;
		while( node->next != nullptr ) {
			if( node->data == value )
				return index;
			node = node->next;
			++index;
		}
		if( node->data == value )
			return index;
		return -1;
	}

	// Returns the value at the head of the list.
	//
	// PRECONDITION: List must not be empty.
	T itemAtHead()
	{
		LinkedListNode<T>* node = head;
		return node->data;
	}

	// Returns the value at the tail of the list.
	//
	// PRECONDITION: List must not be empty.
	T itemAtTail()
	{
		LinkedListNode<T>* node = head;
		while( node->next != nullptr ) {
			node = node->next;
		}
		return node->data;
	}

	// Returns the value at the given index. If the index is out of bounds,
	// returns the item at the tail of the list.
	//
	// PRECONDITION: Index must be in-bounds for proper function.
	//
	// TODO: Add exception handling for index out of bounds.
	T itemAtIndex( unsigned int index )
	{
		LinkedListNode<T>* node = head;
		while( index > 0 && node->next != nullptr ) {
			node = node->next;
			--index;
		}
		return node->data;
	}
};

#endif // _LINKED_LIST_HPP_<commit_msg>remove faulty header guard<commit_after>#ifndef _LINKED_LIST_HPP_
#define _LINKED_LIST_HPP_

#include "linked_list_node.hpp"

template <typename T>
class LinkedList
{
public:
	// pointer to the head of the list
	LinkedListNode<T>* head;

	LinkedList() { head = nullptr; }

	/** METHODS **/

	// Returns true if the list is empty, false otherwise.
	bool empty()
	{
		if( head == nullptr )
			return true;
		return false;
	}

	// Returns the length of the LinkedList.
	unsigned int length()
	{
		if( empty() )
			return 0;
		LinkedListNode<T>* node = head;
		unsigned int count = 1;
		while( node->next != nullptr ) {
			node = node->next;
			count++;
		}
		return count;
	}

	// Add value to the head of the linked list.
	void prepend( T value )
	{
		LinkedListNode<T>* node = new LinkedListNode<T>( value );
		node->next = head;
		head = node;
	}

	// Add value to the end of the linked list.
	void append( T value )
	{
		LinkedListNode<T>* tmp = new LinkedListNode<T>( value );
		if( empty() ) {
			prepend( value );
		} else {
			LinkedListNode<T>* node = head;
			while( node->next != nullptr ) {
				node = node->next;
			}
			node->next = tmp;
		}
	}

	// Inserts value at given index. If the index is out of range,
	// inserts value at the tail of the list.
	void insertAt( T value, unsigned int index )
	{
		LinkedListNode<T>* node = head;
		LinkedListNode<T>* tmp  = new LinkedListNode<T>( value );
		while( index > 1 && node->next != nullptr ) {
			node = node->next;
			--index;
		}
		tmp->next = node->next;
		node->next = tmp;
	}

	// Remove the node at the head of the list.
	//
	// PRECONDITION: List must not be empty.
	T decapitate()
	{
		// if( empty() )
		// 	return;
		LinkedListNode<T>* node = head;
		head = node->next;
		delete node;
		return node->data;
	}

	// Remove the node at the end of the list.
	//
	// PRECONDITION: List must not be empty.
	T decaudate()
	{
		// if list has length 1, decapitate the list.
		if( length() == 1 )
			return decapitate();

		// else, decaudate the list.
		LinkedListNode<T>* node = head;
		LinkedListNode<T>* prev = node;
		while( node->next != nullptr )
		{
			prev = node;
			node = node->next;
		}
		prev->next = nullptr;
		delete node;
		return node->data;
	}

	// Remove the node at the index.
	//
	// Removes the last item in the list if the index is out of bounds.
	//
	// TODO: Raise exception if index out of bounds.
	T removeAt( unsigned int index )
	{
		LinkedListNode<T>* node = head;
		if( index == 0 ) {
			head = node->next;
			delete node;
			return node->data;
		} else {
			LinkedListNode<T>* prev = head;
			while( index > 0 && node->next != nullptr ) {
				prev = node;
				node = node->next;
				--index;
			}
			prev->next = node->next;
			delete node;
			return node->data;
		}
	}

	// Returns true if the list contains the value.
	// Returns false if the list does not contain the value.
	bool contains( T value )
	{
		LinkedListNode<T>* node = head;
		while( node->next != nullptr ) {
			if( node->data == value )
				return true;
			node = node->next;
		}
		if( node->data == value )
			return true;
		return false;
	}

	// Returns the index of the value if it exists in the list.
	// Returns -1 if value is not in the list.
	//
	// Zero indexed.
	unsigned int indexOf( T value )
	{
		unsigned int index = 0;
		LinkedListNode<T>* node = head;
		while( node->next != nullptr ) {
			if( node->data == value )
				return index;
			node = node->next;
			++index;
		}
		if( node->data == value )
			return index;
		return -1;
	}

	// Returns the value at the head of the list.
	//
	// PRECONDITION: List must not be empty.
	T itemAtHead()
	{
		LinkedListNode<T>* node = head;
		return node->data;
	}

	// Returns the value at the tail of the list.
	//
	// PRECONDITION: List must not be empty.
	T itemAtTail()
	{
		LinkedListNode<T>* node = head;
		while( node->next != nullptr ) {
			node = node->next;
		}
		return node->data;
	}

	// Returns the value at the given index. If the index is out of bounds,
	// returns the item at the tail of the list.
	//
	// PRECONDITION: Index must be in-bounds for proper function.
	//
	// TODO: Add exception handling for index out of bounds.
	T itemAtIndex( unsigned int index )
	{
		LinkedListNode<T>* node = head;
		while( index > 0 && node->next != nullptr ) {
			node = node->next;
			--index;
		}
		return node->data;
	}
};

#endif // _LINKED_LIST_HPP_<|endoftext|>