<commit_before>//
//  Created by 乔磊 on 15/10/21.
//  Copyright (c) 2015年 乔磊. All rights reserved.
//

#include <NSolver/Parameters/StabilizationParameters.h>

namespace NSFEMSolver
{
  namespace Parameters
  {
    using namespace dealii;

    template <int dim>
    void StabilizationParameters<dim>::declare_parameters (ParameterHandler &prm)
    {
      prm.enter_subsection ("stabilization parameters");
      {
        prm.declare_entry ("diffusion type", "cell size",
                           Patterns::Anything(),
                           "How to calculate diffusion");

        prm.declare_entry ("diffusion power", "2.0",
                           Patterns::Double(),
                           "power of mesh size for diffusion");

        prm.declare_entry ("diffusion coefficient", "1.0",
                           Patterns::Double(),
                           "predefined diffusion coefficient");
        prm.declare_entry ("entropy visc cE", "1.0",
                           Patterns::Double (0.0),
                           "Scale factor on entropy viscosity");
        prm.declare_entry ("entropy visc cLinear", "0.25",
                           Patterns::Double (0.0),
                           "Scale factor on linear limit of entropy viscosity");
        prm.declare_entry ("entropy use global h min", "false",
                           Patterns::Bool(),
                           "Use global minimum cell size for entropy viscosity");

        prm.declare_entry ("continuation type", "time",
                           Patterns::Anything(),
                           "continuation type");

        prm.declare_entry ("switch threshold","10.0",
                           Patterns::Double(),
                           "Ratio threshold to switch from laplacian to time continuation");

        prm.declare_entry ("Laplacian continuation", "-1.0",
                           Patterns::Double(),
                           "Coefficient for Laplacian continuation");
        prm.declare_entry ("enable partial laplacian", "false",
                           Patterns::Bool(),
                           "Enable partial laplacian");
        prm.declare_entry ("dodge mesh adaptation", "false",
                           Patterns::Bool(),
                           "Avoid doing mesh refinement and decreasing Laplacian continuation on same time step.");
        prm.declare_entry ("Laplacian zero", "1e-9",
                           Patterns::Double(),
                           "Threshold of Laplacian Coefficient to be force to zero");
        prm.declare_entry ("Laplacian Newton tolerance", "0.1",
                           Patterns::Double (0.0),
                           "Threshold of Laplacian Coefficient to be force to zero");
        prm.declare_entry ("Laplacian Newton quadratic", "1.5",
                           Patterns::Double (0.0),
                           "Threshold of Newton convergence rate to be recognized as quadratic convergence.");
        prm.declare_entry ("Laplacian decrease rate", "1.5",
                           Patterns::Double (1.0),
                           "Laplacian decrease rate.");

        prm.declare_entry ("SUPG factor", "-1.0",
                           Patterns::Double(),
                           "SUPG stabilization factor.");

        for (unsigned int di=0; di<EquationComponents<dim>::n_components; ++di)
          {
            prm.declare_entry ("diffusion factor for w_" + Utilities::int_to_string (di),
                               "1.0",
                               Patterns::Double (0),
                               "diffusion factor for component w_" + Utilities::int_to_string (di));
          }
      }
      prm.leave_subsection();
      return;
    }

    template <int dim>
    void StabilizationParameters<dim>::parse_parameters (ParameterHandler &prm)
    {
      prm.enter_subsection ("stabilization parameters");
      {
        {
          const std::string prm_buf = prm.get ("diffusion type");
          if (prm_buf == "entropy")
            {
              diffusion_type = diffu_entropy;
            }
          else if (prm_buf == "entropy_DRB")
            {
              diffusion_type = diffu_entropy_DRB;
            }
          else if (prm_buf == "cell size")
            {
              diffusion_type = diffu_cell_size;
            }
          else if (prm_buf == "const")
            {
              diffusion_type = diffu_const;
            }
          else
            {
              AssertThrow (false, ExcNotImplemented());
            }
        }
        diffusion_power = prm.get_double ("diffusion power");
        diffusion_coefficoent = prm.get_double ("diffusion coefficient");
        entropy_visc_cE = prm.get_double ("entropy visc cE");
        entropy_visc_cLinear = prm.get_double ("entropy visc cLinear");
        entropy_use_global_h_min = prm.get_bool ("entropy use global h min");

        {
          const std::string prm_buf = prm.get ("continuation type");
          if (prm_buf == "timeCFL")
            {
              continuation_type = CT_timeCFL;
            }
          else if (prm_buf == "time")
            {
              continuation_type = CT_time;
            }
          else if (prm_buf == "laplacian")
            {
              continuation_type = CT_laplacian;
            }
          else if (prm_buf == "switch")
            {
              continuation_type = CT_switch;
            }
          else if (prm_buf == "alternative")
            {
              continuation_type = CT_alternative;
            }
          else if (prm_buf == "blend")
            {
              continuation_type = CT_blend;
            }
          else
            {
              AssertThrow (false, ExcNotImplemented());
            }
        }

        continuation_switch_threshold = prm.get_double ("switch threshold");

        laplacian_continuation = prm.get_double ("Laplacian continuation");
        enable_partial_laplacian = prm.get_bool ("enable partial laplacian");
        dodge_mesh_adaptation = prm.get_bool ("dodge mesh adaptation");
        laplacian_zero = prm.get_double ("Laplacian zero");
        laplacian_newton_quadratic = prm.get_double ("Laplacian Newton quadratic");
        laplacian_newton_tolerance = prm.get_double ("Laplacian Newton tolerance");
        laplacian_decrease_rate = prm.get_double ("Laplacian decrease rate");

        for (unsigned int di=0; di<EquationComponents<dim>::n_components; ++di)
          {
            diffusion_factor[di] = prm.get_double ("diffusion factor for w_"
                                                   + Utilities::int_to_string (di));
          }

        SUPG_factor = prm.get_double ("SUPG factor");
      }
      prm.leave_subsection();
      return;
    }

    template struct StabilizationParameters<2>;
    template struct StabilizationParameters<3>;
  }
}
<commit_msg>PT_BCR: change default continuation type to timeCFL for backward compatibility<commit_after>//
//  Created by 乔磊 on 15/10/21.
//  Copyright (c) 2015年 乔磊. All rights reserved.
//

#include <NSolver/Parameters/StabilizationParameters.h>

namespace NSFEMSolver
{
  namespace Parameters
  {
    using namespace dealii;

    template <int dim>
    void StabilizationParameters<dim>::declare_parameters (ParameterHandler &prm)
    {
      prm.enter_subsection ("stabilization parameters");
      {
        prm.declare_entry ("diffusion type", "cell size",
                           Patterns::Anything(),
                           "How to calculate diffusion");

        prm.declare_entry ("diffusion power", "2.0",
                           Patterns::Double(),
                           "power of mesh size for diffusion");

        prm.declare_entry ("diffusion coefficient", "1.0",
                           Patterns::Double(),
                           "predefined diffusion coefficient");
        prm.declare_entry ("entropy visc cE", "1.0",
                           Patterns::Double (0.0),
                           "Scale factor on entropy viscosity");
        prm.declare_entry ("entropy visc cLinear", "0.25",
                           Patterns::Double (0.0),
                           "Scale factor on linear limit of entropy viscosity");
        prm.declare_entry ("entropy use global h min", "false",
                           Patterns::Bool(),
                           "Use global minimum cell size for entropy viscosity");

        prm.declare_entry ("continuation type", "timeCFL",
                           Patterns::Anything(),
                           "continuation type");

        prm.declare_entry ("switch threshold","10.0",
                           Patterns::Double(),
                           "Ratio threshold to switch from laplacian to time continuation");

        prm.declare_entry ("Laplacian continuation", "-1.0",
                           Patterns::Double(),
                           "Coefficient for Laplacian continuation");
        prm.declare_entry ("enable partial laplacian", "false",
                           Patterns::Bool(),
                           "Enable partial laplacian");
        prm.declare_entry ("dodge mesh adaptation", "false",
                           Patterns::Bool(),
                           "Avoid doing mesh refinement and decreasing Laplacian continuation on same time step.");
        prm.declare_entry ("Laplacian zero", "1e-9",
                           Patterns::Double(),
                           "Threshold of Laplacian Coefficient to be force to zero");
        prm.declare_entry ("Laplacian Newton tolerance", "0.1",
                           Patterns::Double (0.0),
                           "Threshold of Laplacian Coefficient to be force to zero");
        prm.declare_entry ("Laplacian Newton quadratic", "1.5",
                           Patterns::Double (0.0),
                           "Threshold of Newton convergence rate to be recognized as quadratic convergence.");
        prm.declare_entry ("Laplacian decrease rate", "1.5",
                           Patterns::Double (1.0),
                           "Laplacian decrease rate.");

        prm.declare_entry ("SUPG factor", "-1.0",
                           Patterns::Double(),
                           "SUPG stabilization factor.");

        for (unsigned int di=0; di<EquationComponents<dim>::n_components; ++di)
          {
            prm.declare_entry ("diffusion factor for w_" + Utilities::int_to_string (di),
                               "1.0",
                               Patterns::Double (0),
                               "diffusion factor for component w_" + Utilities::int_to_string (di));
          }
      }
      prm.leave_subsection();
      return;
    }

    template <int dim>
    void StabilizationParameters<dim>::parse_parameters (ParameterHandler &prm)
    {
      prm.enter_subsection ("stabilization parameters");
      {
        {
          const std::string prm_buf = prm.get ("diffusion type");
          if (prm_buf == "entropy")
            {
              diffusion_type = diffu_entropy;
            }
          else if (prm_buf == "entropy_DRB")
            {
              diffusion_type = diffu_entropy_DRB;
            }
          else if (prm_buf == "cell size")
            {
              diffusion_type = diffu_cell_size;
            }
          else if (prm_buf == "const")
            {
              diffusion_type = diffu_const;
            }
          else
            {
              AssertThrow (false, ExcNotImplemented());
            }
        }
        diffusion_power = prm.get_double ("diffusion power");
        diffusion_coefficoent = prm.get_double ("diffusion coefficient");
        entropy_visc_cE = prm.get_double ("entropy visc cE");
        entropy_visc_cLinear = prm.get_double ("entropy visc cLinear");
        entropy_use_global_h_min = prm.get_bool ("entropy use global h min");

        {
          const std::string prm_buf = prm.get ("continuation type");
          if (prm_buf == "timeCFL")
            {
              continuation_type = CT_timeCFL;
            }
          else if (prm_buf == "time")
            {
              continuation_type = CT_time;
            }
          else if (prm_buf == "laplacian")
            {
              continuation_type = CT_laplacian;
            }
          else if (prm_buf == "switch")
            {
              continuation_type = CT_switch;
            }
          else if (prm_buf == "alternative")
            {
              continuation_type = CT_alternative;
            }
          else if (prm_buf == "blend")
            {
              continuation_type = CT_blend;
            }
          else
            {
              AssertThrow (false, ExcNotImplemented());
            }
        }

        continuation_switch_threshold = prm.get_double ("switch threshold");

        laplacian_continuation = prm.get_double ("Laplacian continuation");
        enable_partial_laplacian = prm.get_bool ("enable partial laplacian");
        dodge_mesh_adaptation = prm.get_bool ("dodge mesh adaptation");
        laplacian_zero = prm.get_double ("Laplacian zero");
        laplacian_newton_quadratic = prm.get_double ("Laplacian Newton quadratic");
        laplacian_newton_tolerance = prm.get_double ("Laplacian Newton tolerance");
        laplacian_decrease_rate = prm.get_double ("Laplacian decrease rate");

        for (unsigned int di=0; di<EquationComponents<dim>::n_components; ++di)
          {
            diffusion_factor[di] = prm.get_double ("diffusion factor for w_"
                                                   + Utilities::int_to_string (di));
          }

        SUPG_factor = prm.get_double ("SUPG factor");
      }
      prm.leave_subsection();
      return;
    }

    template struct StabilizationParameters<2>;
    template struct StabilizationParameters<3>;
  }
}
<|endoftext|>


<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2014 Sanjiban Bairagya <sanjiban22393@gmail.com>
//

#include "PlaybackAnimatedUpdateItem.h"
#include "GeoDataTypes.h"

#include <QString>

namespace Marble
{
PlaybackAnimatedUpdateItem::PlaybackAnimatedUpdateItem( const GeoDataAnimatedUpdate* animatedUpdate )
{
    m_animatedUpdate = animatedUpdate;
}

const GeoDataAnimatedUpdate* PlaybackAnimatedUpdateItem::animatedUpdate() const
{
    return m_animatedUpdate;
}

double PlaybackAnimatedUpdateItem::duration() const
{
    return m_animatedUpdate->duration();
}

void PlaybackAnimatedUpdateItem::play()
{
    if ( m_animatedUpdate->update() ) {
        QVector<GeoDataPlacemark*> placemarkList = m_animatedUpdate->update()->change()->placemarkList();
        for( int i = 0; i < placemarkList.size(); i++ ){
            GeoDataPlacemark* placemark = placemarkList.at( i );
            QString targetId = placemark->targetId();
            if( placemark->isBalloonVisible() ){
                GeoDataDocument* document = rootDocument( placemark );
                GeoDataPlacemark* placemarkFromDocument = findPlacemark( document, targetId );
                if( placemarkFromDocument ){
                    emit balloonShown( placemarkFromDocument );
                }
            } else {
                emit balloonHidden();
            }
        }
    }
}

GeoDataPlacemark* PlaybackAnimatedUpdateItem::findPlacemark( GeoDataFeature* feature, const QString& targetId ) const
{
    if ( feature && feature->nodeType() == GeoDataTypes::GeoDataPlacemarkType ) {
        if( static_cast<GeoDataPlacemark*>( feature )->id() == targetId ){
            return static_cast<GeoDataPlacemark*>( feature );
        }
    }

    GeoDataContainer *container = dynamic_cast<GeoDataContainer*>( feature );
    if ( container ){
        QVector<GeoDataFeature*>::Iterator end = container->end();
        QVector<GeoDataFeature*>::Iterator iter = container->begin();
        for( ; iter != end; ++iter ){
            GeoDataPlacemark *placemark = findPlacemark( *iter, targetId );
            if ( placemark ) {
                return placemark;
            }
        }
    }
    return 0;
}

GeoDataDocument* PlaybackAnimatedUpdateItem::rootDocument( GeoDataObject* object ) const
{
    if( !object || !object->parent() ){
        GeoDataDocument* document = dynamic_cast<GeoDataDocument*>( object );
        return document;
    } else {
        return rootDocument( object->parent() );
    }
    return 0;
}

void PlaybackAnimatedUpdateItem::pause()
{
    //do nothing
}

void PlaybackAnimatedUpdateItem::seek( double position )
{
    Q_UNUSED( position );
    //do nothing
}

void PlaybackAnimatedUpdateItem::stop()
{
    //do nothing
}

}

#include "PlaybackAnimatedUpdateItem.moc"
<commit_msg>Don't crash when an update has no change<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2014 Sanjiban Bairagya <sanjiban22393@gmail.com>
//

#include "PlaybackAnimatedUpdateItem.h"
#include "GeoDataTypes.h"

#include <QString>

namespace Marble
{
PlaybackAnimatedUpdateItem::PlaybackAnimatedUpdateItem( const GeoDataAnimatedUpdate* animatedUpdate )
{
    m_animatedUpdate = animatedUpdate;
}

const GeoDataAnimatedUpdate* PlaybackAnimatedUpdateItem::animatedUpdate() const
{
    return m_animatedUpdate;
}

double PlaybackAnimatedUpdateItem::duration() const
{
    return m_animatedUpdate->duration();
}

void PlaybackAnimatedUpdateItem::play()
{
    if ( m_animatedUpdate->update() && m_animatedUpdate->update()->change() ) {
        QVector<GeoDataPlacemark*> placemarkList = m_animatedUpdate->update()->change()->placemarkList();
        for( int i = 0; i < placemarkList.size(); i++ ){
            GeoDataPlacemark* placemark = placemarkList.at( i );
            QString targetId = placemark->targetId();
            if( placemark->isBalloonVisible() ){
                GeoDataDocument* document = rootDocument( placemark );
                GeoDataPlacemark* placemarkFromDocument = findPlacemark( document, targetId );
                if( placemarkFromDocument ){
                    emit balloonShown( placemarkFromDocument );
                }
            } else {
                emit balloonHidden();
            }
        }
    }
}

GeoDataPlacemark* PlaybackAnimatedUpdateItem::findPlacemark( GeoDataFeature* feature, const QString& targetId ) const
{
    if ( feature && feature->nodeType() == GeoDataTypes::GeoDataPlacemarkType ) {
        if( static_cast<GeoDataPlacemark*>( feature )->id() == targetId ){
            return static_cast<GeoDataPlacemark*>( feature );
        }
    }

    GeoDataContainer *container = dynamic_cast<GeoDataContainer*>( feature );
    if ( container ){
        QVector<GeoDataFeature*>::Iterator end = container->end();
        QVector<GeoDataFeature*>::Iterator iter = container->begin();
        for( ; iter != end; ++iter ){
            GeoDataPlacemark *placemark = findPlacemark( *iter, targetId );
            if ( placemark ) {
                return placemark;
            }
        }
    }
    return 0;
}

GeoDataDocument* PlaybackAnimatedUpdateItem::rootDocument( GeoDataObject* object ) const
{
    if( !object || !object->parent() ){
        GeoDataDocument* document = dynamic_cast<GeoDataDocument*>( object );
        return document;
    } else {
        return rootDocument( object->parent() );
    }
    return 0;
}

void PlaybackAnimatedUpdateItem::pause()
{
    //do nothing
}

void PlaybackAnimatedUpdateItem::seek( double position )
{
    Q_UNUSED( position );
    //do nothing
}

void PlaybackAnimatedUpdateItem::stop()
{
    //do nothing
}

}

#include "PlaybackAnimatedUpdateItem.moc"
<|endoftext|>


<commit_before>/* -*- mode: C; c-basic-offset: 4 -*- */
#ident "Copyright (c) 2007 Tokutek Inc.  All rights reserved."

/* try a reverse compare function to verify that the database always uses the application's
   compare function */

#include <arpa/inet.h>
#include <assert.h>
#include <db_cxx.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#define DIR "dir_test_reverse_compare_fun"
#include "test.h"

int keycompare (const void *key1, unsigned int key1len, const void *key2, unsigned int key2len) {
    if (key1len==key2len) {
	return memcmp(key1,key2,key1len);
    } else if (key1len<key2len) {
	int r = memcmp(key1,key2,key1len);
	if (r<=0) return -1; /* If the keys are the same up to 1's length, then return -1, since key1 is shorter than key2. */
	else return 1;
    } else {
	return -keycompare(key2,key2len,key1,key1len);
    }
}

int reverse_compare(Db *db __attribute__((__unused__)), const Dbt *a, const Dbt*b) {
    return -keycompare(a->get_data(), a->get_size(), b->get_data(), b->get_size());
}

void expect(Dbc *cursor, int k, int v) {
    Dbt key; key.set_flags(DB_DBT_MALLOC);
    Dbt val; val.set_flags(DB_DBT_MALLOC);
    int r = cursor->get(&key, &val, DB_NEXT);
    CKERR(r);
    assert(key.get_size() == sizeof k);
    int kk;
    memcpy(&kk, key.get_data(), key.get_size());
    assert(val.get_size() == sizeof v);
    int vv;
    memcpy(&vv, val.get_data(), val.get_size());
    if (kk != k || vv != v) printf("expect key %d got %d - %d %d\n", htonl(k), htonl(kk), htonl(v), htonl(vv));
    assert(kk == k);
    assert(vv == v);

    free(key.get_data());
    free(val.get_data());
}

void test_reverse_compare(int n, int dup_flags) {
    if (verbose) printf("test_reverse_compare:%d %d\n", n, dup_flags);

    DbEnv * const null_env = 0;
    Db *db;
    DbTxn * const null_txn = 0;
    const char * const fname = DIR "/reverse.compare.db";

    int r;
    int i;

    system("rm -rf " DIR);
    mkdir(DIR, 0777);

    /* create the dup database file */
    db = new Db(null_env, 0);
    assert(db);
    r = db->set_flags(dup_flags);
    CKERR(r);
    r = db->set_pagesize(4096);
    CKERR(r);
    r = db->set_bt_compare(reverse_compare);
    CKERR(r);
    r = db->set_dup_compare(reverse_compare);
    CKERR(r);
    r = db->open(null_txn, fname, "main", DB_BTREE, DB_CREATE, 0666);
    CKERR(r);

    /* insert n unique keys {0, 1,  n-1} */
    for (i=0; i<n; i++) {
        int k, v;
        k = htonl(dup_flags ? n : i);
        Dbt key(&k, sizeof k);
        v = htonl(i);
        Dbt val(&v, sizeof v);
        r = db->put(null_txn, &key, &val, DB_YESOVERWRITE);
        CKERR(r);
    }

    /* reopen the database to force nonleaf buffering */
    r = db->close(0);
    CKERR(r);
    delete db;

    db = new Db(null_env, 0);
    assert(db);
    r = db->set_flags(dup_flags);
    CKERR(r);
    r = db->set_pagesize(4096);
    CKERR(r);
    r = db->set_bt_compare(reverse_compare);
    CKERR(r);
    r = db->set_dup_compare(reverse_compare);
    CKERR(r);
    r = db->open(null_txn, fname, "main", DB_BTREE, 0, 0666);
    CKERR(r);

    /* insert n unique keys {n, n+1,  2*n-1} */
    for (i=n; i<2*n; i++) {
        int k, v;
        k = htonl(dup_flags ? n : i);
        Dbt key(&k, sizeof k);
        v = htonl(i);
        Dbt val(&v, sizeof v);
        r = db->put(null_txn, &key, &val, DB_YESOVERWRITE);
        CKERR(r);
    }

    /* verify the sort order with a cursor */
    Dbc *cursor;
    r = db->cursor(null_txn, &cursor, 0);
    CKERR(r);

    //for (i=0; i<2*n; i++)
    for (i=2*n-1; i>=0; i--)
        expect(cursor, htonl(dup_flags ? n : i), htonl(i));

    r = cursor->close();
    CKERR(r);

    r = db->close(0);
    CKERR(r);
    delete db;
}

int main(int argc, const char *argv[]) {
    parse_args(argc, argv);

    int i;

    for (i = 1; i <= (1<<16); i *= 2) {
        test_reverse_compare(i, 0);
        test_reverse_compare(i, DB_DUP + DB_DUPSORT);
    }
    return 0;
}
<commit_msg>fix the build. addresses #277<commit_after>/* -*- mode: C; c-basic-offset: 4 -*- */
#ident "Copyright (c) 2007 Tokutek Inc.  All rights reserved."

/* try a reverse compare function to verify that the database always uses the application's
   compare function */

#include <arpa/inet.h>
#include <assert.h>
#include <db_cxx.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#define DIR "dir_test_reverse_compare_fun"
int verbose;

int keycompare (const void *key1, unsigned int key1len, const void *key2, unsigned int key2len) {
    if (key1len==key2len) {
	return memcmp(key1,key2,key1len);
    } else if (key1len<key2len) {
	int r = memcmp(key1,key2,key1len);
	if (r<=0) return -1; /* If the keys are the same up to 1's length, then return -1, since key1 is shorter than key2. */
	else return 1;
    } else {
	return -keycompare(key2,key2len,key1,key1len);
    }
}

int reverse_compare(Db *db __attribute__((__unused__)), const Dbt *a, const Dbt*b) {
    return -keycompare(a->get_data(), a->get_size(), b->get_data(), b->get_size());
}

void expect(Dbc *cursor, int k, int v) {
    Dbt key; key.set_flags(DB_DBT_MALLOC);
    Dbt val; val.set_flags(DB_DBT_MALLOC);
    int r = cursor->get(&key, &val, DB_NEXT);
    assert(r == 0);
    assert(key.get_size() == sizeof k);
    int kk;
    memcpy(&kk, key.get_data(), key.get_size());
    assert(val.get_size() == sizeof v);
    int vv;
    memcpy(&vv, val.get_data(), val.get_size());
    if (kk != k || vv != v) printf("expect key %d got %d - %d %d\n", htonl(k), htonl(kk), htonl(v), htonl(vv));
    assert(kk == k);
    assert(vv == v);

    free(key.get_data());
    free(val.get_data());
}

void test_reverse_compare(int n, int dup_flags) {
    if (verbose) printf("test_reverse_compare:%d %d\n", n, dup_flags);

    DbEnv * const null_env = 0;
    Db *db;
    DbTxn * const null_txn = 0;
    const char * const fname = DIR "/reverse.compare.db";

    int r;
    int i;

    system("rm -rf " DIR);
    mkdir(DIR, 0777);

    /* create the dup database file */
    db = new Db(null_env, 0);
    assert(db);
    r = db->set_flags(dup_flags);
    assert(r == 0);
    r = db->set_pagesize(4096);
    assert(r == 0);
    r = db->set_bt_compare(reverse_compare);
    assert(r == 0);
    r = db->set_dup_compare(reverse_compare);
    assert(r == 0);
    r = db->open(null_txn, fname, "main", DB_BTREE, DB_CREATE, 0666);
    assert(r == 0);

    /* insert n unique keys {0, 1,  n-1} */
    for (i=0; i<n; i++) {
        int k, v;
        k = htonl(dup_flags ? n : i);
        Dbt key(&k, sizeof k);
        v = htonl(i);
        Dbt val(&v, sizeof v);
        r = db->put(null_txn, &key, &val, DB_YESOVERWRITE);
        assert(r == 0);
    }

    /* reopen the database to force nonleaf buffering */
    r = db->close(0);
    assert(r == 0);
    delete db;

    db = new Db(null_env, 0);
    assert(db);
    r = db->set_flags(dup_flags);
    assert(r == 0);
    r = db->set_pagesize(4096);
    assert(r == 0);
    r = db->set_bt_compare(reverse_compare);
    assert(r == 0);
    r = db->set_dup_compare(reverse_compare);
    assert(r == 0);
    r = db->open(null_txn, fname, "main", DB_BTREE, 0, 0666);
    assert(r == 0);

    /* insert n unique keys {n, n+1,  2*n-1} */
    for (i=n; i<2*n; i++) {
        int k, v;
        k = htonl(dup_flags ? n : i);
        Dbt key(&k, sizeof k);
        v = htonl(i);
        Dbt val(&v, sizeof v);
        r = db->put(null_txn, &key, &val, DB_YESOVERWRITE);
        assert(r == 0);
    }

    /* verify the sort order with a cursor */
    Dbc *cursor;
    r = db->cursor(null_txn, &cursor, 0);
    assert(r == 0);

    //for (i=0; i<2*n; i++)
    for (i=2*n-1; i>=0; i--)
        expect(cursor, htonl(dup_flags ? n : i), htonl(i));

    r = cursor->close();
    assert(r == 0);

    r = db->close(0);
    assert(r == 0);
    delete db;
}

int main(int argc, const char *argv[]) {
    int i;
    for (i = 1; i <= (1<<16); i *= 2) {
        test_reverse_compare(i, 0);
        test_reverse_compare(i, DB_DUP + DB_DUPSORT);
    }
    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2009-2013 The VOTCA Development Team (http://www.votca.org)
 *
 * 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 <iostream>
#include <fstream>

#include "dlpolytopologyreader.h"
#include "dlpoly/dlp_io_layer.h"

namespace votca { namespace csg {

bool DLPOLYTopologyReader::ReadTopology(string file, Topology &top)
{
    struct FieldSpecsT  FieldBase;
    struct FrameSpecsT  FrameBase;
    struct MolecSpecsT *MolecBase;
    struct FieldSiteT  *FieldSite;
    struct FrameSiteT  *FrameSite;

    int idnode,matms,natms,nmols,nmolt;
    int istateF;

    int inode=matms=natms=nmols=nmolt=0;

    // TODO: istateF must be an enum!
    istateF=1;

    // TODO: we need to fix the file naming!
    field_scan_(&istateF,&matms,&natms,&nmolt);

    MolecBase = new MolecSpecsT[nmolt];
    FieldSite = new FieldSiteT[natms];

    FieldBase.nmols = nmolt;
    FieldBase.natms = natms;

    field_read_(&istateF,&FieldBase,MolecBase,FieldSite);

    // AB: if on return istateF < 0  => in the next F-call the relevant F-arrays will be deallocated (at the end)
    // AB: NOT TO RE-/DE-ALLOCATE F-arrays in the next F-call, reset istateF = 0
    istateF = 0;

    // TODO: fix residue naming / assignment
    Residue *res = top.CreateResidue("no");

    // read the atoms
    int is=0;
    for(int im=0; im<nmolt; im++){
        for(int imr=0; imr<MolecBase[im].nrept; ++imr) {
            Molecule *mi = top.CreateMolecule(MolecBase[im].name);
            for(int ims=0; ims<MolecBase[im].nsites; ims++) {

                BeadType *type = top.GetOrCreateBeadType(FieldSite[is].name); // what is
                Bead *bead = top.CreateBead(1, FieldSite[is].type, type, res->getId(), FieldSite[is].m, FieldSite[is].q);

                stringstream nm;
                nm << bead->getResnr() + 1 << ":" <<  top.getResidue(bead->getResnr())->getName() << ":" << bead->getName();
                mi->AddBead(bead, nm.str());
            }
        }
    }

    delete [] MolecBase;
    delete [] FieldSite;

    std::ifstream fl;
    fl.open("CONFIG");
    if(fl.is_open()) {
      string line;
      getline(fl, line); //title
      getline(fl, line); // 2nd header line
      vec box_vectors[3];
      for (int i=0;i<3;i++){ // read 3 box lines
        getline(fl, line);
        if(fl.eof())
          throw std::runtime_error("unexpected end of file in dlpoly file CONFIG, when reading box vector"  +
              boost::lexical_cast<string>(i));
        Tokenizer tok(line, " ");
        vector<double> fields;
        tok.ConvertToVector<double>(fields);
        box_vectors[i]=vec(fields[0],fields[1],fields[2]);
      }
      matrix box(box_vectors[0],box_vectors[1],box_vectors[2]);
      top.setBox(box);
    }
    else {
      cout << "NOTE: Could open dlploy file CONFIG, so no boundary conditions, where set in the topology" << endl;
    }

    return true;
}

}}

<commit_msg>dlpolytopologyreader: added missing files close<commit_after>/*
 * Copyright 2009-2013 The VOTCA Development Team (http://www.votca.org)
 *
 * 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 <iostream>
#include <fstream>

#include "dlpolytopologyreader.h"
#include "dlpoly/dlp_io_layer.h"

namespace votca { namespace csg {

bool DLPOLYTopologyReader::ReadTopology(string file, Topology &top)
{
    struct FieldSpecsT  FieldBase;
    struct FrameSpecsT  FrameBase;
    struct MolecSpecsT *MolecBase;
    struct FieldSiteT  *FieldSite;
    struct FrameSiteT  *FrameSite;

    int idnode,matms,natms,nmols,nmolt;
    int istateF;

    int inode=matms=natms=nmols=nmolt=0;

    // TODO: istateF must be an enum!
    istateF=1;

    // TODO: we need to fix the file naming!
    field_scan_(&istateF,&matms,&natms,&nmolt);

    MolecBase = new MolecSpecsT[nmolt];
    FieldSite = new FieldSiteT[natms];

    FieldBase.nmols = nmolt;
    FieldBase.natms = natms;

    field_read_(&istateF,&FieldBase,MolecBase,FieldSite);

    // AB: if on return istateF < 0  => in the next F-call the relevant F-arrays will be deallocated (at the end)
    // AB: NOT TO RE-/DE-ALLOCATE F-arrays in the next F-call, reset istateF = 0
    istateF = 0;

    // TODO: fix residue naming / assignment
    Residue *res = top.CreateResidue("no");

    // read the atoms
    int is=0;
    for(int im=0; im<nmolt; im++){
        for(int imr=0; imr<MolecBase[im].nrept; ++imr) {
            Molecule *mi = top.CreateMolecule(MolecBase[im].name);
            for(int ims=0; ims<MolecBase[im].nsites; ims++) {

                BeadType *type = top.GetOrCreateBeadType(FieldSite[is].name); // what is
                Bead *bead = top.CreateBead(1, FieldSite[is].type, type, res->getId(), FieldSite[is].m, FieldSite[is].q);

                stringstream nm;
                nm << bead->getResnr() + 1 << ":" <<  top.getResidue(bead->getResnr())->getName() << ":" << bead->getName();
                mi->AddBead(bead, nm.str());
            }
        }
    }

    delete [] MolecBase;
    delete [] FieldSite;

    std::ifstream fl;
    fl.open("CONFIG");
    if(fl.is_open()) {
      string line;
      getline(fl, line); //title
      getline(fl, line); // 2nd header line
      vec box_vectors[3];
      for (int i=0;i<3;i++){ // read 3 box lines
        getline(fl, line);
        if(fl.eof())
          throw std::runtime_error("unexpected end of file in dlpoly file CONFIG, when reading box vector"  +
              boost::lexical_cast<string>(i));
        Tokenizer tok(line, " ");
        vector<double> fields;
        tok.ConvertToVector<double>(fields);
        box_vectors[i]=vec(fields[0],fields[1],fields[2]);
      }
      matrix box(box_vectors[0],box_vectors[1],box_vectors[2]);
      top.setBox(box);
    }
    else {
      cout << "NOTE: Could open dlploy file CONFIG, so no boundary conditions, where set in the topology" << endl;
    }
    fl.close();

    return true;
}

}}

<|endoftext|>


<commit_before>/***********************************************************************
    filename:   Sample_GLESTest.cpp
    created:    Sat Nov 05 2011
    author:     Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team
 *
 *   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 BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/RendererModules/OpenGLES/Renderer.h"
#include "CEGUI/CEGUI.h"
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>

#include <GLES/egl.h>
#include <GLES/gl.h>
// Include last to avoid the total fail that is the definition of things
// like None, True and False as macros from affecting the other headers.
#include <X11/Xlib.h>
#include <X11/keysym.h>

//----------------------------------------------------------------------------//
// setup default-default path
#ifndef CEGUI_SAMPLE_DATAPATH
    #define CEGUI_SAMPLE_DATAPATH "../datafiles"
#endif

// environment variable that overrides the location of the datafiles
#define DATAPATH_VAR_NAME "CEGUI_SAMPLE_DATAPATH"

//----------------------------------------------------------------------------//
void initialiseResourceGroupDirectories();
void initialiseDefaultResourceGroups();
const char* getDataPathPrefix();

//----------------------------------------------------------------------------//
int main(int argc, char* argv[])
{
    // Create X11 window.
    Display* dpy = XOpenDisplay(0);
    int scn = DefaultScreen(dpy);
    Window wnd = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy),
                                     50, 50, 480, 320, 1,
                                     BlackPixel(dpy, scn),
                                     WhitePixel(dpy, scn));

    XSelectInput(dpy, wnd, StructureNotifyMask |
                           PointerMotionMask |
                           ButtonPressMask | ButtonReleaseMask |
                           KeyPressMask | KeyReleaseMask);
    XMapWindow(dpy, wnd);

    XEvent evt;
    while (true)
    {
        XNextEvent(dpy, &evt);
        if (evt.type == MapNotify)
            break;
    }

    // EGL setup
    EGLDisplay egldpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);

    EGLint majVer, minVer;
    eglInitialize(egldpy, &majVer, &minVer);

    EGLint attrs[] =
    {
        EGL_RED_SIZE,           8,
        EGL_GREEN_SIZE,         8,
        EGL_BLUE_SIZE,          8,
        EGL_RENDERABLE_TYPE,    EGL_OPENGL_ES_BIT,
        EGL_SURFACE_TYPE,       EGL_WINDOW_BIT,
        EGL_NONE
    };

    EGLConfig config;
    EGLint numconfigs;
    eglChooseConfig(egldpy, attrs, &config, 1, &numconfigs);

    EGLSurface surface =
        eglCreateWindowSurface(egldpy, config, (NativeWindowType)wnd, 0);

    EGLContext ctx = eglCreateContext(egldpy, config, 0, 0);
    eglMakeCurrent(egldpy, surface, surface, ctx);

    eglBindAPI(EGL_OPENGL_ES_API);

    // basic gl state setup;
    glViewport(0, 0, 480, 320);
    glClearColor(0.2, 0.2, 0.2, 1);

    // CEGUI setup
    CEGUI::OpenGLESRenderer::bootstrapSystem();
    initialiseResourceGroupDirectories();
    initialiseDefaultResourceGroups();

    CEGUI::SchemeManager::getSingleton().createFromFile("TaharezLook.scheme");
    CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().setDefaultImage("TaharezLook/MouseArrow");
    CEGUI::WindowManager& winMgr(CEGUI::WindowManager::getSingleton());
    CEGUI::Window* root = winMgr.createWindow("DefaultWindow", "root");
    CEGUI::Window* fw = root->createChild("TaharezLook/FrameWindow");
    fw->setPosition(CEGUI::UVector2(CEGUI::UDim(0.25, 0), CEGUI::UDim(0.25, 0)));
    fw->setSize(CEGUI::USize(CEGUI::UDim(0.5, 0), CEGUI::UDim(0.5, 0)));
    fw->setText("OpenGL ES 1 Test");

    CEGUI::System::getSingleton().getDefaultGUIContext().setRootWindow(root);

    // Main looop
    bool running = true;
    while (running)
    {
        while (XPending(dpy))
        {
            XNextEvent(dpy, &evt);

            switch (evt.type)
            {
            case KeyPress:
            {
                int kspkcr;
                KeySym* ks = XGetKeyboardMapping(dpy, evt.xkey.keycode, 1, &kspkcr);

                if (ks[0] == XK_Escape)
                    running = false;

                break;
            }

            case MotionNotify:
                CEGUI::System::getSingleton().injectMousePosition(evt.xmotion.x, evt.xmotion.y);
                break;

            case ButtonPress:
            {
                CEGUI::MouseButton btn;
                if (evt.xbutton.button == Button1)
                    btn = CEGUI::LeftButton;
                else if (evt.xbutton.button == Button2)
                    btn = CEGUI::RightButton;
                else
                    break;

                CEGUI::System::getSingleton().injectMouseButtonDown(btn);
                break;
            }

            case ButtonRelease:
            {
                CEGUI::MouseButton btn;
                if (evt.xbutton.button == Button1)
                    btn = CEGUI::LeftButton;
                else if (evt.xbutton.button == Button2)
                    btn = CEGUI::RightButton;
                else
                    break;

                CEGUI::System::getSingleton().injectMouseButtonUp(btn);
                break;
            }

            }
        }

        glClear(GL_COLOR_BUFFER_BIT);

        CEGUI::System::getSingleton().renderAllGUIContexts();

        eglSwapBuffers(egldpy, surface);
    }

    // cleanup
    CEGUI::OpenGLESRenderer::destroySystem();

    eglMakeCurrent(egldpy, 0, 0, 0);
    eglDestroyContext(egldpy, ctx);
    eglDestroySurface(egldpy, surface);
    eglTerminate(dpy);
    eglReleaseThread();

    XCloseDisplay(dpy);

    return 0;
}

//----------------------------------------------------------------------------//
void initialiseResourceGroupDirectories()
{
    // initialise the required dirs for the DefaultResourceProvider
    CEGUI::DefaultResourceProvider* rp =
        static_cast<CEGUI::DefaultResourceProvider*>
            (CEGUI::System::getSingleton().getResourceProvider());

    const char* dataPathPrefix = getDataPathPrefix();
    char resourcePath[PATH_MAX];

    // for each resource type, set a resource group directory
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "schemes/");
    rp->setResourceGroupDirectory("schemes", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "imagesets/");
    rp->setResourceGroupDirectory("imagesets", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "fonts/");
    rp->setResourceGroupDirectory("fonts", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "layouts/");
    rp->setResourceGroupDirectory("layouts", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "looknfeel/");
    rp->setResourceGroupDirectory("looknfeels", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "lua_scripts/");
    rp->setResourceGroupDirectory("lua_scripts", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "xml_schemas/");
    rp->setResourceGroupDirectory("schemas", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "animations/");
    rp->setResourceGroupDirectory("animations", resourcePath);
}

//----------------------------------------------------------------------------//
void initialiseDefaultResourceGroups()
{
    // set the default resource groups to be used
    CEGUI::ImageManager::setImagesetDefaultResourceGroup("imagesets");
    CEGUI::Font::setDefaultResourceGroup("fonts");
    CEGUI::Scheme::setDefaultResourceGroup("schemes");
    CEGUI::WidgetLookManager::setDefaultResourceGroup("looknfeels");
    CEGUI::WindowManager::setDefaultResourceGroup("layouts");
    CEGUI::ScriptModule::setDefaultResourceGroup("lua_scripts");
    CEGUI::AnimationManager::setDefaultResourceGroup("animations");
    // setup default group for validation schemas
    CEGUI::XMLParser* parser = CEGUI::System::getSingleton().getXMLParser();
    if (parser->isPropertyPresent("SchemaDefaultResourceGroup"))
        parser->setProperty("SchemaDefaultResourceGroup", "schemas");
}

//----------------------------------------------------------------------------//
const char* getDataPathPrefix()
{
    static char dataPathPrefix[PATH_MAX];

    char* envDataPath = 0;

    // get data path from environment var
    envDataPath = getenv(DATAPATH_VAR_NAME);

    // set data path prefix / base directory.  This will
    // be either from an environment variable, or from
    // a compiled in default based on original configure
    // options
    if (envDataPath != 0)
        strcpy(dataPathPrefix, envDataPath);
    else
        strcpy(dataPathPrefix, CEGUI_SAMPLE_DATAPATH);

    return dataPathPrefix;
}

//----------------------------------------------------------------------------//
<commit_msg>Fix the GLES test (hopefully)<commit_after>/***********************************************************************
    filename:   Sample_GLESTest.cpp
    created:    Sat Nov 05 2011
    author:     Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team
 *
 *   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 BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/RendererModules/OpenGLES/Renderer.h"
#include "CEGUI/CEGUI.h"
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>

#include <GLES/egl.h>
#include <GLES/gl.h>
// Include last to avoid the total fail that is the definition of things
// like None, True and False as macros from affecting the other headers.
#include <X11/Xlib.h>
#include <X11/keysym.h>

//----------------------------------------------------------------------------//
// setup default-default path
#ifndef CEGUI_SAMPLE_DATAPATH
    #define CEGUI_SAMPLE_DATAPATH "../datafiles"
#endif

// environment variable that overrides the location of the datafiles
#define DATAPATH_VAR_NAME "CEGUI_SAMPLE_DATAPATH"

//----------------------------------------------------------------------------//
void initialiseResourceGroupDirectories();
void initialiseDefaultResourceGroups();
const char* getDataPathPrefix();

//----------------------------------------------------------------------------//
int main(int argc, char* argv[])
{
    // Create X11 window.
    Display* dpy = XOpenDisplay(0);
    int scn = DefaultScreen(dpy);
    Window wnd = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy),
                                     50, 50, 480, 320, 1,
                                     BlackPixel(dpy, scn),
                                     WhitePixel(dpy, scn));

    XSelectInput(dpy, wnd, StructureNotifyMask |
                           PointerMotionMask |
                           ButtonPressMask | ButtonReleaseMask |
                           KeyPressMask | KeyReleaseMask);
    XMapWindow(dpy, wnd);

    XEvent evt;
    while (true)
    {
        XNextEvent(dpy, &evt);
        if (evt.type == MapNotify)
            break;
    }

    // EGL setup
    EGLDisplay egldpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);

    EGLint majVer, minVer;
    eglInitialize(egldpy, &majVer, &minVer);

    EGLint attrs[] =
    {
        EGL_RED_SIZE,           8,
        EGL_GREEN_SIZE,         8,
        EGL_BLUE_SIZE,          8,
        EGL_RENDERABLE_TYPE,    EGL_OPENGL_ES_BIT,
        EGL_SURFACE_TYPE,       EGL_WINDOW_BIT,
        EGL_NONE
    };

    EGLConfig config;
    EGLint numconfigs;
    eglChooseConfig(egldpy, attrs, &config, 1, &numconfigs);

    EGLSurface surface =
        eglCreateWindowSurface(egldpy, config, (NativeWindowType)wnd, 0);

    EGLContext ctx = eglCreateContext(egldpy, config, 0, 0);
    eglMakeCurrent(egldpy, surface, surface, ctx);

    eglBindAPI(EGL_OPENGL_ES_API);

    // basic gl state setup;
    glViewport(0, 0, 480, 320);
    glClearColor(0.2, 0.2, 0.2, 1);

    // CEGUI setup
    CEGUI::OpenGLESRenderer::bootstrapSystem();
    initialiseResourceGroupDirectories();
    initialiseDefaultResourceGroups();

    CEGUI::SchemeManager::getSingleton().createFromFile("TaharezLook.scheme");
    CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().setDefaultImage("TaharezLook/MouseArrow");
    CEGUI::WindowManager& winMgr(CEGUI::WindowManager::getSingleton());
    CEGUI::Window* root = winMgr.createWindow("DefaultWindow", "root");
    CEGUI::Window* fw = root->createChild("TaharezLook/FrameWindow");
    fw->setPosition(CEGUI::UVector2(CEGUI::UDim(0.25, 0), CEGUI::UDim(0.25, 0)));
    fw->setSize(CEGUI::USize(CEGUI::UDim(0.5, 0), CEGUI::UDim(0.5, 0)));
    fw->setText("OpenGL ES 1 Test");

    CEGUI::System::getSingleton().getDefaultGUIContext().setRootWindow(root);

    // Main looop
    bool running = true;
    while (running)
    {
        while (XPending(dpy))
        {
            XNextEvent(dpy, &evt);

            switch (evt.type)
            {
            case KeyPress:
            {
                int kspkcr;
                KeySym* ks = XGetKeyboardMapping(dpy, evt.xkey.keycode, 1, &kspkcr);

                if (ks[0] == XK_Escape)
                    running = false;

                break;
            }

            case MotionNotify:
                CEGUI::System::getSingleton().getDefaultGUIContext().injectMousePosition(evt.xmotion.x, evt.xmotion.y);
                break;

            case ButtonPress:
            {
                CEGUI::MouseButton btn;
                if (evt.xbutton.button == Button1)
                    btn = CEGUI::LeftButton;
                else if (evt.xbutton.button == Button2)
                    btn = CEGUI::RightButton;
                else
                    break;

                CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseButtonDown(btn);
                break;
            }

            case ButtonRelease:
            {
                CEGUI::MouseButton btn;
                if (evt.xbutton.button == Button1)
                    btn = CEGUI::LeftButton;
                else if (evt.xbutton.button == Button2)
                    btn = CEGUI::RightButton;
                else
                    break;

                CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseButtonUp(btn);
                break;
            }

            }
        }

        glClear(GL_COLOR_BUFFER_BIT);

        CEGUI::System::getSingleton().renderAllGUIContexts();

        eglSwapBuffers(egldpy, surface);
    }

    // cleanup
    CEGUI::OpenGLESRenderer::destroySystem();

    eglMakeCurrent(egldpy, 0, 0, 0);
    eglDestroyContext(egldpy, ctx);
    eglDestroySurface(egldpy, surface);
    eglTerminate(dpy);
    eglReleaseThread();

    XCloseDisplay(dpy);

    return 0;
}

//----------------------------------------------------------------------------//
void initialiseResourceGroupDirectories()
{
    // initialise the required dirs for the DefaultResourceProvider
    CEGUI::DefaultResourceProvider* rp =
        static_cast<CEGUI::DefaultResourceProvider*>
            (CEGUI::System::getSingleton().getResourceProvider());

    const char* dataPathPrefix = getDataPathPrefix();
    char resourcePath[PATH_MAX];

    // for each resource type, set a resource group directory
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "schemes/");
    rp->setResourceGroupDirectory("schemes", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "imagesets/");
    rp->setResourceGroupDirectory("imagesets", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "fonts/");
    rp->setResourceGroupDirectory("fonts", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "layouts/");
    rp->setResourceGroupDirectory("layouts", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "looknfeel/");
    rp->setResourceGroupDirectory("looknfeels", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "lua_scripts/");
    rp->setResourceGroupDirectory("lua_scripts", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "xml_schemas/");
    rp->setResourceGroupDirectory("schemas", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "animations/");
    rp->setResourceGroupDirectory("animations", resourcePath);
}

//----------------------------------------------------------------------------//
void initialiseDefaultResourceGroups()
{
    // set the default resource groups to be used
    CEGUI::ImageManager::setImagesetDefaultResourceGroup("imagesets");
    CEGUI::Font::setDefaultResourceGroup("fonts");
    CEGUI::Scheme::setDefaultResourceGroup("schemes");
    CEGUI::WidgetLookManager::setDefaultResourceGroup("looknfeels");
    CEGUI::WindowManager::setDefaultResourceGroup("layouts");
    CEGUI::ScriptModule::setDefaultResourceGroup("lua_scripts");
    CEGUI::AnimationManager::setDefaultResourceGroup("animations");
    // setup default group for validation schemas
    CEGUI::XMLParser* parser = CEGUI::System::getSingleton().getXMLParser();
    if (parser->isPropertyPresent("SchemaDefaultResourceGroup"))
        parser->setProperty("SchemaDefaultResourceGroup", "schemas");
}

//----------------------------------------------------------------------------//
const char* getDataPathPrefix()
{
    static char dataPathPrefix[PATH_MAX];

    char* envDataPath = 0;

    // get data path from environment var
    envDataPath = getenv(DATAPATH_VAR_NAME);

    // set data path prefix / base directory.  This will
    // be either from an environment variable, or from
    // a compiled in default based on original configure
    // options
    if (envDataPath != 0)
        strcpy(dataPathPrefix, envDataPath);
    else
        strcpy(dataPathPrefix, CEGUI_SAMPLE_DATAPATH);

    return dataPathPrefix;
}

//----------------------------------------------------------------------------//
<|endoftext|>


<commit_before>#include "xchainer/array.h"

#include <cassert>
#include <cstring>

#ifdef XCHAINER_ENABLE_CUDA
#include <cuda.h>
#include <cuda_runtime.h>
#endif  // XCHAINER_ENABLE_CUDA

#include "xchainer/array_math.h"
#include "xchainer/array_repr.h"
#ifdef XCHAINER_ENABLE_CUDA
#include "xchainer/cuda/array_math.h"
#include "xchainer/cuda/cuda_runtime.h"
#endif  // XCHAINER_ENABLE_CUDA
#include "xchainer/device.h"
#include "xchainer/op_node.h"

namespace xchainer {

namespace {

#ifdef XCHAINER_ENABLE_CUDA
std::shared_ptr<void> AllocateCudaManaged(size_t size) {
    std::shared_ptr<void> ptr{};
    {
        void* raw_ptr = nullptr;
        auto raw_ptr_scope = gsl::finally([&]() {
            if (raw_ptr && !ptr) {
                cudaFree(raw_ptr);
            }
        });
        cuda::CheckError(cudaMallocManaged(&raw_ptr, size, cudaMemAttachGlobal));
        ptr.reset(raw_ptr, cudaFree);
    }
    return ptr;
}
#endif  // XCHAINER_ENABLE_CUDA

std::shared_ptr<void> Allocate(const Device& device, size_t size) {
    if (device == MakeDevice("cpu")) {
        return std::make_unique<uint8_t[]>(size);
#ifdef XCHAINER_ENABLE_CUDA
    } else if (device == MakeDevice("cuda")) {
        return AllocateCudaManaged(size);
#endif  // XCHAINER_ENABLE_CUDA
    } else {
        throw DeviceError("invalid device");
    }
}

void MemoryCopy(const Device& device, void* dst_ptr, const void* src_ptr, size_t size) {
    if (device == MakeDevice("cpu")) {
        std::memcpy(dst_ptr, src_ptr, size);
#ifdef XCHAINER_ENABLE_CUDA
    } else if (device == MakeDevice("cuda")) {
        cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, size, cudaMemcpyHostToDevice));
#endif  // XCHAINER_ENABLE_CUDA
    } else {
        throw DeviceError("invalid device");
    }
}

}  // namespace

Array::Array(const Shape& shape, Dtype dtype, std::shared_ptr<void> data, bool requires_grad, int64_t offset)
    : shape_(shape),
      is_contiguous_(true),
      dtype_(dtype),
      data_(nullptr),
      requires_grad_(requires_grad),
      offset_(offset),
      node_(std::make_shared<ArrayNode>()) {
    Device device = GetCurrentDevice();
    if (device == MakeDevice("cpu")) {
        data_ = std::move(data);
#ifdef XCHAINER_ENABLE_CUDA
    } else if (device == MakeDevice("cuda")) {
        size_t size = static_cast<size_t>(shape_.total_size() * GetElementSize(dtype));
        data_ = AllocateCudaManaged(size);
        MemoryCopy(device, data_.get(), data.get(), size);
#endif  // XCHAINER_ENABLE_CUDA
    } else {
        throw DeviceError("invalid device");
    }
}

Array Array::Empty(const Shape& shape, Dtype dtype) {
    size_t size = static_cast<size_t>(shape.total_size() * GetElementSize(dtype));
    std::shared_ptr<void> data = Allocate(GetCurrentDevice(), size);
    return {shape, dtype, data};
}

Array Array::EmptyLike(const Array& array) { return Empty(array.shape(), array.dtype()); }

Array Array::DeepCopy() const {
    auto bytes = total_bytes();
    if (GetCurrentDevice() == MakeDevice("cpu")) {
        std::shared_ptr<void> ret_data = std::make_unique<uint8_t[]>(bytes);
        std::memcpy(ret_data.get(), data_.get(), bytes);
        return {shape_, dtype_, ret_data, requires_grad_, offset_};
#ifdef XCHAINER_ENABLE_CUDA
    } else if (GetCurrentDevice() == MakeDevice("cuda")) {
        void* ret_ptr = nullptr;
        cuda::CheckError(cudaMallocManaged(&ret_ptr, bytes, cudaMemAttachGlobal));
        std::shared_ptr<void> ret_data(ret_ptr, ::cudaFree);
        cuda::CheckError(cudaMemcpy(ret_ptr, data_.get(), bytes, cudaMemcpyDeviceToDevice));
        return {shape_, dtype_, ret_data, requires_grad_, offset_};
#endif  // XCHAINER_ENABLE_CUDA
    } else {
        throw DeviceError("invalid device");
    }
}

Array& Array::operator+=(const Array& rhs) {
    Add(rhs, *this);
    requires_grad_ |= rhs.requires_grad();
    return *this;
}

Array& Array::operator*=(const Array& rhs) {
    Mul(rhs, *this);
    requires_grad_ |= rhs.requires_grad();
    return *this;
}

Array Array::operator+(const Array& rhs) const {
    bool requires_grad = (requires_grad_ || rhs.requires_grad());
    Array out = {shape_, dtype_, std::make_unique<uint8_t[]>(total_bytes()), requires_grad, 0};
    Add(rhs, out);
    return out;
}

Array Array::operator*(const Array& rhs) const {
    bool requires_grad = (requires_grad_ || rhs.requires_grad());
    Array out = {shape_, dtype_, std::make_unique<uint8_t[]>(total_bytes()), requires_grad, 0};
    Mul(rhs, out);
    return out;
}

void Array::Add(const Array& rhs, Array& out) const {
    // TODO: dtype conversion
    CheckEqual(dtype_, rhs.dtype());
    // TODO: broadcasting
    CheckEqual(shape_, rhs.shape());

    if (requires_grad_ || rhs.requires_grad()) {
        const Array& lhs = *this;
        std::shared_ptr<const ArrayNode> lhs_node = node();
        std::shared_ptr<const ArrayNode> rhs_node = rhs.node();
        std::shared_ptr<ArrayNode> out_node = out.RenewNode();
        std::function<Array(const Array&)> empty_func;
        auto lhs_func = lhs.requires_grad() ? [](const Array& gout) { return gout; } : empty_func;
        auto rhs_func = rhs.requires_grad() ? [](const Array& gout) { return gout; } : empty_func;
        auto backward_functions = std::vector<std::function<Array(const Array&)>>{lhs_func, rhs_func};
        std::shared_ptr<OpNode> op_node =
            std::make_shared<OpNode>("add", std::vector<std::shared_ptr<const ArrayNode>>{lhs_node, rhs_node}, backward_functions);
        out_node->set_next_node(op_node);
    }

    Device device = GetCurrentDevice();
    if (device == MakeDevice("cpu")) {
        xchainer::Add(*this, rhs, out);
#ifdef XCHAINER_ENABLE_CUDA
    } else if (device == MakeDevice("cuda")) {
        xchainer::cuda::Add(*this, rhs, out);
#endif  // XCHAINER_ENABLE_CUDA
    } else {
        throw DeviceError("invalid device");
    }
}

void Array::Mul(const Array& rhs, Array& out) const {
    // TODO: dtype conversion
    CheckEqual(dtype_, rhs.dtype());
    // TODO: broadcasting
    CheckEqual(shape_, rhs.shape());

    if (requires_grad_ || rhs.requires_grad()) {
        // deep copy for in-place operation to keep original input
        const Array& lhs = (this == &out) ? DeepCopy() : *this;
        std::shared_ptr<const ArrayNode> lhs_node = node();
        std::shared_ptr<const ArrayNode> rhs_node = rhs.node();
        std::shared_ptr<ArrayNode> out_node = out.RenewNode();
        std::function<Array(const Array&)> empty_func;
        // TODO(sonots): turn off constructing graph (requires_grad) in backward (but, turn on for double backprop)
        auto lhs_func = lhs.requires_grad() ? [rhs](const Array& gout) { return gout * rhs; } : empty_func;
        auto rhs_func = rhs.requires_grad() ? [lhs](const Array& gout) { return gout * lhs; } : empty_func;
        auto backward_functions = std::vector<std::function<Array(const Array&)>>{lhs_func, rhs_func};
        std::shared_ptr<OpNode> op_node =
            std::make_shared<OpNode>("mul", std::vector<std::shared_ptr<const ArrayNode>>{lhs_node, rhs_node}, backward_functions);
        out_node->set_next_node(op_node);
    }

    Device device = GetCurrentDevice();
    if (device == MakeDevice("cpu")) {
        xchainer::Mul(*this, rhs, out);
#ifdef XCHAINER_ENABLE_CUDA
    } else if (device == MakeDevice("cuda")) {
        xchainer::cuda::Mul(*this, rhs, out);
#endif  // XCHAINER_ENABLE_CUDA
    } else {
        throw DeviceError("invalid device");
    }
}

std::string Array::ToString() const { return ArrayRepr(*this); }

namespace {

void DebugDumpComputationalGraph(std::ostream& os, const ArrayNode& array_node, int indent) {
    static const char kIndentChar = ' ';

    os << std::string(static_cast<size_t>(indent * 2), kIndentChar) << "ArrayNode<" << &array_node << ">" << std::endl;

    std::shared_ptr<const OpNode> op = array_node.next_node();
    if (op) {
        os << std::string(static_cast<size_t>((indent + 1) * 2), kIndentChar) << "Op<" << op->name() << ">" << std::endl;
        for (const std::shared_ptr<const ArrayNode>& next_node : op->next_nodes()) {
            DebugDumpComputationalGraph(os, *next_node, static_cast<size_t>(indent + 2));
        }
    }
}

}  // namespace

void DebugDumpComputationalGraph(std::ostream& os, const Array& array, int indent) {
    DebugDumpComputationalGraph(os, *array.node(), indent);
}

}  // namespace xchainer
<commit_msg>Add TODO comments<commit_after>#include "xchainer/array.h"

#include <cassert>
#include <cstring>

#ifdef XCHAINER_ENABLE_CUDA
#include <cuda.h>
#include <cuda_runtime.h>
#endif  // XCHAINER_ENABLE_CUDA

#include "xchainer/array_math.h"
#include "xchainer/array_repr.h"
#ifdef XCHAINER_ENABLE_CUDA
#include "xchainer/cuda/array_math.h"
#include "xchainer/cuda/cuda_runtime.h"
#endif  // XCHAINER_ENABLE_CUDA
#include "xchainer/device.h"
#include "xchainer/op_node.h"

namespace xchainer {

namespace {

#ifdef XCHAINER_ENABLE_CUDA
std::shared_ptr<void> AllocateCudaManaged(size_t size) {
    std::shared_ptr<void> ptr{};
    {
        void* raw_ptr = nullptr;
        auto raw_ptr_scope = gsl::finally([&]() {
            if (raw_ptr && !ptr) {
                cudaFree(raw_ptr);
            }
        });
        cuda::CheckError(cudaMallocManaged(&raw_ptr, size, cudaMemAttachGlobal));
        ptr.reset(raw_ptr, cudaFree);
    }
    return ptr;
}
#endif  // XCHAINER_ENABLE_CUDA

std::shared_ptr<void> Allocate(const Device& device, size_t size) {
    if (device == MakeDevice("cpu")) {
        return std::make_unique<uint8_t[]>(size);
#ifdef XCHAINER_ENABLE_CUDA
    } else if (device == MakeDevice("cuda")) {
        return AllocateCudaManaged(size);
#endif  // XCHAINER_ENABLE_CUDA
    } else {
        throw DeviceError("invalid device");
    }
}

void MemoryCopy(const Device& device, void* dst_ptr, const void* src_ptr, size_t size) {
    if (device == MakeDevice("cpu")) {
        std::memcpy(dst_ptr, src_ptr, size);
#ifdef XCHAINER_ENABLE_CUDA
    } else if (device == MakeDevice("cuda")) {
        cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, size, cudaMemcpyHostToDevice));
#endif  // XCHAINER_ENABLE_CUDA
    } else {
        throw DeviceError("invalid device");
    }
}

}  // namespace

Array::Array(const Shape& shape, Dtype dtype, std::shared_ptr<void> data, bool requires_grad, int64_t offset)
    : shape_(shape),
      is_contiguous_(true),
      dtype_(dtype),
      data_(nullptr),
      requires_grad_(requires_grad),
      offset_(offset),
      node_(std::make_shared<ArrayNode>()) {
    Device device = GetCurrentDevice();
    if (device == MakeDevice("cpu")) {
        data_ = std::move(data);
#ifdef XCHAINER_ENABLE_CUDA
    } else if (device == MakeDevice("cuda")) {
        size_t size = static_cast<size_t>(shape_.total_size() * GetElementSize(dtype));
        data_ = AllocateCudaManaged(size);
        MemoryCopy(device, data_.get(), data.get(), size);
#endif  // XCHAINER_ENABLE_CUDA
    } else {
        throw DeviceError("invalid device");
    }
}

Array Array::Empty(const Shape& shape, Dtype dtype) {
    size_t size = static_cast<size_t>(shape.total_size() * GetElementSize(dtype));
    std::shared_ptr<void> data = Allocate(GetCurrentDevice(), size);
    return {shape, dtype, data};
}

Array Array::EmptyLike(const Array& array) { return Empty(array.shape(), array.dtype()); }

Array Array::DeepCopy() const {
    auto bytes = total_bytes();
    if (GetCurrentDevice() == MakeDevice("cpu")) {
        std::shared_ptr<void> ret_data = std::make_unique<uint8_t[]>(bytes);
        std::memcpy(ret_data.get(), data_.get(), bytes);
        return {shape_, dtype_, ret_data, requires_grad_, offset_};
#ifdef XCHAINER_ENABLE_CUDA
    } else if (GetCurrentDevice() == MakeDevice("cuda")) {
        // TODO(sonots): Better to use abstraction layer such as Allocate or MemoryCopy,
        // but they do not support all cases such as device to device, yet. We need refactoring.
        void* ret_ptr = nullptr;
        cuda::CheckError(cudaMallocManaged(&ret_ptr, bytes, cudaMemAttachGlobal));
        std::shared_ptr<void> ret_data(ret_ptr, ::cudaFree);
        cuda::CheckError(cudaMemcpy(ret_ptr, data_.get(), bytes, cudaMemcpyDeviceToDevice));
        return {shape_, dtype_, ret_data, requires_grad_, offset_};
#endif  // XCHAINER_ENABLE_CUDA
    } else {
        throw DeviceError("invalid device");
    }
}

Array& Array::operator+=(const Array& rhs) {
    Add(rhs, *this);
    requires_grad_ |= rhs.requires_grad();
    return *this;
}

Array& Array::operator*=(const Array& rhs) {
    Mul(rhs, *this);
    requires_grad_ |= rhs.requires_grad();
    return *this;
}

Array Array::operator+(const Array& rhs) const {
    bool requires_grad = (requires_grad_ || rhs.requires_grad());
    Array out = {shape_, dtype_, std::make_unique<uint8_t[]>(total_bytes()), requires_grad, 0};
    Add(rhs, out);
    return out;
}

Array Array::operator*(const Array& rhs) const {
    bool requires_grad = (requires_grad_ || rhs.requires_grad());
    Array out = {shape_, dtype_, std::make_unique<uint8_t[]>(total_bytes()), requires_grad, 0};
    Mul(rhs, out);
    return out;
}

void Array::Add(const Array& rhs, Array& out) const {
    // TODO: dtype conversion
    CheckEqual(dtype_, rhs.dtype());
    // TODO: broadcasting
    CheckEqual(shape_, rhs.shape());

    if (requires_grad_ || rhs.requires_grad()) {
        const Array& lhs = *this;
        std::shared_ptr<const ArrayNode> lhs_node = node();
        std::shared_ptr<const ArrayNode> rhs_node = rhs.node();
        std::shared_ptr<ArrayNode> out_node = out.RenewNode();
        std::function<Array(const Array&)> empty_func;
        auto lhs_func = lhs.requires_grad() ? [](const Array& gout) { return gout; } : empty_func;
        auto rhs_func = rhs.requires_grad() ? [](const Array& gout) { return gout; } : empty_func;
        auto backward_functions = std::vector<std::function<Array(const Array&)>>{lhs_func, rhs_func};
        std::shared_ptr<OpNode> op_node =
            std::make_shared<OpNode>("add", std::vector<std::shared_ptr<const ArrayNode>>{lhs_node, rhs_node}, backward_functions);
        out_node->set_next_node(op_node);
    }

    Device device = GetCurrentDevice();
    if (device == MakeDevice("cpu")) {
        xchainer::Add(*this, rhs, out);
#ifdef XCHAINER_ENABLE_CUDA
    } else if (device == MakeDevice("cuda")) {
        xchainer::cuda::Add(*this, rhs, out);
#endif  // XCHAINER_ENABLE_CUDA
    } else {
        throw DeviceError("invalid device");
    }
}

void Array::Mul(const Array& rhs, Array& out) const {
    // TODO: dtype conversion
    CheckEqual(dtype_, rhs.dtype());
    // TODO: broadcasting
    CheckEqual(shape_, rhs.shape());

    if (requires_grad_ || rhs.requires_grad()) {
        // deep copy for in-place operation to keep original input
        const Array& lhs = (this == &out) ? DeepCopy() : *this;
        std::shared_ptr<const ArrayNode> lhs_node = node();
        std::shared_ptr<const ArrayNode> rhs_node = rhs.node();
        std::shared_ptr<ArrayNode> out_node = out.RenewNode();
        std::function<Array(const Array&)> empty_func;
        // TODO(sonots): turn off constructing graph (requires_grad) in backward (but, turn on for double backprop)
        auto lhs_func = lhs.requires_grad() ? [rhs](const Array& gout) { return gout * rhs; } : empty_func;
        auto rhs_func = rhs.requires_grad() ? [lhs](const Array& gout) { return gout * lhs; } : empty_func;
        auto backward_functions = std::vector<std::function<Array(const Array&)>>{lhs_func, rhs_func};
        std::shared_ptr<OpNode> op_node =
            std::make_shared<OpNode>("mul", std::vector<std::shared_ptr<const ArrayNode>>{lhs_node, rhs_node}, backward_functions);
        out_node->set_next_node(op_node);
    }

    Device device = GetCurrentDevice();
    if (device == MakeDevice("cpu")) {
        xchainer::Mul(*this, rhs, out);
#ifdef XCHAINER_ENABLE_CUDA
    } else if (device == MakeDevice("cuda")) {
        xchainer::cuda::Mul(*this, rhs, out);
#endif  // XCHAINER_ENABLE_CUDA
    } else {
        throw DeviceError("invalid device");
    }
}

std::string Array::ToString() const { return ArrayRepr(*this); }

namespace {

void DebugDumpComputationalGraph(std::ostream& os, const ArrayNode& array_node, int indent) {
    static const char kIndentChar = ' ';

    os << std::string(static_cast<size_t>(indent * 2), kIndentChar) << "ArrayNode<" << &array_node << ">" << std::endl;

    std::shared_ptr<const OpNode> op = array_node.next_node();
    if (op) {
        os << std::string(static_cast<size_t>((indent + 1) * 2), kIndentChar) << "Op<" << op->name() << ">" << std::endl;
        for (const std::shared_ptr<const ArrayNode>& next_node : op->next_nodes()) {
            DebugDumpComputationalGraph(os, *next_node, static_cast<size_t>(indent + 2));
        }
    }
}

}  // namespace

void DebugDumpComputationalGraph(std::ostream& os, const Array& array, int indent) {
    DebugDumpComputationalGraph(os, *array.node(), indent);
}

}  // namespace xchainer
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qgeopositioninfosource_maemo_p.h"
#include <iostream>

#ifdef Q_WS_MAEMO_5
#include <QDateTime>
#endif
#if 0
void dumpQByteArray(const QByteArray &msg)
{
    std::cout << "QByteArray dump:\n";
    std::cout << msg.size() << "  \n";
    int i =  msg.size();
    for (int k = 0; k < i ;k++)
        printf("msg[%d]=%2.2x\n", k, (unsigned char)msg[k]);
}
#endif

using namespace std;

QTM_BEGIN_NAMESPACE

QGeoPositionInfoSourceMaemo::QGeoPositionInfoSourceMaemo(QObject *parent): QGeoPositionInfoSource(parent)
{
    // default values
#ifdef Q_WS_MAEMO_5
    time_interval_ = LOCATION_INTERVAL_5S;
    availableMethods = SatellitePositioningMethods;
#else
    time_interval_ = 5000;
    availableMethods = AllPositioningMethods;
#endif
    distance_interval_ = 10;
    registered_ = false;
    validLastUpdate = false;
    validLastSatUpdate = false;
}

int QGeoPositionInfoSourceMaemo::init()
{
#ifdef Q_WS_MAEMO_5
    g_type_init();

    locationControl = location_gpsd_control_get_default();
    if(locationControl) {
        g_object_set(G_OBJECT(locationControl),
                     "preferred-method", LOCATION_METHOD_USER_SELECTED,
                     "preferred-interval", time_interval_,
                     NULL);
    } else {
        return -1;
    }

    locationDevice =
            (LocationGPSDevice*)g_object_new(LOCATION_TYPE_GPS_DEVICE,
                                             NULL);

    if(locationDevice) {
        errorHandlerId =
            g_signal_connect(G_OBJECT(locationControl), "error-verbose",
                             G_CALLBACK(&locationError),
                             static_cast<void*>(this));
        posChangedId =
            g_signal_connect(G_OBJECT(locationDevice), "changed",
                             G_CALLBACK(&locationChanged),
                             static_cast<void*>(this));
        connectedId =
            g_signal_connect(G_OBJECT(locationDevice), "connected",
                             G_CALLBACK(&deviceConnected),
                             static_cast<void*>(this));
        disconnectedId =
            g_signal_connect(G_OBJECT(locationDevice), "disconnected",
                             G_CALLBACK(&deviceDisconnected),
                             static_cast<void*>(this));
        return 0;
    } else {
        return -1;
    }
#else
    int status;

    dbusComm = new DBusComm();
    status = dbusComm->init();

    QObject::connect(dbusComm, SIGNAL(receivedMessage(const QByteArray &)),
                     this, SLOT(dbusMessages(const QByteArray &)));

    QObject::connect(dbusComm, SIGNAL(receivedPositionUpdate(const QGeoPositionInfo &)),
                     this, SLOT(newPositionUpdate(const QGeoPositionInfo &)));
    return status;
#endif // Q_WS_MAEMO_5
}

void QGeoPositionInfoSourceMaemo::dbusMessages(const QByteArray &msg)
{
    Q_UNUSED(msg)
    // stub

    return;
}

void QGeoPositionInfoSourceMaemo::newPositionUpdate(const QGeoPositionInfo &update)
{
    lastSatUpdate = update;
    validLastSatUpdate = true;
    emit positionUpdated(update);
}

QGeoPositionInfo QGeoPositionInfoSourceMaemo::lastKnownPosition(bool fromSatellitePositioningMethodsOnly) const
{
    if (validLastSatUpdate)
        return lastSatUpdate;

    if (!fromSatellitePositioningMethodsOnly)
        if (validLastUpdate)
            return lastUpdate;

    return QGeoPositionInfo();
}

QGeoPositionInfoSource::PositioningMethods QGeoPositionInfoSourceMaemo::supportedPositioningMethods() const
{
    return availableMethods;
}

void QGeoPositionInfoSourceMaemo::setUpdateInterval(int msec)
{
    msec = (msec < MinimumUpdateInterval) ? MinimumUpdateInterval : msec;

#ifdef Q_WS_MAEMO_5
    time_interval_ = mapUpdateInterval(msec);
    QGeoPositionInfoSource::setUpdateInterval(time_interval_*100);
    if(locationControl) {
        g_object_set(G_OBJECT(locationControl),
                     "preferred-method", LOCATION_METHOD_USER_SELECTED,
                     "preferred-interval", time_interval_,
                     NULL) ;
    }
#else
    QGeoPositionInfoSource::setUpdateInterval(msec);

    if (registered_ == false)
        registered_ = dbusComm->sendDBusRegister();
    dbusComm->sessionConfigRequest(dbusComm->CmdSetInterval, 0, msec);
#endif
}

void QGeoPositionInfoSourceMaemo::setPreferredPositioningMethods(PositioningMethods sources)
{
#ifdef Q_WS_MAEMO_5
    return;
#else
    QGeoPositionInfoSource::setPreferredPositioningMethods(sources);
    if (registered_ == false)
        registered_ = dbusComm->sendDBusRegister();
    dbusComm->sessionConfigRequest(dbusComm->CmdSetMethods, sources, 0);
#endif
}

int QGeoPositionInfoSourceMaemo::minimumUpdateInterval() const
{
    return MinimumUpdateInterval;
}

// public slots:
void QGeoPositionInfoSourceMaemo::startUpdates()
{
#ifdef Q_WS_MAEMO_5
    if(locationControl) {
        if(!errorHandlerId) {
            errorHandlerId =
                g_signal_connect(G_OBJECT(locationControl), "error-verbose",
                                 G_CALLBACK(&locationError),
                                 static_cast<void*>(this));
        }

        if(!posChangedId) {
            posChangedId =
                g_signal_connect(G_OBJECT(locationDevice), "changed",
                                 G_CALLBACK(&locationChanged),
                                 static_cast<void*>(this));
        }

        if(!connectedId) {
            connectedId =
                g_signal_connect(G_OBJECT(locationDevice), "connected",
                                 G_CALLBACK(&deviceConnected),
                                 static_cast<void*>(this));
        }

        if(!disconnectedId) {
            disconnectedId =
                g_signal_connect(G_OBJECT(locationDevice), "disconnected",
                                 G_CALLBACK(&deviceDisconnected),
                                 static_cast<void*>(this));
        }

        location_gpsd_control_start(locationControl);
    } else {

    }
#else
    if (registered_ == false)
        registered_ = dbusComm->sendDBusRegister();

    int cmd = dbusComm->CmdStart;
    dbusComm->sessionConfigRequest(cmd, 222, time_interval_);
#endif
}

void QGeoPositionInfoSourceMaemo::stopUpdates()
{
#ifdef Q_WS_MAEMO_5
    if(locationControl) {
        if(errorHandlerId)
            g_signal_handler_disconnect(G_OBJECT(locationControl),
                                        errorHandlerId);
        if(posChangedId)
            g_signal_handler_disconnect(G_OBJECT(locationDevice),
                                        posChangedId);
        if(connectedId)
            g_signal_handler_disconnect(G_OBJECT(locationDevice),
                                        connectedId);
        if(disconnectedId)
            g_signal_handler_disconnect(G_OBJECT(locationDevice),
                                        disconnectedId);
        errorHandlerId = 0;
        posChangedId = 0;
        connectedId = 0;
        disconnectedId = 0;
        location_gpsd_control_stop(locationControl);
    }
#else
    if (registered_ == false)
        return; // nothing to stop
    dbusComm->sessionConfigRequest(dbusComm->CmdStop, 0, 0);
#endif
}

// Stub

void QGeoPositionInfoSourceMaemo::requestUpdate(int timeout)
{
    if (timeout) {}
}

#ifdef Q_WS_MAEMO_5
void QGeoPositionInfoSourceMaemo::locationError(LocationGPSDevice *device,
                                                gint errorCode, gpointer data)
{
    QString locationError;

    switch (errorCode) {
        case LOCATION_ERROR_USER_REJECTED_DIALOG:
            locationError = "User didn't enable requested methods";
            break;
        case LOCATION_ERROR_USER_REJECTED_SETTINGS:
            locationError = "User changed settings, which disabled location.";
            break;
        case LOCATION_ERROR_BT_GPS_NOT_AVAILABLE:
            locationError = "Problems with BT GPS";
            break;
        case LOCATION_ERROR_METHOD_NOT_ALLOWED_IN_OFFLINE_MODE:
            locationError = "Requested method is not allowed in offline mode";
            break;
        case LOCATION_ERROR_SYSTEM:
            locationError = "System error.";
            break;
        default:
            locationError = "Unknown error.";
    }

    qDebug() << "Location error:" << locationError;
}

void QGeoPositionInfoSourceMaemo::deviceDisconnected(LocationGPSDevice *device,
                                                     gpointer data)
{
    Q_UNUSED(device)

    if (!data)
        return;

    QGeoPositionInfoSourceMaemo *object = (QGeoPositionInfoSourceMaemo *)data;
    object->setOnline(false);
}

void QGeoPositionInfoSourceMaemo::deviceConnected(LocationGPSDevice *device,
                                                  gpointer data)
{
    Q_UNUSED(device)

    if (!data)
        return;

    QGeoPositionInfoSourceMaemo *object = (QGeoPositionInfoSourceMaemo *)data;
    object->setOnline(true);
}

void QGeoPositionInfoSourceMaemo::setOnline(bool status)
{
    emit online(status);
}

bool QGeoPositionInfoSourceMaemo::isOnline() const
{
    if (!locationDevice) {
        return false;
    }

    return locationDevice->online == 1;
}

void QGeoPositionInfoSourceMaemo::locationChanged(LocationGPSDevice *device,
                                                 gpointer data)
{
    QGeoPositionInfo posInfo;
    QGeoCoordinate coordinate;
    QGeoPositionInfoSourceMaemo *object;

    if (!data || !device)
        return;

    object = (QGeoPositionInfoSourceMaemo *)data;

    if (device && device->fix) {
        if (device->fix->fields & LOCATION_GPS_DEVICE_TIME_SET) {
            posInfo.setDateTime(QDateTime::fromTime_t(device->fix->time));
        }

        if (device->fix->fields & LOCATION_GPS_DEVICE_LATLONG_SET) {
            coordinate.setLatitude(device->fix->latitude);
            coordinate.setLongitude(device->fix->longitude);
            posInfo.setAttribute(QGeoPositionInfo::HorizontalAccuracy,
                                 device->fix->eph);
            posInfo.setAttribute(QGeoPositionInfo::VerticalAccuracy,
                                 device->fix->epv);

        }

        if (device->fix->fields & LOCATION_GPS_DEVICE_ALTITUDE_SET) {
            coordinate.setAltitude(device->fix->altitude);
        }

        if (device->fix->fields & LOCATION_GPS_DEVICE_SPEED_SET) {
            posInfo.setAttribute(QGeoPositionInfo::GroundSpeed,
                                 device->fix->speed);
        }

        if (device->fix->fields & LOCATION_GPS_DEVICE_TRACK_SET) {
            posInfo.setAttribute(QGeoPositionInfo::Direction,
                                 device->fix->track);
        }

    }

    if(device->status == LOCATION_GPS_DEVICE_STATUS_FIX) {
        posInfo.setCoordinate(coordinate);
        object->setLocation(posInfo);
    }
}

void QGeoPositionInfoSourceMaemo::setLocation(const QGeoPositionInfo &update)
{
    lastSatUpdate = update;
    validLastSatUpdate = true;
    emit positionUpdated(update);
}

int QGeoPositionInfoSourceMaemo::mapUpdateInterval(int msec) {
    if (msec < 1000)
        return LOCATION_INTERVAL_1S;
    else if ((msec >= 1000) && (msec < 3500))
        return LOCATION_INTERVAL_2S;
    else if ((msec >= 3500) && (msec < 7500))
        return LOCATION_INTERVAL_5S;
    else if ((msec >= 7500) && (msec < 15000))
        return LOCATION_INTERVAL_10S;
    else if ((msec >= 15000) && (msec < 25000))
        return LOCATION_INTERVAL_20S;
    else if ((msec >= 25000) && (msec < 45000))
        return LOCATION_INTERVAL_30S;
    else if ((msec >= 45000) && (msec < 90000))
        return LOCATION_INTERVAL_60S;
    else if (msec >= 90000)
        return LOCATION_INTERVAL_120S;
}

#endif // Q_WS_MAEMO_5

#include "moc_qgeopositioninfosource_maemo_p.cpp"
QTM_END_NAMESPACE

<commit_msg>Initial interval changed to LOCATION_INTERVAL_DEFAULT.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qgeopositioninfosource_maemo_p.h"
#include <iostream>

#ifdef Q_WS_MAEMO_5
#include <QDateTime>
#endif
#if 0
void dumpQByteArray(const QByteArray &msg)
{
    std::cout << "QByteArray dump:\n";
    std::cout << msg.size() << "  \n";
    int i =  msg.size();
    for (int k = 0; k < i ;k++)
        printf("msg[%d]=%2.2x\n", k, (unsigned char)msg[k]);
}
#endif

using namespace std;

QTM_BEGIN_NAMESPACE

QGeoPositionInfoSourceMaemo::QGeoPositionInfoSourceMaemo(QObject *parent): QGeoPositionInfoSource(parent)
{
    // default values
#ifdef Q_WS_MAEMO_5
    time_interval_ = LOCATION_INTERVAL_DEFAULT;
    availableMethods = SatellitePositioningMethods;
#else
    time_interval_ = 5000;
    availableMethods = AllPositioningMethods;
#endif
    distance_interval_ = 10;
    registered_ = false;
    validLastUpdate = false;
    validLastSatUpdate = false;
}

int QGeoPositionInfoSourceMaemo::init()
{
#ifdef Q_WS_MAEMO_5
    g_type_init();

    locationControl = location_gpsd_control_get_default();
    if(locationControl) {
        g_object_set(G_OBJECT(locationControl),
                     "preferred-method", LOCATION_METHOD_USER_SELECTED,
                     "preferred-interval", time_interval_,
                     NULL);
    } else {
        return -1;
    }

    locationDevice =
            (LocationGPSDevice*)g_object_new(LOCATION_TYPE_GPS_DEVICE,
                                             NULL);

    if(locationDevice) {
        errorHandlerId =
            g_signal_connect(G_OBJECT(locationControl), "error-verbose",
                             G_CALLBACK(&locationError),
                             static_cast<void*>(this));
        posChangedId =
            g_signal_connect(G_OBJECT(locationDevice), "changed",
                             G_CALLBACK(&locationChanged),
                             static_cast<void*>(this));
        connectedId =
            g_signal_connect(G_OBJECT(locationDevice), "connected",
                             G_CALLBACK(&deviceConnected),
                             static_cast<void*>(this));
        disconnectedId =
            g_signal_connect(G_OBJECT(locationDevice), "disconnected",
                             G_CALLBACK(&deviceDisconnected),
                             static_cast<void*>(this));
        return 0;
    } else {
        return -1;
    }
#else
    int status;

    dbusComm = new DBusComm();
    status = dbusComm->init();

    QObject::connect(dbusComm, SIGNAL(receivedMessage(const QByteArray &)),
                     this, SLOT(dbusMessages(const QByteArray &)));

    QObject::connect(dbusComm, SIGNAL(receivedPositionUpdate(const QGeoPositionInfo &)),
                     this, SLOT(newPositionUpdate(const QGeoPositionInfo &)));
    return status;
#endif // Q_WS_MAEMO_5
}

void QGeoPositionInfoSourceMaemo::dbusMessages(const QByteArray &msg)
{
    Q_UNUSED(msg)
    // stub

    return;
}

void QGeoPositionInfoSourceMaemo::newPositionUpdate(const QGeoPositionInfo &update)
{
    lastSatUpdate = update;
    validLastSatUpdate = true;
    emit positionUpdated(update);
}

QGeoPositionInfo QGeoPositionInfoSourceMaemo::lastKnownPosition(bool fromSatellitePositioningMethodsOnly) const
{
    if (validLastSatUpdate)
        return lastSatUpdate;

    if (!fromSatellitePositioningMethodsOnly)
        if (validLastUpdate)
            return lastUpdate;

    return QGeoPositionInfo();
}

QGeoPositionInfoSource::PositioningMethods QGeoPositionInfoSourceMaemo::supportedPositioningMethods() const
{
    return availableMethods;
}

void QGeoPositionInfoSourceMaemo::setUpdateInterval(int msec)
{
    msec = (msec < MinimumUpdateInterval) ? MinimumUpdateInterval : msec;

#ifdef Q_WS_MAEMO_5
    time_interval_ = mapUpdateInterval(msec);
    QGeoPositionInfoSource::setUpdateInterval(time_interval_*100);
    if(locationControl) {
        g_object_set(G_OBJECT(locationControl),
                     "preferred-method", LOCATION_METHOD_USER_SELECTED,
                     "preferred-interval", time_interval_,
                     NULL) ;
    }
#else
    QGeoPositionInfoSource::setUpdateInterval(msec);

    if (registered_ == false)
        registered_ = dbusComm->sendDBusRegister();
    dbusComm->sessionConfigRequest(dbusComm->CmdSetInterval, 0, msec);
#endif
}

void QGeoPositionInfoSourceMaemo::setPreferredPositioningMethods(PositioningMethods sources)
{
#ifdef Q_WS_MAEMO_5
    return;
#else
    QGeoPositionInfoSource::setPreferredPositioningMethods(sources);
    if (registered_ == false)
        registered_ = dbusComm->sendDBusRegister();
    dbusComm->sessionConfigRequest(dbusComm->CmdSetMethods, sources, 0);
#endif
}

int QGeoPositionInfoSourceMaemo::minimumUpdateInterval() const
{
    return MinimumUpdateInterval;
}

// public slots:
void QGeoPositionInfoSourceMaemo::startUpdates()
{
#ifdef Q_WS_MAEMO_5
    if(locationControl) {
        if(!errorHandlerId) {
            errorHandlerId =
                g_signal_connect(G_OBJECT(locationControl), "error-verbose",
                                 G_CALLBACK(&locationError),
                                 static_cast<void*>(this));
        }

        if(!posChangedId) {
            posChangedId =
                g_signal_connect(G_OBJECT(locationDevice), "changed",
                                 G_CALLBACK(&locationChanged),
                                 static_cast<void*>(this));
        }

        if(!connectedId) {
            connectedId =
                g_signal_connect(G_OBJECT(locationDevice), "connected",
                                 G_CALLBACK(&deviceConnected),
                                 static_cast<void*>(this));
        }

        if(!disconnectedId) {
            disconnectedId =
                g_signal_connect(G_OBJECT(locationDevice), "disconnected",
                                 G_CALLBACK(&deviceDisconnected),
                                 static_cast<void*>(this));
        }

        location_gpsd_control_start(locationControl);
    } else {

    }
#else
    if (registered_ == false)
        registered_ = dbusComm->sendDBusRegister();

    int cmd = dbusComm->CmdStart;
    dbusComm->sessionConfigRequest(cmd, 222, time_interval_);
#endif
}

void QGeoPositionInfoSourceMaemo::stopUpdates()
{
#ifdef Q_WS_MAEMO_5
    if(locationControl) {
        if(errorHandlerId)
            g_signal_handler_disconnect(G_OBJECT(locationControl),
                                        errorHandlerId);
        if(posChangedId)
            g_signal_handler_disconnect(G_OBJECT(locationDevice),
                                        posChangedId);
        if(connectedId)
            g_signal_handler_disconnect(G_OBJECT(locationDevice),
                                        connectedId);
        if(disconnectedId)
            g_signal_handler_disconnect(G_OBJECT(locationDevice),
                                        disconnectedId);
        errorHandlerId = 0;
        posChangedId = 0;
        connectedId = 0;
        disconnectedId = 0;
        location_gpsd_control_stop(locationControl);
    }
#else
    if (registered_ == false)
        return; // nothing to stop
    dbusComm->sessionConfigRequest(dbusComm->CmdStop, 0, 0);
#endif
}

// Stub

void QGeoPositionInfoSourceMaemo::requestUpdate(int timeout)
{
    if (timeout) {}
}

#ifdef Q_WS_MAEMO_5
void QGeoPositionInfoSourceMaemo::locationError(LocationGPSDevice *device,
                                                gint errorCode, gpointer data)
{
    QString locationError;

    switch (errorCode) {
        case LOCATION_ERROR_USER_REJECTED_DIALOG:
            locationError = "User didn't enable requested methods";
            break;
        case LOCATION_ERROR_USER_REJECTED_SETTINGS:
            locationError = "User changed settings, which disabled location.";
            break;
        case LOCATION_ERROR_BT_GPS_NOT_AVAILABLE:
            locationError = "Problems with BT GPS";
            break;
        case LOCATION_ERROR_METHOD_NOT_ALLOWED_IN_OFFLINE_MODE:
            locationError = "Requested method is not allowed in offline mode";
            break;
        case LOCATION_ERROR_SYSTEM:
            locationError = "System error.";
            break;
        default:
            locationError = "Unknown error.";
    }

    qDebug() << "Location error:" << locationError;
}

void QGeoPositionInfoSourceMaemo::deviceDisconnected(LocationGPSDevice *device,
                                                     gpointer data)
{
    Q_UNUSED(device)

    if (!data)
        return;

    QGeoPositionInfoSourceMaemo *object = (QGeoPositionInfoSourceMaemo *)data;
    object->setOnline(false);
}

void QGeoPositionInfoSourceMaemo::deviceConnected(LocationGPSDevice *device,
                                                  gpointer data)
{
    Q_UNUSED(device)

    if (!data)
        return;

    QGeoPositionInfoSourceMaemo *object = (QGeoPositionInfoSourceMaemo *)data;
    object->setOnline(true);
}

void QGeoPositionInfoSourceMaemo::setOnline(bool status)
{
    emit online(status);
}

bool QGeoPositionInfoSourceMaemo::isOnline() const
{
    if (!locationDevice) {
        return false;
    }

    return locationDevice->online == 1;
}

void QGeoPositionInfoSourceMaemo::locationChanged(LocationGPSDevice *device,
                                                 gpointer data)
{
    QGeoPositionInfo posInfo;
    QGeoCoordinate coordinate;
    QGeoPositionInfoSourceMaemo *object;

    if (!data || !device)
        return;

    object = (QGeoPositionInfoSourceMaemo *)data;

    if (device && device->fix) {
        if (device->fix->fields & LOCATION_GPS_DEVICE_TIME_SET) {
            posInfo.setDateTime(QDateTime::fromTime_t(device->fix->time));
        }

        if (device->fix->fields & LOCATION_GPS_DEVICE_LATLONG_SET) {
            coordinate.setLatitude(device->fix->latitude);
            coordinate.setLongitude(device->fix->longitude);
            posInfo.setAttribute(QGeoPositionInfo::HorizontalAccuracy,
                                 device->fix->eph);
            posInfo.setAttribute(QGeoPositionInfo::VerticalAccuracy,
                                 device->fix->epv);

        }

        if (device->fix->fields & LOCATION_GPS_DEVICE_ALTITUDE_SET) {
            coordinate.setAltitude(device->fix->altitude);
        }

        if (device->fix->fields & LOCATION_GPS_DEVICE_SPEED_SET) {
            posInfo.setAttribute(QGeoPositionInfo::GroundSpeed,
                                 device->fix->speed);
        }

        if (device->fix->fields & LOCATION_GPS_DEVICE_TRACK_SET) {
            posInfo.setAttribute(QGeoPositionInfo::Direction,
                                 device->fix->track);
        }

    }

    if(device->status == LOCATION_GPS_DEVICE_STATUS_FIX) {
        posInfo.setCoordinate(coordinate);
        object->setLocation(posInfo);
    }
}

void QGeoPositionInfoSourceMaemo::setLocation(const QGeoPositionInfo &update)
{
    lastSatUpdate = update;
    validLastSatUpdate = true;
    emit positionUpdated(update);
}

int QGeoPositionInfoSourceMaemo::mapUpdateInterval(int msec) {
    if (msec < 1000)
        return LOCATION_INTERVAL_1S;
    else if ((msec >= 1000) && (msec < 3500))
        return LOCATION_INTERVAL_2S;
    else if ((msec >= 3500) && (msec < 7500))
        return LOCATION_INTERVAL_5S;
    else if ((msec >= 7500) && (msec < 15000))
        return LOCATION_INTERVAL_10S;
    else if ((msec >= 15000) && (msec < 25000))
        return LOCATION_INTERVAL_20S;
    else if ((msec >= 25000) && (msec < 45000))
        return LOCATION_INTERVAL_30S;
    else if ((msec >= 45000) && (msec < 90000))
        return LOCATION_INTERVAL_60S;
    else if (msec >= 90000)
        return LOCATION_INTERVAL_120S;
}

#endif // Q_WS_MAEMO_5

#include "moc_qgeopositioninfosource_maemo_p.cpp"
QTM_END_NAMESPACE

<|endoftext|>