<commit_before>#include <rtt/os/main.h>

#include <boost/program_options.hpp>
#include <iostream>

#ifdef OROGEN_SERVICE_DISCOVERY_ACTIVATED
#include <service_discovery/service_discovery.h>
#endif // OROGEN_SERVICE_DISCOVERY_ACTIVATED

#include <rtt/typekit/RealTimeTypekit.hpp>
<% deployer.rtt_transports.each do |transport_name| %>
#include <rtt/transports/<%= transport_name %>/TransportPlugin.hpp>
<% end %>

<% if component.typekit || !component.used_typekits.empty? %>#include <rtt/types/TypekitPlugin.hpp><% end %>
<% if typekit = component.typekit %>
#include "typekit/Plugin.hpp"
<% deployer.transports.each do |transport_name| %>
#include "typekit/transports/<%= transport_name %>/TransportPlugin.hpp"
<% end %>
<% end %>
<% deployer.used_typekits.each do |tk| %>
    <% next if tk.virtual? %>
#include <<%= tk.name %>/typekit/Plugin.hpp>
    <% deployer.transports.each do |transport_name| %>
#include <<%= tk.name %>/transports/<%= transport_name %>/TransportPlugin.hpp>
    <% end %>
<% end %>

<% task_activities = deployer.task_activities.
        sort_by(&:name) %>

<% task_activities.each do |task| %>
#include <<%= task.context.header_file %>>
<% end %>
<% if deployer.corba_enabled? %>
#include <rtt/transports/corba/ApplicationServer.hpp>
#include <rtt/transports/corba/TaskContextServer.hpp>
#include <rtt/transports/corba/CorbaDispatcher.hpp>
#include <signal.h>
<% end %>

<% require 'set'
    activity_headers = task_activities.
        map { |t| t.activity_type.header }.
        compact.
        to_set %>
<% activity_headers.to_a.sort.each do |header| %>
#include <<%= header %>>
<% end %>

<% if deployer.browse %>
#include <ocl/TaskBrowser.hpp>
<% end %>

#include <rtt/Logger.hpp>
#include <rtt/base/ActivityInterface.hpp>

namespace po = boost::program_options;

class Deinitializer
{
    friend Deinitializer& operator << (Deinitializer&, RTT::base::ActivityInterface&);

    std::vector<RTT::base::ActivityInterface*> m_activities;

#ifdef OROGEN_SERVICE_DISCOVERY_ACTIVATED
    friend Deinitializer& operator << (Deinitializer&, servicediscovery::ServiceDiscovery&);

    std::vector<servicediscovery::ServiceDiscovery*> m_service_discoveries;
#endif

public:
    ~Deinitializer()
    {
        for (std::vector<RTT::base::ActivityInterface*>::const_iterator it = m_activities.begin();
                it != m_activities.end(); ++it)
        {
            (*it)->stop();
        }

#ifdef OROGEN_SERVICE_DISCOVERY_ACTIVATED
        for(std::vector<servicediscovery::ServiceDiscovery*>::iterator sit = m_service_discoveries.begin();
                sit != m_service_discoveries.end(); ++sit)
        {
            (*sit)->stop();
            delete *sit;
        }
#endif
    }
};

Deinitializer& operator << (Deinitializer& deinit, RTT::base::ActivityInterface& activity)
{
    deinit.m_activities.push_back(&activity);
    return deinit;
}

#ifdef OROGEN_SERVICE_DISCOVERY_ACTIVATED
Deinitializer& operator << (Deinitializer& deinit, servicediscovery::ServiceDiscovery& service_discovery)
{
    deinit.m_service_discoveries.push_back(&service_discovery);
    return deinit;
}
#endif

<% if deployer.corba_enabled? %>
int sigint_com[2];
void sigint_quit_orb(int)
{
    uint8_t dummy = 0;
    write(sigint_com[1], &dummy, 1);
}
<% end %>

int ORO_main(int argc, char* argv[])
{
   po::options_description desc("Options");

   desc.add_options()
        ("help", "show all available options supported by this deployment")
        ("prefix", po::value<std::string>(), "Sets a prefix for all TaskContext names")
#ifdef OROGEN_SERVICE_DISCOVERY_ACTIVATED
        ("sd-domain", po::value<std::string>(), "set service discovery domain")
#endif // OROGEN_SERVICE_DISOCVERY_ACTIVATED
        ("rename", po::value< std::vector<std::string> >(), "rename a task of the deployment: --rename oldname:newname");

   po::variables_map vm;
   po::store(po::parse_command_line(argc, argv, desc), vm);
   po::notify(vm);

   if(vm.count("help")) {
       std::cout << desc << std::endl;
       return 0;
   }

   <% if deployer.loglevel %>
   if ( log().getLogLevel() < Logger::<%= deployer.loglevel %> ) {
       log().setLogLevel( Logger::<%= deployer.loglevel %> );
   }
   <% end %>

   RTT::types::TypekitRepository::Import( new RTT::types::RealTimeTypekitPlugin );
   <% if deployer.transports.include?('corba') %>
   RTT::types::TypekitRepository::Import( new RTT::corba::CorbaLibPlugin );
   <% end %>
   <% if deployer.transports.include?('mqueue') %>
   RTT::types::TypekitRepository::Import( new RTT::mqueue::MQLibPlugin );
   <% end %>

   <% if component.typekit %>
   RTT::types::TypekitRepository::Import( new orogen_typekits::<%= component.name %>TypekitPlugin );
   <% deployer.transports.each do |transport_name| %>
   RTT::types::TypekitRepository::Import( new <%= typekit.transport_plugin_name(transport_name) %> );
   <% end %>
   <% end %>
   <% deployer.used_typekits.each do |tk| %>
   <% next if tk.virtual? %>
   RTT::types::TypekitRepository::Import( new orogen_typekits::<%= tk.name %>TypekitPlugin );
       <% deployer.transports.each do |transport_name| %>
   RTT::types::TypekitRepository::Import( new <%= Orocos::Generation::Typekit.transport_plugin_name(transport_name, tk.name) %> );
       <% end %>
   <% end %>

<% if deployer.corba_enabled? %>
    RTT::corba::ApplicationServer::InitOrb(argc, argv);
<% end %>

    std::string prefix = "";

    if( vm.count("prefix"))
        prefix = vm["prefix"].as<std::string>();

    std::string task_name;

    std::map<std::string, std::string> rename_map;

    if ( vm.count("rename") ) {

        const std::vector< std::string>& ren_vec = vm["rename"].as<std::vector <std::string> >();

        for ( unsigned int i = 0; i < ren_vec.size(); i++) {

            const std::string& ren_str = ren_vec.at(i);

            unsigned int colon_pos = ren_str.find(':');
            if ( colon_pos == std::string::npos ) continue;

            rename_map.insert( std::pair<std::string, std::string>(
                ren_str.substr(0,colon_pos), ren_str.substr(colon_pos+1) ));
        }
    }

<% task_activities.each do |task| %>
    task_name = "<%= task.name %>";
    if (rename_map.count(task_name))
        task_name = rename_map[task_name];
    else
        task_name = prefix + task_name;

    <%= task.context.class_name %> task_<%= task.name%>(task_name);
    <%= task.generate_activity_setup %>
    task_<%= task.name %>.setActivity(activity_<%= task.name %>);
    <% task.properties.sort_by { |prop| prop.name }.each do |prop|
        if prop.value %>
    dynamic_cast< RTT::Property<  <%= prop.interface_object.type.cxx_name %> >*>(
            task_<%= task.name %>.properties()->getProperty("<%= prop.name %>"))
        ->set(<%= prop.value.inspect %>);
        <% end %>
    <% end %>

    <% if deployer.corba_enabled? %>
    RTT::corba::TaskContextServer::Create( &task_<%= task.name%> );
    <% if task.realtime? %>
    RTT::corba::CorbaDispatcher::Instance( task_<%= task.name %>.ports(), ORO_SCHED_RT, RTT::os::LowestPriority );
    <% else %>
    RTT::corba::CorbaDispatcher::Instance( task_<%= task.name %>.ports(), ORO_SCHED_OTHER, RTT::os::LowestPriority );
    <% end %>
    <% end %>

<% end %>

   Deinitializer deinit;

#ifdef OROGEN_SERVICE_DISCOVERY_ACTIVATED
    if( vm.count("sd-domain") ) {
<% task_activities.each do |task| %>
    servicediscovery::ServiceConfiguration sd_conf_<%= task.name%>(prefix + "<%= task.name %>", vm["sd-domain"].as<std::string>());
    sd_conf_<%= task.name%>.setDescription("IOR", RTT::corba::TaskContextServer::getIOR(&task_<%= task.name%>));
    servicediscovery::ServiceDiscovery* sd_<%= task.name%> = new servicediscovery::ServiceDiscovery();
    deinit << *sd_<%= task.name%>;
    sd_<%= task.name%>->start(sd_conf_<%= task.name%>);
<% end %>
    }
#endif // OROGEN_SERVICE_DISCOVERY_ACTIVATED

<% if !deployer.loggers.empty?
        deployer.loggers.sort_by { |filename, _| filename }.each do |filename, logger|
            logger.config.each do |type, reported_activity, args| %>
                task_<%= logger.task.name %>.connectPeers(&task_<%= reported_activity.name %>);
                task_<%= logger.task.name %>.report<%= type %>(<%= args.map { |v| "\"#{v}\"" }.join(", ") %>);
            <% end %>
        <% end %>
<% end %>

<% deployer.peers.sort_by { |a, b| [a.name, b.name] }.each do |a, b| %>
    task_<%= a.name %>.connectPeers(&task_<%= b.name %>);
<% end %>

<% deployer.connections.
    sort_by { |src, dst, policy| [src.name, dst.name] }.
    each do |src, dst, policy|
        if src.kind_of?(TaskDeployment) %>
            task_<%= src.activity.name %>.connectPorts(&task_<%= dst.activity.name %>);
        <% else %>
        {
            <%= policy.to_code("policy") %>
            RTT::base::OutputPortInterface* src = dynamic_cast<RTT::base::OutputPortInterface*>(
                    task_<%= src.activity.name %>.ports()->getPort("<%= src.name %>"));
            RTT::base::InputPortInterface* dst = dynamic_cast<RTT::base::InputPortInterface*>(
                    task_<%= dst.activity.name %>.ports()->getPort("<%= dst.name %>"));
            src->createConnection(*dst, policy);
        }
        <% end %>
    <% end %>

    // Start some activities
<% task_activities.each do |task| %>
    deinit << *activity_<%= task.name%>;

    <% if task.start?
        if task.context.needs_configuration? %>
    if (!task_<%= task.name %>.configure())
    {
        RTT::log(RTT::Error) << "cannot configure <%= task.name %>" << RTT::endlog();
        return -1;
    }
        <% end %>
    if (!task_<%= task.name %>.start())
    {
        RTT::log(RTT::Error) << "cannot start <%= task.name %>" << RTT::endlog();
        return -1;
    }
    <% end %>
<% end %>

<% if deployer.corba_enabled? %>
    /** Setup shutdown procedure on SIGINT. We use a pipe-based channel to do
        so, as we can't shutdown the ORB from the signal handler */
    if (pipe(sigint_com) == -1)
    {
        std::cerr << "failed to setup SIGINT handler: " << strerror(errno) << std::endl;
        return 1;
    }

    struct sigaction sigint_handler;
    sigint_handler.sa_handler = &sigint_quit_orb;
    sigemptyset(&sigint_handler.sa_mask);
    sigint_handler.sa_flags     = 0;
    sigint_handler.sa_restorer  = 0;
    if (-1 == sigaction(SIGINT, &sigint_handler, 0))
    {
        std::cerr << "failed to install SIGINT handler" << std::endl;
        return 1;
    }
    sigset_t unblock_sigint;
    sigemptyset(&unblock_sigint);
    sigaddset(&unblock_sigint, SIGINT);
    if (-1 == sigprocmask(SIG_UNBLOCK, &unblock_sigint, NULL))
    {
        std::cerr << "failed to install SIGINT handler" << std::endl;
        return 1;
    }
    RTT::corba::TaskContextServer::ThreadOrb();
    while (true)
    {
        uint8_t dummy;
        int read_count = read(sigint_com[0], &dummy, 1);
        if (read_count == 1)
            break;
    }

    RTT::corba::TaskContextServer::ShutdownOrb();
    RTT::corba::TaskContextServer::DestroyOrb();
<% elsif deployer.browse %>
    OCL::TaskBrowser browser(& task_<%= deployer.browse.name %>);
    browser.loop();
<% end %>

    return 0;
}

<commit_msg>fixed compile warning in template for generated deployments<commit_after>#include <rtt/os/main.h>

#include <boost/program_options.hpp>
#include <iostream>

#ifdef OROGEN_SERVICE_DISCOVERY_ACTIVATED
#include <service_discovery/service_discovery.h>
#endif // OROGEN_SERVICE_DISCOVERY_ACTIVATED

#include <rtt/typekit/RealTimeTypekit.hpp>
<% deployer.rtt_transports.each do |transport_name| %>
#include <rtt/transports/<%= transport_name %>/TransportPlugin.hpp>
<% end %>

<% if component.typekit || !component.used_typekits.empty? %>#include <rtt/types/TypekitPlugin.hpp><% end %>
<% if typekit = component.typekit %>
#include "typekit/Plugin.hpp"
<% deployer.transports.each do |transport_name| %>
#include "typekit/transports/<%= transport_name %>/TransportPlugin.hpp"
<% end %>
<% end %>
<% deployer.used_typekits.each do |tk| %>
    <% next if tk.virtual? %>
#include <<%= tk.name %>/typekit/Plugin.hpp>
    <% deployer.transports.each do |transport_name| %>
#include <<%= tk.name %>/transports/<%= transport_name %>/TransportPlugin.hpp>
    <% end %>
<% end %>

<% task_activities = deployer.task_activities.
        sort_by(&:name) %>

<% task_activities.each do |task| %>
#include <<%= task.context.header_file %>>
<% end %>
<% if deployer.corba_enabled? %>
#include <rtt/transports/corba/ApplicationServer.hpp>
#include <rtt/transports/corba/TaskContextServer.hpp>
#include <rtt/transports/corba/CorbaDispatcher.hpp>
#include <signal.h>
<% end %>

<% require 'set'
    activity_headers = task_activities.
        map { |t| t.activity_type.header }.
        compact.
        to_set %>
<% activity_headers.to_a.sort.each do |header| %>
#include <<%= header %>>
<% end %>

<% if deployer.browse %>
#include <ocl/TaskBrowser.hpp>
<% end %>

#include <rtt/Logger.hpp>
#include <rtt/base/ActivityInterface.hpp>

namespace po = boost::program_options;

class Deinitializer
{
    friend Deinitializer& operator << (Deinitializer&, RTT::base::ActivityInterface&);

    std::vector<RTT::base::ActivityInterface*> m_activities;

#ifdef OROGEN_SERVICE_DISCOVERY_ACTIVATED
    friend Deinitializer& operator << (Deinitializer&, servicediscovery::ServiceDiscovery&);

    std::vector<servicediscovery::ServiceDiscovery*> m_service_discoveries;
#endif

public:
    ~Deinitializer()
    {
        for (std::vector<RTT::base::ActivityInterface*>::const_iterator it = m_activities.begin();
                it != m_activities.end(); ++it)
        {
            (*it)->stop();
        }

#ifdef OROGEN_SERVICE_DISCOVERY_ACTIVATED
        for(std::vector<servicediscovery::ServiceDiscovery*>::iterator sit = m_service_discoveries.begin();
                sit != m_service_discoveries.end(); ++sit)
        {
            (*sit)->stop();
            delete *sit;
        }
#endif
    }
};

Deinitializer& operator << (Deinitializer& deinit, RTT::base::ActivityInterface& activity)
{
    deinit.m_activities.push_back(&activity);
    return deinit;
}

#ifdef OROGEN_SERVICE_DISCOVERY_ACTIVATED
Deinitializer& operator << (Deinitializer& deinit, servicediscovery::ServiceDiscovery& service_discovery)
{
    deinit.m_service_discoveries.push_back(&service_discovery);
    return deinit;
}
#endif

<% if deployer.corba_enabled? %>
int sigint_com[2];
void sigint_quit_orb(int)
{
    uint8_t dummy = 0;
    unsigned int sent = 0;
    while(sent < sizeof(uint8_t))
    {
	int ret = write(sigint_com[1], &dummy, sizeof(uint8_t));
	if(ret < 0)
	{
	    std::cerr << "Failed to signal quit to orb" << std::endl;
	    break;
	}
	sent += ret;
    }
}
<% end %>

int ORO_main(int argc, char* argv[])
{
   po::options_description desc("Options");

   desc.add_options()
        ("help", "show all available options supported by this deployment")
        ("prefix", po::value<std::string>(), "Sets a prefix for all TaskContext names")
#ifdef OROGEN_SERVICE_DISCOVERY_ACTIVATED
        ("sd-domain", po::value<std::string>(), "set service discovery domain")
#endif // OROGEN_SERVICE_DISOCVERY_ACTIVATED
        ("rename", po::value< std::vector<std::string> >(), "rename a task of the deployment: --rename oldname:newname");

   po::variables_map vm;
   po::store(po::parse_command_line(argc, argv, desc), vm);
   po::notify(vm);

   if(vm.count("help")) {
       std::cout << desc << std::endl;
       return 0;
   }

   <% if deployer.loglevel %>
   if ( log().getLogLevel() < Logger::<%= deployer.loglevel %> ) {
       log().setLogLevel( Logger::<%= deployer.loglevel %> );
   }
   <% end %>

   RTT::types::TypekitRepository::Import( new RTT::types::RealTimeTypekitPlugin );
   <% if deployer.transports.include?('corba') %>
   RTT::types::TypekitRepository::Import( new RTT::corba::CorbaLibPlugin );
   <% end %>
   <% if deployer.transports.include?('mqueue') %>
   RTT::types::TypekitRepository::Import( new RTT::mqueue::MQLibPlugin );
   <% end %>

   <% if component.typekit %>
   RTT::types::TypekitRepository::Import( new orogen_typekits::<%= component.name %>TypekitPlugin );
   <% deployer.transports.each do |transport_name| %>
   RTT::types::TypekitRepository::Import( new <%= typekit.transport_plugin_name(transport_name) %> );
   <% end %>
   <% end %>
   <% deployer.used_typekits.each do |tk| %>
   <% next if tk.virtual? %>
   RTT::types::TypekitRepository::Import( new orogen_typekits::<%= tk.name %>TypekitPlugin );
       <% deployer.transports.each do |transport_name| %>
   RTT::types::TypekitRepository::Import( new <%= Orocos::Generation::Typekit.transport_plugin_name(transport_name, tk.name) %> );
       <% end %>
   <% end %>

<% if deployer.corba_enabled? %>
    RTT::corba::ApplicationServer::InitOrb(argc, argv);
<% end %>

    std::string prefix = "";

    if( vm.count("prefix"))
        prefix = vm["prefix"].as<std::string>();

    std::string task_name;

    std::map<std::string, std::string> rename_map;

    if ( vm.count("rename") ) {

        const std::vector< std::string>& ren_vec = vm["rename"].as<std::vector <std::string> >();

        for ( unsigned int i = 0; i < ren_vec.size(); i++) {

            const std::string& ren_str = ren_vec.at(i);

            unsigned int colon_pos = ren_str.find(':');
            if ( colon_pos == std::string::npos ) continue;

            rename_map.insert( std::pair<std::string, std::string>(
                ren_str.substr(0,colon_pos), ren_str.substr(colon_pos+1) ));
        }
    }

<% task_activities.each do |task| %>
    task_name = "<%= task.name %>";
    if (rename_map.count(task_name))
        task_name = rename_map[task_name];
    else
        task_name = prefix + task_name;

    <%= task.context.class_name %> task_<%= task.name%>(task_name);
    <%= task.generate_activity_setup %>
    task_<%= task.name %>.setActivity(activity_<%= task.name %>);
    <% task.properties.sort_by { |prop| prop.name }.each do |prop|
        if prop.value %>
    dynamic_cast< RTT::Property<  <%= prop.interface_object.type.cxx_name %> >*>(
            task_<%= task.name %>.properties()->getProperty("<%= prop.name %>"))
        ->set(<%= prop.value.inspect %>);
        <% end %>
    <% end %>

    <% if deployer.corba_enabled? %>
    RTT::corba::TaskContextServer::Create( &task_<%= task.name%> );
    <% if task.realtime? %>
    RTT::corba::CorbaDispatcher::Instance( task_<%= task.name %>.ports(), ORO_SCHED_RT, RTT::os::LowestPriority );
    <% else %>
    RTT::corba::CorbaDispatcher::Instance( task_<%= task.name %>.ports(), ORO_SCHED_OTHER, RTT::os::LowestPriority );
    <% end %>
    <% end %>

<% end %>

   Deinitializer deinit;

#ifdef OROGEN_SERVICE_DISCOVERY_ACTIVATED
    if( vm.count("sd-domain") ) {
<% task_activities.each do |task| %>
    servicediscovery::ServiceConfiguration sd_conf_<%= task.name%>(prefix + "<%= task.name %>", vm["sd-domain"].as<std::string>());
    sd_conf_<%= task.name%>.setDescription("IOR", RTT::corba::TaskContextServer::getIOR(&task_<%= task.name%>));
    servicediscovery::ServiceDiscovery* sd_<%= task.name%> = new servicediscovery::ServiceDiscovery();
    deinit << *sd_<%= task.name%>;
    sd_<%= task.name%>->start(sd_conf_<%= task.name%>);
<% end %>
    }
#endif // OROGEN_SERVICE_DISCOVERY_ACTIVATED

<% if !deployer.loggers.empty?
        deployer.loggers.sort_by { |filename, _| filename }.each do |filename, logger|
            logger.config.each do |type, reported_activity, args| %>
                task_<%= logger.task.name %>.connectPeers(&task_<%= reported_activity.name %>);
                task_<%= logger.task.name %>.report<%= type %>(<%= args.map { |v| "\"#{v}\"" }.join(", ") %>);
            <% end %>
        <% end %>
<% end %>

<% deployer.peers.sort_by { |a, b| [a.name, b.name] }.each do |a, b| %>
    task_<%= a.name %>.connectPeers(&task_<%= b.name %>);
<% end %>

<% deployer.connections.
    sort_by { |src, dst, policy| [src.name, dst.name] }.
    each do |src, dst, policy|
        if src.kind_of?(TaskDeployment) %>
            task_<%= src.activity.name %>.connectPorts(&task_<%= dst.activity.name %>);
        <% else %>
        {
            <%= policy.to_code("policy") %>
            RTT::base::OutputPortInterface* src = dynamic_cast<RTT::base::OutputPortInterface*>(
                    task_<%= src.activity.name %>.ports()->getPort("<%= src.name %>"));
            RTT::base::InputPortInterface* dst = dynamic_cast<RTT::base::InputPortInterface*>(
                    task_<%= dst.activity.name %>.ports()->getPort("<%= dst.name %>"));
            src->createConnection(*dst, policy);
        }
        <% end %>
    <% end %>

    // Start some activities
<% task_activities.each do |task| %>
    deinit << *activity_<%= task.name%>;

    <% if task.start?
        if task.context.needs_configuration? %>
    if (!task_<%= task.name %>.configure())
    {
        RTT::log(RTT::Error) << "cannot configure <%= task.name %>" << RTT::endlog();
        return -1;
    }
        <% end %>
    if (!task_<%= task.name %>.start())
    {
        RTT::log(RTT::Error) << "cannot start <%= task.name %>" << RTT::endlog();
        return -1;
    }
    <% end %>
<% end %>

<% if deployer.corba_enabled? %>
    /** Setup shutdown procedure on SIGINT. We use a pipe-based channel to do
        so, as we can't shutdown the ORB from the signal handler */
    if (pipe(sigint_com) == -1)
    {
        std::cerr << "failed to setup SIGINT handler: " << strerror(errno) << std::endl;
        return 1;
    }

    struct sigaction sigint_handler;
    sigint_handler.sa_handler = &sigint_quit_orb;
    sigemptyset(&sigint_handler.sa_mask);
    sigint_handler.sa_flags     = 0;
    sigint_handler.sa_restorer  = 0;
    if (-1 == sigaction(SIGINT, &sigint_handler, 0))
    {
        std::cerr << "failed to install SIGINT handler" << std::endl;
        return 1;
    }
    sigset_t unblock_sigint;
    sigemptyset(&unblock_sigint);
    sigaddset(&unblock_sigint, SIGINT);
    if (-1 == sigprocmask(SIG_UNBLOCK, &unblock_sigint, NULL))
    {
        std::cerr << "failed to install SIGINT handler" << std::endl;
        return 1;
    }
    RTT::corba::TaskContextServer::ThreadOrb();
    while (true)
    {
        uint8_t dummy;
        int read_count = read(sigint_com[0], &dummy, 1);
        if (read_count == 1)
            break;
    }

    RTT::corba::TaskContextServer::ShutdownOrb();
    RTT::corba::TaskContextServer::DestroyOrb();
<% elsif deployer.browse %>
    OCL::TaskBrowser browser(& task_<%= deployer.browse.name %>);
    browser.loop();
<% end %>

    return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: VColumn.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 02:10:00 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/sdbcx/VColumn.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
// -------------------------------------------------------------------------
using namespace connectivity;
using namespace connectivity::sdbcx;
using namespace cppu;
using namespace connectivity;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::sdbc;

// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OColumn::getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException)
{
    if(isNew())
        return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VColumnDescription");
    return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VColumn");
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OColumn::getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException)
{
    ::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);
    if(isNew())
        aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.ColumnDescription");
    else
        aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Column");

    return aSupported;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL OColumn::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException)
{
    Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
    const ::rtl::OUString* pSupported = aSupported.getConstArray();
    const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
    for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
        ;

    return pSupported != pEnd;
}
// -------------------------------------------------------------------------
OColumn::OColumn(sal_Bool _bCase)
    :OColumnDescriptor_BASE(m_aMutex)
    ,ODescriptor(OColumnDescriptor_BASE::rBHelper,_bCase,sal_True)
    ,m_IsNullable(ColumnValue::NULLABLE)
    ,m_Precision(0)
    ,m_Scale(0)
    ,m_Type(0)
    ,m_IsAutoIncrement(sal_False)
    ,m_IsRowVersion(sal_False)
    ,m_IsCurrency(sal_False)
{
    construct();
}
// -------------------------------------------------------------------------
OColumn::OColumn(   const ::rtl::OUString& _Name,
                    const ::rtl::OUString& _TypeName,
                    const ::rtl::OUString& _DefaultValue,
                    sal_Int32       _IsNullable,
                    sal_Int32       _Precision,
                    sal_Int32       _Scale,
                    sal_Int32       _Type,
                    sal_Bool        _IsAutoIncrement,
                    sal_Bool        _IsRowVersion,
                    sal_Bool        _IsCurrency,
                    sal_Bool        _bCase)
    :OColumnDescriptor_BASE(m_aMutex)
    ,ODescriptor(OColumnDescriptor_BASE::rBHelper,_bCase)
    ,m_TypeName(_TypeName)
    ,m_DefaultValue(_DefaultValue)
    ,m_IsNullable(_IsNullable)
    ,m_Precision(_Precision)
    ,m_Scale(_Scale)
    ,m_Type(_Type)
    ,m_IsAutoIncrement(_IsAutoIncrement)
    ,m_IsRowVersion(_IsRowVersion)
    ,m_IsCurrency(_IsCurrency)
{
    m_Name = _Name;

    construct();
}
// -------------------------------------------------------------------------
OColumn::~OColumn()
{
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OColumn::createArrayHelper( sal_Int32 /*_nId*/ ) const
{
    return doCreateArrayHelper();
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& SAL_CALL OColumn::getInfoHelper()
{
    return *OColumn_PROP::getArrayHelper(isNew() ? 1 : 0);
}
// -----------------------------------------------------------------------------
void SAL_CALL OColumn::acquire() throw()
{
    OColumnDescriptor_BASE::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OColumn::release() throw()
{
    OColumnDescriptor_BASE::release();
}
// -----------------------------------------------------------------------------
Any SAL_CALL OColumn::queryInterface( const Type & rType ) throw(RuntimeException)
{
    Any aRet = ODescriptor::queryInterface( rType);
    if(!aRet.hasValue())
    {
        if(!isNew())
            aRet = OColumn_BASE::queryInterface(rType);
        if(!aRet.hasValue())
            aRet = OColumnDescriptor_BASE::queryInterface( rType);
    }
    return aRet;
}
// -------------------------------------------------------------------------
Sequence< Type > SAL_CALL OColumn::getTypes(  ) throw(RuntimeException)
{
    if(isNew())
        return ::comphelper::concatSequences(ODescriptor::getTypes(),OColumnDescriptor_BASE::getTypes());

    return ::comphelper::concatSequences(ODescriptor::getTypes(),OColumn_BASE::getTypes(),OColumnDescriptor_BASE::getTypes());
}
// -------------------------------------------------------------------------
void OColumn::construct()
{
    ODescriptor::construct();

    sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY;

    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPENAME),            PROPERTY_ID_TYPENAME,           nAttrib,&m_TypeName,        ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DESCRIPTION),     PROPERTY_ID_DESCRIPTION,        nAttrib,&m_Description,     ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE),        PROPERTY_ID_DEFAULTVALUE,       nAttrib,&m_DefaultValue,    ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRECISION),       PROPERTY_ID_PRECISION,          nAttrib,&m_Precision,       ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE),                PROPERTY_ID_TYPE,               nAttrib,&m_Type,            ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE),           PROPERTY_ID_SCALE,              nAttrib,&m_Scale,           ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISNULLABLE),      PROPERTY_ID_ISNULLABLE,         nAttrib,&m_IsNullable,      ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISAUTOINCREMENT), PROPERTY_ID_ISAUTOINCREMENT,    nAttrib,&m_IsAutoIncrement, ::getBooleanCppuType());
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISROWVERSION),        PROPERTY_ID_ISROWVERSION,       nAttrib,&m_IsRowVersion,    ::getBooleanCppuType());
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY),      PROPERTY_ID_ISCURRENCY,         nAttrib,&m_IsCurrency,      ::getBooleanCppuType());
}
// -------------------------------------------------------------------------
void OColumn::disposing(void)
{
    OPropertySetHelper::disposing();

    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OColumnDescriptor_BASE::rBHelper.bDisposed);

}
// -------------------------------------------------------------------------
Reference< XPropertySet > SAL_CALL OColumn::createDataDescriptor(  ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OColumnDescriptor_BASE::rBHelper.bDisposed);

    OColumn* pNewColumn = new OColumn(  m_Name,
                                        m_TypeName,
                                        m_DefaultValue,
                                        m_IsNullable,
                                        m_Precision,
                                        m_Scale,
                                        m_Type,
                                        m_IsAutoIncrement,
                                        m_IsRowVersion,
                                        m_IsCurrency,
                                        isCaseSensitive());
    pNewColumn->m_Description = m_Description;
    pNewColumn->setNew(sal_True);
    return pNewColumn;
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OColumn::getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException)
{
    return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper());
}
// -----------------------------------------------------------------------------
// XNamed
::rtl::OUString SAL_CALL OColumn::getName(  ) throw(::com::sun::star::uno::RuntimeException)
{
    return m_Name;
}
// -----------------------------------------------------------------------------
void SAL_CALL OColumn::setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException)
{
    m_Name = aName;
}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS pchfix02 (1.16.60); FILE MERGED 2006/09/01 17:22:36 kaib 1.16.60.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: VColumn.cxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 03:10:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/sdbcx/VColumn.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
// -------------------------------------------------------------------------
using namespace connectivity;
using namespace connectivity::sdbcx;
using namespace cppu;
using namespace connectivity;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::sdbc;

// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OColumn::getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException)
{
    if(isNew())
        return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VColumnDescription");
    return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VColumn");
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OColumn::getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException)
{
    ::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);
    if(isNew())
        aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.ColumnDescription");
    else
        aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Column");

    return aSupported;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL OColumn::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException)
{
    Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
    const ::rtl::OUString* pSupported = aSupported.getConstArray();
    const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
    for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
        ;

    return pSupported != pEnd;
}
// -------------------------------------------------------------------------
OColumn::OColumn(sal_Bool _bCase)
    :OColumnDescriptor_BASE(m_aMutex)
    ,ODescriptor(OColumnDescriptor_BASE::rBHelper,_bCase,sal_True)
    ,m_IsNullable(ColumnValue::NULLABLE)
    ,m_Precision(0)
    ,m_Scale(0)
    ,m_Type(0)
    ,m_IsAutoIncrement(sal_False)
    ,m_IsRowVersion(sal_False)
    ,m_IsCurrency(sal_False)
{
    construct();
}
// -------------------------------------------------------------------------
OColumn::OColumn(   const ::rtl::OUString& _Name,
                    const ::rtl::OUString& _TypeName,
                    const ::rtl::OUString& _DefaultValue,
                    sal_Int32       _IsNullable,
                    sal_Int32       _Precision,
                    sal_Int32       _Scale,
                    sal_Int32       _Type,
                    sal_Bool        _IsAutoIncrement,
                    sal_Bool        _IsRowVersion,
                    sal_Bool        _IsCurrency,
                    sal_Bool        _bCase)
    :OColumnDescriptor_BASE(m_aMutex)
    ,ODescriptor(OColumnDescriptor_BASE::rBHelper,_bCase)
    ,m_TypeName(_TypeName)
    ,m_DefaultValue(_DefaultValue)
    ,m_IsNullable(_IsNullable)
    ,m_Precision(_Precision)
    ,m_Scale(_Scale)
    ,m_Type(_Type)
    ,m_IsAutoIncrement(_IsAutoIncrement)
    ,m_IsRowVersion(_IsRowVersion)
    ,m_IsCurrency(_IsCurrency)
{
    m_Name = _Name;

    construct();
}
// -------------------------------------------------------------------------
OColumn::~OColumn()
{
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OColumn::createArrayHelper( sal_Int32 /*_nId*/ ) const
{
    return doCreateArrayHelper();
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& SAL_CALL OColumn::getInfoHelper()
{
    return *OColumn_PROP::getArrayHelper(isNew() ? 1 : 0);
}
// -----------------------------------------------------------------------------
void SAL_CALL OColumn::acquire() throw()
{
    OColumnDescriptor_BASE::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OColumn::release() throw()
{
    OColumnDescriptor_BASE::release();
}
// -----------------------------------------------------------------------------
Any SAL_CALL OColumn::queryInterface( const Type & rType ) throw(RuntimeException)
{
    Any aRet = ODescriptor::queryInterface( rType);
    if(!aRet.hasValue())
    {
        if(!isNew())
            aRet = OColumn_BASE::queryInterface(rType);
        if(!aRet.hasValue())
            aRet = OColumnDescriptor_BASE::queryInterface( rType);
    }
    return aRet;
}
// -------------------------------------------------------------------------
Sequence< Type > SAL_CALL OColumn::getTypes(  ) throw(RuntimeException)
{
    if(isNew())
        return ::comphelper::concatSequences(ODescriptor::getTypes(),OColumnDescriptor_BASE::getTypes());

    return ::comphelper::concatSequences(ODescriptor::getTypes(),OColumn_BASE::getTypes(),OColumnDescriptor_BASE::getTypes());
}
// -------------------------------------------------------------------------
void OColumn::construct()
{
    ODescriptor::construct();

    sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY;

    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPENAME),            PROPERTY_ID_TYPENAME,           nAttrib,&m_TypeName,        ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DESCRIPTION),     PROPERTY_ID_DESCRIPTION,        nAttrib,&m_Description,     ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DEFAULTVALUE),        PROPERTY_ID_DEFAULTVALUE,       nAttrib,&m_DefaultValue,    ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRECISION),       PROPERTY_ID_PRECISION,          nAttrib,&m_Precision,       ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE),                PROPERTY_ID_TYPE,               nAttrib,&m_Type,            ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE),           PROPERTY_ID_SCALE,              nAttrib,&m_Scale,           ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISNULLABLE),      PROPERTY_ID_ISNULLABLE,         nAttrib,&m_IsNullable,      ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISAUTOINCREMENT), PROPERTY_ID_ISAUTOINCREMENT,    nAttrib,&m_IsAutoIncrement, ::getBooleanCppuType());
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISROWVERSION),        PROPERTY_ID_ISROWVERSION,       nAttrib,&m_IsRowVersion,    ::getBooleanCppuType());
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY),      PROPERTY_ID_ISCURRENCY,         nAttrib,&m_IsCurrency,      ::getBooleanCppuType());
}
// -------------------------------------------------------------------------
void OColumn::disposing(void)
{
    OPropertySetHelper::disposing();

    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OColumnDescriptor_BASE::rBHelper.bDisposed);

}
// -------------------------------------------------------------------------
Reference< XPropertySet > SAL_CALL OColumn::createDataDescriptor(  ) throw(RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OColumnDescriptor_BASE::rBHelper.bDisposed);

    OColumn* pNewColumn = new OColumn(  m_Name,
                                        m_TypeName,
                                        m_DefaultValue,
                                        m_IsNullable,
                                        m_Precision,
                                        m_Scale,
                                        m_Type,
                                        m_IsAutoIncrement,
                                        m_IsRowVersion,
                                        m_IsCurrency,
                                        isCaseSensitive());
    pNewColumn->m_Description = m_Description;
    pNewColumn->setNew(sal_True);
    return pNewColumn;
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OColumn::getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException)
{
    return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper());
}
// -----------------------------------------------------------------------------
// XNamed
::rtl::OUString SAL_CALL OColumn::getName(  ) throw(::com::sun::star::uno::RuntimeException)
{
    return m_Name;
}
// -----------------------------------------------------------------------------
void SAL_CALL OColumn::setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException)
{
    m_Name = aName;
}
// -----------------------------------------------------------------------------

<|endoftext|>


<commit_before><commit_msg>cppcheck: delete unneeded variable in connectivity testmoz/main.cxx<commit_after><|endoftext|>


<commit_before>#include <stack.cpp>
#include <catch.hpp>
#include <iostream>
using namespace std;

SCENARIO("count", "[count]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.count()==1);
}

SCENARIO("push", "[push]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.count()==1);
  REQUIRE(s.pop()==1);
}

SCENARIO("pop", "[pop]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.count()==1);
  REQUIRE(s.pop()==1);
}

SCENARIO("prisv", "[prisv]"){
  stack<int> s;
  s.push(1);
  stack<int> s2;
  s2=s;
  REQUIRE(s.count()==1);
  REQUIRE(s.pop()==1);
}
SCENARIO("copy", "[copy]"){
  stack<int> s;
  s.push(1);
  stack <int> a = s;
  REQUIRE(a.count()==1);
  REQUIRE(a.pop()==1);
}
<commit_msg>Update init.cpp<commit_after>#include <stack.cpp>
#include <catch.hpp>
#include <iostream>
using namespace std;

SCENARIO("count", "[count]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.count()==1);
}

SCENARIO("push", "[push]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.count()==1);
  REQUIRE(s.pop()==1);
}

SCENARIO("pop", "[pop]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.count()==1);
  REQUIRE(s.pop()==1);
}

SCENARIO("prisv", "[prisv]"){
  stack<int> s;
  s.push(1);
  stack<int> s2;
  s2=s;
  REQUIRE(s.count()==1);
  REQUIRE(s.pop()==1);
}
SCENARIO("copy", "[copy]"){
  stack<int> s;
  s.push(1);
  stack <int> a = s;
  REQUIRE(a.count()==1);
  REQUIRE(a.pop()==1);
}
SCENARIO("test", "[test]"){
  stack<int> s();
  REQUIRE(s.count()==0);
}
<|endoftext|>


<commit_before>#include "operators.hpp"
#include <gtest/gtest.h>

TEST (classify_translation, classification) {
    operators t_operators;
    // clang-format off
    /* reference */
    points_t reference = {
        { 1, { 100, 200 } }, { 2, { 200, 200 } },
        { 3, { 100, 100 } }, { 4, { 200, 100 } }
    };
    /* translate x: -2, Y: +3 */
    points_t t_m2_p3 = {
        { 1, { 98, 203 } }, { 2, { 198, 203 } },
        { 3, { 98, 103 } }, { 4, { 198, 103 } }
    };
    /* translate x: 5, Y: -42 */
    points_t t_p5_m42 = {
        { 1, { 105, 158 } }, { 2, { 205, 158 } },
        { 3, { 105, 58 } }, { 4, { 205, 58 } }
    };
    /* translate x: 0, Y: 0 */
    points_t t_p0_m0 = {
        { 1, { 100, 200 } }, { 2, { 200, 200 } },
        { 3, { 100, 100 } }, { 4, { 200, 100 } }
    };
    /* translate not enough points, so T=0,0 */
    points_t t_too_few_points = {
        { 1, { 100, 200 } }, { 2, { 200, 200 } }
    };
    // clang-format on
    translation_t translation = { 0, 0 };

    /* translate x: -2, Y: +3 */
    translation = t_operators.classify_translation (reference, t_m2_p3);
    ASSERT_EQ (translation.x, -2);
    ASSERT_EQ (translation.y, +3);

    /* translate x: 5, Y: -42 */
    translation = t_operators.classify_translation (reference, t_p5_m42);
    ASSERT_EQ (translation.x, +5);
    ASSERT_EQ (translation.y, -42);

    /* translate x: 0, Y: 0 */
    translation = t_operators.classify_translation (reference, t_p0_m0);
    ASSERT_EQ (translation.x, 0);
    ASSERT_EQ (translation.y, 0);

    /* translate not enough points, so T=0,0 */
    translation = t_operators.classify_translation (reference, t_too_few_points);
    ASSERT_EQ (translation.x, 0);
    ASSERT_EQ (translation.y, 0);
}
<commit_msg>rename testcase<commit_after>#include "operators.hpp"
#include <gtest/gtest.h>

TEST (translation, classification) {
    operators t_operators;
    // clang-format off
    /* reference */
    points_t reference = {
        { 1, { 100, 200 } }, { 2, { 200, 200 } },
        { 3, { 100, 100 } }, { 4, { 200, 100 } }
    };
    /* translate x: -2, Y: +3 */
    points_t t_m2_p3 = {
        { 1, { 98, 203 } }, { 2, { 198, 203 } },
        { 3, { 98, 103 } }, { 4, { 198, 103 } }
    };
    /* translate x: 5, Y: -42 */
    points_t t_p5_m42 = {
        { 1, { 105, 158 } }, { 2, { 205, 158 } },
        { 3, { 105, 58 } }, { 4, { 205, 58 } }
    };
    /* translate x: 0, Y: 0 */
    points_t t_p0_m0 = {
        { 1, { 100, 200 } }, { 2, { 200, 200 } },
        { 3, { 100, 100 } }, { 4, { 200, 100 } }
    };
    /* translate not enough points, so T=0,0 */
    points_t t_too_few_points = {
        { 1, { 100, 200 } }, { 2, { 200, 200 } }
    };
    // clang-format on
    translation_t translation = { 0, 0 };

    /* translate x: -2, Y: +3 */
    translation = t_operators.classify_translation (reference, t_m2_p3);
    ASSERT_EQ (translation.x, -2);
    ASSERT_EQ (translation.y, +3);

    /* translate x: 5, Y: -42 */
    translation = t_operators.classify_translation (reference, t_p5_m42);
    ASSERT_EQ (translation.x, +5);
    ASSERT_EQ (translation.y, -42);

    /* translate x: 0, Y: 0 */
    translation = t_operators.classify_translation (reference, t_p0_m0);
    ASSERT_EQ (translation.x, 0);
    ASSERT_EQ (translation.y, 0);

    /* translate not enough points, so T=0,0 */
    translation = t_operators.classify_translation (reference, t_too_few_points);
    ASSERT_EQ (translation.x, 0);
    ASSERT_EQ (translation.y, 0);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <stdexcept>

#include <pqxx/pqxx>

namespace pqxx
{
namespace test
{

class test_failure : public PGSTD::logic_error
{
  const PGSTD::string m_file;
  int m_line;

public:
  test_failure(
	const PGSTD::string &ffile, int fline, const PGSTD::string &desc) :
    logic_error(desc),
    m_file(ffile),
    m_line(fline)
  {}

  ~test_failure() throw () {}

  const PGSTD::string &file() const throw () { return m_file; }
  int line() const throw () { return m_line; }
};

// Run a libpqxx test function.
template<typename TESTFUNC>
inline int pqxxtest(TESTFUNC &func)
{
  try
  {
    func();
  }
  catch (const test_failure &e)
  {
    PGSTD::cerr << "Test failure in " + e.file() + " line " +
	to_string(e.line()) << ": " << e.what() << PGSTD::endl;
    return 1;
  }
  catch (const sql_error &e)
  {
    PGSTD::cerr << "SQL error: " << e.what() << PGSTD::endl
         << "Query was: " << e.query() << PGSTD::endl;
    return 1;
  }
  catch (const PGSTD::exception &e)
  {
    PGSTD::cerr << "Exception: " << e.what() << PGSTD::endl;
    return 2;
  }
  catch (...)
  {
    PGSTD::cerr << "Unknown exception" << PGSTD::endl;
    return 100;
  }

  return 0;
} // pqxxtest()

/// Does this backend have generate_series()?
inline bool have_generate_series(const connection_base &c)
{
  return c.server_version() >= 80000;
}

/// For backends that don't have generate_series(): sequence of ints
/** If the backend lacks generate_series(), prepares a temp table called
 * series" containing given range of numbers (including lowest and highest).
 *
 * Use select_series() to construct a query selecting a range of numbers.  For
 * the workaround on older backends to work, the ranges of numbers passed to
 * select_series() must be subsets of the range passed here.
 */
inline void prepare_series(transaction_base &t, int lowest, int highest)
{
  if (!have_generate_series(t.conn()))
  {
    t.exec("CREATE TEMP TABLE series(x integer)");
    for (int x=lowest; x <= highest; ++x)
      t.exec("INSERT INTO series(x) VALUES (" + to_string(x) + ")");
  }
}

/// Generate query selecting series of numbers from lowest to highest, inclusive
/** Needs to see connection object to determine whether the backend supports
 * generate_series().
 */
inline
PGSTD::string select_series(connection_base &conn, int lowest, int highest)
{
  if (pqxx::test::have_generate_series(conn))
    return
	"SELECT generate_series(" +
	to_string(lowest) + ", " + to_string(highest) + ")";

  return
	"SELECT x FROM series "
	"WHERE "
	  "x >= " + to_string(lowest) + " AND "
	  "x <= " + to_string(highest) + " "
	"ORDER BY x";
}

/// Base class for libpqxx tests.  Sets up a connection and transaction.
template<typename CONNECTION=connection, typename TRANSACTION=work>
class TestCase
{
public:
  typedef void (*testfunc)(connection_base &, transaction_base &);

  // func takes connection and transaction as arguments.
  TestCase(const PGSTD::string &name, testfunc func) :
    m_conn(),
    m_trans(m_conn, name),
    m_func(func)
  {
    // Workaround for older backend versions that lack generate_series().
    prepare_series(m_trans, 0, 100);
  }

  void operator()() { m_func(m_conn, m_trans); }

private:
  CONNECTION m_conn;
  TRANSACTION m_trans;
  testfunc m_func;
};

// Verify that variable has the expected value.
#define PQXX_CHECK_EQUAL(actual, expected, desc) \
	if (!(expected == actual)) throw pqxx::test::test_failure( \
		__FILE__, \
		__LINE__, \
		PGSTD::string(desc) + " " \
		"(" #actual " <> " #expected ": " + \
		"expected=" + to_string(expected) + ", " \
		"actual=" + to_string(actual) + ")");

// Verify that "action" throws "exception_type."
#define PQXX_CHECK_THROWS(action, exception_type, desc) \
	{ \
	  bool pqxx_check_throws_failed = true; \
	  try \
	  { \
	    action ; \
	    pqxx_check_throws_failed = false; \
	  } \
	  catch (const exception_type &) {} \
	  catch (const PGSTD::exception &e) \
	  { \
	    throw pqxx::test::test_failure( \
		__FILE__, \
		__LINE__, \
		PGSTD::string(desc) + " " \
		"(" #action ": " \
		"expected=" #exception_type ", " \
		"threw='" + e.what() + ")"); \
	  } \
	  catch (...) \
	  { \
	    throw pqxx::test::test_failure( \
		__FILE__, \
		__LINE__, \
		PGSTD::string(desc) + " " \
		"(" #action ": " "unexpected exception)"); \
	  } \
	  if (!pqxx_check_throws_failed) throw pqxx::test::test_failure( \
		__FILE__, \
		__LINE__, \
		PGSTD::string(desc) + " " \
		"(" #action ": " \
		"expected=" #exception_type ", " \
		"did not throw)"); \
	}

} // namespace test
} // namespace pqxx

<commit_msg>Missing quote in exception message.<commit_after>#include <iostream>
#include <stdexcept>

#include <pqxx/pqxx>

namespace pqxx
{
namespace test
{

class test_failure : public PGSTD::logic_error
{
  const PGSTD::string m_file;
  int m_line;

public:
  test_failure(
	const PGSTD::string &ffile, int fline, const PGSTD::string &desc) :
    logic_error(desc),
    m_file(ffile),
    m_line(fline)
  {}

  ~test_failure() throw () {}

  const PGSTD::string &file() const throw () { return m_file; }
  int line() const throw () { return m_line; }
};

// Run a libpqxx test function.
template<typename TESTFUNC>
inline int pqxxtest(TESTFUNC &func)
{
  try
  {
    func();
  }
  catch (const test_failure &e)
  {
    PGSTD::cerr << "Test failure in " + e.file() + " line " +
	to_string(e.line()) << ": " << e.what() << PGSTD::endl;
    return 1;
  }
  catch (const sql_error &e)
  {
    PGSTD::cerr << "SQL error: " << e.what() << PGSTD::endl
         << "Query was: " << e.query() << PGSTD::endl;
    return 1;
  }
  catch (const PGSTD::exception &e)
  {
    PGSTD::cerr << "Exception: " << e.what() << PGSTD::endl;
    return 2;
  }
  catch (...)
  {
    PGSTD::cerr << "Unknown exception" << PGSTD::endl;
    return 100;
  }

  return 0;
} // pqxxtest()

/// Does this backend have generate_series()?
inline bool have_generate_series(const connection_base &c)
{
  return c.server_version() >= 80000;
}

/// For backends that don't have generate_series(): sequence of ints
/** If the backend lacks generate_series(), prepares a temp table called
 * series" containing given range of numbers (including lowest and highest).
 *
 * Use select_series() to construct a query selecting a range of numbers.  For
 * the workaround on older backends to work, the ranges of numbers passed to
 * select_series() must be subsets of the range passed here.
 */
inline void prepare_series(transaction_base &t, int lowest, int highest)
{
  if (!have_generate_series(t.conn()))
  {
    t.exec("CREATE TEMP TABLE series(x integer)");
    for (int x=lowest; x <= highest; ++x)
      t.exec("INSERT INTO series(x) VALUES (" + to_string(x) + ")");
  }
}

/// Generate query selecting series of numbers from lowest to highest, inclusive
/** Needs to see connection object to determine whether the backend supports
 * generate_series().
 */
inline
PGSTD::string select_series(connection_base &conn, int lowest, int highest)
{
  if (pqxx::test::have_generate_series(conn))
    return
	"SELECT generate_series(" +
	to_string(lowest) + ", " + to_string(highest) + ")";

  return
	"SELECT x FROM series "
	"WHERE "
	  "x >= " + to_string(lowest) + " AND "
	  "x <= " + to_string(highest) + " "
	"ORDER BY x";
}

/// Base class for libpqxx tests.  Sets up a connection and transaction.
template<typename CONNECTION=connection, typename TRANSACTION=work>
class TestCase
{
public:
  typedef void (*testfunc)(connection_base &, transaction_base &);

  // func takes connection and transaction as arguments.
  TestCase(const PGSTD::string &name, testfunc func) :
    m_conn(),
    m_trans(m_conn, name),
    m_func(func)
  {
    // Workaround for older backend versions that lack generate_series().
    prepare_series(m_trans, 0, 100);
  }

  void operator()() { m_func(m_conn, m_trans); }

private:
  CONNECTION m_conn;
  TRANSACTION m_trans;
  testfunc m_func;
};

// Verify that variable has the expected value.
#define PQXX_CHECK_EQUAL(actual, expected, desc) \
	if (!(expected == actual)) throw pqxx::test::test_failure( \
		__FILE__, \
		__LINE__, \
		PGSTD::string(desc) + " " \
		"(" #actual " <> " #expected ": " + \
		"expected=" + to_string(expected) + ", " \
		"actual=" + to_string(actual) + ")");

// Verify that "action" throws "exception_type."
#define PQXX_CHECK_THROWS(action, exception_type, desc) \
	{ \
	  bool pqxx_check_throws_failed = true; \
	  try \
	  { \
	    action ; \
	    pqxx_check_throws_failed = false; \
	  } \
	  catch (const exception_type &) {} \
	  catch (const PGSTD::exception &e) \
	  { \
	    throw pqxx::test::test_failure( \
		__FILE__, \
		__LINE__, \
		PGSTD::string(desc) + " " \
		"(" #action ": " \
		"expected=" #exception_type ", " \
		"threw='" + e.what() + "')"); \
	  } \
	  catch (...) \
	  { \
	    throw pqxx::test::test_failure( \
		__FILE__, \
		__LINE__, \
		PGSTD::string(desc) + " " \
		"(" #action ": " "unexpected exception)"); \
	  } \
	  if (!pqxx_check_throws_failed) throw pqxx::test::test_failure( \
		__FILE__, \
		__LINE__, \
		PGSTD::string(desc) + " " \
		"(" #action ": " \
		"expected=" #exception_type ", " \
		"did not throw)"); \
	}

} // namespace test
} // namespace pqxx

<|endoftext|>


<commit_before>/**
 * @file
 * @author Alexander Sherikov
 * @date 05.01.2012 17:00:43 MSK
 */

/****************************************
 * INCLUDES
 ****************************************/

/****************************************
 * FUNCTIONS
 ****************************************/

void printVectors (
        FILE *file_op,
        vector<double> &data_x,
        vector<double> &data_y,
        const char *name)
{
    fprintf(file_op,"%s = [\n", name);
    for (unsigned int i=0; i < data_x.size(); i++)
    {
        fprintf(file_op, "%f %f;\n", data_x[i], data_y[i]);
    }
    fprintf(file_op, "];\n\n plot(%s(:,1), %s(:,2), 'k')\n", name, name);
}

void printVectors (
        FILE *file_op,
        vector<double> &data_x,
        vector<double> &data_y,
        vector<double> &data_z,
        const char *name)
{
    fprintf(file_op,"%s = [\n", name);
    for (unsigned int i=0; i < data_x.size(); i++)
    {
        fprintf(file_op, "%f %f %f;\n", data_x[i], data_y[i], data_z[i]);
    }
    fprintf(file_op, "];\n\n plot3(%s(:,1), %s(:,2), %s(:,3), 'r')\n", name, name, name);
}
<commit_msg>Plot vectors using format string.<commit_after>/**
 * @file
 * @author Alexander Sherikov
 * @date 05.01.2012 17:00:43 MSK
 */

/****************************************
 * INCLUDES
 ****************************************/

/****************************************
 * FUNCTIONS
 ****************************************/

void printVectors (
        FILE *file_op,
        vector<double> &data_x,
        vector<double> &data_y,
        const char *name,
        const char *format)
{
    fprintf(file_op,"%s = [\n", name);
    for (unsigned int i=0; i < data_x.size(); i++)
    {
        fprintf(file_op, "%f %f;\n", data_x[i], data_y[i]);
    }
    fprintf(file_op, "];\n\n plot(%s(:,1), %s(:,2), '%s')\n", name, name, format);
}

void printVectors (
        FILE *file_op,
        vector<double> &data_x,
        vector<double> &data_y,
        vector<double> &data_z,
        const char *name,
        const char *format)
{
    fprintf(file_op,"%s = [\n", name);
    for (unsigned int i=0; i < data_x.size(); i++)
    {
        fprintf(file_op, "%f %f %f;\n", data_x[i], data_y[i], data_z[i]);
    }
    fprintf(file_op, "];\n\n plot3(%s(:,1), %s(:,2), %s(:,3), '%s')\n", name, name, name, format);
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 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$
** GNU Lesser General Public License Usage
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdeclarativegeneralinfo_p.h"
#include "qsystemgeneralinfo.h"
#include <QMetaType>
#include <QDebug>

QT_BEGIN_NAMESPACE

Q_GLOBAL_STATIC(QSystemInfo, generalInfo)

/*!
    \qmlclass GeneralInfo QDeclarativeGeneralInfo
    \brief The GeneralInfo element allows you access to general system information and to receive notifications from the device.

    \inherits QSystemInfo

    \ingroup qml-systeminfo
    \since Mobility 1.1

    This element is part of the \bold{QtMobility.systeminfo 1.1} module.
    It is a convience class to make QML usage easier.

    Note: To use notification signals, you need to use the start* slots.

    \qml

        Component.onCompleted {
            generalInfo.startCurrentLanguageChanged()
        }

    \endqml

\sa QSystemInfo
*/

/*!
    \qmlsignal SystemInfo::startCurrentLanguageChanged()
    \since Mobility 1.1

    This handler is called when current system language has changed.
    Note: To receive this notification, you must first call \a startCurrentLanguageChanged.
*/
QDeclarativeGeneralInfo::QDeclarativeGeneralInfo(QObject *parent) :
    QSystemInfo(parent)
{
}

void QDeclarativeGeneralInfo::startCurrentLanguageChanged()
{
    connect(generalInfo(),SIGNAL(currentLanguageChanged(QString)),
            this,SLOT(declarativeCurrentLanguageChanged(QString)),Qt::UniqueConnection);
}

void QDeclarativeGeneralInfo::declarativeCurrentLanguageChanged(const QString &language)
{
    Q_EMIT currentLanguageChanged(language);
}

/*!
  \qmlproperty string QDeclarativeGeneralInfo::osVersion
  \since Mobility 1.1

   Returns the version of the Operating System.
*/
QString QDeclarativeGeneralInfo::osVersion()
{
    return generalInfo()->version(QSystemInfo::Os);
}

/*!
  \qmlproperty string QDeclarativeGeneralInfo::qtCoreVersion
  \since Mobility 1.1

   Returns the version of the installed Qt Core library.
*/
QString QDeclarativeGeneralInfo::qtCoreVersion()
{
    return generalInfo()->version(QSystemInfo::QtCore);
}

/*!
  \qmlproperty string QDeclarativeGeneralInfo::firmwareVersion
  \since Mobility 1.1

   Returns the version of the firmware as a whole.
*/
QString QDeclarativeGeneralInfo::firmwareVersion()
{
    return generalInfo()->version(QSystemInfo::Firmware);
}

/*!
  \qmlproperty string QDeclarativeGeneralInfo::qtMobilityVersion
  \since Mobility 1.1

   Returns the version of the installed Qt Mobility library.
*/
QString QDeclarativeGeneralInfo::qtMobilityVersion()
{
    return generalInfo()->version(QSystemInfo::QtMobility);
}

<commit_msg>Improve GeneralInfo QML Element documentation.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 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$
** GNU Lesser General Public License Usage
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdeclarativegeneralinfo_p.h"
#include "qsystemgeneralinfo.h"
#include <QMetaType>
#include <QDebug>

QT_BEGIN_NAMESPACE

Q_GLOBAL_STATIC(QSystemInfo, generalInfo)

/*!
    \qmlclass GeneralInfo QDeclarativeGeneralInfo
    \brief The GeneralInfo element allows you access to general system information and to receive notifications from the device.

    \inherits QSystemInfo

    \ingroup qml-systeminfo
    \since Mobility 1.1

    This element is part of the \bold{QtMobility.systeminfo 1.1} module.
    It is a convience class to make QML usage easier.

    Note: To use notification signals, you need to use the start* slots.

    \qml

        Component.onCompleted {
            generalInfo.startCurrentLanguageChanged()
        }

    \endqml

\sa QSystemInfo
*/

/*!
    \qmlsignal GeneralInfo::startCurrentLanguageChanged(string language)
    \since Mobility 1.1

    This handler is called when current system language has changed.
    Note: To receive this notification, you must first call \a startCurrentLanguageChanged.
*/
QDeclarativeGeneralInfo::QDeclarativeGeneralInfo(QObject *parent) :
    QSystemInfo(parent)
{
}

/*!
    \qmlmethod void GeneralInfo::startCurrentLanguageChanged()
    \since Mobility 1.1

    Start the connection for the currentLanguageChanged signal.
*/
void QDeclarativeGeneralInfo::startCurrentLanguageChanged()
{
    connect(generalInfo(),SIGNAL(currentLanguageChanged(QString)),
            this,SLOT(declarativeCurrentLanguageChanged(QString)),Qt::UniqueConnection);
}

void QDeclarativeGeneralInfo::declarativeCurrentLanguageChanged(const QString &language)
{
    Q_EMIT currentLanguageChanged(language);
}

/*!
  \qmlproperty string GeneralInfo::osVersion
  \since Mobility 1.1

   Returns the version of the Operating System.
*/
QString QDeclarativeGeneralInfo::osVersion()
{
    return generalInfo()->version(QSystemInfo::Os);
}

/*!
  \qmlproperty string GeneralInfo::qtCoreVersion
  \since Mobility 1.1

   Returns the version of the installed Qt Core library.
*/
QString QDeclarativeGeneralInfo::qtCoreVersion()
{
    return generalInfo()->version(QSystemInfo::QtCore);
}

/*!
  \qmlproperty string GeneralInfo::firmwareVersion
  \since Mobility 1.1

   Returns the version of the firmware as a whole.
*/
QString QDeclarativeGeneralInfo::firmwareVersion()
{
    return generalInfo()->version(QSystemInfo::Firmware);
}

/*!
  \qmlproperty string GeneralInfo::qtMobilityVersion
  \since Mobility 1.1

   Returns the version of the installed Qt Mobility library.
*/
QString QDeclarativeGeneralInfo::qtMobilityVersion()
{
    return generalInfo()->version(QSystemInfo::QtMobility);
}

/*!
    \qmlproperty string GeneralInfo::currentLanguage
    \since Mobility 1.1
    Returns the current language in two letter ISO 639-1 format.
 */

/*!
    \qmlproperty list GeneralInfo::availableLanguages
    \since Mobility 1.1
    Returns a QStringList of available Qt language translations in two letter ISO 639-1 format.
    If the Qt translations cannot be found, returns the current system language.
*/

/*!
    \qmlproperty string GeneralInfo::currentCountryCode
    \since Mobility 1.1
    Returns the two letter ISO 3166-1 for the current country code.
*/

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2008-2018 the MRtrix3 contributors.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, you can obtain one at http://mozilla.org/MPL/2.0/
 *
 * MRtrix3 is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * For more details, see http://www.mrtrix.org/
 */

#include "command.h"
#include "header.h"
#include "image.h"
#include "progressbar.h"
#include "file/path.h"
#include "file/utils.h"
#include "fixel/helpers.h"

#include "fixel/filter/base.h"
#include "fixel/filter/connect.h"
#include "fixel/filter/smooth.h"
#include "stats/cfe.h"

using namespace MR;
using namespace App;
using namespace MR::Fixel;

const char* filters[] = { "connect", "smooth", nullptr };

void usage ()
{
  AUTHOR = "Robert E. Smith (robert.smith@florey.edu.au)";

  SYNOPSIS = "Perform filtering operations on fixel-based data";

  DESCRIPTION
  + "If the first input to the command is a specific fixel data file, then a filtered version of only that file "
    "will be generated by the command. Alternatively, if the input is the location of a fixel directory, then the "
    "command will create a duplicate of the fixel directory, and apply the specified filter operation to all "
    "fixel data files within the directory."

  + "For the smoothing filter, it is typically recommended that the provided fixel-fixel connectivity matrix should "
    "include both streamline-based connection strength and spatial distance between fixels; this can be generated "
    "by the MRtrix3 command fixelconnectivity, specifically using the -smoothing option.";

  ARGUMENTS
  + Argument ("input", "the input: either a fixel data file, or a fixel directory (see Description)").type_various()
  + Argument ("filter", "the filtering operation to perform; options are: " + join (filters, ", ")).type_choice (filters)
  + Argument ("output", "the output: either a fixel data file, or a fixel directory (see Description)").type_various();

  OPTIONS
  + Option ("matrix", "provide a fixel-fixel connectivity matrix for filtering operations that require it")
    + Argument ("file").type_file_in();

}

using value_type = float;

void run()
{
  Header index_header;
  Image<float> single_file;
  vector<Header> multiple_files;
  Header output_header;
  try {
    index_header = Fixel::find_index_header (Fixel::get_fixel_directory (argument[0]));
    single_file = Image<float>::open (argument[0]);
    Fixel::check_data_file (single_file);
    output_header = Header (single_file);
  } catch (...) {
    try {
      index_header = Fixel::find_index_header (argument[0]);
      multiple_files = Fixel::find_data_headers (argument[0], index_header);
      if (multiple_files.empty())
        throw Exception ("No fixel data files found in directory \"" + argument[0] + "\"");
      output_header = Header (multiple_files[0]);
    } catch (...) {
      throw Exception ("Could not interpret first argument \"" + argument[0] + "\" as either a fixel data file, or a fixel directory");
    }
  }

  if (single_file.valid() && !Fixel::fixels_match (index_header, single_file))
    throw Exception ("File \"" + argument[0] + "\" is not a valid fixel data file (does not match corresponding index image)");

  Fixel::Matrix::norm_matrix_type matrix;
  auto opt = get_options ("matrix");
  if (opt.size())
    Fixel::Matrix::load (opt[0][0], matrix);

  std::unique_ptr<Fixel::Filter::Base> filter;
  switch (int(argument[1])) {
    case 0:
      if (matrix.empty())
        throw Exception ("For filter \"connect\", fixel-fixel connectivity matrix must be provided via the -matrix option");
      filter.reset (new Fixel::Filter::Connect (matrix));
      output_header.datatype() = DataType::UInt32;
      output_header.datatype().set_byte_order_native();
      break;
    case 1:
      if (matrix.empty())
        throw Exception ("For filter \"smooth\", fixel-fixel connectivity matrix must be provided via the -matrix option");
      filter.reset (new Fixel::Filter::Smooth (matrix));
      break;
    default:
      assert (0);
  }

  if (single_file.valid()) {
    auto output_image = Image<float>::create (argument[2], single_file);
    CONSOLE (std::string ("Applying \"") + filters[argument[1]] + "\" operation to fixel data file \"" + single_file.name() + "\"");
    (*filter) (single_file, output_image);
  } else {
    Fixel::copy_index_and_directions_file (argument[0], argument[2]);
    ProgressBar progress (std::string ("Applying \"") + filters[argument[1]] + "\" operation to " + str(multiple_files.size()) + " fixel data files",
                          multiple_files.size());
    for (auto& H : multiple_files) {
      auto input_image = H.get_image<float>();
      auto output_image = Image<float>::create (Path::join (argument[2], Path::basename (H.name())), H);
      (*filter) (input_image, output_image);
      ++progress;
    }
  }

}
<commit_msg>fixelfilter: Test input as directory rather than file first<commit_after>/*
 * Copyright (c) 2008-2018 the MRtrix3 contributors.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, you can obtain one at http://mozilla.org/MPL/2.0/
 *
 * MRtrix3 is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * For more details, see http://www.mrtrix.org/
 */

#include "command.h"
#include "header.h"
#include "image.h"
#include "progressbar.h"
#include "file/path.h"
#include "file/utils.h"
#include "fixel/helpers.h"

#include "fixel/filter/base.h"
#include "fixel/filter/connect.h"
#include "fixel/filter/smooth.h"
#include "stats/cfe.h"

using namespace MR;
using namespace App;
using namespace MR::Fixel;

const char* filters[] = { "connect", "smooth", nullptr };

void usage ()
{
  AUTHOR = "Robert E. Smith (robert.smith@florey.edu.au)";

  SYNOPSIS = "Perform filtering operations on fixel-based data";

  DESCRIPTION
  + "If the first input to the command is a specific fixel data file, then a filtered version of only that file "
    "will be generated by the command. Alternatively, if the input is the location of a fixel directory, then the "
    "command will create a duplicate of the fixel directory, and apply the specified filter operation to all "
    "fixel data files within the directory."

  + "For the smoothing filter, it is typically recommended that the provided fixel-fixel connectivity matrix should "
    "include both streamline-based connection strength and spatial distance between fixels; this can be generated "
    "by the MRtrix3 command fixelconnectivity, specifically using the -smoothing option.";

  ARGUMENTS
  + Argument ("input", "the input: either a fixel data file, or a fixel directory (see Description)").type_various()
  + Argument ("filter", "the filtering operation to perform; options are: " + join (filters, ", ")).type_choice (filters)
  + Argument ("output", "the output: either a fixel data file, or a fixel directory (see Description)").type_various();

  OPTIONS
  + Option ("matrix", "provide a fixel-fixel connectivity matrix for filtering operations that require it")
    + Argument ("file").type_file_in();

}

using value_type = float;

void run()
{
  Header index_header;
  Image<float> single_file;
  vector<Header> multiple_files;
  Header output_header;
  try {
    index_header = Fixel::find_index_header (argument[0]);
    multiple_files = Fixel::find_data_headers (argument[0], index_header);
    if (multiple_files.empty())
      throw Exception ("No fixel data files found in directory \"" + argument[0] + "\"");
    output_header = Header (multiple_files[0]);
  } catch (...) {
    try {
      index_header = Fixel::find_index_header (Fixel::get_fixel_directory (argument[0]));
      single_file = Image<float>::open (argument[0]);
      Fixel::check_data_file (single_file);
      output_header = Header (single_file);
    } catch (...) {
      throw Exception ("Could not interpret first argument \"" + argument[0] + "\" as either a fixel data file, or a fixel directory");
    }
  }

  if (single_file.valid() && !Fixel::fixels_match (index_header, single_file))
    throw Exception ("File \"" + argument[0] + "\" is not a valid fixel data file (does not match corresponding index image)");

  Fixel::Matrix::norm_matrix_type matrix;
  auto opt = get_options ("matrix");
  if (opt.size())
    Fixel::Matrix::load (opt[0][0], matrix);

  std::unique_ptr<Fixel::Filter::Base> filter;
  switch (int(argument[1])) {
    case 0:
      if (matrix.empty())
        throw Exception ("For filter \"connect\", fixel-fixel connectivity matrix must be provided via the -matrix option");
      filter.reset (new Fixel::Filter::Connect (matrix));
      output_header.datatype() = DataType::UInt32;
      output_header.datatype().set_byte_order_native();
      break;
    case 1:
      if (matrix.empty())
        throw Exception ("For filter \"smooth\", fixel-fixel connectivity matrix must be provided via the -matrix option");
      filter.reset (new Fixel::Filter::Smooth (matrix));
      break;
    default:
      assert (0);
  }

  if (single_file.valid()) {
    auto output_image = Image<float>::create (argument[2], single_file);
    CONSOLE (std::string ("Applying \"") + filters[argument[1]] + "\" operation to fixel data file \"" + single_file.name() + "\"");
    (*filter) (single_file, output_image);
  } else {
    Fixel::copy_index_and_directions_file (argument[0], argument[2]);
    ProgressBar progress (std::string ("Applying \"") + filters[argument[1]] + "\" operation to " + str(multiple_files.size()) + " fixel data files",
                          multiple_files.size());
    for (auto& H : multiple_files) {
      auto input_image = H.get_image<float>();
      auto output_image = Image<float>::create (Path::join (argument[2], Path::basename (H.name())), H);
      (*filter) (input_image, output_image);
      ++progress;
    }
  }

}
<|endoftext|>


<commit_before>/*
    This file is part of the KOrganizer alarm daemon.

    Copyright (c) 2000,2003 Cornelius Schumacher <schumacher@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

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

#include <qhbox.h>
#include <qvbox.h>
#include <qlabel.h>
#include <qfile.h>
#include <qspinbox.h>
#include <qlayout.h>
#include <qpushbutton.h>
#include <qcstring.h>
#include <qdatastream.h>

#include <kapplication.h>
#include <dcopclient.h>
#include <klocale.h>
#include <kprocess.h>
#include <kaudioplayer.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <knotifyclient.h>
#include <kcombobox.h>
#include <kwin.h>
#include <klockfile.h>

#include <libkcal/event.h>

#include "koeventviewer.h"

#include "alarmdialog.h"
#include "alarmdialog.moc"

AlarmDialog::AlarmDialog( QWidget *parent, const char *name )
  : KDialogBase( Plain, WType_TopLevel | WStyle_Customize | WStyle_StaysOnTop |
                 WStyle_DialogBorder,
                 parent, name, false, i18n("Alarm"), Ok | User1 | User2/* | User3*/, Ok/*3*/,
                 false, i18n("Suspend"), i18n("Edit...") ),
                 mSuspendTimer(this)
{
  QWidget *topBox = plainPage();
  QBoxLayout *topLayout = new QVBoxLayout( topBox );
  topLayout->setSpacing( spacingHint() );

  QLabel *label = new QLabel( i18n("The following events triggered alarms:"),
                              topBox );
  topLayout->addWidget( label );

  mEventViewer = new KOEventViewer( topBox );
  topLayout->addWidget( mEventViewer );

  QHBox *suspendBox = new QHBox( topBox );
  suspendBox->setSpacing( spacingHint() );
  topLayout->addWidget( suspendBox );

  new QLabel( i18n("Suspend duration:"), suspendBox );
  mSuspendSpin = new QSpinBox( 1, 9999, 1, suspendBox );
  mSuspendSpin->setValue( 5 );  // default suspend duration

  mSuspendUnit = new KComboBox( suspendBox );
  mSuspendUnit->insertItem( i18n("minute(s)") );
  mSuspendUnit->insertItem( i18n("hour(s)") );
  mSuspendUnit->insertItem( i18n("day(s)") );
  mSuspendUnit->insertItem( i18n("week(s)") );

  connect( mSuspendSpin, SIGNAL( valueChanged(int) ), actionButton(User1), SLOT( setFocus() ) );
  connect( mSuspendUnit, SIGNAL( activated(int) ), actionButton(User1), SLOT( setFocus() ) );
  connect( mSuspendUnit, SIGNAL( activated(int) ), actionButton(User2), SLOT( setFocus() ) );

  // showButton( User2/*3*/, false );

  setMinimumSize( 300, 200 );
}

AlarmDialog::~AlarmDialog()
{
}

void AlarmDialog::setIncidence( Incidence *incidence )
{
  mEventViewer->appendIncidence( incidence );
  mIncidence = incidence;
}

void AlarmDialog::setRemindAt( QDateTime dt )
{
  mRemindAt = dt;
}

void AlarmDialog::slotOk()
{
  accept();
  emit finishedSignal( this );
}

void AlarmDialog::slotUser1()
{
  if ( !isVisible() )
    return;

  int unit=1;
  switch (mSuspendUnit->currentItem()) {
    case 3: // weeks
      unit *=  7;
    case 2: // days
      unit *= 24;
    case 1: // hours
      unit *= 60;
    case 0: // minutes
      unit *= 60;
    default:
      break;
  }

  setTimer( unit * mSuspendSpin->value() );
  accept();
}

void AlarmDialog::setTimer( int seconds )
{
  connect( &mSuspendTimer, SIGNAL( timeout() ), SLOT( show() ) );
  mSuspendTimer.start( 1000 * seconds, true );
  mRemindAt = QDateTime::currentDateTime();
  mRemindAt = mRemindAt.addSecs( seconds );
}

void AlarmDialog::slotUser2()
{
  if ( !kapp->dcopClient()->isApplicationRegistered( "korganizer" ) ) {
    if ( kapp->startServiceByDesktopName( "korganizer", QString::null ) )
      KMessageBox::error( 0, i18n("Could not start KOrganizer.") );
  }

  kapp->dcopClient()->send( "korganizer", "KOrganizerIface",
                            "editIncidence(QString)",
                             mIncidence->uid() );

  // get desktop # where korganizer (or kontact) runs
  QByteArray replyData;
  QCString object, replyType;
  object = kapp->dcopClient()->isApplicationRegistered( "kontact" ) ?
           "kontact-mainwindow#1" : "KOrganizer MainWindow";
  if (!kapp->dcopClient()->call( "korganizer", object,
                            "getWinID()", 0, replyType, replyData, true, -1 ) ) {
  }

  if ( replyType == "int" ) {
    int desktop, window;
    QDataStream ds( replyData, IO_ReadOnly );
    ds >> window;
    desktop = KWin::windowInfo( window ).desktop();

    if ( KWin::currentDesktop() == desktop ) {
      KWin::iconifyWindow( winId(), false );
    }
    else
      KWin::setCurrentDesktop( desktop );

    KWin::activateWindow( KWin::transientFor( window ) );
  }
}

void AlarmDialog::show()
{
  KDialogBase::show();
  raise();
  KWin::forceActiveWindow( winId() );
  actionButton( KDialogBase::Ok )->setFocus();
  eventNotification();
// FIXME: go to foreground but don't steal focus
}

void AlarmDialog::eventNotification()
{
  bool beeped = false;
  Alarm::List alarms = mIncidence->alarms();
  Alarm::List::ConstIterator it;
  for ( it = alarms.begin(); it != alarms.end(); ++it ) {
    Alarm *alarm = *it;
// FIXME: Check whether this should be done for all multiple alarms
    if (alarm->type() == Alarm::Procedure) {
      kdDebug(5890) << "Starting program: '" << alarm->programFile() << "'" << endl;
      KProcess proc;
      proc << QFile::encodeName(alarm->programFile());
      proc.start(KProcess::DontCare);
    }
    else if (alarm->type() == Alarm::Audio) {
      beeped = true;
      KAudioPlayer::play(QFile::encodeName(alarm->audioFile()));
    }
  }

  if ( !beeped ) {
    KNotifyClient::beep();
  }
}

void AlarmDialog::wakeUp()
{
  if ( mRemindAt <= QDateTime::currentDateTime() )
    show();
  else
    setTimer( QDateTime::currentDateTime().secsTo( mRemindAt ) );
}

void AlarmDialog::slotSave()
{
  KConfig *config = kapp->config();
  KLockFile::Ptr lock = config->lockFile();
  if ( lock.data()->lock() != KLockFile::LockOK )
    return;

  config->setGroup( "General" );
  int numReminders = config->readNumEntry("Reminders", 0);
  config->writeEntry( "Reminders", ++numReminders );

  config->setGroup( QString("Incidence-%1").arg(numReminders) );
  config->writeEntry( "UID", mIncidence->uid() );
  config->writeEntry( "RemindAt", mRemindAt );
  config->sync();
  lock.data()->unlock();
}

<commit_msg>- don't steal focus BUG: 56545<commit_after>/*
    This file is part of the KOrganizer alarm daemon.

    Copyright (c) 2000,2003 Cornelius Schumacher <schumacher@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

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

#include <qhbox.h>
#include <qvbox.h>
#include <qlabel.h>
#include <qfile.h>
#include <qspinbox.h>
#include <qlayout.h>
#include <qpushbutton.h>
#include <qcstring.h>
#include <qdatastream.h>

#include <kapplication.h>
#include <dcopclient.h>
#include <klocale.h>
#include <kprocess.h>
#include <kaudioplayer.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <knotifyclient.h>
#include <kcombobox.h>
#include <kwin.h>
#include <klockfile.h>

#include <libkcal/event.h>

#include "koeventviewer.h"

#include "alarmdialog.h"
#include "alarmdialog.moc"

AlarmDialog::AlarmDialog( QWidget *parent, const char *name )
  : KDialogBase( Plain, WType_TopLevel | WStyle_Customize | WStyle_StaysOnTop |
                 WStyle_DialogBorder,
                 parent, name, false, i18n("Alarm"), Ok | User1 | User2/* | User3*/, Ok/*3*/,
                 false, i18n("Suspend"), i18n("Edit...") ),
                 mSuspendTimer(this)
{
  QWidget *topBox = plainPage();
  QBoxLayout *topLayout = new QVBoxLayout( topBox );
  topLayout->setSpacing( spacingHint() );

  QLabel *label = new QLabel( i18n("The following events triggered alarms:"),
                              topBox );
  topLayout->addWidget( label );

  mEventViewer = new KOEventViewer( topBox );
  topLayout->addWidget( mEventViewer );

  QHBox *suspendBox = new QHBox( topBox );
  suspendBox->setSpacing( spacingHint() );
  topLayout->addWidget( suspendBox );

  new QLabel( i18n("Suspend duration:"), suspendBox );
  mSuspendSpin = new QSpinBox( 1, 9999, 1, suspendBox );
  mSuspendSpin->setValue( 5 );  // default suspend duration

  mSuspendUnit = new KComboBox( suspendBox );
  mSuspendUnit->insertItem( i18n("minute(s)") );
  mSuspendUnit->insertItem( i18n("hour(s)") );
  mSuspendUnit->insertItem( i18n("day(s)") );
  mSuspendUnit->insertItem( i18n("week(s)") );

  connect( mSuspendSpin, SIGNAL( valueChanged(int) ), actionButton(User1), SLOT( setFocus() ) );
  connect( mSuspendUnit, SIGNAL( activated(int) ), actionButton(User1), SLOT( setFocus() ) );
  connect( mSuspendUnit, SIGNAL( activated(int) ), actionButton(User2), SLOT( setFocus() ) );

  // showButton( User2/*3*/, false );

  setMinimumSize( 300, 200 );
}

AlarmDialog::~AlarmDialog()
{
}

void AlarmDialog::setIncidence( Incidence *incidence )
{
  mEventViewer->appendIncidence( incidence );
  mIncidence = incidence;
}

void AlarmDialog::setRemindAt( QDateTime dt )
{
  mRemindAt = dt;
}

void AlarmDialog::slotOk()
{
  accept();
  emit finishedSignal( this );
}

void AlarmDialog::slotUser1()
{
  if ( !isVisible() )
    return;

  int unit=1;
  switch (mSuspendUnit->currentItem()) {
    case 3: // weeks
      unit *=  7;
    case 2: // days
      unit *= 24;
    case 1: // hours
      unit *= 60;
    case 0: // minutes
      unit *= 60;
    default:
      break;
  }

  setTimer( unit * mSuspendSpin->value() );
  accept();
}

void AlarmDialog::setTimer( int seconds )
{
  connect( &mSuspendTimer, SIGNAL( timeout() ), SLOT( show() ) );
  mSuspendTimer.start( 1000 * seconds, true );
  mRemindAt = QDateTime::currentDateTime();
  mRemindAt = mRemindAt.addSecs( seconds );
}

void AlarmDialog::slotUser2()
{
  if ( !kapp->dcopClient()->isApplicationRegistered( "korganizer" ) ) {
    if ( kapp->startServiceByDesktopName( "korganizer", QString::null ) )
      KMessageBox::error( 0, i18n("Could not start KOrganizer.") );
  }

  kapp->dcopClient()->send( "korganizer", "KOrganizerIface",
                            "editIncidence(QString)",
                             mIncidence->uid() );

  // get desktop # where korganizer (or kontact) runs
  QByteArray replyData;
  QCString object, replyType;
  object = kapp->dcopClient()->isApplicationRegistered( "kontact" ) ?
           "kontact-mainwindow#1" : "KOrganizer MainWindow";
  if (!kapp->dcopClient()->call( "korganizer", object,
                            "getWinID()", 0, replyType, replyData, true, -1 ) ) {
  }

  if ( replyType == "int" ) {
    int desktop, window;
    QDataStream ds( replyData, IO_ReadOnly );
    ds >> window;
    desktop = KWin::windowInfo( window ).desktop();

    if ( KWin::currentDesktop() == desktop ) {
      KWin::iconifyWindow( winId(), false );
    }
    else
      KWin::setCurrentDesktop( desktop );

    KWin::activateWindow( KWin::transientFor( window ) );
  }
}

void AlarmDialog::show()
{
  KDialogBase::show();
  KWin::setState( winId(), NET::KeepAbove );
  KWin::setOnAllDesktops( winId(), true );
  eventNotification();
}

void AlarmDialog::eventNotification()
{
  bool beeped = false;
  Alarm::List alarms = mIncidence->alarms();
  Alarm::List::ConstIterator it;
  for ( it = alarms.begin(); it != alarms.end(); ++it ) {
    Alarm *alarm = *it;
// FIXME: Check whether this should be done for all multiple alarms
    if (alarm->type() == Alarm::Procedure) {
      kdDebug(5890) << "Starting program: '" << alarm->programFile() << "'" << endl;
      KProcess proc;
      proc << QFile::encodeName(alarm->programFile());
      proc.start(KProcess::DontCare);
    }
    else if (alarm->type() == Alarm::Audio) {
      beeped = true;
      KAudioPlayer::play(QFile::encodeName(alarm->audioFile()));
    }
  }

  if ( !beeped ) {
    KNotifyClient::beep();
  }
}

void AlarmDialog::wakeUp()
{
  if ( mRemindAt <= QDateTime::currentDateTime() )
    show();
  else
    setTimer( QDateTime::currentDateTime().secsTo( mRemindAt ) );
}

void AlarmDialog::slotSave()
{
  KConfig *config = kapp->config();
  KLockFile::Ptr lock = config->lockFile();
  if ( lock.data()->lock() != KLockFile::LockOK )
    return;

  config->setGroup( "General" );
  int numReminders = config->readNumEntry("Reminders", 0);
  config->writeEntry( "Reminders", ++numReminders );

  config->setGroup( QString("Incidence-%1").arg(numReminders) );
  config->writeEntry( "UID", mIncidence->uid() );
  config->writeEntry( "RemindAt", mRemindAt );
  config->sync();
  lock.data()->unlock();
}

<|endoftext|>