<commit_before>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved.  Released under a BSD (revised)
license as described in the file LICENSE.
 */
#include <stdint.h>
#include "parse_primitives.h"
#include "v_array.h"
#include "example.h"
#include "simple_label.h"
#include "gd.h"
#include "global_data.h"
#include "memory.h"

int compare_feature(const void* p1, const void* p2) {
  feature* f1 = (feature*) p1;
  feature* f2 = (feature*) p2;
  if(f1->weight_index < f2->weight_index) return -1;
  else if(f1->weight_index > f2->weight_index) return 1;
  else return 0;
}

float collision_cleanup(v_array<feature> feature_map) {

 int pos = 0;
 float sum_sq = 0.;

 for(uint32_t i = 1;i < feature_map.size();i++) {
    if(feature_map[i].weight_index == feature_map[pos].weight_index)
      feature_map[pos].x += feature_map[i].x;
    else {
      sum_sq += feature_map[pos].x*feature_map[pos].x;
      feature_map[++pos] = feature_map[i];
    }
  }
  sum_sq += feature_map[pos].x*feature_map[pos].x;
  feature_map.end = &(feature_map[pos]);
  feature_map.end++;
  return sum_sq;
}

audit_data copy_audit_data(audit_data &src) {
  audit_data dst;
  dst.space = (char*)calloc_or_die(strlen(src.space)+1, sizeof(char));
  strcpy(dst.space, src.space);
  dst.feature = (char*)calloc_or_die(strlen(src.feature)+1, sizeof(char));
  strcpy(dst.feature, src.feature);
  dst.weight_index = src.weight_index;
  dst.x = src.x;
  dst.alloced = src.alloced;
  return dst;
}

namespace VW {
void copy_example_label(example* dst, example* src, size_t label_size, void(*copy_label)(void*&,void*)) {
  if (!src->ld) {
    if (dst->ld) free(dst->ld);  // TODO: this should be a delete_label, really
    dst->ld = NULL;
  } else {
    if ((label_size == 0) && (copy_label == NULL)) {
      if (dst->ld) free(dst->ld);  // TODO: this should be a delete_label, really
      dst->ld = NULL;
    } else if (copy_label) {
      copy_label(dst->ld, src->ld);
    } else {
      //dst->ld = (void*)malloc(label_size);
      memcpy(dst->ld, src->ld, label_size);
    }
  }
}

void copy_example_data(bool audit, example* dst, example* src)
{
  //std::cerr << "copy_example_data dst = " << dst << std::endl;
  copy_array(dst->tag, src->tag);
  dst->example_counter = src->example_counter;

  copy_array(dst->indices, src->indices);
  for (size_t i=0; i<256; i++)
    copy_array(dst->atomics[i], src->atomics[i]);
  dst->ft_offset = src->ft_offset;

  if (audit)
    for (size_t i=0; i<256; i++)
      copy_array(dst->audit_features[i], src->audit_features[i], copy_audit_data);

  dst->num_features = src->num_features;
  dst->partial_prediction = src->partial_prediction;
  copy_array(dst->topic_predictions, src->topic_predictions);
  dst->loss = src->loss;
  dst->example_t = src->example_t;
  memcpy(dst->sum_feat_sq, src->sum_feat_sq, 256 * sizeof(float));
  dst->total_sum_feat_sq = src->total_sum_feat_sq;
  dst->revert_weight = src->revert_weight;
  dst->test_only = src->test_only;
  dst->end_pass = src->end_pass;
  dst->sorted = src->sorted;
  dst->in_use = src->in_use;}

void copy_example_data(bool audit, example* dst, example* src, size_t label_size, void(*copy_label)(void*&,void*)) {
  copy_example_data(audit, dst, src);
  copy_example_label(dst, src, label_size, copy_label);
}
}

struct features_and_source
{
  v_array<feature> feature_map; //map to store sparse feature vectors
  uint32_t stride_shift;
  uint32_t mask;
  weight* base;
};

void vec_store(vw& all, features_and_source& p, float fx, uint32_t fi) {
  feature f = {fx, fi};
  p.feature_map.push_back(f);
}

namespace VW {
  feature* get_features(vw& all, example* ec, size_t& feature_map_len, float& total_sum_sq)
{
	features_and_source fs;
	fs.stride_shift = all.reg.stride_shift;
	fs.mask = (uint32_t)all.reg.weight_mask >> all.reg.stride_shift;
	fs.base = all.reg.weight_vector;
	GD::foreach_feature<features_and_source, vec_store>(all, *ec, fs);
	qsort(fs.feature_map.begin, fs.feature_map.size(), sizeof(feature), compare_feature);
	total_sum_sq = collision_cleanup(fs.feature_map);
	feature_map_len = fs.feature_map.size();
	return fs.feature_map.begin;
}

void return_features(feature* f)
{
	if (f != NULL)
		free(f);
}
}

flat_example* flatten_example(vw& all, example *ec)
{
	flat_example* fec = (flat_example*) calloc_or_die(1,sizeof(flat_example));
	fec->ld = (label_data*)calloc_or_die(1, sizeof(label_data));
	memcpy(fec->ld, ec->ld, sizeof(label_data));

	fec->tag_len = ec->tag.size();
	if (fec->tag_len >0)
	  {
	    fec->tag = (char*)calloc_or_die(fec->tag_len+1, sizeof(char));
	    memcpy(fec->tag,ec->tag.begin, fec->tag_len);
	  }

	fec->example_counter = ec->example_counter;
	fec->ft_offset = ec->ft_offset;
	fec->num_features = ec->num_features;

	fec->feature_map = VW::get_features(all, ec, fec->feature_map_len, fec->total_sum_feat_sq);

	return fec;
}

void free_flatten_example(flat_example* fec)
{  //note: The label memory should be freed by by freeing the original example.
  if (fec)
    {
      if (fec->feature_map_len > 0)
	free(fec->feature_map);
      if (fec->tag_len > 0)
	free(fec->tag);
      free(fec->ld);
      free(fec);
    }
}

example *alloc_examples(size_t label_size, size_t count=1)
{
  example* ec = (example*)calloc_or_die(count, sizeof(example));
  if (ec == NULL) return NULL;
  for (size_t i=0; i<count; i++) {
    ec[i].ld = calloc_or_die(1, label_size);
    if (ec[i].ld == NULL) {
      for (size_t j=0; j<i; j++) free(ec[j].ld);
      free(ec);
      return NULL;
    }
    ec[i].in_use = true;
    ec[i].ft_offset = 0;
    //  std::cerr << "  alloc_example.indices.begin=" << ec->indices.begin << " end=" << ec->indices.end << " // ld = " << ec->ld << "\t|| me = " << ec << std::endl;
  }
  return ec;
}

void dealloc_example(void(*delete_label)(void*), example&ec)
{
  if (delete_label) {
    delete_label(ec.ld);
  }
  ec.tag.delete_v();

  ec.topic_predictions.delete_v();

  free(ec.ld);
  for (size_t j = 0; j < 256; j++)
    {
      ec.atomics[j].delete_v();

      if (ec.audit_features[j].begin != ec.audit_features[j].end_array)
        {
          for (audit_data* temp = ec.audit_features[j].begin;
               temp != ec.audit_features[j].end; temp++)
            if (temp->alloced) {
              free(temp->space);
              free(temp->feature);
              temp->alloced = false;
            }
	  ec.audit_features[j].delete_v();
        }
    }
  ec.indices.delete_v();
}

<commit_msg>changes to collision_cleanup and vec_store<commit_after>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved.  Released under a BSD (revised)
license as described in the file LICENSE.
 */
#include <stdint.h>
#include "parse_primitives.h"
#include "v_array.h"
#include "example.h"
#include "simple_label.h"
#include "gd.h"
#include "global_data.h"
#include "memory.h"

int compare_feature(const void* p1, const void* p2) {
  feature* f1 = (feature*) p1;
  feature* f2 = (feature*) p2;
  if(f1->weight_index < f2->weight_index) return -1;
  else if(f1->weight_index > f2->weight_index) return 1;
  else return 0;
}

float collision_cleanup(v_array<feature>& feature_map) {

 int pos = 0;
 float sum_sq = 0.;

 for(uint32_t i = 1;i < feature_map.size();i++) {
    if(feature_map[i].weight_index == feature_map[pos].weight_index)
      feature_map[pos].x += feature_map[i].x;
    else {
      sum_sq += feature_map[pos].x*feature_map[pos].x;
      feature_map[++pos] = feature_map[i];
    }
  }
  sum_sq += feature_map[pos].x*feature_map[pos].x;
  feature_map.end = &(feature_map[pos]);
  feature_map.end++;
  return sum_sq;
}

audit_data copy_audit_data(audit_data &src) {
  audit_data dst;
  dst.space = (char*)calloc_or_die(strlen(src.space)+1, sizeof(char));
  strcpy(dst.space, src.space);
  dst.feature = (char*)calloc_or_die(strlen(src.feature)+1, sizeof(char));
  strcpy(dst.feature, src.feature);
  dst.weight_index = src.weight_index;
  dst.x = src.x;
  dst.alloced = src.alloced;
  return dst;
}

namespace VW {
void copy_example_label(example* dst, example* src, size_t label_size, void(*copy_label)(void*&,void*)) {
  if (!src->ld) {
    if (dst->ld) free(dst->ld);  // TODO: this should be a delete_label, really
    dst->ld = NULL;
  } else {
    if ((label_size == 0) && (copy_label == NULL)) {
      if (dst->ld) free(dst->ld);  // TODO: this should be a delete_label, really
      dst->ld = NULL;
    } else if (copy_label) {
      copy_label(dst->ld, src->ld);
    } else {
      //dst->ld = (void*)malloc(label_size);
      memcpy(dst->ld, src->ld, label_size);
    }
  }
}

void copy_example_data(bool audit, example* dst, example* src)
{
  //std::cerr << "copy_example_data dst = " << dst << std::endl;
  copy_array(dst->tag, src->tag);
  dst->example_counter = src->example_counter;

  copy_array(dst->indices, src->indices);
  for (size_t i=0; i<256; i++)
    copy_array(dst->atomics[i], src->atomics[i]);
  dst->ft_offset = src->ft_offset;

  if (audit)
    for (size_t i=0; i<256; i++)
      copy_array(dst->audit_features[i], src->audit_features[i], copy_audit_data);

  dst->num_features = src->num_features;
  dst->partial_prediction = src->partial_prediction;
  copy_array(dst->topic_predictions, src->topic_predictions);
  dst->loss = src->loss;
  dst->example_t = src->example_t;
  memcpy(dst->sum_feat_sq, src->sum_feat_sq, 256 * sizeof(float));
  dst->total_sum_feat_sq = src->total_sum_feat_sq;
  dst->revert_weight = src->revert_weight;
  dst->test_only = src->test_only;
  dst->end_pass = src->end_pass;
  dst->sorted = src->sorted;
  dst->in_use = src->in_use;}

void copy_example_data(bool audit, example* dst, example* src, size_t label_size, void(*copy_label)(void*&,void*)) {
  copy_example_data(audit, dst, src);
  copy_example_label(dst, src, label_size, copy_label);
}
}

struct features_and_source
{
  v_array<feature> feature_map; //map to store sparse feature vectors
  uint32_t stride_shift;
  uint32_t mask;
  weight* base;
};

void vec_store(vw& all, features_and_source& p, float fx, uint32_t fi) {
  uint32_t mask = (uint32_t)all.reg.weight_mask >> all.reg.stride_shift;
  feature f = {fx, (fi >> all.reg.stride_shit) & mask};
  p.feature_map.push_back(f);
}

namespace VW {
  feature* get_features(vw& all, example* ec, size_t& feature_map_len, float& total_sum_sq)
{
	features_and_source fs;
	fs.stride_shift = all.reg.stride_shift;
	fs.mask = (uint32_t)all.reg.weight_mask >> all.reg.stride_shift;
	fs.base = all.reg.weight_vector;
	GD::foreach_feature<features_and_source, vec_store>(all, *ec, fs);
	qsort(fs.feature_map.begin, fs.feature_map.size(), sizeof(feature), compare_feature);
	total_sum_sq = collision_cleanup(fs.feature_map);
	feature_map_len = fs.feature_map.size();
	return fs.feature_map.begin;
}

void return_features(feature* f)
{
	if (f != NULL)
		free(f);
}
}

flat_example* flatten_example(vw& all, example *ec)
{
	flat_example* fec = (flat_example*) calloc_or_die(1,sizeof(flat_example));
	fec->ld = (label_data*)calloc_or_die(1, sizeof(label_data));
	memcpy(fec->ld, ec->ld, sizeof(label_data));

	fec->tag_len = ec->tag.size();
	if (fec->tag_len >0)
	  {
	    fec->tag = (char*)calloc_or_die(fec->tag_len+1, sizeof(char));
	    memcpy(fec->tag,ec->tag.begin, fec->tag_len);
	  }

	fec->example_counter = ec->example_counter;
	fec->ft_offset = ec->ft_offset;
	fec->num_features = ec->num_features;

	fec->feature_map = VW::get_features(all, ec, fec->feature_map_len, fec->total_sum_feat_sq);

	return fec;
}

void free_flatten_example(flat_example* fec)
{  //note: The label memory should be freed by by freeing the original example.
  if (fec)
    {
      if (fec->feature_map_len > 0)
	free(fec->feature_map);
      if (fec->tag_len > 0)
	free(fec->tag);
      free(fec->ld);
      free(fec);
    }
}

example *alloc_examples(size_t label_size, size_t count=1)
{
  example* ec = (example*)calloc_or_die(count, sizeof(example));
  if (ec == NULL) return NULL;
  for (size_t i=0; i<count; i++) {
    ec[i].ld = calloc_or_die(1, label_size);
    if (ec[i].ld == NULL) {
      for (size_t j=0; j<i; j++) free(ec[j].ld);
      free(ec);
      return NULL;
    }
    ec[i].in_use = true;
    ec[i].ft_offset = 0;
    //  std::cerr << "  alloc_example.indices.begin=" << ec->indices.begin << " end=" << ec->indices.end << " // ld = " << ec->ld << "\t|| me = " << ec << std::endl;
  }
  return ec;
}

void dealloc_example(void(*delete_label)(void*), example&ec)
{
  if (delete_label) {
    delete_label(ec.ld);
  }
  ec.tag.delete_v();

  ec.topic_predictions.delete_v();

  free(ec.ld);
  for (size_t j = 0; j < 256; j++)
    {
      ec.atomics[j].delete_v();

      if (ec.audit_features[j].begin != ec.audit_features[j].end_array)
        {
          for (audit_data* temp = ec.audit_features[j].begin;
               temp != ec.audit_features[j].end; temp++)
            if (temp->alloced) {
              free(temp->space);
              free(temp->feature);
              temp->alloced = false;
            }
	  ec.audit_features[j].delete_v();
        }
    }
  ec.indices.delete_v();
}

<|endoftext|>


<commit_before>/*******************************************************************
 KNotes -- Notes for the KDE project

 Copyright (c) 2002-2004, Michael Brade <brade@kde.org>

 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*******************************************************************/

#include <qfile.h>
#include <qfont.h>
#include <qpoint.h>
#include <qcolor.h>
#include <qstringlist.h>
#include <qtextstream.h>

#include <kdebug.h>
#include <kapplication.h>
#include <kglobal.h>
#include <kurl.h>
#include <kstandarddirs.h>
#include <ksimpleconfig.h>
#include <kio/netaccess.h>

#include <unistd.h>

#include "knoteslegacy.h"
#include "knoteconfig.h"
#include "version.h"

#include "libkcal/calendarlocal.h"
#include "libkcal/journal.h"

#include <netwm.h>

using namespace KCal;

void KNotesLegacy::cleanUp()
{
    // remove old (KDE 1.x) local config file if it still exists
    QString configfile = KGlobal::dirs()->saveLocation( "config" ) + "knotesrc";
    KSimpleConfig *test = new KSimpleConfig( configfile );
    test->setGroup( "General" );
    double version = test->readDoubleNumEntry( "version", 1.0 );
    delete test;

    if ( version == 1.0 &&
         !( checkAccess( configfile, W_OK ) &&
            KIO::NetAccess::del( KURL(configfile), 0 ) ) )
    {
        kdError(5500) << k_funcinfo << "Could not delete old config file!" << endl;
    }
}

bool KNotesLegacy::convert( CalendarLocal *calendar )
{
    bool converted = false;

    QDir noteDir( KGlobal::dirs()->saveLocation( "appdata", "notes/" ) );
    QStringList notes = noteDir.entryList( QDir::Files, QDir::Name );
    for ( QStringList::Iterator note = notes.begin(); note != notes.end(); note++ )
    {
        QString file = noteDir.absFilePath( *note );
        KSimpleConfig* test = new KSimpleConfig( file );
        test->setGroup( "General" );
        double version = test->readDoubleNumEntry( "version", 1.0 );

        if ( version < 3.0 )
        {
            delete test;

            // create the new note
            Journal *journal = new Journal();
            bool success;

            if ( version < 2.0 )
                success = convertKNotes1Config( journal, noteDir, *note );
            else
                success = convertKNotes2Config( journal, noteDir, *note );

            // could not convert file => do not add a new note
            if ( !success )
                delete journal;
            else
            {
                calendar->addJournal( journal );
                converted = true;
            }
        }
        // window state changed for version 3.2
        else if ( version < 3.2 )
        {
            uint state = test->readUnsignedLongNumEntry( "state", NET::SkipTaskbar );
            test->writeEntry( "ShowInTaskbar", (state & NET::SkipTaskbar) ? false : true );
            test->writeEntry( "KeepAbove", (state & NET::KeepAbove) ? true : false );
            test->deleteEntry( "state" );
            delete test;
        }
    }

    return converted;
}

bool KNotesLegacy::convertKNotes1Config( Journal *journal, QDir& noteDir,
        const QString& file )
{
    QFile infile( noteDir.absFilePath( file ) );
    if ( !infile.open( IO_ReadOnly ) )
    {
        kdError(5500) << k_funcinfo << "Could not open input file: \""
                      << infile.name() << "\"" << endl;
        return false;
    }

    QTextStream input( &infile );

    // get the name
    journal->setSummary( input.readLine() );

    QStringList props = QStringList::split( '+', input.readLine() );

    // robustness
    if ( props.count() != 13 )
    {
        kdWarning(5500) << k_funcinfo << "The file \"" << infile.name()
                        << "\" lacks version information but is not a valid "
                        << "KNotes 1 config file either!" << endl;
        return false;
    }

    // the new configfile's name
    QString configFile = noteDir.absFilePath( journal->uid() );

    // set the defaults
    KIO::NetAccess::copy(
        KURL( KGlobal::dirs()->saveLocation( "config" ) + "knotesrc" ),
        KURL( configFile ),
        0
    );

    KNoteConfig config( KSharedConfig::openConfig( configFile, false, false ) );
    config.readConfig();
    config.setVersion( KNOTES_VERSION );

    // get the geometry
    config.setWidth( props[3].toUInt() );
    config.setHeight( props[4].toUInt() );

    // get the background color
    uint red = input.readLine().toUInt();
    uint green = input.readLine().toUInt();
    uint blue = input.readLine().toUInt();
    config.setBgColor( QColor( red, green, blue ) );

    // get the foreground color
    red = input.readLine().toUInt();
    green = input.readLine().toUInt();
    blue = input.readLine().toUInt();
    config.setFgColor( QColor( red, green, blue ) );

    // get the font
    QString fontfamily = input.readLine();
    if ( fontfamily.isEmpty() )
        fontfamily = QString( "helvetica" );
    uint size = input.readLine().toUInt();
    size = QMAX( size, 4 );
    uint weight = input.readLine().toUInt();
    bool italic = ( input.readLine().toUInt() == 1 );
    QFont font( fontfamily, size, weight, italic );

    config.setTitleFont( font );
    config.setFont( font );

    // 3d frame? Not supported yet!
    input.readLine();

    // autoindent
    config.setAutoIndent( input.readLine().toUInt() == 1 );

    // KNotes 1 never had rich text
    config.setRichText( false );

    int note_desktop = props[0].toUInt();

    // hidden or on all desktops?
    if ( input.readLine().toUInt() == 1 )
        note_desktop = 0;
    else if ( props[11].toUInt() == 1 )
        note_desktop = NETWinInfo::OnAllDesktops;

    config.setDesktop( note_desktop );
    config.setPosition( QPoint( props[1].toUInt(), props[2].toUInt() ) );
    config.setKeepAbove( props[12].toUInt() & 2048 );

    config.writeConfig();

    // get the text
    QString text;
    while ( !input.atEnd() )
    {
        text.append( input.readLine() );
        if ( !input.atEnd() )
            text.append( '\n' );
    }

    journal->setDescription( text );

    if ( !infile.remove() )
        kdWarning(5500) << k_funcinfo << "Could not delete input file: \"" << infile.name() << "\"" << endl;

    return true;
}

bool KNotesLegacy::convertKNotes2Config( Journal *journal, QDir& noteDir,
        const QString& file )
{
    QString configFile = noteDir.absFilePath( journal->uid() );

    // new name for config file
    if ( !noteDir.rename( file, journal->uid() ) )
    {
        kdError(5500) << k_funcinfo << "Could not rename input file: \""
                      << noteDir.absFilePath( file ) << "\" to \""
                      << configFile << "\"!" << endl;
        return false;
    }

    // update the config
    KConfig config( configFile );
    config.setGroup( "Data" );
    journal->setSummary( config.readEntry( "name" ) );
    config.deleteGroup( "Data", true );
    config.setGroup( "General" );
    config.writeEntry( "version", KNOTES_VERSION );
    config.setGroup( "WindowDisplay" );
    uint state = config.readUnsignedLongNumEntry( "state", NET::SkipTaskbar );
    config.writeEntry( "ShowInTaskbar", (state & NET::SkipTaskbar) ? false : true );
    config.writeEntry( "KeepAbove", (state & NET::KeepAbove) ? true : false );
    config.deleteEntry( "state" );

    // load the saved text and put it in the journal
    QFile infile( noteDir.absFilePath( "." + file + "_data" ) );
    if ( infile.open( IO_ReadOnly ) )
    {
        QTextStream input( &infile );
        input.setEncoding( QTextStream::UnicodeUTF8 );
        journal->setDescription( input.read() );
        if ( !infile.remove() )
            kdWarning(5500) << k_funcinfo << "Could not delete data file: \"" << infile.name() << "\"" << endl;
    }
    else
        kdWarning(5500) << k_funcinfo << "Could not open data file: \"" << infile.name() << "\"" << endl;

    return true;
}
<commit_msg>Don't try to read from, and remove, a file that doesn't exist. This fixes a kdError on knotes startup.<commit_after>/*******************************************************************
 KNotes -- Notes for the KDE project

 Copyright (c) 2002-2004, Michael Brade <brade@kde.org>

 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*******************************************************************/

#include <qfile.h>
#include <qfont.h>
#include <qpoint.h>
#include <qcolor.h>
#include <qstringlist.h>
#include <qtextstream.h>

#include <kdebug.h>
#include <kapplication.h>
#include <kglobal.h>
#include <kurl.h>
#include <kstandarddirs.h>
#include <ksimpleconfig.h>
#include <kio/netaccess.h>

#include <unistd.h>

#include "knoteslegacy.h"
#include "knoteconfig.h"
#include "version.h"

#include "libkcal/calendarlocal.h"
#include "libkcal/journal.h"

#include <netwm.h>

using namespace KCal;

void KNotesLegacy::cleanUp()
{
    // remove old (KDE 1.x) local config file if it still exists
    QString configfile = KGlobal::dirs()->saveLocation( "config" ) + "knotesrc";
    if ( QFile::exists( configfile ) ) {
        KSimpleConfig *test = new KSimpleConfig( configfile );
        test->setGroup( "General" );
        double version = test->readDoubleNumEntry( "version", 1.0 );
        delete test;

        if ( version == 1.0 ) {
            if ( !( checkAccess( configfile, W_OK ) &&
                    QFile::remove( configfile ) ) )
            {
                kdError(5500) << k_funcinfo << "Could not delete old config file " << configfile << endl;
            }
        }
    }
}

bool KNotesLegacy::convert( CalendarLocal *calendar )
{
    bool converted = false;

    QDir noteDir( KGlobal::dirs()->saveLocation( "appdata", "notes/" ) );
    QStringList notes = noteDir.entryList( QDir::Files, QDir::Name );
    for ( QStringList::Iterator note = notes.begin(); note != notes.end(); note++ )
    {
        QString file = noteDir.absFilePath( *note );
        KSimpleConfig* test = new KSimpleConfig( file );
        test->setGroup( "General" );
        double version = test->readDoubleNumEntry( "version", 1.0 );

        if ( version < 3.0 )
        {
            delete test;

            // create the new note
            Journal *journal = new Journal();
            bool success;

            if ( version < 2.0 )
                success = convertKNotes1Config( journal, noteDir, *note );
            else
                success = convertKNotes2Config( journal, noteDir, *note );

            // could not convert file => do not add a new note
            if ( !success )
                delete journal;
            else
            {
                calendar->addJournal( journal );
                converted = true;
            }
        }
        // window state changed for version 3.2
        else if ( version < 3.2 )
        {
            uint state = test->readUnsignedLongNumEntry( "state", NET::SkipTaskbar );
            test->writeEntry( "ShowInTaskbar", (state & NET::SkipTaskbar) ? false : true );
            test->writeEntry( "KeepAbove", (state & NET::KeepAbove) ? true : false );
            test->deleteEntry( "state" );
            delete test;
        }
    }

    return converted;
}

bool KNotesLegacy::convertKNotes1Config( Journal *journal, QDir& noteDir,
        const QString& file )
{
    QFile infile( noteDir.absFilePath( file ) );
    if ( !infile.open( IO_ReadOnly ) )
    {
        kdError(5500) << k_funcinfo << "Could not open input file: \""
                      << infile.name() << "\"" << endl;
        return false;
    }

    QTextStream input( &infile );

    // get the name
    journal->setSummary( input.readLine() );

    QStringList props = QStringList::split( '+', input.readLine() );

    // robustness
    if ( props.count() != 13 )
    {
        kdWarning(5500) << k_funcinfo << "The file \"" << infile.name()
                        << "\" lacks version information but is not a valid "
                        << "KNotes 1 config file either!" << endl;
        return false;
    }

    // the new configfile's name
    QString configFile = noteDir.absFilePath( journal->uid() );

    // set the defaults
    KIO::NetAccess::copy(
        KURL( KGlobal::dirs()->saveLocation( "config" ) + "knotesrc" ),
        KURL( configFile ),
        0
    );

    KNoteConfig config( KSharedConfig::openConfig( configFile, false, false ) );
    config.readConfig();
    config.setVersion( KNOTES_VERSION );

    // get the geometry
    config.setWidth( props[3].toUInt() );
    config.setHeight( props[4].toUInt() );

    // get the background color
    uint red = input.readLine().toUInt();
    uint green = input.readLine().toUInt();
    uint blue = input.readLine().toUInt();
    config.setBgColor( QColor( red, green, blue ) );

    // get the foreground color
    red = input.readLine().toUInt();
    green = input.readLine().toUInt();
    blue = input.readLine().toUInt();
    config.setFgColor( QColor( red, green, blue ) );

    // get the font
    QString fontfamily = input.readLine();
    if ( fontfamily.isEmpty() )
        fontfamily = QString( "helvetica" );
    uint size = input.readLine().toUInt();
    size = QMAX( size, 4 );
    uint weight = input.readLine().toUInt();
    bool italic = ( input.readLine().toUInt() == 1 );
    QFont font( fontfamily, size, weight, italic );

    config.setTitleFont( font );
    config.setFont( font );

    // 3d frame? Not supported yet!
    input.readLine();

    // autoindent
    config.setAutoIndent( input.readLine().toUInt() == 1 );

    // KNotes 1 never had rich text
    config.setRichText( false );

    int note_desktop = props[0].toUInt();

    // hidden or on all desktops?
    if ( input.readLine().toUInt() == 1 )
        note_desktop = 0;
    else if ( props[11].toUInt() == 1 )
        note_desktop = NETWinInfo::OnAllDesktops;

    config.setDesktop( note_desktop );
    config.setPosition( QPoint( props[1].toUInt(), props[2].toUInt() ) );
    config.setKeepAbove( props[12].toUInt() & 2048 );

    config.writeConfig();

    // get the text
    QString text;
    while ( !input.atEnd() )
    {
        text.append( input.readLine() );
        if ( !input.atEnd() )
            text.append( '\n' );
    }

    journal->setDescription( text );

    if ( !infile.remove() )
        kdWarning(5500) << k_funcinfo << "Could not delete input file: \"" << infile.name() << "\"" << endl;

    return true;
}

bool KNotesLegacy::convertKNotes2Config( Journal *journal, QDir& noteDir,
        const QString& file )
{
    QString configFile = noteDir.absFilePath( journal->uid() );

    // new name for config file
    if ( !noteDir.rename( file, journal->uid() ) )
    {
        kdError(5500) << k_funcinfo << "Could not rename input file: \""
                      << noteDir.absFilePath( file ) << "\" to \""
                      << configFile << "\"!" << endl;
        return false;
    }

    // update the config
    KConfig config( configFile );
    config.setGroup( "Data" );
    journal->setSummary( config.readEntry( "name" ) );
    config.deleteGroup( "Data", true );
    config.setGroup( "General" );
    config.writeEntry( "version", KNOTES_VERSION );
    config.setGroup( "WindowDisplay" );
    uint state = config.readUnsignedLongNumEntry( "state", NET::SkipTaskbar );
    config.writeEntry( "ShowInTaskbar", (state & NET::SkipTaskbar) ? false : true );
    config.writeEntry( "KeepAbove", (state & NET::KeepAbove) ? true : false );
    config.deleteEntry( "state" );

    // load the saved text and put it in the journal
    QFile infile( noteDir.absFilePath( "." + file + "_data" ) );
    if ( infile.open( IO_ReadOnly ) )
    {
        QTextStream input( &infile );
        input.setEncoding( QTextStream::UnicodeUTF8 );
        journal->setDescription( input.read() );
        if ( !infile.remove() )
            kdWarning(5500) << k_funcinfo << "Could not delete data file: \"" << infile.name() << "\"" << endl;
    }
    else
        kdWarning(5500) << k_funcinfo << "Could not open data file: \"" << infile.name() << "\"" << endl;

    return true;
}
<|endoftext|>


<commit_before>#include <string>
#include <iostream>
#include <codecvt>
#include <locale>
#include <stdexcept>
#include <iomanip>
#include <ctime>
#include <sstream>

#include <Winsock2.h>
#include <windows.h>

#include "utils_win.h"
#include "logger.h"

using namespace tracker::utils;
using namespace tracker::logger;

class ConslogOutput : public Output {
  void emit(std::wstring log_json) {
    std::wcout << log_json << std::endl;
  }
};

// TODO, error logging
class FluentdUdpOutput : public Output {
public:
  FluentdUdpOutput(): port(20039), host("FLUENTD_HOST_IP_IS_HERE") {
    if (!initWinsock()) {
      throw std::runtime_error("FluentdUdpOutput: Winsock initialize error");
    }
  }

  void emit(std::wstring log_json) {
    std::wstring_convert<std::codecvt_utf8<wchar_t>> utf8_conv;
    send(utf8_conv.to_bytes(log_json + L"\n"));
  }

private:
  bool initWinsock(void) {
    WSADATA wsaData;
    return WSAStartup(MAKEWORD(2, 2), &wsaData) == NO_ERROR;
  }

  void send(std::string &log) {
    SOCKET sendSocket = INVALID_SOCKET;
    sockaddr_in recvAddr;

    sendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sendSocket == INVALID_SOCKET) {
      // std::cout << "create UDP socket error" << std::endl;
      return;
    }

    recvAddr.sin_family = AF_INET;
    recvAddr.sin_port = htons(port);
    recvAddr.sin_addr.s_addr = inet_addr(host.c_str());

    if (sendto(sendSocket, log.c_str(), log.size(), 0, (SOCKADDR *)&recvAddr, sizeof(recvAddr)) == SOCKET_ERROR) {
      // std::cout << "UDP sendto error" << std::endl;
    }

    closesocket(sendSocket);
  }

  int port;
  std::string host;
};

class ActivityLog : public Log {
public:
  ActivityLog(std::wstring &stat,
    std::wstring &activeUsername,
    std::wstring &activeWindowText,
    std::wstring &activeFilename) : status(stat), username(activeUsername),
                                    windowText(activeWindowText), filename(activeFilename), Log(L"activity") {
  }

  std::wstring to_json(void) {
    return std::wstring(L"{")
           + L" \"status\":\"" + status + L"\""
           + L",\"user\":\"" + username + L"\""
           + L",\"window_text\":\"" + windowText + L"\""
           + L",\"filename\":\"" + filename
           + L"\"}";
  }

private:
  std::wstring status;
  std::wstring username;
  std::wstring windowText;
  std::wstring filename;
};

class InternalLog : public Log {
public:
  InternalLog(std::wstring lev, std::wstring msg): Log(L"log"), level(lev), message(msg) { }

  std::wstring to_json(void) {
    return std::wstring(L"{")
           + L" \"timestamp\":\"" + current_time_and_date()
           + L",\"level\":\"" + level
           + L",\"message\":\"" + message
           + L"\"}";
  }

private:
  std::wstring current_time_and_date() {
    std::wstringstream ss;

    std::time_t t = std::time(NULL);
    ss << std::put_time(std::localtime(&t), L"%c");

    return ss.str();
  }

  std::wstring level;
  std::wstring message;
};

class CounterFilter : public Filter {
public:
  CounterFilter(int cnt = 60) : max_count(cnt), count(0) { }

  bool apply(Log *log) {
    count += 1;

    if (count >= max_count) {
      count = 0;
      return true;
    }

    return false;
  }

  void set_max(int cnt) {
    count = 0;
    max_count = cnt;
  }

private:
  int count;
  int max_count;
};

int main(void) {
  Logger logger;

  FluentdUdpOutput fluentd_udp_output;
  logger.route(L"activity", &fluentd_udp_output);

  ConslogOutput consolg_output;
  CounterFilter counter_filter(0);
  consolg_output.withFilter(&counter_filter);
  logger.route(L"log", &consolg_output);

  logger.send(InternalLog(L"INFO", L"starting activity-tracker"));
  counter_filter.set_max(60);
  while(true) {
    HWND activeWindow = GetForegroundWindow();
    DWORD activePID;
    GetWindowThreadProcessId(activeWindow, &activePID);

    std::wstring activeWindowText = getActiveWindowText(activeWindow);
    std::wstring activeFilename = getAcitveFilename(activePID);
    std::wstring activeUsername = getActiveUsername();
    std::wstring status = isIdle() ? L"idle" : L"active";

    logger.send(ActivityLog(status, activeUsername, activeWindowText, activeFilename));
    logger.send(InternalLog(L"INFO", L"activity-tracker is running..."));

    Sleep(1000);
  }
}

<commit_msg>fix(typo): add missing closing quotation<commit_after>#include <string>
#include <iostream>
#include <codecvt>
#include <locale>
#include <stdexcept>
#include <iomanip>
#include <ctime>
#include <sstream>

#include <Winsock2.h>
#include <windows.h>

#include "utils_win.h"
#include "logger.h"

using namespace tracker::utils;
using namespace tracker::logger;

class ConslogOutput : public Output {
  void emit(std::wstring log_json) {
    std::wcout << log_json << std::endl;
  }
};

// TODO, error logging
class FluentdUdpOutput : public Output {
public:
  FluentdUdpOutput(): port(20039), host("FLUENTD_HOST_IP_IS_HERE") {
    if (!initWinsock()) {
      throw std::runtime_error("FluentdUdpOutput: Winsock initialize error");
    }
  }

  void emit(std::wstring log_json) {
    std::wstring_convert<std::codecvt_utf8<wchar_t>> utf8_conv;
    send(utf8_conv.to_bytes(log_json + L"\n"));
  }

private:
  bool initWinsock(void) {
    WSADATA wsaData;
    return WSAStartup(MAKEWORD(2, 2), &wsaData) == NO_ERROR;
  }

  void send(std::string &log) {
    SOCKET sendSocket = INVALID_SOCKET;
    sockaddr_in recvAddr;

    sendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sendSocket == INVALID_SOCKET) {
      // std::cout << "create UDP socket error" << std::endl;
      return;
    }

    recvAddr.sin_family = AF_INET;
    recvAddr.sin_port = htons(port);
    recvAddr.sin_addr.s_addr = inet_addr(host.c_str());

    if (sendto(sendSocket, log.c_str(), log.size(), 0, (SOCKADDR *)&recvAddr, sizeof(recvAddr)) == SOCKET_ERROR) {
      // std::cout << "UDP sendto error" << std::endl;
    }

    closesocket(sendSocket);
  }

  int port;
  std::string host;
};

class ActivityLog : public Log {
public:
  ActivityLog(std::wstring &stat,
    std::wstring &activeUsername,
    std::wstring &activeWindowText,
    std::wstring &activeFilename) : status(stat), username(activeUsername),
                                    windowText(activeWindowText), filename(activeFilename), Log(L"activity") {
  }

  std::wstring to_json(void) {
    return std::wstring(L"{")
           + L" \"status\":\"" + status + L"\""
           + L",\"user\":\"" + username + L"\""
           + L",\"window_text\":\"" + windowText + L"\""
           + L",\"filename\":\"" + filename
           + L"\"}";
  }

private:
  std::wstring status;
  std::wstring username;
  std::wstring windowText;
  std::wstring filename;
};

class InternalLog : public Log {
public:
  InternalLog(std::wstring lev, std::wstring msg): Log(L"log"), level(lev), message(msg) { }

  std::wstring to_json(void) {
    return std::wstring(L"{")
           + L" \"timestamp\":\"" + current_time_and_date() + L"\""
           + L",\"level\":\"" + level + L"\""
           + L",\"message\":\"" + message
           + L"\"}";
  }

private:
  std::wstring current_time_and_date() {
    std::wstringstream ss;

    std::time_t t = std::time(NULL);
    ss << std::put_time(std::localtime(&t), L"%c");

    return ss.str();
  }

  std::wstring level;
  std::wstring message;
};

class CounterFilter : public Filter {
public:
  CounterFilter(int cnt = 60) : max_count(cnt), count(0) { }

  bool apply(Log *log) {
    count += 1;

    if (count >= max_count) {
      count = 0;
      return true;
    }

    return false;
  }

  void set_max(int cnt) {
    count = 0;
    max_count = cnt;
  }

private:
  int count;
  int max_count;
};

int main(void) {
  Logger logger;

  FluentdUdpOutput fluentd_udp_output;
  logger.route(L"activity", &fluentd_udp_output);

  ConslogOutput consolg_output;
  CounterFilter counter_filter(0);
  consolg_output.withFilter(&counter_filter);
  logger.route(L"log", &consolg_output);

  logger.send(InternalLog(L"INFO", L"starting activity-tracker"));
  counter_filter.set_max(60);
  while(true) {
    HWND activeWindow = GetForegroundWindow();
    DWORD activePID;
    GetWindowThreadProcessId(activeWindow, &activePID);

    std::wstring activeWindowText = getActiveWindowText(activeWindow);
    std::wstring activeFilename = getAcitveFilename(activePID);
    std::wstring activeUsername = getActiveUsername();
    std::wstring status = isIdle() ? L"idle" : L"active";

    logger.send(ActivityLog(status, activeUsername, activeWindowText, activeFilename));
    logger.send(InternalLog(L"INFO", L"activity-tracker is running..."));

    Sleep(1000);
  }
}

<|endoftext|>


<commit_before>#include "palabos3D.h"
#include "palabos3D.hh"
#include <vector>
#include <cmath>
#include <time.h>
#include <cfloat>

using namespace plb;
using namespace plb::descriptors;
using namespace std;

typedef double T;
typedef Array<T,3> Velocity;
#define DESCRIPTOR MRTD3Q19Descriptor
typedef MRTdynamics<T,DESCRIPTOR> BackgroundDynamics;
typedef AnechoicMRTdynamics<T,DESCRIPTOR> AnechoicBackgroundDynamics;

// ---------------------------------------------
// Includes of acoustics resources
#include "acoustics/acoustics3D.h"
using namespace plb_acoustics_3D;
// ---------------------------------------------

int main(int argc, char **argv){
    plbInit(&argc, &argv);

    const T rho0 = 1;
    const T drho = rho0/100;
    const plint radius = 20;
    const plint diameter = 2*radius;
    const plint nx = 6*diameter + 60;
    //const plint nx = 2*diameter + 60;
    const plint ny = 6*diameter + 60;
    //const plint ny = 2*diameter + 60;
    const plint position_duct_z = 0;
    //const plint length_duct = 0.5*(30 + 120 + 5*113 + 3*diameter);
    const plint length_duct = 3*(3*diameter);
    //const plint length_duct = 3*diameter;
    const plint nz = length_duct + 3*diameter + 30;
    //const plint nz = length_duct + 3*diameter + 30;
    const T lattice_speed_sound = 1/sqrt(3);
    const T omega = 1.985;
    const plint maxT = 1*(pow(2,13) + nz*sqrt(3));
    Array<T,3> u0(0, 0, 0);
    const Array<plint,3> position(nx/2, ny/2, position_duct_z);
    const plint thickness_duct = 2;
    const plint radius_intern = radius - 2;
    const plint maxT_final_source = maxT - nz*sqrt(3);
    const T ka_max = 2.5;
    const T ka_min = 0;
    const T cs2 = lattice_speed_sound*lattice_speed_sound;
    clock_t t;

    // Saving a propery directory
    std::string fNameOut = currentDateTime() + "+tmp";
    std::string command = "mkdir -p " + fNameOut;
    char to_char_command[1024];
    strcpy(to_char_command, command.c_str());
    system(to_char_command);
    std::string command_copy_script_matlab = "cp duct_radiation.m " + fNameOut;
    char to_char_command_copy_script_matlab[1024];
    strcpy(to_char_command_copy_script_matlab, command_copy_script_matlab.c_str());
    system(to_char_command_copy_script_matlab);
    global::directories().setOutputDir(fNameOut+"/");

    // Setting anechoic dynamics like this way
    MultiBlockLattice3D<T, DESCRIPTOR> lattice(nx, ny, nz,  new AnechoicBackgroundDynamics(omega));
    defineDynamics(lattice, lattice.getBoundingBox(), new BackgroundDynamics(omega));

    pcout << "Creation of the lattice. Time max: " << maxT << endl;
    pcout << "Duct radius: " << radius << endl;

    pcout << getMultiBlockInfo(lattice) << std::endl;

    // Switch off periodicity.
    lattice.periodicity().toggleAll(false);

    pcout << "Initilization of rho and u." << endl;
    initializeAtEquilibrium(lattice, lattice.getBoundingBox(), rho0 , u0);

    // Set NoDynamics to improve performance!
    plint off_set_z = position_duct_z + length_duct - 3*diameter - 30;
    set_nodynamics(lattice, nx, ny, off_set_z);

    T rhoBar_target = 0;
    //const T mach_number = 0.2;
    const T mach_number = 0;
    const T velocity_flow = mach_number*lattice_speed_sound;
    Array<T,3> j_target(0, 0, 0);
    T size_anechoic_buffer = 30;
    defineAnechoicMRTBoards_limited(nx, ny, nz, lattice, size_anechoic_buffer,
      omega, j_target, j_target, j_target, j_target, j_target, j_target,
      rhoBar_target, off_set_z);

    //const T mach_number = 0;
    build_duct(lattice, nx, ny, position, radius, length_duct, thickness_duct, omega);

    lattice.initialize();

    pcout << std::endl << "Voxelizing the domain." << std::endl;

    pcout << "Simulation begins" << endl;

    // Setting probes ------------------------------------------
    plint begin_microphone = length_duct/2;
    System_Abom_Measurement system_abom_measurement(lattice, position,
        begin_microphone, length_duct, radius, fNameOut);

    plint double_microphone_distance = 5;

    plint distance_boca = 0*radius;
    string name_boca = "boca";
    Two_Microphones two_microphones_boca(radius, double_microphone_distance,
            length_duct, position, fNameOut, name_boca, distance_boca, nx, ny, nz);

    plint distance_1r = 1*radius;
    string name_1r = "1r";
    Two_Microphones two_microphones_1r(radius, double_microphone_distance,
            length_duct, position, fNameOut, name_1r, distance_1r, nx, ny, nz);

    plint distance_2r = 2*radius;
    string name_2r = "2r";
    Two_Microphones two_microphones_2r(radius, double_microphone_distance,
            length_duct, position, fNameOut, name_2r, distance_2r, nx, ny, nz);

    plint distance_3r = 3*radius;
    string name_3r = "3r";
    Two_Microphones two_microphones_3r(radius, double_microphone_distance,
            length_duct, position, fNameOut, name_3r, distance_3r, nx, ny, nz);

    plint distance_6r = length_duct - 100;
    string name_6r = "listening";
    Two_Microphones two_microphones_6r(radius, double_microphone_distance,
            length_duct, position, fNameOut, name_6r, distance_6r, nx, ny, nz);

    // Setting probes to evaluate coefficient reflection of ABC
    Array<plint,3> position_A(nx/2, ny/2, nz - 30);
    Array<plint,3> position_B(nx/2, ny - 30, nz - 30);
    Array<plint,3> position_C(nx/2, ny - 30, nz/2);
    Array<plint,3> position_D(nx/2, 0.75*ny, length_duct + 31);
    string name_abc = "abc";
    Coefficient_Reflection_Probes coefficient_reflection_probes(position_A,
    position_B, position_C, position_D, fNameOut, name_abc);

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

    // Recording entering signal -------------------------------
    std::string signal_in_string = fNameOut+"/signal_in.dat";
    char to_char_signal_in[1024];
    strcpy(to_char_signal_in, signal_in_string.c_str());
    plb_ofstream history_signal_in(to_char_signal_in);
    // ---------------------------------------------------------

    // Important information about simulation ------------------
    t = clock();
    std::string AllSimulationInfo_string = fNameOut + "/AllSimulationInfo.txt";
    char to_char_AllSimulationInfo[1024];
    strcpy(to_char_AllSimulationInfo, AllSimulationInfo_string.c_str());
    plb_ofstream AllSimulationInfo(to_char_AllSimulationInfo);

    std::string title = "\nVALIDANDO LS PARA DEIXAR O CODIGO ENXUTO.\n";

    AllSimulationInfo << endl
    << title << endl
    << "Dados da simulação" << endl
    << "Lattice:" << endl << endl
    << "nx: " << nx << " ny: " << ny << " nz: " << nz << endl
    << " omega: " << omega << endl << endl
    << "Tempos: " << endl
    << "Total Time step: " << maxT << endl
    << "Raio do duto: " << radius << endl
    << "Espessura: " << thickness_duct << endl
    << "Tamanho duto: " << length_duct << endl
    << "Posicao do duto: " << position[2] << endl
    << "Começo dos microfones em lattice: " << begin_microphone << endl;
    // --------------------------------------------------------

    // Mean for-loop
    for (plint iT=0; iT<maxT; ++iT){
        if (iT <= maxT_final_source /*&& iT > maxT/2*/){
            plint total_signals = 20;
	        T chirp_hand = get_linear_chirp_AZ(ka_max,  total_signals, maxT_final_source, iT - maxT/2, drho, radius);
            //T chirp_hand = get_linear_chirp(ka_min, ka_max, maxT_final_source, iT, drho, radius);
            //T rho_changing = 1. + drho*sin(2*M_PI*(lattice_speed_sound/20)*iT);
            history_signal_in << setprecision(10) << chirp_hand << endl;
            Array<T,3> j_target(0, 0, velocity_flow);
            set_source(lattice, position, chirp_hand, j_target, radius, radius_intern, nx, ny);
        }else{
            Array<T,3> j_target(0, 0, velocity_flow);
            set_source(lattice, position, rho0, j_target, radius, radius_intern, nx, ny);
        }

        if (iT % 50 == 0) {
            pcout << "Iteration " << iT << endl;
             pcout << " energy ="
            << setprecision(10) << getStoredAverageEnergy<T>(lattice)
            << " rho ="
            << getStoredAverageDensity<T>(lattice)
            << " max_velocity ="
            << setprecision(10) << (getStoredMaxVelocity<T>(lattice))/lattice_speed_sound
            << endl;
        }

        if (iT == (maxT/2) + (maxT/4)) {
            //writeGifs(lattice,iT);
            //writeVTK(lattice, iT, rho0, drho);
        }

        if (iT%50 == 0) {
            //writeGifs(lattice,iT);
            writeVTK(lattice, iT, rho0, drho);
        }

        // extract values of pressure and velocities
        system_abom_measurement.save_point(lattice, rho0, cs2);
        two_microphones_1r.save_point(lattice, rho0, cs2);
        two_microphones_2r.save_point(lattice, rho0, cs2);
        two_microphones_3r.save_point(lattice, rho0, cs2);
        two_microphones_6r.save_point(lattice, rho0, cs2);
        two_microphones_boca.save_point(lattice, rho0, cs2);
        coefficient_reflection_probes.save_point(lattice, rho0, cs2);

        lattice.collideAndStream();
    }

    t = (clock() - t)/CLOCKS_PER_SEC;
    AllSimulationInfo << endl << "Execution time: " << t << " segundos" << endl;

    pcout << "End of simulation at iteration " << endl;
}
<commit_msg>now with 4.5 of size of duct<commit_after>#include "palabos3D.h"
#include "palabos3D.hh"
#include <vector>
#include <cmath>
#include <time.h>
#include <cfloat>

using namespace plb;
using namespace plb::descriptors;
using namespace std;

typedef double T;
typedef Array<T,3> Velocity;
#define DESCRIPTOR MRTD3Q19Descriptor
typedef MRTdynamics<T,DESCRIPTOR> BackgroundDynamics;
typedef AnechoicMRTdynamics<T,DESCRIPTOR> AnechoicBackgroundDynamics;

// ---------------------------------------------
// Includes of acoustics resources
#include "acoustics/acoustics3D.h"
using namespace plb_acoustics_3D;
// ---------------------------------------------

int main(int argc, char **argv){
    plbInit(&argc, &argv);

    const T rho0 = 1;
    const T drho = rho0/100;
    const plint radius = 20;
    const plint diameter = 2*radius;
    const plint nx = 6*diameter + 60;
    //const plint nx = 2*diameter + 60;
    const plint ny = 6*diameter + 60;
    //const plint ny = 2*diameter + 60;
    const plint position_duct_z = 0;
    //const plint length_duct = 0.5*(30 + 120 + 5*113 + 3*diameter);
    const plint length_duct = 1.5*(3*diameter);
    //const plint length_duct = 3*diameter;
    const plint nz = length_duct + 3*diameter + 30;
    //const plint nz = length_duct + 3*diameter + 30;
    const T lattice_speed_sound = 1/sqrt(3);
    const T omega = 1.985;
    const plint maxT = 1*(pow(2,13) + nz*sqrt(3));
    Array<T,3> u0(0, 0, 0);
    const Array<plint,3> position(nx/2, ny/2, position_duct_z);
    const plint thickness_duct = 2;
    const plint radius_intern = radius - 2;
    const plint maxT_final_source = maxT - nz*sqrt(3);
    const T ka_max = 2.5;
    const T ka_min = 0;
    const T cs2 = lattice_speed_sound*lattice_speed_sound;
    clock_t t;

    // Saving a propery directory
    std::string fNameOut = currentDateTime() + "+tmp";
    std::string command = "mkdir -p " + fNameOut;
    char to_char_command[1024];
    strcpy(to_char_command, command.c_str());
    system(to_char_command);
    std::string command_copy_script_matlab = "cp duct_radiation.m " + fNameOut;
    char to_char_command_copy_script_matlab[1024];
    strcpy(to_char_command_copy_script_matlab, command_copy_script_matlab.c_str());
    system(to_char_command_copy_script_matlab);
    global::directories().setOutputDir(fNameOut+"/");

    // Setting anechoic dynamics like this way
    MultiBlockLattice3D<T, DESCRIPTOR> lattice(nx, ny, nz,  new AnechoicBackgroundDynamics(omega));
    defineDynamics(lattice, lattice.getBoundingBox(), new BackgroundDynamics(omega));

    pcout << "Creation of the lattice. Time max: " << maxT << endl;
    pcout << "Duct radius: " << radius << endl;

    pcout << getMultiBlockInfo(lattice) << std::endl;

    // Switch off periodicity.
    lattice.periodicity().toggleAll(false);

    pcout << "Initilization of rho and u." << endl;
    initializeAtEquilibrium(lattice, lattice.getBoundingBox(), rho0 , u0);

    // Set NoDynamics to improve performance!
    plint off_set_z = position_duct_z + length_duct - 3*diameter - 30;
    set_nodynamics(lattice, nx, ny, off_set_z);

    T rhoBar_target = 0;
    //const T mach_number = 0.2;
    const T mach_number = 0;
    const T velocity_flow = mach_number*lattice_speed_sound;
    Array<T,3> j_target(0, 0, 0);
    T size_anechoic_buffer = 30;
    defineAnechoicMRTBoards_limited(nx, ny, nz, lattice, size_anechoic_buffer,
      omega, j_target, j_target, j_target, j_target, j_target, j_target,
      rhoBar_target, off_set_z);

    //const T mach_number = 0;
    build_duct(lattice, nx, ny, position, radius, length_duct, thickness_duct, omega);

    lattice.initialize();

    pcout << std::endl << "Voxelizing the domain." << std::endl;

    pcout << "Simulation begins" << endl;

    // Setting probes ------------------------------------------
    plint begin_microphone = length_duct/2;
    System_Abom_Measurement system_abom_measurement(lattice, position,
        begin_microphone, length_duct, radius, fNameOut);

    plint double_microphone_distance = 5;

    plint distance_boca = 0*radius;
    string name_boca = "boca";
    Two_Microphones two_microphones_boca(radius, double_microphone_distance,
            length_duct, position, fNameOut, name_boca, distance_boca, nx, ny, nz);

    plint distance_1r = 1*radius;
    string name_1r = "1r";
    Two_Microphones two_microphones_1r(radius, double_microphone_distance,
            length_duct, position, fNameOut, name_1r, distance_1r, nx, ny, nz);

    plint distance_2r = 2*radius;
    string name_2r = "2r";
    Two_Microphones two_microphones_2r(radius, double_microphone_distance,
            length_duct, position, fNameOut, name_2r, distance_2r, nx, ny, nz);

    plint distance_3r = 3*radius;
    string name_3r = "3r";
    Two_Microphones two_microphones_3r(radius, double_microphone_distance,
            length_duct, position, fNameOut, name_3r, distance_3r, nx, ny, nz);

    plint distance_6r = length_duct - 100;
    string name_6r = "listening";
    Two_Microphones two_microphones_6r(radius, double_microphone_distance,
            length_duct, position, fNameOut, name_6r, distance_6r, nx, ny, nz);

    // Setting probes to evaluate coefficient reflection of ABC
    Array<plint,3> position_A(nx/2, ny/2, nz - 30);
    Array<plint,3> position_B(nx/2, ny - 30, nz - 30);
    Array<plint,3> position_C(nx/2, ny - 30, nz/2);
    Array<plint,3> position_D(nx/2, 0.75*ny, length_duct + 31);
    string name_abc = "abc";
    Coefficient_Reflection_Probes coefficient_reflection_probes(position_A,
    position_B, position_C, position_D, fNameOut, name_abc);

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

    // Recording entering signal -------------------------------
    std::string signal_in_string = fNameOut+"/signal_in.dat";
    char to_char_signal_in[1024];
    strcpy(to_char_signal_in, signal_in_string.c_str());
    plb_ofstream history_signal_in(to_char_signal_in);
    // ---------------------------------------------------------

    // Important information about simulation ------------------
    t = clock();
    std::string AllSimulationInfo_string = fNameOut + "/AllSimulationInfo.txt";
    char to_char_AllSimulationInfo[1024];
    strcpy(to_char_AllSimulationInfo, AllSimulationInfo_string.c_str());
    plb_ofstream AllSimulationInfo(to_char_AllSimulationInfo);

    std::string title = "\nVALIDANDO LS PARA DEIXAR O CODIGO ENXUTO.\n";

    AllSimulationInfo << endl
    << title << endl
    << "Dados da simulação" << endl
    << "Lattice:" << endl << endl
    << "nx: " << nx << " ny: " << ny << " nz: " << nz << endl
    << " omega: " << omega << endl << endl
    << "Tempos: " << endl
    << "Total Time step: " << maxT << endl
    << "Raio do duto: " << radius << endl
    << "Espessura: " << thickness_duct << endl
    << "Tamanho duto: " << length_duct << endl
    << "Posicao do duto: " << position[2] << endl
    << "Começo dos microfones em lattice: " << begin_microphone << endl;
    // --------------------------------------------------------

    // Mean for-loop
    for (plint iT=0; iT<maxT; ++iT){
        if (iT <= maxT_final_source /*&& iT > maxT/2*/){
            plint total_signals = 20;
	        T chirp_hand = get_linear_chirp_AZ(ka_max,  total_signals, maxT_final_source, iT - maxT/2, drho, radius);
            //T chirp_hand = get_linear_chirp(ka_min, ka_max, maxT_final_source, iT, drho, radius);
            //T rho_changing = 1. + drho*sin(2*M_PI*(lattice_speed_sound/20)*iT);
            history_signal_in << setprecision(10) << chirp_hand << endl;
            Array<T,3> j_target(0, 0, velocity_flow);
            set_source(lattice, position, chirp_hand, j_target, radius, radius_intern, nx, ny);
        }else{
            Array<T,3> j_target(0, 0, velocity_flow);
            set_source(lattice, position, rho0, j_target, radius, radius_intern, nx, ny);
        }

        if (iT % 50 == 0) {
            pcout << "Iteration " << iT << endl;
             pcout << " energy ="
            << setprecision(10) << getStoredAverageEnergy<T>(lattice)
            << " rho ="
            << getStoredAverageDensity<T>(lattice)
            << " max_velocity ="
            << setprecision(10) << (getStoredMaxVelocity<T>(lattice))/lattice_speed_sound
            << endl;
        }

        if (iT == (maxT/2) + (maxT/4)) {
            //writeGifs(lattice,iT);
            //writeVTK(lattice, iT, rho0, drho);
        }

        if (iT%50 == 0) {
            //writeGifs(lattice,iT);
            writeVTK(lattice, iT, rho0, drho);
        }

        // extract values of pressure and velocities
        system_abom_measurement.save_point(lattice, rho0, cs2);
        two_microphones_1r.save_point(lattice, rho0, cs2);
        two_microphones_2r.save_point(lattice, rho0, cs2);
        two_microphones_3r.save_point(lattice, rho0, cs2);
        two_microphones_6r.save_point(lattice, rho0, cs2);
        two_microphones_boca.save_point(lattice, rho0, cs2);
        coefficient_reflection_probes.save_point(lattice, rho0, cs2);

        lattice.collideAndStream();
    }

    t = (clock() - t)/CLOCKS_PER_SEC;
    AllSimulationInfo << endl << "Execution time: " << t << " segundos" << endl;

    pcout << "End of simulation at iteration " << endl;
}
<|endoftext|>


<commit_before><commit_msg>Revert r22555, "Linux: make gfx::Canvas honor GTK font settings."<commit_after><|endoftext|>


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

#include "taskpane/TaskPaneTreeNode.hxx"

#include "taskpane/ControlContainer.hxx"
#include "taskpane/TitledControl.hxx"

#include <vector>
#include <algorithm>

namespace sd { namespace toolpanel {

TreeNode::TreeNode (
    TreeNode* pParent)
    : mpParent (pParent),
      mpControlContainer (new ControlContainer(this)),
      maStateChangeListeners()
{
}

TreeNode::~TreeNode (void)
{
}

bool TreeNode::IsLeaf (void)
{
    return (mpControlContainer.get()==NULL);
}

bool TreeNode::IsRoot (void)
{
    return (mpParent==NULL);
}

void TreeNode::SetParentNode (TreeNode* pNewParent)
{
    mpParent = pNewParent;
    GetWindow()->SetParent (pNewParent->GetWindow());
}

TreeNode* TreeNode::GetParentNode (void)
{
    return mpParent;
}

::Window* TreeNode::GetWindow (void)
{
    return NULL;
}

const ::Window* TreeNode::GetConstWindow (void) const
{
    return const_cast<TreeNode*>(this)->GetWindow();
}

sal_Int32 TreeNode::GetMinimumWidth (void)
{
    sal_Int32 nTotalMinimumWidth = 0;
    unsigned int nCount = mpControlContainer->GetControlCount();
    for (unsigned int nIndex=0; nIndex<nCount; nIndex++)
    {
        TreeNode* pChild = mpControlContainer->GetControl (nIndex);
        sal_Int32 nMinimumWidth = pChild->GetMinimumWidth ();
        if (nMinimumWidth > nTotalMinimumWidth)
            nTotalMinimumWidth = nMinimumWidth;
    }

    return nTotalMinimumWidth;;
}

ObjectBarManager* TreeNode::GetObjectBarManager (void)
{
    if (mpParent != NULL)
        return mpParent->GetObjectBarManager();
    else
        return NULL;
}

bool TreeNode::IsResizable (void)
{
    return false;
}

void TreeNode::RequestResize (void)
{
    if (mpParent != NULL)
        mpParent->RequestResize();
}

ControlContainer& TreeNode::GetControlContainer (void)
{
    return *mpControlContainer.get();
}

bool TreeNode::Expand (bool bExpansionState)
{
    bool bExpansionStateChanged (false);

    if (IsExpandable() && IsExpanded()!=bExpansionState)
    {
        if (bExpansionState)
            GetWindow()->Show();
        else
            GetWindow()->Hide();
        bExpansionStateChanged = true;

        FireStateChangeEvent (EID_EXPANSION_STATE_CHANGED);
    }

    return bExpansionStateChanged;
}

bool TreeNode::IsExpanded (void) const
{
    if (GetConstWindow()!=NULL)
        return GetConstWindow()->IsVisible();
    else
        return false;
}

bool TreeNode::IsExpandable (void) const
{
    return GetConstWindow()!=NULL;
}

void TreeNode::Show (bool bExpansionState)
{
    if (GetWindow() != NULL)
    {
        bool bWasShowing (IsShowing());
        GetWindow()->Show (bExpansionState);
        if (bWasShowing != bExpansionState)
            FireStateChangeEvent (EID_SHOWING_STATE_CHANGED);
    }
}

bool TreeNode::IsShowing (void) const
{
    const ::Window* pWindow = const_cast<TreeNode*>(this)->GetWindow();
    if (pWindow != NULL)
        return pWindow->IsVisible();
    else
        return false;
}

TaskPaneShellManager* TreeNode::GetShellManager (void)
{
    if (mpParent != NULL)
        return mpParent->GetShellManager();
    else
        return NULL;
}

::com::sun::star::uno::Reference<
    ::com::sun::star::accessibility::XAccessible> TreeNode::GetAccessibleObject (void)
{
    ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible> xAccessible;
    ::Window* pWindow = GetWindow();
    if (pWindow != NULL)
    {
        xAccessible = pWindow->GetAccessible(FALSE);
        if ( ! xAccessible.is())
        {
            ::com::sun::star::uno::Reference<
                ::com::sun::star::accessibility::XAccessible> xParent;
            if (pWindow!=NULL && pWindow->GetAccessibleParentWindow()!=NULL)
                xParent = pWindow->GetAccessibleParentWindow()->GetAccessible();
            xAccessible = CreateAccessibleObject(xParent);
            pWindow->SetAccessible(xAccessible);
        }
    }
    return xAccessible;
}

::com::sun::star::uno::Reference<
    ::com::sun::star::accessibility::XAccessible> TreeNode::CreateAccessibleObject (
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>& rxParent)
{
    if (GetWindow() != NULL)
        return GetWindow()->CreateAccessible();
    else
        return NULL;
}

void TreeNode::AddStateChangeListener (const Link& rListener)
{
    if (::std::find (
        maStateChangeListeners.begin(),
        maStateChangeListeners.end(),
        rListener) == maStateChangeListeners.end())
    {
        maStateChangeListeners.push_back(rListener);
    }
}

void TreeNode::RemoveStateChangeListener (const Link& rListener)
{
    maStateChangeListeners.erase (
        ::std::find (
            maStateChangeListeners.begin(),
            maStateChangeListeners.end(),
            rListener));
}

void TreeNode::FireStateChangeEvent (
    TreeNodeStateChangeEventId eEventId,
    TreeNode* pChild) const
{
    TreeNodeStateChangeEvent aEvent (*this, eEventId, pChild);
    StateChangeListenerContainer aContainerCopy(maStateChangeListeners);
    StateChangeListenerContainer::iterator aLink (aContainerCopy.begin());
    StateChangeListenerContainer::iterator aEnd (aContainerCopy.end());
    while (aLink!=aEnd)
    {
        aLink->Call (&aEvent);
        ++aLink;
    }
}

TreeNodeStateChangeEvent::TreeNodeStateChangeEvent (
    const TreeNode& rNode,
    TreeNodeStateChangeEventId eEventId,
    TreeNode* pChild)
    : mrSource(rNode),
      meEventId(eEventId),
      mpChild(pChild)
{
}

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

#include "taskpane/TaskPaneTreeNode.hxx"

#include "taskpane/ControlContainer.hxx"
#include "taskpane/TitledControl.hxx"

#include <vector>
#include <algorithm>

namespace sd { namespace toolpanel {

TreeNode::TreeNode (
    TreeNode* pParent)
    : mpParent (pParent),
      mpControlContainer (new ControlContainer(this)),
      maStateChangeListeners()
{
}

TreeNode::~TreeNode (void)
{
}

bool TreeNode::IsLeaf (void)
{
    return (mpControlContainer.get()==NULL);
}

bool TreeNode::IsRoot (void)
{
    return (mpParent==NULL);
}

void TreeNode::SetParentNode (TreeNode* pNewParent)
{
    mpParent = pNewParent;
    GetWindow()->SetParent (pNewParent->GetWindow());
}

TreeNode* TreeNode::GetParentNode (void)
{
    return mpParent;
}

::Window* TreeNode::GetWindow (void)
{
    return NULL;
}

const ::Window* TreeNode::GetConstWindow (void) const
{
    return const_cast<TreeNode*>(this)->GetWindow();
}

sal_Int32 TreeNode::GetMinimumWidth (void)
{
    sal_Int32 nTotalMinimumWidth = 0;
    unsigned int nCount = mpControlContainer->GetControlCount();
    for (unsigned int nIndex=0; nIndex<nCount; nIndex++)
    {
        TreeNode* pChild = mpControlContainer->GetControl (nIndex);
        sal_Int32 nMinimumWidth = pChild->GetMinimumWidth ();
        if (nMinimumWidth > nTotalMinimumWidth)
            nTotalMinimumWidth = nMinimumWidth;
    }

    return nTotalMinimumWidth;;
}

ObjectBarManager* TreeNode::GetObjectBarManager (void)
{
    if (mpParent != NULL)
        return mpParent->GetObjectBarManager();
    else
        return NULL;
}

bool TreeNode::IsResizable (void)
{
    return false;
}

void TreeNode::RequestResize (void)
{
    if (mpParent != NULL)
        mpParent->RequestResize();
}

ControlContainer& TreeNode::GetControlContainer (void)
{
    return *mpControlContainer.get();
}

bool TreeNode::Expand (bool bExpansionState)
{
    bool bExpansionStateChanged (false);

    if (IsExpandable() && IsExpanded()!=bExpansionState)
    {
        if (bExpansionState)
            GetWindow()->Show();
        else
            GetWindow()->Hide();
        bExpansionStateChanged = true;

        FireStateChangeEvent (EID_EXPANSION_STATE_CHANGED);
    }

    return bExpansionStateChanged;
}

bool TreeNode::IsExpanded (void) const
{
    if (GetConstWindow()!=NULL)
        return GetConstWindow()->IsVisible();
    else
        return false;
}

bool TreeNode::IsExpandable (void) const
{
    return GetConstWindow()!=NULL;
}

void TreeNode::Show (bool bExpansionState)
{
    if (GetWindow() != NULL)
    {
        bool bWasShowing (IsShowing());
        GetWindow()->Show (bExpansionState);
        if (bWasShowing != bExpansionState)
            FireStateChangeEvent (EID_SHOWING_STATE_CHANGED);
    }
}

bool TreeNode::IsShowing (void) const
{
    const ::Window* pWindow = const_cast<TreeNode*>(this)->GetWindow();
    if (pWindow != NULL)
        return pWindow->IsVisible();
    else
        return false;
}

TaskPaneShellManager* TreeNode::GetShellManager (void)
{
    if (mpParent != NULL)
        return mpParent->GetShellManager();
    else
        return NULL;
}

::com::sun::star::uno::Reference<
    ::com::sun::star::accessibility::XAccessible> TreeNode::GetAccessibleObject (void)
{
    ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible> xAccessible;
    ::Window* pWindow = GetWindow();
    if (pWindow != NULL)
    {
        xAccessible = pWindow->GetAccessible(FALSE);
        if ( ! xAccessible.is())
        {
            ::com::sun::star::uno::Reference<
                ::com::sun::star::accessibility::XAccessible> xParent;
            if (pWindow!=NULL && pWindow->GetAccessibleParentWindow()!=NULL)
                xParent = pWindow->GetAccessibleParentWindow()->GetAccessible();
            xAccessible = CreateAccessibleObject(xParent);
            pWindow->SetAccessible(xAccessible);
        }
    }
    return xAccessible;
}

::com::sun::star::uno::Reference<
    ::com::sun::star::accessibility::XAccessible> TreeNode::CreateAccessibleObject (
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>& rxParent)
{
    if (GetWindow() != NULL)
        return GetWindow()->CreateAccessible();
    else
        return NULL;
}

void TreeNode::AddStateChangeListener (const Link& rListener)
{
    if (::std::find (
        maStateChangeListeners.begin(),
        maStateChangeListeners.end(),
        rListener) == maStateChangeListeners.end())
    {
        maStateChangeListeners.push_back(rListener);
    }
}

void TreeNode::RemoveStateChangeListener (const Link& rListener)
{
    maStateChangeListeners.erase (
        ::std::find (
            maStateChangeListeners.begin(),
            maStateChangeListeners.end(),
            rListener));
}

void TreeNode::FireStateChangeEvent (
    TreeNodeStateChangeEventId eEventId,
    TreeNode* pChild) const
{
    TreeNodeStateChangeEvent aEvent (*this, eEventId, pChild);
    StateChangeListenerContainer aContainerCopy(maStateChangeListeners);
    StateChangeListenerContainer::iterator aLink (aContainerCopy.begin());
    StateChangeListenerContainer::iterator aEnd (aContainerCopy.end());
    while (aLink!=aEnd)
    {
        aLink->Call (&aEvent);
        ++aLink;
    }
}

TreeNodeStateChangeEvent::TreeNodeStateChangeEvent (
    const TreeNode& rNode,
    TreeNodeStateChangeEventId eEventId,
    TreeNode* pChild)
    : mrSource(rNode),
      meEventId(eEventId),
      mpChild(pChild)
{
}

} } // end of namespace ::sd::toolpanel
<|endoftext|>


<commit_before>/*
 *---------------------------------------------------------------------------*
 *
 * Copyright (c) 2000, Johan Bengtsson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 *---------------------------------------------------------------------------*/

#define _USE_BSD

#include <sys/time.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>

#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <signal.h>

#include <errno.h>

#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/filestream.h"

#include "machdep.h"
#ifdef LINUX
#include "linux.h"
#endif
#ifdef sunos5
#include "sunos5.h"
#endif
#ifdef MACOSX
#include "macosx.h"
#endif

#define CAN_USE_RLIMIT_RSS
#define CAN_USE_RLIMIT_CPU
#define USLEEP_USECS 10000

int main (int argc, char *argv[] )
{
     struct rusage kid_usage;
     pid_t  kid;
     int    kid_status;
     int    exit_status = EXIT_SUCCESS;
     int    i, opt, echo_args = 0, exit_flag;
     long   sample_time=0, time = 0, track_time = 0;
     char   *jsonOutput = 0;

     long maxkbytes=0; //kilobytes
     long maxseconds=0; //seconds
     long maxmillis=0;

     //unsigned long start, end;
     int max_samples = 80;

     memtime_info_tracker info_tracker(max_samples);

     if (argc < 2) {
	  char *tmp = strrchr(argv[0], '/');
	  tmp = (tmp ? tmp + 1 : argv[0]);

	  fprintf(stderr,
		  "%s: usage %s [ -o JSON_output_file ] [-t <interval>] [-e] [-m <maxkilobytes>] [-c <maxcpuseconds>] <cmd> [<params>]\n",
		  tmp,tmp);
	  exit(EXIT_FAILURE);
     }

     while ((opt = getopt(argc, argv, "+eo:t:m:c:")) != -1) {

	  switch (opt) {
          case 'o' :
               jsonOutput=optarg;
               break;

	  case 'e' :
	       echo_args = 1;
	       break;

	  case 't' :
	       errno = 0;
	       sample_time = strtol(optarg, NULL, 0);
	       if (errno) {
		    perror("Illegal argument to t option");
		    exit(EXIT_FAILURE);
	       }
	       break;
	  case 'm' :
	       errno = 0;
	       maxkbytes = atoi(optarg);
	       if (errno) {
		    perror("Illegal argument to m option");
		    exit(EXIT_FAILURE);
	       }
	       break;

	  case 'c' :
	       errno = 0;
	       maxseconds = atoi(optarg);
	       if (errno) {
		    perror("Illegal argument to c option");
		    exit(EXIT_FAILURE);
	       }
		  maxmillis=1000*maxseconds;
	       break;

	  }
     }

     if (echo_args) {
	  fprintf(stderr,"Command line: ");
	  for (i = optind; i < argc; i++)
	       fprintf(stderr,"%s ", argv[i]);
	  fprintf(stderr,"\n");
     }

     struct memtime_info info, final_info;
     info_tracker.track(final_info); // start the timer

     memtime_limit lim;
     memtime_fork f;

     switch (kid = f.native_fork()) {

     case -1 :
	  perror("fork failed");
	  exit(EXIT_FAILURE);

     case 0 :
#if defined(CAN_USE_RLIMIT_RSS)
	  if (maxkbytes>0) {
	       lim.set_mem_limit((long)maxkbytes*1024);
	  }
#endif
#if defined(CAN_USE_RLIMIT_CPU)
	  if (maxseconds>0) {
	       lim.set_cpu_limit((long)maxseconds);
	  }
#endif
	  execvp(argv[optind], &(argv[optind]));
	  perror("exec failed");
	  exit(EXIT_FAILURE);

     default :
	  break;
     }

     try {
       process_tracker tracker(kid);

     do {

	  if ((track_time++ & 0x3f) == 0) {
	    info = tracker.get_sample();
            info_tracker.track(info);

	     if (sample_time) {
	       time++;
	       if (time == 10 * sample_time) {

		    fprintf(stderr,"%.2f user, %.2f system, %.2f elapsed"
			    " -- VSize = %ldKB, RSS = %ldKB\n",
			    (double)info.utime_ms/1000.0,
			    (double)info.stime_ms/1000.0,
			    (double)(info_tracker.get_walltime_ms())/1000.0,
			    info.vsize_kb, info.rss_kb);
		    fflush(stdout);

		    time = 1;
	       }
            }
#if !defined(CAN_USE_RLIMIT_RSS)
	    if ((maxkbytes > 0) && (info.vsize_kb > maxkbytes)) {
	  	kill(kid,SIGTERM);
	    }
#endif
#if !defined(CAN_USE_RLIMIT_CPU)
	    if ((maxmillis > 0) && (info.utime_ms > maxmillis)) {
	  	kill(kid,SIGTERM);
	    }
#endif
	  }

	  if (usleep(USLEEP_USECS) != 0)
              fprintf(stderr, "Could not usleep(USLEEP_USECS)\n");

	  exit_flag = ((wait4(kid, &kid_status, WNOHANG, &kid_usage) == kid)
		       && (WIFEXITED(kid_status) || WIFSIGNALED(kid_status)));

     } while (!exit_flag);

     info_tracker.set_end(final_info);

     if (WIFEXITED(kid_status)) {
	  fprintf(stderr, "Exit [%d]\n", WEXITSTATUS(kid_status));
          exit_status += WEXITSTATUS(kid_status);
     } else {
	  fprintf(stderr, "Killed [%d]\n", WTERMSIG(kid_status));
          exit_status += WTERMSIG(kid_status);
     }

     {
	  double kid_utime = ((double)kid_usage.ru_utime.tv_sec
			      + (double)kid_usage.ru_utime.tv_usec / 1E6);
	  double kid_stime = ((double)kid_usage.ru_stime.tv_sec
			      + (double)kid_usage.ru_stime.tv_usec / 1E6);

          info_tracker.set_times(kid_utime * 1000.0, kid_stime * 1000.0);

	  fprintf(stderr, "%.2f user, %.2f system, %.2f elapsed -- "
		  "Max VSize = %ldKB, Max RSS = %ldKB\n",
		  kid_utime, kid_stime, (double)(final_info.get_walltime_ms()) / 1000.0,
		  info_tracker.get_max_vmem(), info_tracker.get_max_rss());

          if (jsonOutput != 0) {

	  rapidjson::Document report;
          char *realPath = NULL, tmpPath[4096];
	  if (report.Parse<0>("{}").HasParseError() != 0)
	    printf("Error!\n");
	    assert(report.IsObject());
            {
                realPath = realpath(argv[optind], tmpPath);
                if (realPath == NULL) {
                    report.AddMember("program", argv[optind], report.GetAllocator());
                } else {
	            report.AddMember("program", realPath, report.GetAllocator());
                }
            }

	    rapidjson::Value args;
	    args.SetArray();
	    args.Reserve(argc-optind, report.GetAllocator());
	    for(int i=optind+1 ; i < argc ; i++) {
	      args.PushBack(argv[i], report.GetAllocator());
	    }
	    report.AddMember("arguments", args, report.GetAllocator());
	    report.AddMember("exit_status", exit_status, report.GetAllocator());
            memtime_info final_usage = info_tracker.get_final_info();

	    //report.AddMember("utime", kid_utime, report.GetAllocator());
	    //report.AddMember("stime", kid_stime, report.GetAllocator());
	    //report.AddMember("max_vmem_kb", (int64_t) info_tracker.get_max_vmem(), report.GetAllocator());
	    //report.AddMember("max_rss_kb", (int64_t) info_tracker.get_max_rss(), report.GetAllocator());
	    report.AddMember("start_time", (int64_t) final_info.start_ms/1000, report.GetAllocator());
	    report.AddMember("wall_time", (double) (final_info.end_ms - final_info.start_ms)/1000.0, report.GetAllocator());

            info_tracker.get_final_info().getJSON("usage", report);

            FILE *fp = fopen(jsonOutput, "w");
            if (fp != 0) {
	      rapidjson::FileStream f(fp);
              rapidjson::PrettyWriter<rapidjson::FileStream> writer(f);
              report.Accept(writer);        // Accept() traverses the DOM and generates Handler events.
              fclose(fp);
            }
            //if (realPath != NULL) free(realPath);

          }

     }

     } catch (...) {
          perror("Abnormal termination of memtime\n");
     }

     exit(exit_status);
}

<commit_msg>added -q quiet flag<commit_after>/*
 *---------------------------------------------------------------------------*
 *
 * Copyright (c) 2000, Johan Bengtsson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 *---------------------------------------------------------------------------*/

#define _USE_BSD

#include <sys/time.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>

#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <signal.h>

#include <errno.h>

#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/filestream.h"

#include "machdep.h"
#ifdef LINUX
#include "linux.h"
#endif
#ifdef sunos5
#include "sunos5.h"
#endif
#ifdef MACOSX
#include "macosx.h"
#endif

#define CAN_USE_RLIMIT_RSS
#define CAN_USE_RLIMIT_CPU
#define USLEEP_USECS 10000

int main (int argc, char *argv[] )
{
     struct rusage kid_usage;
     pid_t  kid;
     int    kid_status;
     int    exit_status = EXIT_SUCCESS;
     int    i, opt, echo_args = 0, quiet = 0, exit_flag;
     long   sample_time=0, time = 0, track_time = 0;
     char   *jsonOutput = 0;

     long maxkbytes=0; //kilobytes
     long maxseconds=0; //seconds
     long maxmillis=0;

     //unsigned long start, end;
     int max_samples = 80;

     memtime_info_tracker info_tracker(max_samples);

     if (argc < 2) {
	  char *tmp = strrchr(argv[0], '/');
	  tmp = (tmp ? tmp + 1 : argv[0]);

	  fprintf(stderr,
		  "%s: usage %s [ -o JSON_output_file ] [-t <interval>] [-q] [-e] [-m <maxkilobytes>] [-c <maxcpuseconds>] <cmd> [<params>]\n",
		  tmp,tmp);
	  exit(EXIT_FAILURE);
     }

     while ((opt = getopt(argc, argv, "+eqo:t:m:c:")) != -1) {

	  switch (opt) {
          case 'o' :
               jsonOutput=optarg;
               break;

	  case 'e' :
	       echo_args = 1;
	       break;

          case 'q' :
               quiet = 1;
               break;

	  case 't' :
	       errno = 0;
	       sample_time = strtol(optarg, NULL, 0);
	       if (errno) {
		    perror("Illegal argument to t option");
		    exit(EXIT_FAILURE);
	       }
	       break;
	  case 'm' :
	       errno = 0;
	       maxkbytes = atoi(optarg);
	       if (errno) {
		    perror("Illegal argument to m option");
		    exit(EXIT_FAILURE);
	       }
	       break;

	  case 'c' :
	       errno = 0;
	       maxseconds = atoi(optarg);
	       if (errno) {
		    perror("Illegal argument to c option");
		    exit(EXIT_FAILURE);
	       }
		  maxmillis=1000*maxseconds;
	       break;

	  }
     }

     if (echo_args && quiet == 0) {
	  fprintf(stderr,"Command line: ");
	  for (i = optind; i < argc; i++)
	       fprintf(stderr,"%s ", argv[i]);
	  fprintf(stderr,"\n");
     }

     struct memtime_info info, final_info;
     info_tracker.track(final_info); // start the timer

     memtime_limit lim;
     memtime_fork f;

     switch (kid = f.native_fork()) {

     case -1 :
	  perror("fork failed");
	  exit(EXIT_FAILURE);

     case 0 :
#if defined(CAN_USE_RLIMIT_RSS)
	  if (maxkbytes>0) {
	       lim.set_mem_limit((long)maxkbytes*1024);
	  }
#endif
#if defined(CAN_USE_RLIMIT_CPU)
	  if (maxseconds>0) {
	       lim.set_cpu_limit((long)maxseconds);
	  }
#endif
	  execvp(argv[optind], &(argv[optind]));
	  perror("exec failed");
	  exit(EXIT_FAILURE);

     default :
	  break;
     }

     try {
       process_tracker tracker(kid);

     do {

	  if ((track_time++ & 0x3f) == 0) {
	    info = tracker.get_sample();
            info_tracker.track(info);

	     if (sample_time) {
	       time++;
	       if (time == 10 * sample_time) {

                    if (quiet == 0)
		        fprintf(stderr,"%.2f user, %.2f system, %.2f elapsed"
			    " -- VSize = %ldKB, RSS = %ldKB\n",
			    (double)info.utime_ms/1000.0,
			    (double)info.stime_ms/1000.0,
			    (double)(info_tracker.get_walltime_ms())/1000.0,
			    info.vsize_kb, info.rss_kb);
		    fflush(stdout);

		    time = 1;
	       }
            }
#if !defined(CAN_USE_RLIMIT_RSS)
	    if ((maxkbytes > 0) && (info.vsize_kb > maxkbytes)) {
	  	kill(kid,SIGTERM);
	    }
#endif
#if !defined(CAN_USE_RLIMIT_CPU)
	    if ((maxmillis > 0) && (info.utime_ms > maxmillis)) {
	  	kill(kid,SIGTERM);
	    }
#endif
	  }

	  if (usleep(USLEEP_USECS) != 0 && quiet == 0)
              fprintf(stderr, "Could not usleep(USLEEP_USECS)\n");

	  exit_flag = ((wait4(kid, &kid_status, WNOHANG, &kid_usage) == kid)
		       && (WIFEXITED(kid_status) || WIFSIGNALED(kid_status)));

     } while (!exit_flag);

     info_tracker.set_end(final_info);

     if (WIFEXITED(kid_status)) {
          if (quiet == 0)
	      fprintf(stderr, "Exit [%d]\n", WEXITSTATUS(kid_status));
          exit_status += WEXITSTATUS(kid_status);
     } else {
          if (quiet == 0)
	      fprintf(stderr, "Killed [%d]\n", WTERMSIG(kid_status));
          exit_status += WTERMSIG(kid_status);
     }

     {
	  double kid_utime = ((double)kid_usage.ru_utime.tv_sec
			      + (double)kid_usage.ru_utime.tv_usec / 1E6);
	  double kid_stime = ((double)kid_usage.ru_stime.tv_sec
			      + (double)kid_usage.ru_stime.tv_usec / 1E6);

          info_tracker.set_times(kid_utime * 1000.0, kid_stime * 1000.0);

          if (quiet == 0)
	      fprintf(stderr, "%.2f user, %.2f system, %.2f elapsed -- "
		  "Max VSize = %ldKB, Max RSS = %ldKB\n",
		  kid_utime, kid_stime, (double)(final_info.get_walltime_ms()) / 1000.0,
		  info_tracker.get_max_vmem(), info_tracker.get_max_rss());

          if (jsonOutput != 0) {

	  rapidjson::Document report;
          char *realPath = NULL, tmpPath[4096];
	  if (report.Parse<0>("{}").HasParseError() != 0)
	    printf("Error!\n");
	    assert(report.IsObject());
            {
                realPath = realpath(argv[optind], tmpPath);
                if (realPath == NULL) {
                    report.AddMember("program", argv[optind], report.GetAllocator());
                } else {
	            report.AddMember("program", realPath, report.GetAllocator());
                }
            }

	    rapidjson::Value args;
	    args.SetArray();
	    args.Reserve(argc-optind, report.GetAllocator());
	    for(int i=optind+1 ; i < argc ; i++) {
	      args.PushBack(argv[i], report.GetAllocator());
	    }
	    report.AddMember("arguments", args, report.GetAllocator());
	    report.AddMember("exit_status", exit_status, report.GetAllocator());
            memtime_info final_usage = info_tracker.get_final_info();

	    //report.AddMember("utime", kid_utime, report.GetAllocator());
	    //report.AddMember("stime", kid_stime, report.GetAllocator());
	    //report.AddMember("max_vmem_kb", (int64_t) info_tracker.get_max_vmem(), report.GetAllocator());
	    //report.AddMember("max_rss_kb", (int64_t) info_tracker.get_max_rss(), report.GetAllocator());
	    report.AddMember("start_time", (int64_t) final_info.start_ms/1000, report.GetAllocator());
	    report.AddMember("wall_time", (double) (final_info.end_ms - final_info.start_ms)/1000.0, report.GetAllocator());

            info_tracker.get_final_info().getJSON("usage", report);

            FILE *fp = fopen(jsonOutput, "w");
            if (fp != 0) {
	      rapidjson::FileStream f(fp);
              rapidjson::PrettyWriter<rapidjson::FileStream> writer(f);
              report.Accept(writer);        // Accept() traverses the DOM and generates Handler events.
              fclose(fp);
            }
            //if (realPath != NULL) free(realPath);

          }

     }

     } catch (...) {
          perror("Abnormal termination of memtime\n");
     }

     exit(exit_status);
}

<|endoftext|>