<commit_before>#include <tianchi/core/tcstring.h>

#include <QTextCodec>
#include <QFile>
#include <QTextStream>

TcString::TcString()
{
}

QByteArray TcString::first(QByteArray& str, const QByteArray& split)
{
    QByteArray ret;
    int endOf = str.indexOf(split);
    if ( endOf == 0 )
    {
        str.remove(0, 1);
    }
    else
    if ( endOf > 0 )
    {
        ret = str.left(endOf);
        str.remove(0, endOf +1);
    }
    else
    {
        ret = str;
    }

    return ret;
}

int TcString::find(const QStringList& ss, const QString& s)
{
    int ret = -1;
    for( int i=0;i<ss.count();i++ )
    {
        if ( ss.at(i).compare(s) == 0 )
        {
            ret = i;
            break;
        }
    }
    return ret;
}

int TcString::findOf(const QStringList& list, const QString& key)
{
    int ret = -1;
    for( int i=0;i<list.count();i++ )
    {
        if ( list.at(i).trimmed().compare(key.trimmed(), Qt::CaseInsensitive)==0 )
        {
            ret = i;
            break;
        }
    }
    return ret;
}

bool TcString::filter(const QString& text, const QStringList& filters)
{
    bool ret = filters.count() <= 0;
    foreach(QString s, filters)
    {
        s = s.trimmed();
        if ( ! s.isEmpty() )
        {
            if ( text.indexOf(s, Qt::CaseInsensitive) >= 0 )
            {
                ret = true;
                break;
            }
        }
    }
    return ret;
}

/// ֽաӢģ
int TcString::splitHumanName(QString full, QString& sur, QString& real, QString& english)
{
    QString surs = QTextCodec::codecForLocale()->toUnicode(
                               "ŷ\n̫ʷ\nľ\nϹ\n˾\n\n\nϹ\nٹ\n"
                               "\nĺ\n\nξ\n\n\n̨\nʸ\n\n"
                               "\nұ\n̫\n\n\nĽ\n\n\n\n"
                               "\n˾ͽ\n\n˾\n\nӳ\n\n˾\n\n"
                               "\n\n\n\n\n\n׸\n\nذ\n"
                               "й\nԯ\n\nθ\n\n\n\n\n\n"
                               "΢\n\n\n\n\n\n\n\nɽ\n"
                               "\n\n\n\n\n\n\n\n\n"
                               "\n\n\nٳ\n\nɣ\nī\n\nʦ\n");
    QStringList doubleSurnames = surs.split("\n");

    full = full.trimmed();

    int ret = 0;
    if ( ! full.isEmpty() )
    {
        if ( full.length() != full.toLocal8Bit().length() )
        {//
            foreach(QString s, doubleSurnames)
            {
                if ( ! s.isEmpty() && full.startsWith(s) )
                {
                    sur = s;
                    ret = 2;
                    break;
                }
            }
            if ( ret != 2 )
            {
                sur = full.mid(0, 1);
                ret = 1;
            }
            real = full.mid(sur.length());
        }else
        {// Ӣ
            QStringList ss = full.split(" ", QString::SkipEmptyParts);
            english = "";
            for( int i=0;i<ss.count();i++ )
            {
                QString t = ss.at(i);
                if ( i == ss.count()-1 )
                {
                    sur = t;
                }else
                {
                    english += t + " ";
                }
            }
            english = english.trimmed();

            ret = 3;
        }
    }
    return ret;
}

QString TcString::getTextByIndex(const char* strings, int index)
{
    QStringList ss = QTextCodec::codecForLocale()->toUnicode(strings).split("\n", QString::SkipEmptyParts);
    return ss.at(index);
}

// class StringList
TcStringList::TcStringList()
{
    #if defined(Q_OS_WIN)
        m_lineBreak = "\r\n";
    #elif defined(Q_OS_LINUX)
        m_lineBreak = "\n";
    #elif defined(Q_OS_MAC)
        m_lineBreak = "\r";
    #else
        m_lineBreak = "\n";
    #endif
}

bool TcStringList::loadFrom(const QString& fileName)
{
    bool ret = false;
    QFile f(fileName);
    if ( f.open(QFile::Text | QFile::ReadOnly) )
    {
        clear();
        QTextStream in(&f);
        while(!in.atEnd())
        {
            this->append(in.readLine());
        }
        f.close();
        ret = false;
    }
    return ret;
}

bool TcStringList::saveTo(const QString& fileName)
{
    bool ret = false;
    QFile f(fileName);
    if ( f.open(QFile::Text | QFile::WriteOnly) )
    {
        QTextStream out(&f);
        foreach(QString s, *this)
        {
            out<<s<<lineBreak();
        }
        f.close();
    }
    return ret;
}
<commit_msg>change TcString::find() implementation<commit_after>#include <tianchi/core/tcstring.h>

#include <QTextCodec>
#include <QFile>
#include <QTextStream>

TcString::TcString()
{
}

QByteArray TcString::first(QByteArray& str, const QByteArray& split)
{
    QByteArray ret;
    int endOf = str.indexOf(split);
    if ( endOf == 0 )
    {
        str.remove(0, 1);
    }
    else
    if ( endOf > 0 )
    {
        ret = str.left(endOf);
        str.remove(0, endOf +1);
    }
    else
    {
        ret = str;
    }

    return ret;
}

int TcString::find(const QStringList& ss, const QString& s)
{
    return ss.indexOf(s);
}

int TcString::findOf(const QStringList& list, const QString& key)
{
    int ret = -1;
    for( int i=0;i<list.count();i++ )
    {
        if ( list.at(i).trimmed().compare(key.trimmed(), Qt::CaseInsensitive)==0 )
        {
            ret = i;
            break;
        }
    }
    return ret;
}

bool TcString::filter(const QString& text, const QStringList& filters)
{
    bool ret = filters.count() <= 0;
    foreach(QString s, filters)
    {
        s = s.trimmed();
        if ( ! s.isEmpty() )
        {
            if ( text.indexOf(s, Qt::CaseInsensitive) >= 0 )
            {
                ret = true;
                break;
            }
        }
    }
    return ret;
}

/// ֽաӢģ
int TcString::splitHumanName(QString full, QString& sur, QString& real, QString& english)
{
    QString surs = QTextCodec::codecForLocale()->toUnicode(
                               "ŷ\n̫ʷ\nľ\nϹ\n˾\n\n\nϹ\nٹ\n"
                               "\nĺ\n\nξ\n\n\n̨\nʸ\n\n"
                               "\nұ\n̫\n\n\nĽ\n\n\n\n"
                               "\n˾ͽ\n\n˾\n\nӳ\n\n˾\n\n"
                               "\n\n\n\n\n\n׸\n\nذ\n"
                               "й\nԯ\n\nθ\n\n\n\n\n\n"
                               "΢\n\n\n\n\n\n\n\nɽ\n"
                               "\n\n\n\n\n\n\n\n\n"
                               "\n\n\nٳ\n\nɣ\nī\n\nʦ\n");
    QStringList doubleSurnames = surs.split("\n");

    full = full.trimmed();

    int ret = 0;
    if ( ! full.isEmpty() )
    {
        if ( full.length() != full.toLocal8Bit().length() )
        {//
            foreach(QString s, doubleSurnames)
            {
                if ( ! s.isEmpty() && full.startsWith(s) )
                {
                    sur = s;
                    ret = 2;
                    break;
                }
            }
            if ( ret != 2 )
            {
                sur = full.mid(0, 1);
                ret = 1;
            }
            real = full.mid(sur.length());
        }else
        {// Ӣ
            QStringList ss = full.split(" ", QString::SkipEmptyParts);
            english = "";
            for( int i=0;i<ss.count();i++ )
            {
                QString t = ss.at(i);
                if ( i == ss.count()-1 )
                {
                    sur = t;
                }else
                {
                    english += t + " ";
                }
            }
            english = english.trimmed();

            ret = 3;
        }
    }
    return ret;
}

QString TcString::getTextByIndex(const char* strings, int index)
{
    QStringList ss = QTextCodec::codecForLocale()->toUnicode(strings).split("\n", QString::SkipEmptyParts);
    return ss.at(index);
}

// class StringList
TcStringList::TcStringList()
{
    #if defined(Q_OS_WIN)
        m_lineBreak = "\r\n";
    #elif defined(Q_OS_LINUX)
        m_lineBreak = "\n";
    #elif defined(Q_OS_MAC)
        m_lineBreak = "\r";
    #else
        m_lineBreak = "\n";
    #endif
}

bool TcStringList::loadFrom(const QString& fileName)
{
    bool ret = false;
    QFile f(fileName);
    if ( f.open(QFile::Text | QFile::ReadOnly) )
    {
        clear();
        QTextStream in(&f);
        while(!in.atEnd())
        {
            this->append(in.readLine());
        }
        f.close();
        ret = false;
    }
    return ret;
}

bool TcStringList::saveTo(const QString& fileName)
{
    bool ret = false;
    QFile f(fileName);
    if ( f.open(QFile::Text | QFile::WriteOnly) )
    {
        QTextStream out(&f);
        foreach(QString s, *this)
        {
            out<<s<<lineBreak();
        }
        f.close();
    }
    return ret;
}
<|endoftext|>


<commit_before>/*
            This file is part of:
                NoahFrame
            https://github.com/ketoo/NoahGameFrame

   Copyright 2009 - 2018 NoahFrame(NoahGameFrame)

   File creator: lvsheng.huang

   NoahFrame is open-source software and you can redistribute it and/or modify
   it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#include "NFCLevelModule.h"

bool NFCLevelModule::Init()
{
	mbExpForHero = true;
    return true;
}

bool NFCLevelModule::Shut()
{
    return true;
}

bool NFCLevelModule::Execute()
{

    return true;
}

bool NFCLevelModule::AfterInit()
{
    m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>();
    m_pLogModule = pPluginManager->FindModule<NFILogModule>();
    m_pPropertyConfigModule = pPluginManager->FindModule<NFIPropertyConfigModule>();
	m_pElementModule = pPluginManager->FindModule<NFIElementModule>();
	//m_pHeroModule = pPluginManager->FindModule<NFIHeroModule>();

    return true;
}

int NFCLevelModule::AddExp(const NFGUID& self, const int64_t nExp)
{
	if (mbExpForHero)
	{
		//m_pHeroModule->AddHeroExp(self, nExp);
		return 0;
	}

    int eJobType = m_pKernelModule->GetPropertyInt32(self, NFrame::Player::Job());
    int64_t nCurExp = m_pKernelModule->GetPropertyInt(self, NFrame::Player::EXP());
    int nLevel = m_pKernelModule->GetPropertyInt32(self, NFrame::Player::Level());
    int64_t nMaxExp = (int)m_pPropertyConfigModule->CalculateBaseValue(eJobType, nLevel, NFrame::Player::MAXEXP());

    nCurExp += nExp;

    int64_t nRemainExp = nCurExp - nMaxExp;
    while (nRemainExp >= 0)
    {

        nLevel++;

        m_pKernelModule->SetPropertyInt(self, NFrame::Player::Level(), nLevel);

        nCurExp = nRemainExp;

        nMaxExp = (int)m_pPropertyConfigModule->CalculateBaseValue(eJobType, nLevel, NFrame::Player::MAXEXP());
        if (nMaxExp <= 0)
        {
            break;
        }

        nRemainExp -= nMaxExp;
    }

    m_pKernelModule->SetPropertyInt(self, NFrame::Player::EXP(), nCurExp);

    return 0;
}<commit_msg>add hero module for game server<commit_after>/*
            This file is part of:
                NoahFrame
            https://github.com/ketoo/NoahGameFrame

   Copyright 2009 - 2018 NoahFrame(NoahGameFrame)

   File creator: lvsheng.huang

   NoahFrame is open-source software and you can redistribute it and/or modify
   it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#include "NFCLevelModule.h"

bool NFCLevelModule::Init()
{
	mbExpForHero = true;
    return true;
}

bool NFCLevelModule::Shut()
{
    return true;
}

bool NFCLevelModule::Execute()
{

    return true;
}

bool NFCLevelModule::AfterInit()
{
    m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>();
    m_pLogModule = pPluginManager->FindModule<NFILogModule>();
    m_pPropertyConfigModule = pPluginManager->FindModule<NFIPropertyConfigModule>();
	m_pElementModule = pPluginManager->FindModule<NFIElementModule>();
	m_pHeroModule = pPluginManager->FindModule<NFIHeroModule>();

    return true;
}

int NFCLevelModule::AddExp(const NFGUID& self, const int64_t nExp)
{
	if (mbExpForHero)
	{
		m_pHeroModule->AddHeroExp(self, nExp);
		return 0;
	}

    int eJobType = m_pKernelModule->GetPropertyInt32(self, NFrame::Player::Job());
    int64_t nCurExp = m_pKernelModule->GetPropertyInt(self, NFrame::Player::EXP());
    int nLevel = m_pKernelModule->GetPropertyInt32(self, NFrame::Player::Level());
    int64_t nMaxExp = (int)m_pPropertyConfigModule->CalculateBaseValue(eJobType, nLevel, NFrame::Player::MAXEXP());

    nCurExp += nExp;

    int64_t nRemainExp = nCurExp - nMaxExp;
    while (nRemainExp >= 0)
    {

        nLevel++;

        m_pKernelModule->SetPropertyInt(self, NFrame::Player::Level(), nLevel);

        nCurExp = nRemainExp;

        nMaxExp = (int)m_pPropertyConfigModule->CalculateBaseValue(eJobType, nLevel, NFrame::Player::MAXEXP());
        if (nMaxExp <= 0)
        {
            break;
        }

        nRemainExp -= nMaxExp;
    }

    m_pKernelModule->SetPropertyInt(self, NFrame::Player::EXP(), nCurExp);

    return 0;
}<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkPointSetWriter.h"
#include <iostream>
#include <fstream>

//
// Initialization of the xml tags.
//

const char* mitk::PointSetWriter::XML_POINT_SET_FILE = "point_set_file" ;

const char* mitk::PointSetWriter::XML_FILE_VERSION = "file_version" ;

const char* mitk::PointSetWriter::XML_POINT_SET = "point_set" ;

const char* mitk::PointSetWriter::XML_POINT = "point" ;

const char* mitk::PointSetWriter::XML_ID = "id" ;

const char* mitk::PointSetWriter::XML_X = "x" ;

const char* mitk::PointSetWriter::XML_Y = "y" ;

const char* mitk::PointSetWriter::XML_Z = "z" ;

const char* mitk::PointSetWriter::VERSION_STRING = "0.1" ;

mitk::PointSetWriter::PointSetWriter()
    : m_FileName(""), m_FilePrefix(""), m_FilePattern("")
{
    this->SetNumberOfRequiredInputs( 1 );
    this->SetNumberOfOutputs( 1 );
    this->SetNthOutput( 0, mitk::PointSet::New().GetPointer() );
    m_Indent = 2;
    m_IndentDepth = 0;
    m_Success = false;
}

mitk::PointSetWriter::~PointSetWriter()
{}

void mitk::PointSetWriter::GenerateData()
{
    m_Success = false;
    m_IndentDepth = 0;

    //
    // Opening the file to write to
    //
    if ( m_FileName == "" )
    {
        itkWarningMacro( << "Sorry, filename has not been set!" );
        return ;
    }
    std::ofstream out( m_FileName.c_str() );
    if ( !out.good() )
    {
        itkWarningMacro( << "Sorry, file " << m_FileName << " could not be opened!" );
        out.close();
        return ;
    }

    //
    // Here the actual xml writing begins
    //
    WriteXMLHeader( out );
    WriteStartElement( XML_POINT_SET_FILE, out );
    WriteStartElement( XML_FILE_VERSION, out );
    WriteCharacterData( VERSION_STRING, out );
    WriteEndElement( XML_FILE_VERSION, out, false );

    //
    // for each input object write its xml representation to
    // the stream
    //
    for ( unsigned int i = 0 ; i < this->GetNumberOfInputs(); ++i )
    {
        InputType::Pointer pointSet = this->GetInput( i );
        assert( pointSet.IsNotNull() );
        WriteXML( pointSet.GetPointer(), out );
    }

    WriteEndElement( XML_POINT_SET_FILE, out );

    if ( !out.good() ) // some error during output
    {
      out.close();
      throw std::ios_base::failure("Some error during point set writing.");
    }

    out.close();
    m_Success = true;
    m_MimeType = "application/MITK.PointSet";
}

void mitk::PointSetWriter::WriteXML( mitk::PointSet* pointSet, std::ofstream& out )
{
    WriteStartElement( XML_POINT_SET, out );
    mitk::PointSet::PointsContainer* pointsContainer = pointSet->GetPointSet()->GetPoints();
    mitk::PointSet::PointsContainer::Iterator it;
    for ( it = pointsContainer->Begin(); it != pointsContainer->End(); ++it )
    {
        WriteStartElement( XML_POINT, out );

        WriteStartElement( XML_ID, out );
        WriteCharacterData( ConvertToString( it->Index() ).c_str() , out );
        WriteEndElement( XML_ID, out, false );

        mitk::PointSet::PointType point = it->Value();

        WriteStartElement( XML_X, out );
        WriteCharacterData( ConvertToString( point[ 0 ] ).c_str(), out );
        WriteEndElement( XML_X, out, false );

        WriteStartElement( XML_Y, out );
        WriteCharacterData( ConvertToString( point[ 1 ] ).c_str(), out );
        WriteEndElement( XML_Y, out, false );

        WriteStartElement( XML_Z, out );
        WriteCharacterData( ConvertToString( point[ 2 ] ).c_str(), out );
        WriteEndElement( XML_Z, out, false );

        WriteEndElement( XML_POINT, out );
    }
    WriteEndElement( XML_POINT_SET, out );
}

void mitk::PointSetWriter::ResizeInputs( const unsigned int& num )
{
    unsigned int prevNum = this->GetNumberOfInputs();
    this->SetNumberOfInputs( num );
    for ( unsigned int i = prevNum; i < num; ++i )
    {
        this->SetNthInput( i, mitk::PointSet::New().GetPointer() );
    }
}

void mitk::PointSetWriter::SetInput( InputType* pointSet )
{
    this->ProcessObject::SetNthInput( 0, pointSet );
}

void mitk::PointSetWriter::SetInput( const unsigned int& id, InputType* pointSet )
{
    if ( id >= this->GetNumberOfInputs() )
        this->ResizeInputs( id + 1 );
    this->ProcessObject::SetNthInput( id, pointSet );
}

mitk::PointSet* mitk::PointSetWriter::GetInput()
{
    if ( this->GetNumberOfInputs() < 1 )
    {
        return 0;
    }
    else
    {
        return dynamic_cast<InputType*> ( this->GetInput( 0 ) );
    }
}

mitk::PointSet* mitk::PointSetWriter::GetInput( const unsigned int& num )
{
    return dynamic_cast<InputType*> ( this->ProcessObject::GetInput( num ) );
}

template < typename T>
std::string mitk::PointSetWriter::ConvertToString( T value )
{
    std::ostringstream o;
    if ( o << value )
        return o.str();
    else
        return "conversion error";
}

void mitk::PointSetWriter::WriteXMLHeader( std::ofstream &file )
{
    file << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
}

void mitk::PointSetWriter::WriteStartElement( const char *const tag, std::ofstream &file )
{
    file << std::endl;
    WriteIndent( file );
    file << '<' << tag << '>';
    m_IndentDepth++;
}

void mitk::PointSetWriter::WriteEndElement( const char *const tag, std::ofstream &file, const bool& indent )
{
    m_IndentDepth--;
    if ( indent )
    {
        file << std::endl;
        WriteIndent( file );
    }
    file << '<' << '/' << tag << '>';
}

void mitk::PointSetWriter::WriteCharacterData( const char *const data, std::ofstream &file )
{
    file << data;
}

void mitk::PointSetWriter::WriteStartElement( std::string &tag, std::ofstream &file )
{
    WriteStartElement( tag.c_str(), file );
}

void mitk::PointSetWriter::WriteEndElement( std::string &tag, std::ofstream &file, const bool& indent )
{
    WriteEndElement( tag.c_str(), file, indent );
}

void mitk::PointSetWriter::WriteCharacterData( std::string &data, std::ofstream &file )
{
    WriteCharacterData( data.c_str(), file );
}

void mitk::PointSetWriter::WriteIndent( std::ofstream& file )
{
    std::string spaces( m_IndentDepth * m_Indent, ' ' );
    file << spaces.c_str();
}

bool mitk::PointSetWriter::GetSuccess() const
{
    return m_Success;
}

bool mitk::PointSetWriter::CanWriteDataType( DataTreeNode* input )
{
  if ( input )
  {
    mitk::BaseData* data = input->GetData();
    if ( data )
    {
       mitk::PointSet::Pointer pointSet = dynamic_cast<mitk::PointSet*>( data );
       if( pointSet.IsNotNull() )
       {
         //this writer has no "SetDefaultExtension()" - function
         m_Extension = ".mps";
         return true;
       }
    }
  }
  return false;
}

void mitk::PointSetWriter::SetInput( DataTreeNode* input )
{
  if( input && CanWriteDataType( input ) )
    this->ProcessObject::SetNthInput( 0, dynamic_cast<mitk::PointSet*>( input->GetData() ) );
}

std::string mitk::PointSetWriter::GetWritenMIMEType()
{
  return m_MimeType;
}

std::vector<std::string> mitk::PointSetWriter::GetPossibleFileExtensions()
{
  std::vector<std::string> possibleFileExtensions;
  possibleFileExtensions.push_back(".mps");
  return possibleFileExtensions;
}

std::string mitk::PointSetWriter::GetFileExtension()
{
  return m_Extension;
}
<commit_msg>FIX (#1611): throw exception when file can not be opened<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkPointSetWriter.h"
#include <iostream>
#include <fstream>

//
// Initialization of the xml tags.
//

const char* mitk::PointSetWriter::XML_POINT_SET_FILE = "point_set_file" ;

const char* mitk::PointSetWriter::XML_FILE_VERSION = "file_version" ;

const char* mitk::PointSetWriter::XML_POINT_SET = "point_set" ;

const char* mitk::PointSetWriter::XML_POINT = "point" ;

const char* mitk::PointSetWriter::XML_ID = "id" ;

const char* mitk::PointSetWriter::XML_X = "x" ;

const char* mitk::PointSetWriter::XML_Y = "y" ;

const char* mitk::PointSetWriter::XML_Z = "z" ;

const char* mitk::PointSetWriter::VERSION_STRING = "0.1" ;

mitk::PointSetWriter::PointSetWriter()
    : m_FileName(""), m_FilePrefix(""), m_FilePattern("")
{
    this->SetNumberOfRequiredInputs( 1 );
    this->SetNumberOfOutputs( 1 );
    this->SetNthOutput( 0, mitk::PointSet::New().GetPointer() );
    m_Indent = 2;
    m_IndentDepth = 0;
    m_Success = false;
}

mitk::PointSetWriter::~PointSetWriter()
{}

void mitk::PointSetWriter::GenerateData()
{
    m_Success = false;
    m_IndentDepth = 0;

    //
    // Opening the file to write to
    //
    if ( m_FileName == "" )
    {
        itkWarningMacro( << "Sorry, filename has not been set!" );
        return ;
    }
    std::ofstream out( m_FileName.c_str() );
    if ( !out.good() )
    {
      itkExceptionMacro(<< "File " << m_FileName << " could not be opened!");
        itkWarningMacro( << "Sorry, file " << m_FileName << " could not be opened!" );
        out.close();
        return ;
    }

    //
    // Here the actual xml writing begins
    //
    WriteXMLHeader( out );
    WriteStartElement( XML_POINT_SET_FILE, out );
    WriteStartElement( XML_FILE_VERSION, out );
    WriteCharacterData( VERSION_STRING, out );
    WriteEndElement( XML_FILE_VERSION, out, false );

    //
    // for each input object write its xml representation to
    // the stream
    //
    for ( unsigned int i = 0 ; i < this->GetNumberOfInputs(); ++i )
    {
        InputType::Pointer pointSet = this->GetInput( i );
        assert( pointSet.IsNotNull() );
        WriteXML( pointSet.GetPointer(), out );
    }

    WriteEndElement( XML_POINT_SET_FILE, out );

    if ( !out.good() ) // some error during output
    {
      out.close();
      throw std::ios_base::failure("Some error during point set writing.");
    }

    out.close();
    m_Success = true;
    m_MimeType = "application/MITK.PointSet";
}

void mitk::PointSetWriter::WriteXML( mitk::PointSet* pointSet, std::ofstream& out )
{
    WriteStartElement( XML_POINT_SET, out );
    mitk::PointSet::PointsContainer* pointsContainer = pointSet->GetPointSet()->GetPoints();
    mitk::PointSet::PointsContainer::Iterator it;
    for ( it = pointsContainer->Begin(); it != pointsContainer->End(); ++it )
    {
        WriteStartElement( XML_POINT, out );

        WriteStartElement( XML_ID, out );
        WriteCharacterData( ConvertToString( it->Index() ).c_str() , out );
        WriteEndElement( XML_ID, out, false );

        mitk::PointSet::PointType point = it->Value();

        WriteStartElement( XML_X, out );
        WriteCharacterData( ConvertToString( point[ 0 ] ).c_str(), out );
        WriteEndElement( XML_X, out, false );

        WriteStartElement( XML_Y, out );
        WriteCharacterData( ConvertToString( point[ 1 ] ).c_str(), out );
        WriteEndElement( XML_Y, out, false );

        WriteStartElement( XML_Z, out );
        WriteCharacterData( ConvertToString( point[ 2 ] ).c_str(), out );
        WriteEndElement( XML_Z, out, false );

        WriteEndElement( XML_POINT, out );
    }
    WriteEndElement( XML_POINT_SET, out );
}

void mitk::PointSetWriter::ResizeInputs( const unsigned int& num )
{
    unsigned int prevNum = this->GetNumberOfInputs();
    this->SetNumberOfInputs( num );
    for ( unsigned int i = prevNum; i < num; ++i )
    {
        this->SetNthInput( i, mitk::PointSet::New().GetPointer() );
    }
}

void mitk::PointSetWriter::SetInput( InputType* pointSet )
{
    this->ProcessObject::SetNthInput( 0, pointSet );
}

void mitk::PointSetWriter::SetInput( const unsigned int& id, InputType* pointSet )
{
    if ( id >= this->GetNumberOfInputs() )
        this->ResizeInputs( id + 1 );
    this->ProcessObject::SetNthInput( id, pointSet );
}

mitk::PointSet* mitk::PointSetWriter::GetInput()
{
    if ( this->GetNumberOfInputs() < 1 )
    {
        return 0;
    }
    else
    {
        return dynamic_cast<InputType*> ( this->GetInput( 0 ) );
    }
}

mitk::PointSet* mitk::PointSetWriter::GetInput( const unsigned int& num )
{
    return dynamic_cast<InputType*> ( this->ProcessObject::GetInput( num ) );
}

template < typename T>
std::string mitk::PointSetWriter::ConvertToString( T value )
{
    std::ostringstream o;
    if ( o << value )
        return o.str();
    else
        return "conversion error";
}

void mitk::PointSetWriter::WriteXMLHeader( std::ofstream &file )
{
    file << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
}

void mitk::PointSetWriter::WriteStartElement( const char *const tag, std::ofstream &file )
{
    file << std::endl;
    WriteIndent( file );
    file << '<' << tag << '>';
    m_IndentDepth++;
}

void mitk::PointSetWriter::WriteEndElement( const char *const tag, std::ofstream &file, const bool& indent )
{
    m_IndentDepth--;
    if ( indent )
    {
        file << std::endl;
        WriteIndent( file );
    }
    file << '<' << '/' << tag << '>';
}

void mitk::PointSetWriter::WriteCharacterData( const char *const data, std::ofstream &file )
{
    file << data;
}

void mitk::PointSetWriter::WriteStartElement( std::string &tag, std::ofstream &file )
{
    WriteStartElement( tag.c_str(), file );
}

void mitk::PointSetWriter::WriteEndElement( std::string &tag, std::ofstream &file, const bool& indent )
{
    WriteEndElement( tag.c_str(), file, indent );
}

void mitk::PointSetWriter::WriteCharacterData( std::string &data, std::ofstream &file )
{
    WriteCharacterData( data.c_str(), file );
}

void mitk::PointSetWriter::WriteIndent( std::ofstream& file )
{
    std::string spaces( m_IndentDepth * m_Indent, ' ' );
    file << spaces.c_str();
}

bool mitk::PointSetWriter::GetSuccess() const
{
    return m_Success;
}

bool mitk::PointSetWriter::CanWriteDataType( DataTreeNode* input )
{
  if ( input )
  {
    mitk::BaseData* data = input->GetData();
    if ( data )
    {
       mitk::PointSet::Pointer pointSet = dynamic_cast<mitk::PointSet*>( data );
       if( pointSet.IsNotNull() )
       {
         //this writer has no "SetDefaultExtension()" - function
         m_Extension = ".mps";
         return true;
       }
    }
  }
  return false;
}

void mitk::PointSetWriter::SetInput( DataTreeNode* input )
{
  if( input && CanWriteDataType( input ) )
    this->ProcessObject::SetNthInput( 0, dynamic_cast<mitk::PointSet*>( input->GetData() ) );
}

std::string mitk::PointSetWriter::GetWritenMIMEType()
{
  return m_MimeType;
}

std::vector<std::string> mitk::PointSetWriter::GetPossibleFileExtensions()
{
  std::vector<std::string> possibleFileExtensions;
  possibleFileExtensions.push_back(".mps");
  return possibleFileExtensions;
}

std::string mitk::PointSetWriter::GetFileExtension()
{
  return m_Extension;
}
<|endoftext|>


<commit_before>#include "mount.hpp"
#include <silicium/ptr_observable.hpp>
#include <silicium/error_or.hpp>
#include <silicium/connecting_observable.hpp>
#include <silicium/coroutine.hpp>
#include <silicium/virtualized_observable.hpp>
#include <silicium/received_from_socket_source.hpp>
#include <silicium/sending_observable.hpp>
#include <silicium/virtualized_source.hpp>
#include <silicium/observable_source.hpp>
#include <silicium/http/http.hpp>
#include <silicium/thread.hpp>
#include <silicium/std_threading.hpp>
#include <server/path.hpp>
#include <fuse.h>
#include <future>
#include <boost/ref.hpp>

namespace fileserver
{
	namespace
	{
		using file_offset = std::intmax_t;

		struct linear_file
		{
			file_offset size;
			Si::unique_observable<Si::error_or<Si::incoming_bytes>> content;
		};

		struct file_service
		{
			virtual ~file_service();
			virtual Si::unique_observable<Si::error_or<linear_file>> open(unknown_digest const &name) = 0;
		};

		file_service::~file_service()
		{
		}

		struct http_file_service : file_service
		{
			explicit http_file_service(boost::asio::io_service &io, boost::asio::ip::tcp::endpoint server)
				: io(&io)
				, server(server)
			{
			}

			virtual Si::unique_observable<Si::error_or<linear_file>> open(unknown_digest const &name) SILICIUM_OVERRIDE
			{
				return Si::erase_unique(Si::make_coroutine<Si::error_or<linear_file>>(std::bind(&http_file_service::open_impl, this, std::placeholders::_1, name)));
			}

		private:

			boost::asio::io_service *io = nullptr;
			boost::asio::ip::tcp::endpoint server;

			void open_impl(
				Si::yield_context<Si::error_or<linear_file>> yield,
				unknown_digest const &requested_name)
			{
				auto socket = std::make_shared<boost::asio::ip::tcp::socket>(*io);
				Si::connecting_observable connector(*socket, server);
				{
					boost::optional<boost::system::error_code> const ec = yield.get_one(connector);
					assert(ec);
					if (*ec)
					{
						return yield(*ec);
					}
				}

				std::vector<char> request_buffer;
				{
					Si::http::request_header request;
					request.http_version = "HTTP/1.0";
					request.method = "GET";
					request.path = "/";
					encode_ascii_hex_digits(requested_name.begin(), requested_name.end(), std::back_inserter(request.path));
					request.arguments["Host"] = server.address().to_string();
					auto request_sink = Si::make_container_sink(request_buffer);
					Si::http::write_header(request_sink, request);
				}
				Si::sending_observable sending(*socket, boost::make_iterator_range(request_buffer.data(), request_buffer.data() + request_buffer.size()));
				{
					boost::optional<Si::error_or<std::size_t>> const ec = yield.get_one(sending);
					assert(ec);
					if (ec->error())
					{
						return yield(*ec->error());
					}
					assert(ec->get() == request_buffer.size());
				}

				std::array<char, 8192> buffer;
				Si::socket_observable receiving(*socket, boost::make_iterator_range(buffer.data(), buffer.data() + buffer.size()));
				auto receiving_source = Si::virtualize_source(Si::make_observable_source(std::move(receiving), yield));
				Si::received_from_socket_source response_source(receiving_source);
				boost::optional<Si::http::response_header> const response_header = Si::http::parse_response_header(response_source);
				if (!response_header)
				{
					throw std::logic_error("todo 1");
				}

				auto content_length_header = response_header->arguments.find("Content-Length");
				if (content_length_header == response_header->arguments.end())
				{
					throw std::logic_error("todo 2");
				}

				std::vector<byte> first_part(response_source.buffered().begin, response_source.buffered().end);
				file_offset const file_size = boost::lexical_cast<file_offset>(content_length_header->second);
				linear_file file{file_size, Si::erase_unique(Si::make_coroutine<Si::error_or<Si::incoming_bytes>>(
					[first_part, socket, file_size]
						(Si::yield_context<Si::error_or<Si::incoming_bytes>> yield)
					{
						yield(Si::incoming_bytes(
							reinterpret_cast<char const *>(first_part.data()),
							reinterpret_cast<char const *>(first_part.data() + first_part.size())));
						file_offset receive_counter = first_part.size();
						std::array<char, 8192> buffer;
						Si::socket_observable receiving(*socket, boost::make_iterator_range(buffer.data(), buffer.data() + buffer.size()));
						while (receive_counter < file_size)
						{
							auto piece = yield.get_one(receiving);
							if (!piece)
							{
								break;
							}
							if (!piece->is_error())
							{
								receive_counter += piece->get().size();
							}
							yield(*piece);
						}
					}))};
				yield(std::move(file));
			}
		};

		struct file_system
		{
			boost::asio::io_service io;
			std::unique_ptr<file_service> backend;
			std::future<void> worker;
			boost::optional<boost::asio::io_service::work> keep_running;
			unknown_digest root;
		};

		char const * const hello_path = "/hello";
		char const * const hello_str = "Hello, fuse!\n";

		unknown_digest root;

		void *init(struct fuse_conn_info *conn)
		{
			assert(!root.empty());
			auto fs = Si::make_unique<file_system>();
			fs->backend = Si::make_unique<http_file_service>(fs->io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::loopback(), 8080));
			fs->keep_running = boost::in_place(boost::ref(fs->io));
			auto &io = fs->io;
			fs->worker = std::async(std::launch::async, [&io]()
			{
				io.run();
			});
			fs->root = std::move(root);
			return fs.release();
		}

		void destroy(void *private_data)
		{
			std::unique_ptr<file_system>(static_cast<file_system *>(private_data));
		}

		int hello_getattr(const char *path, struct stat *stbuf)
		{
			int res = 0;

			memset(stbuf, 0, sizeof(struct stat));
			if (strcmp(path, "/") == 0) {
				stbuf->st_mode = S_IFDIR | 0755;
				stbuf->st_nlink = 2;
			} else if (strcmp(path, hello_path) == 0) {
				stbuf->st_mode = S_IFREG | 0444;
				stbuf->st_nlink = 1;
				stbuf->st_size = strlen(hello_str);
			} else
				res = -ENOENT;

			return res;
		}

		int hello_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
					 off_t offset, struct fuse_file_info *fi)
		{
			(void) offset;
			(void) fi;

			Si::error_or<linear_file> file;
			file_system * const fs = static_cast<file_system *>(fuse_get_context()->private_data);
			Si::detail::event<Si::std_threading> waiting;
			waiting.block(Si::transform(fs->backend->open(fs->root), [&file](Si::error_or<linear_file> opened_file)
			{
				file = std::move(opened_file);
				return Si::nothing();
			}));

			if (file.is_error())
			{
				return -ENOENT;
			}

			if (strcmp(path, "/") != 0)
				return -ENOENT;

			filler(buf, ".", NULL, 0);
			filler(buf, "..", NULL, 0);
			filler(buf, hello_path + 1, NULL, 0);

			return 0;
		}

		int hello_open(const char *path, struct fuse_file_info *fi)
		{
			if (strcmp(path, hello_path) != 0)
				return -ENOENT;

			if ((fi->flags & 3) != O_RDONLY)
				return -EACCES;

			return 0;
		}

		int hello_read(const char *path, char *buf, size_t size, off_t offset,
					  struct fuse_file_info *fi)
		{
			size_t len;
			(void) fi;
			if(strcmp(path, hello_path) != 0)
				return -ENOENT;

			len = strlen(hello_str);
			if (static_cast<size_t>(offset) < len) {
				if (offset + size > len)
					size = len - offset;
				memcpy(buf, hello_str + offset, size);
			} else
				size = 0;

			return static_cast<int>(size);
		}

		struct user_data_for_fuse
		{

		};

		struct chan_deleter
		{
			fileserver::path mount_point;

			void operator()(fuse_chan *chan) const
			{
				fuse_unmount(mount_point.c_str(), chan);
			}
		};

		struct fuse_deleter
		{
			void operator()(fuse *f) const
			{
				fuse_destroy(f);
			}
		};
	}

	void mount_directory(unknown_digest const &root_digest, boost::filesystem::path const &mount_point)
	{
		chan_deleter deleter;
		deleter.mount_point = fileserver::path(mount_point);
		fuse_args args{};
		std::unique_ptr<fuse_chan, chan_deleter> chan(fuse_mount(mount_point.c_str(), &args), std::move(deleter));
		if (!chan)
		{
			throw std::runtime_error("fuse_mount failure");
		}
		fuse_operations operations{};
		operations.init = init;
		operations.destroy = destroy;
		operations.getattr = hello_getattr;
		operations.readdir = hello_readdir;
		operations.open = hello_open;
		operations.read = hello_read;
		root = root_digest;
		user_data_for_fuse user_data;
		std::unique_ptr<fuse, fuse_deleter> const f(fuse_new(chan.get(), &args, &operations, sizeof(operations), &user_data));
		if (!f)
		{
			throw std::runtime_error("fuse_new failure");
		}

		//fuse_new seems to take ownership of the fuse_chan
		chan.release();

		fuse_loop(f.get());
	}
}
<commit_msg>listing the root directory works partially<commit_after>#include "mount.hpp"
#include <silicium/ptr_observable.hpp>
#include <silicium/error_or.hpp>
#include <silicium/connecting_observable.hpp>
#include <silicium/coroutine.hpp>
#include <silicium/virtualized_observable.hpp>
#include <silicium/received_from_socket_source.hpp>
#include <silicium/sending_observable.hpp>
#include <silicium/virtualized_source.hpp>
#include <silicium/observable_source.hpp>
#include <silicium/http/http.hpp>
#include <silicium/thread.hpp>
#include <silicium/std_threading.hpp>
#include <server/path.hpp>
#include <server/directory_listing.hpp>
#include <fuse.h>
#include <future>
#include <boost/ref.hpp>

namespace fileserver
{
	namespace
	{
		using file_offset = std::intmax_t;

		struct linear_file
		{
			file_offset size;
			Si::unique_observable<Si::error_or<Si::incoming_bytes>> content;
		};

		struct file_service
		{
			virtual ~file_service();
			virtual Si::unique_observable<Si::error_or<linear_file>> open(unknown_digest const &name) = 0;
		};

		file_service::~file_service()
		{
		}

		struct http_file_service : file_service
		{
			explicit http_file_service(boost::asio::io_service &io, boost::asio::ip::tcp::endpoint server)
				: io(&io)
				, server(server)
			{
			}

			virtual Si::unique_observable<Si::error_or<linear_file>> open(unknown_digest const &name) SILICIUM_OVERRIDE
			{
				return Si::erase_unique(Si::make_coroutine<Si::error_or<linear_file>>(std::bind(&http_file_service::open_impl, this, std::placeholders::_1, name)));
			}

		private:

			boost::asio::io_service *io = nullptr;
			boost::asio::ip::tcp::endpoint server;

			void open_impl(
				Si::yield_context<Si::error_or<linear_file>> yield,
				unknown_digest const &requested_name)
			{
				auto socket = std::make_shared<boost::asio::ip::tcp::socket>(*io);
				Si::connecting_observable connector(*socket, server);
				{
					boost::optional<boost::system::error_code> const ec = yield.get_one(connector);
					assert(ec);
					if (*ec)
					{
						return yield(*ec);
					}
				}

				std::vector<char> request_buffer;
				{
					Si::http::request_header request;
					request.http_version = "HTTP/1.0";
					request.method = "GET";
					request.path = "/";
					encode_ascii_hex_digits(requested_name.begin(), requested_name.end(), std::back_inserter(request.path));
					request.arguments["Host"] = server.address().to_string();
					auto request_sink = Si::make_container_sink(request_buffer);
					Si::http::write_header(request_sink, request);
				}
				Si::sending_observable sending(*socket, boost::make_iterator_range(request_buffer.data(), request_buffer.data() + request_buffer.size()));
				{
					boost::optional<Si::error_or<std::size_t>> const ec = yield.get_one(sending);
					assert(ec);
					if (ec->error())
					{
						return yield(*ec->error());
					}
					assert(ec->get() == request_buffer.size());
				}

				std::array<char, 8192> buffer;
				Si::socket_observable receiving(*socket, boost::make_iterator_range(buffer.data(), buffer.data() + buffer.size()));
				auto receiving_source = Si::virtualize_source(Si::make_observable_source(std::move(receiving), yield));
				Si::received_from_socket_source response_source(receiving_source);
				boost::optional<Si::http::response_header> const response_header = Si::http::parse_response_header(response_source);
				if (!response_header)
				{
					throw std::logic_error("todo 1");
				}

				auto content_length_header = response_header->arguments.find("Content-Length");
				if (content_length_header == response_header->arguments.end())
				{
					throw std::logic_error("todo 2");
				}

				std::vector<byte> first_part(response_source.buffered().begin, response_source.buffered().end);
				file_offset const file_size = boost::lexical_cast<file_offset>(content_length_header->second);
				linear_file file{file_size, Si::erase_unique(Si::make_coroutine<Si::error_or<Si::incoming_bytes>>(
					[first_part, socket, file_size]
						(Si::yield_context<Si::error_or<Si::incoming_bytes>> yield)
					{
						yield(Si::incoming_bytes(
							reinterpret_cast<char const *>(first_part.data()),
							reinterpret_cast<char const *>(first_part.data() + first_part.size())));
						file_offset receive_counter = first_part.size();
						std::array<char, 8192> buffer;
						Si::socket_observable receiving(*socket, boost::make_iterator_range(buffer.data(), buffer.data() + buffer.size()));
						while (receive_counter < file_size)
						{
							auto piece = yield.get_one(receiving);
							if (!piece)
							{
								break;
							}
							if (!piece->is_error())
							{
								receive_counter += piece->get().size();
							}
							yield(*piece);
						}
					}))};
				yield(std::move(file));
			}
		};

		struct file_system
		{
			boost::asio::io_service io;
			std::unique_ptr<file_service> backend;
			std::future<void> worker;
			boost::optional<boost::asio::io_service::work> keep_running;
			unknown_digest root;
		};

		char const * const hello_path = "/hello";
		char const * const hello_str = "Hello, fuse!\n";

		unknown_digest root;

		void *init(struct fuse_conn_info *conn)
		{
			assert(!root.empty());
			auto fs = Si::make_unique<file_system>();
			fs->backend = Si::make_unique<http_file_service>(fs->io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::loopback(), 8080));
			fs->keep_running = boost::in_place(boost::ref(fs->io));
			auto &io = fs->io;
			fs->worker = std::async(std::launch::async, [&io]()
			{
				io.run();
			});
			fs->root = std::move(root);
			return fs.release();
		}

		void destroy(void *private_data)
		{
			std::unique_ptr<file_system>(static_cast<file_system *>(private_data));
		}

		int hello_getattr(const char *path, struct stat *stbuf)
		{
			int res = 0;

			memset(stbuf, 0, sizeof(struct stat));
			if (strcmp(path, "/") == 0) {
				stbuf->st_mode = S_IFDIR | 0755;
				stbuf->st_nlink = 2;
			} else if (strcmp(path, hello_path) == 0) {
				stbuf->st_mode = S_IFREG | 0444;
				stbuf->st_nlink = 1;
				stbuf->st_size = strlen(hello_str);
			} else
				res = -ENOENT;

			return res;
		}

		struct local_yield_context : Si::detail::yield_context_impl<Si::nothing>
		{
			virtual void push_result(Si::nothing result) SILICIUM_OVERRIDE
			{
				boost::ignore_unused(result);
				SILICIUM_UNREACHABLE();
			}

			virtual void get_one(Si::observable<Si::nothing> &target) SILICIUM_OVERRIDE
			{
				Si::detail::event<Si::std_threading> waiting;
				waiting.block(Si::ref(target));
			}
		};

		int hello_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
					 off_t offset, struct fuse_file_info *fi)
		{
			(void) offset;
			(void) fi;

			Si::error_or<linear_file> file;
			file_system * const fs = static_cast<file_system *>(fuse_get_context()->private_data);
			Si::detail::event<Si::std_threading> waiting;
			waiting.block(Si::transform(fs->backend->open(fs->root), [&file](Si::error_or<linear_file> opened_file)
			{
				file = std::move(opened_file);
				return Si::nothing();
			}));

			if (file.is_error())
			{
				return -ENOENT;
			}

			local_yield_context yield_impl;
			Si::yield_context<Si::nothing> yield(yield_impl);
			auto receiving_source = Si::virtualize_source(Si::make_observable_source(std::move(file).get().content, yield));
			Si::received_from_socket_source content_source(receiving_source);
			auto parsed = deserialize_json(std::move(content_source));
			return Si::visit<int>(
				parsed,
				[buf, filler](std::unique_ptr<directory_listing> &listing)
			{
				filler(buf, ".", NULL, 0);
				filler(buf, "..", NULL, 0);
				for (auto const &entry : listing->entries)
				{
					struct stat s{};
					s.st_size = 100;
					s.st_mode = 0777 | __S_IFREG;
					filler(buf, entry.first.c_str(), &s, 0);
				}
				return 0;
			},
				[](std::size_t)
			{
				return -ENOENT;
			});
		}

		int hello_open(const char *path, struct fuse_file_info *fi)
		{
			if (strcmp(path, hello_path) != 0)
				return -ENOENT;

			if ((fi->flags & 3) != O_RDONLY)
				return -EACCES;

			return 0;
		}

		int hello_read(const char *path, char *buf, size_t size, off_t offset,
					  struct fuse_file_info *fi)
		{
			size_t len;
			(void) fi;
			if(strcmp(path, hello_path) != 0)
				return -ENOENT;

			len = strlen(hello_str);
			if (static_cast<size_t>(offset) < len) {
				if (offset + size > len)
					size = len - offset;
				memcpy(buf, hello_str + offset, size);
			} else
				size = 0;

			return static_cast<int>(size);
		}

		struct user_data_for_fuse
		{

		};

		struct chan_deleter
		{
			fileserver::path mount_point;

			void operator()(fuse_chan *chan) const
			{
				fuse_unmount(mount_point.c_str(), chan);
			}
		};

		struct fuse_deleter
		{
			void operator()(fuse *f) const
			{
				fuse_destroy(f);
			}
		};
	}

	void mount_directory(unknown_digest const &root_digest, boost::filesystem::path const &mount_point)
	{
		chan_deleter deleter;
		deleter.mount_point = fileserver::path(mount_point);
		fuse_args args{};
		std::unique_ptr<fuse_chan, chan_deleter> chan(fuse_mount(mount_point.c_str(), &args), std::move(deleter));
		if (!chan)
		{
			throw std::runtime_error("fuse_mount failure");
		}
		fuse_operations operations{};
		operations.init = init;
		operations.destroy = destroy;
		operations.getattr = hello_getattr;
		operations.readdir = hello_readdir;
		operations.open = hello_open;
		operations.read = hello_read;
		root = root_digest;
		user_data_for_fuse user_data;
		std::unique_ptr<fuse, fuse_deleter> const f(fuse_new(chan.get(), &args, &operations, sizeof(operations), &user_data));
		if (!f)
		{
			throw std::runtime_error("fuse_new failure");
		}

		//fuse_new seems to take ownership of the fuse_chan
		chan.release();

		fuse_loop(f.get());
	}
}
<|endoftext|>


<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * Flacon - audio File Encoder
 * https://github.com/flacon/flacon
 *
 * Copyright: 2012-2013
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.

 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "splitter.h"
#include "disc.h"
#include "decoder.h"

#include <QDebug>

/************************************************
 *
 ************************************************/
Splitter::Splitter(const Disc *disc, const QString &workDir, bool extractPregap, PreGapType preGapType, QObject *parent):
    Worker(parent),
    mDisc(disc),
    mWorkDir(workDir),
    mExtractPregap(extractPregap),
    mPreGapType(preGapType)
{
}

/************************************************
 *
 ************************************************/
void Splitter::run()
{
    mCurrentTrack = nullptr;
    Decoder decoder;

    try
    {
        decoder.open(mDisc->audioFileName());
    }
    catch (FlaconError &err)
    {
        emit error(mTracks.first(),
              tr("I can't read %1:
%2",
                 "Splitter error. %1 is a file name, %2 is a system error text.")
              .arg(mDisc->audioFileName())
              .arg(err.what()));
        return;
    }

    // Extract pregap to separate file ....................
    if (mExtractPregap)
    {
        mCurrentTrack  = mDisc->preGapTrack();
        CueIndex start = mDisc->track(0)->cueIndex(0);
        CueIndex end   = mDisc->track(0)->cueIndex(1);
        QString outFileName = QString("%1/pregap.wav").arg(mWorkDir);

        try
        {
            decoder.extract(start, end, outFileName);
        }
        catch (FlaconError &err)
        {
            qWarning() << "Splitter error for pregap track : " <<  err.what();
            deleteFile(outFileName);
            emit error(mCurrentTrack, err.what());
            return;
        }

        emit trackReady(mCurrentTrack, outFileName);
    }
    // Extract pregap to separate file ....................

    // We havn't pregap in the GUI and pregap is short so we suppress progress for pregap track
    connect(&decoder, SIGNAL(progress(int)),
            this, SLOT(decoderProgress(int)));

    for (int i=0; i<mDisc->count(); ++i)
    {
        mCurrentTrack = mDisc->track(i);
        if (!mTracks.contains(mCurrentTrack))
            continue;

        QString outFileName = QString("%1/track-%2.wav").arg(mWorkDir).arg(i+1, 2, 10, QLatin1Char('0'));

        CueIndex start, end;
        if (i==0 && mPreGapType == PreGapType::AddToFirstTrack)
            start = CueTime("00:00:00");
        else
            start = mDisc->track(i)->cueIndex(1);

        if (i<mDisc->count()-1)
            end = mDisc->track(i+1)->cueIndex(01);

        try
        {
            decoder.extract(start, end, outFileName);
        }
        catch (FlaconError &err)
        {
            qWarning() << "Splitter error for track " << mCurrentTrack->trackNum() << ": " <<  err.what();
            deleteFile(outFileName);
            emit error(mCurrentTrack, err.what());

        }

        qDebug() << "Splitter trackReady:" << *mCurrentTrack << outFileName;
        emit trackReady(mCurrentTrack, outFileName);
    }
}

/************************************************
 *
 ************************************************/
void Splitter::decoderProgress(int percent)
{
    emit trackProgress(mCurrentTrack, TrackState::Splitting, percent);
}
<commit_msg>Fix. If several disks have the same output directory, temporary track files are overwritten. Use uniq id for every disk.<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * Flacon - audio File Encoder
 * https://github.com/flacon/flacon
 *
 * Copyright: 2012-2013
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.

 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "splitter.h"
#include "disc.h"
#include "decoder.h"

#include <QDebug>

/************************************************
 *
 ************************************************/
Splitter::Splitter(const Disc *disc, const QString &workDir, bool extractPregap, PreGapType preGapType, QObject *parent):
    Worker(parent),
    mDisc(disc),
    mWorkDir(workDir),
    mExtractPregap(extractPregap),
    mPreGapType(preGapType)
{
}

/************************************************
 *
 ************************************************/
void Splitter::run()
{
    static QAtomicInteger<quint64> globalUid(1);
    QString uid = QString("%1").arg(globalUid.fetchAndAddRelaxed(1), 4, 10, QLatin1Char('0'));

    mCurrentTrack = nullptr;
    Decoder decoder;

    try
    {
        decoder.open(mDisc->audioFileName());
    }
    catch (FlaconError &err)
    {
        emit error(mTracks.first(),
              tr("I can't read %1:
%2",
                 "Splitter error. %1 is a file name, %2 is a system error text.")
              .arg(mDisc->audioFileName())
              .arg(err.what()));
        return;
    }

    // Extract pregap to separate file ....................
    if (mExtractPregap)
    {
        mCurrentTrack  = mDisc->preGapTrack();
        CueIndex start = mDisc->track(0)->cueIndex(0);
        CueIndex end   = mDisc->track(0)->cueIndex(1);
        QString outFileName = QString("%1/pregap-%2.wav").arg(mWorkDir).arg(uid);

        try
        {
            decoder.extract(start, end, outFileName);
        }
        catch (FlaconError &err)
        {
            qWarning() << "Splitter error for pregap track : " <<  err.what();
            deleteFile(outFileName);
            emit error(mCurrentTrack, err.what());
            return;
        }

        emit trackReady(mCurrentTrack, outFileName);
    }
    // Extract pregap to separate file ....................

    // We havn't pregap in the GUI and pregap is short so we suppress progress for pregap track
    connect(&decoder, SIGNAL(progress(int)),
            this, SLOT(decoderProgress(int)));

    qDebug() << "Start splitting" << mDisc->count() << "tracks from" << mDisc->audioFileName();
    for (int i=0; i<mDisc->count(); ++i)
    {
        mCurrentTrack = mDisc->track(i);
        if (!mTracks.contains(mCurrentTrack))
            continue;

        QString outFileName = QString("%1/track-%2_%3.wav").arg(mWorkDir).arg(uid).arg(i+1, 2, 10, QLatin1Char('0'));

        CueIndex start, end;
        if (i==0 && mPreGapType == PreGapType::AddToFirstTrack)
            start = CueTime("00:00:00");
        else
            start = mDisc->track(i)->cueIndex(1);

        if (i<mDisc->count()-1)
            end = mDisc->track(i+1)->cueIndex(01);

        try
        {
            decoder.extract(start, end, outFileName);
        }
        catch (FlaconError &err)
        {
            qWarning() << "Splitter error for track " << mCurrentTrack->trackNum() << ": " <<  err.what();
            deleteFile(outFileName);
            emit error(mCurrentTrack, err.what());

        }

        qDebug() << "Splitter trackReady:" << *mCurrentTrack << outFileName;
        emit trackReady(mCurrentTrack, outFileName);
    }
}

/************************************************
 *
 ************************************************/
void Splitter::decoderProgress(int percent)
{
    emit trackProgress(mCurrentTrack, TrackState::Splitting, percent);
}
<|endoftext|>


<commit_before>/*
    This file is part of Akregator.

    Copyright (C) 2004 Stanislav Karchebny <Stanislav.Karchebny@kdemail.net>
                  2005 Frank Osterfeld <frank.osterfeld at kdemail.net>
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include "article.h"
#include "feed.h"
#include "feedstorage.h"
#include "storage.h"
#include "utils.h"

#include <syndication/syndication.h>

#include <QDateTime>
#include <qdom.h>
#include <QRegExp>
#include <QStringList>
#include <QList>

#include <kdebug.h>
#include <kurl.h>

using namespace Syndication;

namespace Akregator {

struct Article::Private
{
    /** The status of the article is stored in an int, the bits having the
        following meaning:

        0000 0001 Deleted
        0000 0010 Trash
        0000 0100 New
        0000 1000 Read
        0001 0000 Keep
     */

    enum Status {Deleted=0x01, Trash=0x02, New=0x04, Read=0x08, Keep=0x10};

    int status;
    QString guid;
    uint hash;
    Backend::FeedStorage* archive;
    QDateTime pubDate;
    Feed* feed;
};

Article::Article() : d(new Private)
{
    d->hash = 0;
    d->status = 0;
    d->feed = 0;
    d->archive = 0;
    d->pubDate.setTime_t(1);

}

Article::Article(const QString& guid, Feed* feed) : d(new Private)
{
    d->feed = feed;
    d->guid = guid;
    d->archive = feed->storage()->archiveFor(feed->xmlUrl());
    d->status = d->archive->status(d->guid);
    d->pubDate.setTime_t(d->archive->pubDate(d->guid));
    d->hash = d->archive->hash(d->guid);
}

void Article::initialize(ItemPtr article, Backend::FeedStorage* archive)
{
    d->archive = archive;
    d->status = Private::New;

    QList<PersonPtr> authorList = article->authors();

    QString author;

    if (!authorList.isEmpty())
    {
        PersonPtr person = *(authorList.begin());

        if (!person->email().isNull())
        {
            if (!person->name().isNull())
                author = QString("%2").arg(person->email()).arg(person->name());
            else
                author = QString("%2").arg(person->email()).arg(person->email());
        }
        else if (!person->name().isNull())
        {
            if (!person->uri().isNull())
                author = QString("%2").arg(person->uri()).arg(person->name());
            else
                author = person->name();
        }
    }

    d->hash = Utils::calcHash(article->title() + article->description() + article->link() + author);

    d->guid = article->id();

    if (!d->archive->contains(d->guid))
    {
        d->archive->addEntry(d->guid);

        d->archive->setHash(d->guid, d->hash);
        QString title = article->title();
        if (title.isEmpty())
            title = buildTitle(article->description());
        d->archive->setTitle(d->guid, title);
        d->archive->setDescription(d->guid, article->description());
        d->archive->setLink(d->guid, article->link());
        //d->archive->setComments(d->guid, article.comments());
        //d->archive->setCommentsLink(d->guid, article.commentsLink().url());
        d->archive->setGuidIsPermaLink(d->guid, false);
        d->archive->setGuidIsHash(d->guid, d->guid.startsWith("hash:"));
        const time_t datePublished = article->datePublished();
        if ( datePublished > 0 )
            d->pubDate.setTime_t( datePublished );
        else
            d->pubDate = QDateTime::currentDateTime();
        d->archive->setPubDate(d->guid, d->pubDate.toTime_t());
        d->archive->setAuthor(d->guid, author);
    }
    else
    {
        // always update comments count, as it's not used for hash calculation
        //d->archive->setComments(d->guid, article.comments());
        if (d->hash != d->archive->hash(d->guid)) //article is in archive, was it modified?
        { // if yes, update
            d->pubDate.setTime_t(d->archive->pubDate(d->guid));
            d->archive->setHash(d->guid, d->hash);
            QString title = article->title();
            if (title.isEmpty())
                title = buildTitle(article->description());
            d->archive->setTitle(d->guid, title);
            d->archive->setDescription(d->guid, article->description());
            d->archive->setLink(d->guid, article->link());
            d->archive->setAuthor(d->guid, author);
            //d->archive->setCommentsLink(d->guid, article.commentsLink());
        }
    }
}

Article::Article(ItemPtr article, Feed* feed) : d(new Private)
{
    Q_ASSERT( feed );
    d->feed = feed;
    initialize(article, feed->storage()->archiveFor(feed->xmlUrl()));
}

Article::Article(ItemPtr article, Backend::FeedStorage* archive) : d(new Private)
{
    d->feed = 0;
    initialize(article, archive);
}

bool Article::isNull() const
{
    return d->archive == 0; // TODO: use proper null state
}

void Article::offsetPubDate(int secs)
{
   d->pubDate = d->pubDate.addSecs(secs);
   d->archive->setPubDate(d->guid, d->pubDate.toTime_t());

}

void Article::setDeleted()
{
    if (isDeleted())
        return;

    setStatus(Read);
    d->status = Private::Deleted | Private::Read;
    d->archive->setStatus(d->guid, d->status);
    d->archive->setDeleted(d->guid);

    if (d->feed)
        d->feed->setArticleDeleted(*this);
}

bool Article::isDeleted() const
{
    return (d->status & Private::Deleted) != 0;
}

Article::Article(const Article &other) : d(new Private)
{
    d = other.d;
}

Article::~Article()
{
}

Article &Article::operator=(const Article &other)
{
    d = other.d;
}

bool Article::operator<(const Article &other) const
{
    return pubDate() > other.pubDate() ||
            (pubDate() == other.pubDate() && guid() < other.guid() );
}

bool Article::operator<=(const Article &other) const
{
    return (pubDate() > other.pubDate() || *this == other);
}

bool Article::operator>(const Article &other) const
{
    return pubDate() < other.pubDate() ||
            (pubDate() == other.pubDate() && guid() > other.guid() );
}

bool Article::operator>=(const Article &other) const
{
    return (pubDate() > other.pubDate() || *this == other);
}

bool Article::operator==(const Article &other) const
{
    return d->guid == other.guid();
}

bool Article::operator!=(const Article &other) const
{
    return d->guid != other.guid();
}

int Article::status() const
{
    if ((d->status & Private::Read) != 0)
        return Read;

    if ((d->status & Private::New) != 0)
        return New;

    return Unread;
}

void Article::setStatus(int stat)
{
    int oldStatus = status();

    if (oldStatus != stat)
    {
        switch (stat)
        {
            case Read:
                d->status = (d->status | Private::Read) & ~Private::New;
                break;
            case Unread:
                d->status = (d->status & ~Private::Read) & ~Private::New;
                break;
            case New:
                d->status = (d->status | Private::New) & ~Private::Read;
                break;
        }
        d->archive->setStatus(d->guid, d->status);
        if (d->feed)
            d->feed->setArticleChanged(*this, oldStatus);
     }
}

QString Article::title() const
{
    return d->archive->title(d->guid);
}

QString Article::author() const
{
    return d->archive->author(d->guid);
}

KUrl Article::link() const
{
    return d->archive->link(d->guid);
}

QString Article::description() const
{
    return d->archive->description(d->guid);
}

QString Article::guid() const
{
    return d->guid;
}

KUrl Article::commentsLink() const
{
    return d->archive->commentsLink(d->guid);
}

int Article::comments() const
{

    return d->archive->comments(d->guid);
}

bool Article::guidIsPermaLink() const
{
    return d->archive->guidIsPermaLink(d->guid);
}

bool Article::guidIsHash() const
{
    return d->archive->guidIsHash(d->guid);
}

uint Article::hash() const
{
    return d->hash;
}

bool Article::keep() const
{
    return (d->status & Private::Keep) != 0;
}

void Article::setKeep(bool keep)
{
    d->status = keep ? (d->status | Private::Keep) : (d->status & ~Private::Keep);
    d->archive->setStatus(d->guid, d->status);
    if (d->feed)
        d->feed->setArticleChanged(*this);
}

Feed* Article::feed() const
{ return d->feed; }

const QDateTime& Article::pubDate() const
{
    return d->pubDate;
}

QString Article::buildTitle(const QString& description)
{
    QString s = description;
    if (description.trimmed().isEmpty())
        return "";

    int i = s.indexOf('>',500); /*avoid processing too much */
    if (i != -1)
        s = s.left(i+1);
    QRegExp rx("(<([^\\s>]*)(?:[^>]*)>)[^<]*", Qt::CaseInsensitive);
    QString tagName, toReplace, replaceWith;
    while (rx.indexIn(s) != -1 )
    {
        tagName=rx.cap(2);
        if (tagName=="SCRIPT"||tagName=="script")
            toReplace=rx.cap(0); // strip tag AND tag contents
        else if (tagName.startsWith("br") || tagName.startsWith("BR"))
        {
            toReplace=rx.cap(1);
            replaceWith=" ";
        }
        else
            toReplace=rx.cap(1);  // strip just tag
        s=s.replace(s.indexOf(toReplace),toReplace.length(),replaceWith); // do the deed
    }
    if (s.length()> 90)
        s=s.left(90)+"...";
    return s.simplified();
}
} // namespace Akregator
<commit_msg>fix assignment operator<commit_after>/*
    This file is part of Akregator.

    Copyright (C) 2004 Stanislav Karchebny <Stanislav.Karchebny@kdemail.net>
                  2005 Frank Osterfeld <frank.osterfeld at kdemail.net>
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include "article.h"
#include "feed.h"
#include "feedstorage.h"
#include "storage.h"
#include "utils.h"

#include <syndication/syndication.h>

#include <QDateTime>
#include <qdom.h>
#include <QRegExp>
#include <QStringList>
#include <QList>

#include <kdebug.h>
#include <kurl.h>

using namespace Syndication;

namespace Akregator {

struct Article::Private
{
    /** The status of the article is stored in an int, the bits having the
        following meaning:

        0000 0001 Deleted
        0000 0010 Trash
        0000 0100 New
        0000 1000 Read
        0001 0000 Keep
     */

    enum Status {Deleted=0x01, Trash=0x02, New=0x04, Read=0x08, Keep=0x10};

    int status;
    QString guid;
    uint hash;
    Backend::FeedStorage* archive;
    QDateTime pubDate;
    Feed* feed;
};

Article::Article() : d(new Private)
{
    d->hash = 0;
    d->status = 0;
    d->feed = 0;
    d->archive = 0;
    d->pubDate.setTime_t(1);

}

Article::Article(const QString& guid, Feed* feed) : d(new Private)
{
    d->feed = feed;
    d->guid = guid;
    d->archive = feed->storage()->archiveFor(feed->xmlUrl());
    d->status = d->archive->status(d->guid);
    d->pubDate.setTime_t(d->archive->pubDate(d->guid));
    d->hash = d->archive->hash(d->guid);
}

void Article::initialize(ItemPtr article, Backend::FeedStorage* archive)
{
    d->archive = archive;
    d->status = Private::New;

    QList<PersonPtr> authorList = article->authors();

    QString author;

    if (!authorList.isEmpty())
    {
        PersonPtr person = *(authorList.begin());

        if (!person->email().isNull())
        {
            if (!person->name().isNull())
                author = QString("%2").arg(person->email()).arg(person->name());
            else
                author = QString("%2").arg(person->email()).arg(person->email());
        }
        else if (!person->name().isNull())
        {
            if (!person->uri().isNull())
                author = QString("%2").arg(person->uri()).arg(person->name());
            else
                author = person->name();
        }
    }

    d->hash = Utils::calcHash(article->title() + article->description() + article->link() + author);

    d->guid = article->id();

    if (!d->archive->contains(d->guid))
    {
        d->archive->addEntry(d->guid);

        d->archive->setHash(d->guid, d->hash);
        QString title = article->title();
        if (title.isEmpty())
            title = buildTitle(article->description());
        d->archive->setTitle(d->guid, title);
        d->archive->setDescription(d->guid, article->description());
        d->archive->setLink(d->guid, article->link());
        //d->archive->setComments(d->guid, article.comments());
        //d->archive->setCommentsLink(d->guid, article.commentsLink().url());
        d->archive->setGuidIsPermaLink(d->guid, false);
        d->archive->setGuidIsHash(d->guid, d->guid.startsWith("hash:"));
        const time_t datePublished = article->datePublished();
        if ( datePublished > 0 )
            d->pubDate.setTime_t( datePublished );
        else
            d->pubDate = QDateTime::currentDateTime();
        d->archive->setPubDate(d->guid, d->pubDate.toTime_t());
        d->archive->setAuthor(d->guid, author);
    }
    else
    {
        // always update comments count, as it's not used for hash calculation
        //d->archive->setComments(d->guid, article.comments());
        if (d->hash != d->archive->hash(d->guid)) //article is in archive, was it modified?
        { // if yes, update
            d->pubDate.setTime_t(d->archive->pubDate(d->guid));
            d->archive->setHash(d->guid, d->hash);
            QString title = article->title();
            if (title.isEmpty())
                title = buildTitle(article->description());
            d->archive->setTitle(d->guid, title);
            d->archive->setDescription(d->guid, article->description());
            d->archive->setLink(d->guid, article->link());
            d->archive->setAuthor(d->guid, author);
            //d->archive->setCommentsLink(d->guid, article.commentsLink());
        }
    }
}

Article::Article(ItemPtr article, Feed* feed) : d(new Private)
{
    Q_ASSERT( feed );
    d->feed = feed;
    initialize(article, feed->storage()->archiveFor(feed->xmlUrl()));
}

Article::Article(ItemPtr article, Backend::FeedStorage* archive) : d(new Private)
{
    d->feed = 0;
    initialize(article, archive);
}

bool Article::isNull() const
{
    return d->archive == 0; // TODO: use proper null state
}

void Article::offsetPubDate(int secs)
{
   d->pubDate = d->pubDate.addSecs(secs);
   d->archive->setPubDate(d->guid, d->pubDate.toTime_t());

}

void Article::setDeleted()
{
    if (isDeleted())
        return;

    setStatus(Read);
    d->status = Private::Deleted | Private::Read;
    d->archive->setStatus(d->guid, d->status);
    d->archive->setDeleted(d->guid);

    if (d->feed)
        d->feed->setArticleDeleted(*this);
}

bool Article::isDeleted() const
{
    return (d->status & Private::Deleted) != 0;
}

Article::Article(const Article &other) : d(new Private)
{
    d = other.d;
}

Article::~Article()
{
}

Article &Article::operator=(const Article &other)
{
    d = other.d;
    return *this;
}

bool Article::operator<(const Article &other) const
{
    return pubDate() > other.pubDate() ||
            (pubDate() == other.pubDate() && guid() < other.guid() );
}

bool Article::operator<=(const Article &other) const
{
    return (pubDate() > other.pubDate() || *this == other);
}

bool Article::operator>(const Article &other) const
{
    return pubDate() < other.pubDate() ||
            (pubDate() == other.pubDate() && guid() > other.guid() );
}

bool Article::operator>=(const Article &other) const
{
    return (pubDate() > other.pubDate() || *this == other);
}

bool Article::operator==(const Article &other) const
{
    return d->guid == other.guid();
}

bool Article::operator!=(const Article &other) const
{
    return d->guid != other.guid();
}

int Article::status() const
{
    if ((d->status & Private::Read) != 0)
        return Read;

    if ((d->status & Private::New) != 0)
        return New;

    return Unread;
}

void Article::setStatus(int stat)
{
    int oldStatus = status();

    if (oldStatus != stat)
    {
        switch (stat)
        {
            case Read:
                d->status = (d->status | Private::Read) & ~Private::New;
                break;
            case Unread:
                d->status = (d->status & ~Private::Read) & ~Private::New;
                break;
            case New:
                d->status = (d->status | Private::New) & ~Private::Read;
                break;
        }
        d->archive->setStatus(d->guid, d->status);
        if (d->feed)
            d->feed->setArticleChanged(*this, oldStatus);
     }
}

QString Article::title() const
{
    return d->archive->title(d->guid);
}

QString Article::author() const
{
    return d->archive->author(d->guid);
}

KUrl Article::link() const
{
    return d->archive->link(d->guid);
}

QString Article::description() const
{
    return d->archive->description(d->guid);
}

QString Article::guid() const
{
    return d->guid;
}

KUrl Article::commentsLink() const
{
    return d->archive->commentsLink(d->guid);
}

int Article::comments() const
{

    return d->archive->comments(d->guid);
}

bool Article::guidIsPermaLink() const
{
    return d->archive->guidIsPermaLink(d->guid);
}

bool Article::guidIsHash() const
{
    return d->archive->guidIsHash(d->guid);
}

uint Article::hash() const
{
    return d->hash;
}

bool Article::keep() const
{
    return (d->status & Private::Keep) != 0;
}

void Article::setKeep(bool keep)
{
    d->status = keep ? (d->status | Private::Keep) : (d->status & ~Private::Keep);
    d->archive->setStatus(d->guid, d->status);
    if (d->feed)
        d->feed->setArticleChanged(*this);
}

Feed* Article::feed() const
{ return d->feed; }

const QDateTime& Article::pubDate() const
{
    return d->pubDate;
}

QString Article::buildTitle(const QString& description)
{
    QString s = description;
    if (description.trimmed().isEmpty())
        return "";

    int i = s.indexOf('>',500); /*avoid processing too much */
    if (i != -1)
        s = s.left(i+1);
    QRegExp rx("(<([^\\s>]*)(?:[^>]*)>)[^<]*", Qt::CaseInsensitive);
    QString tagName, toReplace, replaceWith;
    while (rx.indexIn(s) != -1 )
    {
        tagName=rx.cap(2);
        if (tagName=="SCRIPT"||tagName=="script")
            toReplace=rx.cap(0); // strip tag AND tag contents
        else if (tagName.startsWith("br") || tagName.startsWith("BR"))
        {
            toReplace=rx.cap(1);
            replaceWith=" ";
        }
        else
            toReplace=rx.cap(1);  // strip just tag
        s=s.replace(s.indexOf(toReplace),toReplace.length(),replaceWith); // do the deed
    }
    if (s.length()> 90)
        s=s.left(90)+"...";
    return s.simplified();
}
} // namespace Akregator
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_OPERATORS_RECONSTRUCTIONS_HH
#define DUNE_GDT_OPERATORS_RECONSTRUCTIONS_HH

#include <type_traits>
#include <limits>

#include <dune/common/dynmatrix.hh>

#include <dune/geometry/quadraturerules.hh>

#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/functions/constant.hh>

#include <dune/gdt/playground/spaces/raviartthomas/pdelab.hh>
#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/localevaluation/swipdg.hh>

namespace Dune {
namespace GDT {
namespace Operators {

/**
 *  \todo Add more static checks that GridViewType and LocalizableFunctionType match.
 *  \todo Derived from operator interfaces.
 */
template< class GridViewType, class LocalizableFunctionType >
class DiffusiveFluxReconstruction
{
  static_assert(GridViewType::dimension == 2, "Only implemented for dimDomain 2 at the moment!");
  static_assert(std::is_base_of< Stuff::IsLocalizableFunction, LocalizableFunctionType >::value,
                "LocalizableFunctionType has to be tagged as Stuff::IsLocalizableFunction!");
public:
  typedef typename GridViewType::template Codim< 0 >::Entity EntityType;
  typedef typename GridViewType::ctype DomainFieldType;
  static const unsigned int dimDomain = GridViewType::dimension;
  typedef typename LocalizableFunctionType::RangeFieldType FieldType;
  typedef typename LocalizableFunctionType::DomainType DomainType;

private:
  static_assert(dimDomain == 2, "Not implemented!");

public:
  DiffusiveFluxReconstruction(const GridViewType& grid_view,
                const LocalizableFunctionType& diffusion)
    : grid_view_(grid_view)
    , diffusion_(diffusion)
  {}

  template< class GV, class V >
  void apply(const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, FieldType, 1 >& source,
             DiscreteFunction< Spaces::RaviartThomas::PdelabBased< GV, 0, FieldType, dimDomain >, V >& range) const
  {
    const auto& rtn0_space = range.space();
    auto& range_vector = range.vector();
    const FieldType infinity = std::numeric_limits< FieldType >::infinity();
    for (size_t ii = 0; ii < range_vector.size(); ++ii)
      range_vector[ii] = infinity;
    const LocalEvaluation::SWIPDG::Inner< LocalizableFunctionType > inner_evaluation(diffusion_);
    const LocalEvaluation::SWIPDG::BoundaryLHS< LocalizableFunctionType > boundary_evaluation(diffusion_);
    const Stuff::Functions::Constant< EntityType, DomainFieldType, dimDomain, FieldType, 1 > constant_one(1);
    DomainType normal(0);
    DomainType xx_entity(0);
    DynamicMatrix< FieldType > tmp_matrix(1, 1, 0);
    DynamicMatrix< FieldType > tmp_matrix_en_en(1, 1, 0);
    DynamicMatrix< FieldType > tmp_matrix_en_ne(1, 1, 0);
    std::vector< typename Spaces::RaviartThomas::PdelabBased< GV, 0, FieldType, dimDomain >::BaseFunctionSetType::RangeType >
        basis_values(rtn0_space.mapper().maxNumDofs(),
                     typename Spaces::RaviartThomas::PdelabBased< GV, 0, FieldType, dimDomain >::BaseFunctionSetType::RangeType(0));
    // walk the grid
    const auto entity_it_end = grid_view_.template end< 0 >();
    for (auto entity_it = grid_view_.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) {
      const auto& entity = *entity_it;
      const auto local_DoF_indices = rtn0_space.local_DoF_indices(entity);
      const auto global_DoF_indices = rtn0_space.mapper().globalIndices(entity);
      assert(global_DoF_indices.size() == local_DoF_indices.size());
      const auto local_diffusion = diffusion_.local_function(entity);
      const auto local_source = source.local_function(entity);
      const auto local_basis = rtn0_space.base_function_set(entity);
      const auto local_constant_one = constant_one.local_function(entity);
      // walk the intersections
      const auto intersection_it_end = grid_view_.iend(entity);
      for (auto intersection_it = grid_view_.ibegin(entity);
           intersection_it != intersection_it_end;
           ++intersection_it) {
        const auto& intersection = *intersection_it;
        if (intersection.neighbor() && !intersection.boundary()) {
          const auto neighbor_ptr = intersection.outside();
          const auto& neighbor = *neighbor_ptr;
          if (grid_view_.indexSet().index(entity) < grid_view_.indexSet().index(neighbor)) {
            const auto local_diffusion_neighbor = diffusion_.local_function(neighbor);
            const auto local_source_neighbor = source.local_function(neighbor);
            const auto local_constant_one_neighbor = constant_one.local_function(neighbor);
            const size_t local_intersection_index = intersection.indexInInside();
            const size_t local_DoF_index = local_DoF_indices[local_intersection_index];
            // do a face quadrature
            FieldType lhs = 0;
            FieldType rhs = 0;
            const size_t integrand_order = inner_evaluation.order(*local_diffusion,
                                                                  *local_diffusion_neighbor,
                                                                  *local_constant_one,
                                                                  *local_source,
                                                                  *local_constant_one_neighbor,
                                                                  *local_source_neighbor);
            assert(integrand_order < std::numeric_limits< int >::max());
            const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain - 1 >::rule(intersection.type(),
                                                                                int(integrand_order));
            const auto quadrature_it_end = quadrature.end();
            for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) {
              const auto& xx_intersection = quadrature_it->position();
              xx_entity = intersection.geometryInInside().global(xx_intersection);
              normal = intersection.unitOuterNormal(xx_intersection);
              const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection);
              const FieldType weigth = quadrature_it->weight();
              // evalaute
              local_basis.evaluate(xx_entity, basis_values);
              const auto& basis_value = basis_values[local_DoF_index];
              tmp_matrix *= 0.0;
              tmp_matrix_en_en *= 0.0;
              tmp_matrix_en_ne *= 0.0;
              inner_evaluation.evaluate(*local_diffusion,
                                        *local_diffusion_neighbor,
                                        *local_constant_one,
                                        *local_source,
                                        *local_constant_one_neighbor,
                                        *local_source_neighbor,
                                        intersection,
                                        xx_intersection,
                                        tmp_matrix_en_en, // <- we are interested in this one
                                        tmp_matrix,
                                        tmp_matrix_en_ne, // <- and this one
                                        tmp_matrix);
              // compute integrals
              assert(tmp_matrix_en_en.rows() >= 1);
              assert(tmp_matrix_en_en.cols() >= 1);
              assert(tmp_matrix_en_ne.rows() >= 1);
              assert(tmp_matrix_en_ne.cols() >= 1);
              lhs += integration_factor * weigth * (basis_value * normal);
              rhs += integration_factor * weigth * (tmp_matrix_en_en[0][0] + tmp_matrix_en_ne[0][0]);
            } // do a face quadrature
            // set DoF
            const size_t global_DoF_index = global_DoF_indices[local_DoF_index];
            // and make sure we are the first to do so
            assert(!(range_vector[global_DoF_index] < infinity));
            range_vector[global_DoF_index] = rhs / lhs;
          }
        } else if (intersection.boundary() && !intersection.neighbor()) {
          const size_t local_intersection_index = intersection.indexInInside();
          const size_t local_DoF_index = local_DoF_indices[local_intersection_index];
          // do a face quadrature
          FieldType lhs = 0;
          FieldType rhs = 0;
          const size_t integrand_order = boundary_evaluation.order(*local_diffusion,
                                                                   *local_source,
                                                                   *local_constant_one);
          assert(integrand_order < std::numeric_limits< int >::max());
          const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain - 1 >::rule(intersection.type(),
                                                                                int(integrand_order));
          const auto quadrature_it_end = quadrature.end();
          for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) {
            const auto xx_intersection = quadrature_it->position();
            normal = intersection.unitOuterNormal(xx_intersection);
            const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection);
            const FieldType weigth = quadrature_it->weight();
            xx_entity = intersection.geometryInInside().global(xx_intersection);
            // evalaute
            local_basis.evaluate(xx_entity, basis_values);
            const auto& basis_value = basis_values[local_DoF_index];
            tmp_matrix *= 0.0;
            boundary_evaluation.evaluate(*local_diffusion,
                                         *local_constant_one,
                                         *local_source,
                                         intersection,
                                         xx_intersection,
                                         tmp_matrix);
            // compute integrals
            assert(tmp_matrix.rows() >= 1);
            assert(tmp_matrix.cols() >= 1);
            lhs += integration_factor * weigth * (basis_value * normal);
            rhs += integration_factor * weigth * tmp_matrix[0][0];
          } // do a face quadrature
          // set DoF
          const size_t global_DoF_index = global_DoF_indices[local_DoF_index];
          assert(!(range_vector[global_DoF_index] < infinity));
          // and make sure we are the first to do so
          range_vector[global_DoF_index] = rhs / lhs;
        } else
          DUNE_THROW_COLORFULLY(Stuff::Exceptions::internal_error, "Unknown intersection type!");
      } // walk the intersections
    } // walk the grid
  } // ... apply(...)

private:
  const GridViewType& grid_view_;
  const LocalizableFunctionType& diffusion_;
}; // class DiffusiveFluxReconstruction

} // namespace Operators
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_OPERATORS_RECONSTRUCTIONS_HH
<commit_msg>[operators.fluxreconstruction] extend signature<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_OPERATORS_RECONSTRUCTIONS_HH
#define DUNE_GDT_OPERATORS_RECONSTRUCTIONS_HH

#include <type_traits>
#include <limits>

#include <dune/common/dynmatrix.hh>

#include <dune/geometry/quadraturerules.hh>

#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/functions/constant.hh>

#include <dune/gdt/playground/spaces/raviartthomas/pdelab.hh>
#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/localevaluation/swipdg.hh>

namespace Dune {
namespace GDT {
namespace Operators {

template< class GridViewType, class DiffusionFactorType, class DiffusionTensorType = void >
class DiffusiveFluxReconstruction;

/**
 *  \todo Add more static checks that GridViewType and LocalizableFunctionType match.
 *  \todo Derive from operator interfaces.
 */
template< class GridViewType, class LocalizableFunctionType >
class DiffusiveFluxReconstruction< GridViewType, LocalizableFunctionType, void >
{
  static_assert(GridViewType::dimension == 2, "Only implemented for dimDomain 2 at the moment!");
  static_assert(std::is_base_of< Stuff::IsLocalizableFunction, LocalizableFunctionType >::value,
                "LocalizableFunctionType has to be tagged as Stuff::IsLocalizableFunction!");
public:
  typedef typename GridViewType::template Codim< 0 >::Entity EntityType;
  typedef typename GridViewType::ctype DomainFieldType;
  static const unsigned int dimDomain = GridViewType::dimension;
  typedef typename LocalizableFunctionType::RangeFieldType FieldType;
  typedef typename LocalizableFunctionType::DomainType DomainType;

private:
  static_assert(dimDomain == 2, "Not implemented!");

public:
  DiffusiveFluxReconstruction(const GridViewType& grid_view, const LocalizableFunctionType& diffusion)
    : grid_view_(grid_view)
    , diffusion_(diffusion)
  {}

  template< class GV, class V >
  void apply(const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, FieldType, 1 >& source,
             DiscreteFunction< Spaces::RaviartThomas::PdelabBased< GV, 0, FieldType, dimDomain >, V >& range) const
  {
    const auto& rtn0_space = range.space();
    auto& range_vector = range.vector();
    const FieldType infinity = std::numeric_limits< FieldType >::infinity();
    for (size_t ii = 0; ii < range_vector.size(); ++ii)
      range_vector[ii] = infinity;
    const LocalEvaluation::SWIPDG::Inner< LocalizableFunctionType > inner_evaluation(diffusion_);
    const LocalEvaluation::SWIPDG::BoundaryLHS< LocalizableFunctionType > boundary_evaluation(diffusion_);
    const Stuff::Functions::Constant< EntityType, DomainFieldType, dimDomain, FieldType, 1 > constant_one(1);
    DomainType normal(0);
    DomainType xx_entity(0);
    DynamicMatrix< FieldType > tmp_matrix(1, 1, 0);
    DynamicMatrix< FieldType > tmp_matrix_en_en(1, 1, 0);
    DynamicMatrix< FieldType > tmp_matrix_en_ne(1, 1, 0);
    std::vector< typename Spaces::RaviartThomas::PdelabBased< GV, 0, FieldType, dimDomain >::BaseFunctionSetType::RangeType >
        basis_values(rtn0_space.mapper().maxNumDofs(),
                     typename Spaces::RaviartThomas::PdelabBased< GV, 0, FieldType, dimDomain >::BaseFunctionSetType::RangeType(0));
    // walk the grid
    const auto entity_it_end = grid_view_.template end< 0 >();
    for (auto entity_it = grid_view_.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) {
      const auto& entity = *entity_it;
      const auto local_DoF_indices = rtn0_space.local_DoF_indices(entity);
      const auto global_DoF_indices = rtn0_space.mapper().globalIndices(entity);
      assert(global_DoF_indices.size() == local_DoF_indices.size());
      const auto local_diffusion = diffusion_.local_function(entity);
      const auto local_source = source.local_function(entity);
      const auto local_basis = rtn0_space.base_function_set(entity);
      const auto local_constant_one = constant_one.local_function(entity);
      // walk the intersections
      const auto intersection_it_end = grid_view_.iend(entity);
      for (auto intersection_it = grid_view_.ibegin(entity);
           intersection_it != intersection_it_end;
           ++intersection_it) {
        const auto& intersection = *intersection_it;
        if (intersection.neighbor() && !intersection.boundary()) {
          const auto neighbor_ptr = intersection.outside();
          const auto& neighbor = *neighbor_ptr;
          if (grid_view_.indexSet().index(entity) < grid_view_.indexSet().index(neighbor)) {
            const auto local_diffusion_neighbor = diffusion_.local_function(neighbor);
            const auto local_source_neighbor = source.local_function(neighbor);
            const auto local_constant_one_neighbor = constant_one.local_function(neighbor);
            const size_t local_intersection_index = intersection.indexInInside();
            const size_t local_DoF_index = local_DoF_indices[local_intersection_index];
            // do a face quadrature
            FieldType lhs = 0;
            FieldType rhs = 0;
            const size_t integrand_order = inner_evaluation.order(*local_diffusion,
                                                                  *local_diffusion_neighbor,
                                                                  *local_constant_one,
                                                                  *local_source,
                                                                  *local_constant_one_neighbor,
                                                                  *local_source_neighbor);
            assert(integrand_order < std::numeric_limits< int >::max());
            const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain - 1 >::rule(intersection.type(),
                                                                                int(integrand_order));
            const auto quadrature_it_end = quadrature.end();
            for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) {
              const auto& xx_intersection = quadrature_it->position();
              xx_entity = intersection.geometryInInside().global(xx_intersection);
              normal = intersection.unitOuterNormal(xx_intersection);
              const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection);
              const FieldType weigth = quadrature_it->weight();
              // evalaute
              local_basis.evaluate(xx_entity, basis_values);
              const auto& basis_value = basis_values[local_DoF_index];
              tmp_matrix *= 0.0;
              tmp_matrix_en_en *= 0.0;
              tmp_matrix_en_ne *= 0.0;
              inner_evaluation.evaluate(*local_diffusion,
                                        *local_diffusion_neighbor,
                                        *local_constant_one,
                                        *local_source,
                                        *local_constant_one_neighbor,
                                        *local_source_neighbor,
                                        intersection,
                                        xx_intersection,
                                        tmp_matrix_en_en, // <- we are interested in this one
                                        tmp_matrix,
                                        tmp_matrix_en_ne, // <- and this one
                                        tmp_matrix);
              // compute integrals
              assert(tmp_matrix_en_en.rows() >= 1);
              assert(tmp_matrix_en_en.cols() >= 1);
              assert(tmp_matrix_en_ne.rows() >= 1);
              assert(tmp_matrix_en_ne.cols() >= 1);
              lhs += integration_factor * weigth * (basis_value * normal);
              rhs += integration_factor * weigth * (tmp_matrix_en_en[0][0] + tmp_matrix_en_ne[0][0]);
            } // do a face quadrature
            // set DoF
            const size_t global_DoF_index = global_DoF_indices[local_DoF_index];
            // and make sure we are the first to do so
            assert(!(range_vector[global_DoF_index] < infinity));
            range_vector[global_DoF_index] = rhs / lhs;
          }
        } else if (intersection.boundary() && !intersection.neighbor()) {
          const size_t local_intersection_index = intersection.indexInInside();
          const size_t local_DoF_index = local_DoF_indices[local_intersection_index];
          // do a face quadrature
          FieldType lhs = 0;
          FieldType rhs = 0;
          const size_t integrand_order = boundary_evaluation.order(*local_diffusion,
                                                                   *local_source,
                                                                   *local_constant_one);
          assert(integrand_order < std::numeric_limits< int >::max());
          const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain - 1 >::rule(intersection.type(),
                                                                                int(integrand_order));
          const auto quadrature_it_end = quadrature.end();
          for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) {
            const auto xx_intersection = quadrature_it->position();
            normal = intersection.unitOuterNormal(xx_intersection);
            const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection);
            const FieldType weigth = quadrature_it->weight();
            xx_entity = intersection.geometryInInside().global(xx_intersection);
            // evalaute
            local_basis.evaluate(xx_entity, basis_values);
            const auto& basis_value = basis_values[local_DoF_index];
            tmp_matrix *= 0.0;
            boundary_evaluation.evaluate(*local_diffusion,
                                         *local_constant_one,
                                         *local_source,
                                         intersection,
                                         xx_intersection,
                                         tmp_matrix);
            // compute integrals
            assert(tmp_matrix.rows() >= 1);
            assert(tmp_matrix.cols() >= 1);
            lhs += integration_factor * weigth * (basis_value * normal);
            rhs += integration_factor * weigth * tmp_matrix[0][0];
          } // do a face quadrature
          // set DoF
          const size_t global_DoF_index = global_DoF_indices[local_DoF_index];
          assert(!(range_vector[global_DoF_index] < infinity));
          // and make sure we are the first to do so
          range_vector[global_DoF_index] = rhs / lhs;
        } else
          DUNE_THROW_COLORFULLY(Stuff::Exceptions::internal_error, "Unknown intersection type!");
      } // walk the intersections
    } // walk the grid
  } // ... apply(...)

private:
  const GridViewType& grid_view_;
  const LocalizableFunctionType& diffusion_;
}; // class DiffusiveFluxReconstruction

} // namespace Operators
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_OPERATORS_RECONSTRUCTIONS_HH
<|endoftext|>