<commit_before>/*

Copyright (c) 2013, Project OSRM, Dennis Luxen, others
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#include "Library/OSRM.h"

#include "Server/ServerFactory.h"

#include "Util/GitDescription.h"
#include "Util/InputFileUtil.h"
#include "Util/ProgramOptions.h"
#include "Util/SimpleLogger.h"
#include "Util/UUID.h"

#ifdef __linux__
#include <sys/mman.h>
#endif

#include <signal.h>

#include <boost/bind.hpp>
// #include <boost/date_time.hpp>
#include <boost/thread.hpp>

#include <iostream>

#ifdef _WIN32
boost::function0<void> console_ctrl_function;

BOOL WINAPI console_ctrl_handler(DWORD ctrl_type)
{
  switch (ctrl_type)
  {
  case CTRL_C_EVENT:
  case CTRL_BREAK_EVENT:
  case CTRL_CLOSE_EVENT:
  case CTRL_SHUTDOWN_EVENT:
    console_ctrl_function();
    return TRUE;
  default:
    return FALSE;
  }
}
#endif

int main (int argc, const char * argv[])
{
    try
    {
        LogPolicy::GetInstance().Unmute();

        bool use_shared_memory = false, trial = false;
        std::string ip_address;
        int ip_port, requested_thread_num;

        ServerPaths server_paths;

        const unsigned init_result = GenerateServerProgramOptions(argc,
                                                                  argv,
                                                                  server_paths,
                                                                  ip_address,
                                                                  ip_port,
                                                                  requested_thread_num,
                                                                  use_shared_memory,
                                                                  trial);
        if (init_result == INIT_OK_DO_NOT_START_ENGINE)
        {
            return 0;
        }
        if (init_result == INIT_FAILED)
        {
            return 1;
        }

#ifdef __linux__
        const int lock_flags = MCL_CURRENT | MCL_FUTURE;
        if (-1 == mlockall(lock_flags))
        {
            SimpleLogger().Write(logWARNING) << "Process " << argv[0] << " could not be locked to RAM";
        }
#endif
        SimpleLogger().Write() <<
            "starting up engines, " << g_GIT_DESCRIPTION << ", " <<
            "compiled at " << __DATE__ << ", " __TIME__;

        if(use_shared_memory)
        {
            SimpleLogger().Write(logDEBUG) << "Loading from shared memory";
        }
        else
        {
            SimpleLogger().Write() << "HSGR file:\t" << server_paths["hsgrdata"];
            SimpleLogger().Write(logDEBUG) << "Nodes file:\t" << server_paths["nodesdata"];
            SimpleLogger().Write(logDEBUG) << "Edges file:\t" << server_paths["edgesdata"];
            SimpleLogger().Write(logDEBUG) << "Geometry file:\t" << server_paths["geometries"];
            SimpleLogger().Write(logDEBUG) << "RAM file:\t" << server_paths["ramindex"];
            SimpleLogger().Write(logDEBUG) << "Index file:\t" << server_paths["fileindex"];
            SimpleLogger().Write(logDEBUG) << "Names file:\t" << server_paths["namesdata"];
            SimpleLogger().Write(logDEBUG) << "Timestamp file:\t" << server_paths["timestamp"];
            SimpleLogger().Write(logDEBUG) << "Threads:\t" << requested_thread_num;
            SimpleLogger().Write(logDEBUG) << "IP address:\t" << ip_address;
            SimpleLogger().Write(logDEBUG) << "IP port:\t" << ip_port;
        }
#ifndef _WIN32
        int sig = 0;
        sigset_t new_mask;
        sigset_t old_mask;
        sigfillset(&new_mask);
        pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask);
#endif

        OSRM osrm_lib(server_paths, use_shared_memory);
        Server * routing_server = ServerFactory::CreateServer(
                        ip_address,
                        ip_port,
                        requested_thread_num
                     );

        routing_server->GetRequestHandlerPtr().RegisterRoutingMachine(&osrm_lib);

        if( trial )
        {
            SimpleLogger().Write() << "trial run, quitting after successful initialization";
        }
        else
        {
            boost::thread server_thread(boost::bind(&Server::Run, routing_server));

#ifndef _WIN32
            sigset_t wait_mask;
            pthread_sigmask(SIG_SETMASK, &old_mask, 0);
            sigemptyset(&wait_mask);
            sigaddset(&wait_mask, SIGINT);
            sigaddset(&wait_mask, SIGQUIT);
            sigaddset(&wait_mask, SIGTERM);
            pthread_sigmask(SIG_BLOCK, &wait_mask, 0);
            SimpleLogger().Write() << "running and waiting for requests";
            sigwait(&wait_mask, &sig);
#else
            // Set console control handler to allow server to be stopped.
            console_ctrl_function = boost::bind(&Server::Stop, routing_server);
            SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
            SimpleLogger().Write() << "running and waiting for requests";
            routing_server->Run();
#endif
            SimpleLogger().Write() << "initiating shutdown";
            routing_server->Stop();
            SimpleLogger().Write() << "stopping threads";

            if (!server_thread.timed_join(boost::posix_time::seconds(2)))
            {
                SimpleLogger().Write(logDEBUG) << "Threads did not finish within 2 seconds. Hard abort!";
            }
        }

        SimpleLogger().Write() << "freeing objects";
        delete routing_server;
        SimpleLogger().Write() << "shutdown completed";
    }
    catch (const std::exception& e)
    {
        SimpleLogger().Write(logWARNING) << "exception: " << e.what();
        return 1;
    }
#ifdef __linux__
    munlockall();
#endif

    return 0;
}
<commit_msg>shorten line<commit_after>/*

Copyright (c) 2013, Project OSRM, Dennis Luxen, others
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#include "Library/OSRM.h"

#include "Server/ServerFactory.h"

#include "Util/GitDescription.h"
#include "Util/InputFileUtil.h"
#include "Util/ProgramOptions.h"
#include "Util/SimpleLogger.h"
#include "Util/UUID.h"

#ifdef __linux__
#include <sys/mman.h>
#endif

#include <signal.h>

#include <boost/bind.hpp>
// #include <boost/date_time.hpp>
#include <boost/thread.hpp>

#include <iostream>

#ifdef _WIN32
boost::function0<void> console_ctrl_function;

BOOL WINAPI console_ctrl_handler(DWORD ctrl_type)
{
  switch (ctrl_type)
  {
  case CTRL_C_EVENT:
  case CTRL_BREAK_EVENT:
  case CTRL_CLOSE_EVENT:
  case CTRL_SHUTDOWN_EVENT:
    console_ctrl_function();
    return TRUE;
  default:
    return FALSE;
  }
}
#endif

int main (int argc, const char * argv[])
{
    try
    {
        LogPolicy::GetInstance().Unmute();

        bool use_shared_memory = false, trial = false;
        std::string ip_address;
        int ip_port, requested_thread_num;

        ServerPaths server_paths;

        const unsigned init_result = GenerateServerProgramOptions(argc,
                                                                  argv,
                                                                  server_paths,
                                                                  ip_address,
                                                                  ip_port,
                                                                  requested_thread_num,
                                                                  use_shared_memory,
                                                                  trial);
        if (init_result == INIT_OK_DO_NOT_START_ENGINE)
        {
            return 0;
        }
        if (init_result == INIT_FAILED)
        {
            return 1;
        }

#ifdef __linux__
        const int lock_flags = MCL_CURRENT | MCL_FUTURE;
        if (-1 == mlockall(lock_flags))
        {
            SimpleLogger().Write(logWARNING) << argv[0] << " could not be locked to RAM";
        }
#endif
        SimpleLogger().Write() <<
            "starting up engines, " << g_GIT_DESCRIPTION << ", " <<
            "compiled at " << __DATE__ << ", " __TIME__;

        if(use_shared_memory)
        {
            SimpleLogger().Write(logDEBUG) << "Loading from shared memory";
        }
        else
        {
            SimpleLogger().Write() << "HSGR file:\t" << server_paths["hsgrdata"];
            SimpleLogger().Write(logDEBUG) << "Nodes file:\t" << server_paths["nodesdata"];
            SimpleLogger().Write(logDEBUG) << "Edges file:\t" << server_paths["edgesdata"];
            SimpleLogger().Write(logDEBUG) << "Geometry file:\t" << server_paths["geometries"];
            SimpleLogger().Write(logDEBUG) << "RAM file:\t" << server_paths["ramindex"];
            SimpleLogger().Write(logDEBUG) << "Index file:\t" << server_paths["fileindex"];
            SimpleLogger().Write(logDEBUG) << "Names file:\t" << server_paths["namesdata"];
            SimpleLogger().Write(logDEBUG) << "Timestamp file:\t" << server_paths["timestamp"];
            SimpleLogger().Write(logDEBUG) << "Threads:\t" << requested_thread_num;
            SimpleLogger().Write(logDEBUG) << "IP address:\t" << ip_address;
            SimpleLogger().Write(logDEBUG) << "IP port:\t" << ip_port;
        }
#ifndef _WIN32
        int sig = 0;
        sigset_t new_mask;
        sigset_t old_mask;
        sigfillset(&new_mask);
        pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask);
#endif

        OSRM osrm_lib(server_paths, use_shared_memory);
        Server * routing_server = ServerFactory::CreateServer(
                        ip_address,
                        ip_port,
                        requested_thread_num
                     );

        routing_server->GetRequestHandlerPtr().RegisterRoutingMachine(&osrm_lib);

        if( trial )
        {
            SimpleLogger().Write() << "trial run, quitting after successful initialization";
        }
        else
        {
            boost::thread server_thread(boost::bind(&Server::Run, routing_server));

#ifndef _WIN32
            sigset_t wait_mask;
            pthread_sigmask(SIG_SETMASK, &old_mask, 0);
            sigemptyset(&wait_mask);
            sigaddset(&wait_mask, SIGINT);
            sigaddset(&wait_mask, SIGQUIT);
            sigaddset(&wait_mask, SIGTERM);
            pthread_sigmask(SIG_BLOCK, &wait_mask, 0);
            SimpleLogger().Write() << "running and waiting for requests";
            sigwait(&wait_mask, &sig);
#else
            // Set console control handler to allow server to be stopped.
            console_ctrl_function = boost::bind(&Server::Stop, routing_server);
            SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
            SimpleLogger().Write() << "running and waiting for requests";
            routing_server->Run();
#endif
            SimpleLogger().Write() << "initiating shutdown";
            routing_server->Stop();
            SimpleLogger().Write() << "stopping threads";

            if (!server_thread.timed_join(boost::posix_time::seconds(2)))
            {
                SimpleLogger().Write(logDEBUG) << "Threads did not finish within 2 seconds. Hard abort!";
            }
        }

        SimpleLogger().Write() << "freeing objects";
        delete routing_server;
        SimpleLogger().Write() << "shutdown completed";
    }
    catch (const std::exception& e)
    {
        SimpleLogger().Write(logWARNING) << "exception: " << e.what();
        return 1;
    }
#ifdef __linux__
    munlockall();
#endif

    return 0;
}
<|endoftext|>


<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXDE-Qt - a lightweight, Qt based, desktop toolset
 *
 * Authors:
 *   Christian Surlykke <christian@surlykke.dk>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

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

#include <QDebug>

#include <LXQt/Power>

#include "powermanagementsettings.h"

namespace PowerManagementSettingsConstants
{
    const QString RUN_CHECK_LEVEL = "runCheckLevel";
    const QString ENABLE_BATTERY_WATCHER_KEY = "enableBatteryWatcher";
    const QString ENABLE_LID_WATCHER_KEY = "enableLidWatcher";
    const QString ENABLE_IDLENESS_WATCHER_KEY = "enableIdlenessWatcher";
    const QString LID_CLOSED_ACTION_KEY = "lidClosedAction";
    const QString LID_CLOSED_AC_ACTION_KEY = "lidClosedAcAction";
    const QString LID_CLOSED_EXT_MON_ACTION_KEY = "lidClosedExtMonAction";
    const QString LID_CLOSED_EXT_MON_AC_ACTION_KEY = "lidClosedExtMonAcAction";
    const QString ENABLE_EXT_MON_LIDCLOSED_ACTIONS_KEY = "enableExtMonLidClosedActions";
    const QString POWER_LOW_ACTION_KEY = "powerLowAction";
    const QString POWER_LOW_WARNING_KEY = "powerLowWarning";
    const QString POWER_LOW_LEVEL_KEY = "powerLowLevel";
    const QString SHOW_ICON_KEY = "showIcon";
    const QString USE_THEME_ICONS_KEY = "useThemeIcons";
    const QString IDLENESS_ACTION_KEY = "idlenessAction";
    const QString IDLENESS_TIME_SECS_KEY = "idlenessTimeSecs";
}

using namespace PowerManagementSettingsConstants;

PowerManagementSettings::PowerManagementSettings(QObject* parent) : LXQt::Settings("lxqt-powermanagement")
{
}

PowerManagementSettings::~PowerManagementSettings()
{
}

int PowerManagementSettings::getRunCheckLevel()
{
    return value(RUN_CHECK_LEVEL, 0).toInt();
}

void PowerManagementSettings::setRunCheckLevel(int newLevel)
{
    setValue(RUN_CHECK_LEVEL, newLevel);
}

bool PowerManagementSettings::isBatteryWatcherEnabled()
{
    return value(ENABLE_BATTERY_WATCHER_KEY, true).toBool();
}

void PowerManagementSettings::setBatteryWatcherEnabled(bool batteryWatcherEnabled)
{
    setValue(ENABLE_BATTERY_WATCHER_KEY, batteryWatcherEnabled);
}

int PowerManagementSettings::getPowerLowAction()
{
    return value(POWER_LOW_ACTION_KEY, 0).toInt();
}

void PowerManagementSettings::setPowerLowAction(int powerLowAction)
{
    setValue(POWER_LOW_ACTION_KEY, powerLowAction);
}

int PowerManagementSettings::getPowerLowLevel()
{
    return value(POWER_LOW_LEVEL_KEY, 5).toInt();
}

void PowerManagementSettings::setPowerLowLevel(int powerLowLevel)
{
    setValue(POWER_LOW_LEVEL_KEY, powerLowLevel);
}

int PowerManagementSettings::getPowerLowWarningTime()
{
    return value(POWER_LOW_WARNING_KEY, 30).toInt();
}

void PowerManagementSettings::setPowerLowWarningTime(int powerLowWarningTime)
{
    setValue(POWER_LOW_WARNING_KEY, powerLowWarningTime);
}

bool PowerManagementSettings::isShowIcon()
{
    return value(SHOW_ICON_KEY, true).toBool();
}

void PowerManagementSettings::setShowIcon(bool showIcon)
{
    setValue(SHOW_ICON_KEY, showIcon);
}

bool PowerManagementSettings::isUseThemeIcons()
{
    return value(USE_THEME_ICONS_KEY, false).toBool();
}

void PowerManagementSettings::setUseThemeIcons(bool useThemeIcons)
{
    setValue(USE_THEME_ICONS_KEY, useThemeIcons);
}

bool PowerManagementSettings::isLidWatcherEnabled()
{
    return value(ENABLE_LID_WATCHER_KEY, true).toBool();
}

void PowerManagementSettings::setLidWatcherEnabled(bool lidWatcherEnabled)
{
    setValue(ENABLE_LID_WATCHER_KEY, lidWatcherEnabled);
}

int PowerManagementSettings::getLidClosedAcAction()
{
    return value(LID_CLOSED_AC_ACTION_KEY, 0).toInt();
}

void PowerManagementSettings::setLidClosedAcAction(int lidClosedAcAction)
{
    setValue(LID_CLOSED_AC_ACTION_KEY, lidClosedAcAction);
}

int PowerManagementSettings::getLidClosedAction()
{
    return value(LID_CLOSED_ACTION_KEY, 0).toInt();
}

void PowerManagementSettings::setLidClosedAction(int lidClosedAction)
{
    setValue(LID_CLOSED_ACTION_KEY, lidClosedAction);
}

int PowerManagementSettings::getLidClosedExtMonAcAction()
{
    return value(LID_CLOSED_EXT_MON_AC_ACTION_KEY, 0).toInt();
}

void PowerManagementSettings::setLidClosedExtMonAcAction(int lidClosedExtMonAcAction)
{
    setValue(LID_CLOSED_EXT_MON_AC_ACTION_KEY, lidClosedExtMonAcAction);
}

int PowerManagementSettings::getLidClosedExtMonAction()
{
    return value(LID_CLOSED_EXT_MON_ACTION_KEY, 0).toInt();
}

void PowerManagementSettings::setLidClosedExtMonAction(int lidClosedExtMonAction)
{
    setValue(LID_CLOSED_EXT_MON_ACTION_KEY, lidClosedExtMonAction);
}

bool PowerManagementSettings::isEnableExtMonLidClosedActions()
{
    return value(ENABLE_EXT_MON_LIDCLOSED_ACTIONS_KEY, 0).toBool();
}

void PowerManagementSettings::setEnableExtMonLidClosedActions(bool enableExtMonLidClosedActions)
{
    setValue(ENABLE_EXT_MON_LIDCLOSED_ACTIONS_KEY, enableExtMonLidClosedActions);
}

int PowerManagementSettings::getIdlenessAction()
{
    // default to nothing (-1)
    return value(IDLENESS_ACTION_KEY, -1).toInt();
}

void PowerManagementSettings::setIdlenessAction(int idlenessAction)
{
    setValue(IDLENESS_ACTION_KEY, idlenessAction);
}

int PowerManagementSettings::getIdlenessTimeSecs()
{
    // default to 15 minutes
    return value(IDLENESS_TIME_SECS_KEY, 900).toInt();
}

void PowerManagementSettings::setIdlenessTimeSecs(int idlenessTimeSecs)
{
    setValue(IDLENESS_TIME_SECS_KEY, idlenessTimeSecs);
}

bool PowerManagementSettings::isIdlenessWatcherEnabled()
{
    return value(ENABLE_IDLENESS_WATCHER_KEY, false).toBool();
}

void PowerManagementSettings::setIdlenessWatcherEnabled(bool idlenessWatcherEnabled)
{
    setValue(ENABLE_IDLENESS_WATCHER_KEY, idlenessWatcherEnabled);
}

<commit_msg>Default to no action if the action is not specified in the config file<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXDE-Qt - a lightweight, Qt based, desktop toolset
 *
 * Authors:
 *   Christian Surlykke <christian@surlykke.dk>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

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

#include <QDebug>

#include <LXQt/Power>

#include "powermanagementsettings.h"

namespace PowerManagementSettingsConstants
{
    const QString RUN_CHECK_LEVEL = "runCheckLevel";
    const QString ENABLE_BATTERY_WATCHER_KEY = "enableBatteryWatcher";
    const QString ENABLE_LID_WATCHER_KEY = "enableLidWatcher";
    const QString ENABLE_IDLENESS_WATCHER_KEY = "enableIdlenessWatcher";
    const QString LID_CLOSED_ACTION_KEY = "lidClosedAction";
    const QString LID_CLOSED_AC_ACTION_KEY = "lidClosedAcAction";
    const QString LID_CLOSED_EXT_MON_ACTION_KEY = "lidClosedExtMonAction";
    const QString LID_CLOSED_EXT_MON_AC_ACTION_KEY = "lidClosedExtMonAcAction";
    const QString ENABLE_EXT_MON_LIDCLOSED_ACTIONS_KEY = "enableExtMonLidClosedActions";
    const QString POWER_LOW_ACTION_KEY = "powerLowAction";
    const QString POWER_LOW_WARNING_KEY = "powerLowWarning";
    const QString POWER_LOW_LEVEL_KEY = "powerLowLevel";
    const QString SHOW_ICON_KEY = "showIcon";
    const QString USE_THEME_ICONS_KEY = "useThemeIcons";
    const QString IDLENESS_ACTION_KEY = "idlenessAction";
    const QString IDLENESS_TIME_SECS_KEY = "idlenessTimeSecs";
}

using namespace PowerManagementSettingsConstants;

PowerManagementSettings::PowerManagementSettings(QObject* parent) : LXQt::Settings("lxqt-powermanagement")
{
}

PowerManagementSettings::~PowerManagementSettings()
{
}

int PowerManagementSettings::getRunCheckLevel()
{
    return value(RUN_CHECK_LEVEL, 0).toInt();
}

void PowerManagementSettings::setRunCheckLevel(int newLevel)
{
    setValue(RUN_CHECK_LEVEL, newLevel);
}

bool PowerManagementSettings::isBatteryWatcherEnabled()
{
    return value(ENABLE_BATTERY_WATCHER_KEY, true).toBool();
}

void PowerManagementSettings::setBatteryWatcherEnabled(bool batteryWatcherEnabled)
{
    setValue(ENABLE_BATTERY_WATCHER_KEY, batteryWatcherEnabled);
}

int PowerManagementSettings::getPowerLowAction()
{
    return value(POWER_LOW_ACTION_KEY, -1).toInt();
}

void PowerManagementSettings::setPowerLowAction(int powerLowAction)
{
    setValue(POWER_LOW_ACTION_KEY, powerLowAction);
}

int PowerManagementSettings::getPowerLowLevel()
{
    return value(POWER_LOW_LEVEL_KEY, 5).toInt();
}

void PowerManagementSettings::setPowerLowLevel(int powerLowLevel)
{
    setValue(POWER_LOW_LEVEL_KEY, powerLowLevel);
}

int PowerManagementSettings::getPowerLowWarningTime()
{
    return value(POWER_LOW_WARNING_KEY, 30).toInt();
}

void PowerManagementSettings::setPowerLowWarningTime(int powerLowWarningTime)
{
    setValue(POWER_LOW_WARNING_KEY, powerLowWarningTime);
}

bool PowerManagementSettings::isShowIcon()
{
    return value(SHOW_ICON_KEY, true).toBool();
}

void PowerManagementSettings::setShowIcon(bool showIcon)
{
    setValue(SHOW_ICON_KEY, showIcon);
}

bool PowerManagementSettings::isUseThemeIcons()
{
    return value(USE_THEME_ICONS_KEY, false).toBool();
}

void PowerManagementSettings::setUseThemeIcons(bool useThemeIcons)
{
    setValue(USE_THEME_ICONS_KEY, useThemeIcons);
}

bool PowerManagementSettings::isLidWatcherEnabled()
{
    return value(ENABLE_LID_WATCHER_KEY, true).toBool();
}

void PowerManagementSettings::setLidWatcherEnabled(bool lidWatcherEnabled)
{
    setValue(ENABLE_LID_WATCHER_KEY, lidWatcherEnabled);
}

int PowerManagementSettings::getLidClosedAcAction()
{
    return value(LID_CLOSED_AC_ACTION_KEY, -1).toInt();
}

void PowerManagementSettings::setLidClosedAcAction(int lidClosedAcAction)
{
    setValue(LID_CLOSED_AC_ACTION_KEY, lidClosedAcAction);
}

int PowerManagementSettings::getLidClosedAction()
{
    return value(LID_CLOSED_ACTION_KEY, -1).toInt();
}

void PowerManagementSettings::setLidClosedAction(int lidClosedAction)
{
    setValue(LID_CLOSED_ACTION_KEY, lidClosedAction);
}

int PowerManagementSettings::getLidClosedExtMonAcAction()
{
    return value(LID_CLOSED_EXT_MON_AC_ACTION_KEY, -1).toInt();
}

void PowerManagementSettings::setLidClosedExtMonAcAction(int lidClosedExtMonAcAction)
{
    setValue(LID_CLOSED_EXT_MON_AC_ACTION_KEY, lidClosedExtMonAcAction);
}

int PowerManagementSettings::getLidClosedExtMonAction()
{
    return value(LID_CLOSED_EXT_MON_ACTION_KEY, -1).toInt();
}

void PowerManagementSettings::setLidClosedExtMonAction(int lidClosedExtMonAction)
{
    setValue(LID_CLOSED_EXT_MON_ACTION_KEY, lidClosedExtMonAction);
}

bool PowerManagementSettings::isEnableExtMonLidClosedActions()
{
    return value(ENABLE_EXT_MON_LIDCLOSED_ACTIONS_KEY, 0).toBool();
}

void PowerManagementSettings::setEnableExtMonLidClosedActions(bool enableExtMonLidClosedActions)
{
    setValue(ENABLE_EXT_MON_LIDCLOSED_ACTIONS_KEY, enableExtMonLidClosedActions);
}

int PowerManagementSettings::getIdlenessAction()
{
    // default to nothing (-1)
    return value(IDLENESS_ACTION_KEY, -1).toInt();
}

void PowerManagementSettings::setIdlenessAction(int idlenessAction)
{
    setValue(IDLENESS_ACTION_KEY, idlenessAction);
}

int PowerManagementSettings::getIdlenessTimeSecs()
{
    // default to 15 minutes
    return value(IDLENESS_TIME_SECS_KEY, 900).toInt();
}

void PowerManagementSettings::setIdlenessTimeSecs(int idlenessTimeSecs)
{
    setValue(IDLENESS_TIME_SECS_KEY, idlenessTimeSecs);
}

bool PowerManagementSettings::isIdlenessWatcherEnabled()
{
    return value(ENABLE_IDLENESS_WATCHER_KEY, false).toBool();
}

void PowerManagementSettings::setIdlenessWatcherEnabled(bool idlenessWatcherEnabled)
{
    setValue(ENABLE_IDLENESS_WATCHER_KEY, idlenessWatcherEnabled);
}

<|endoftext|>


<commit_before>/* http_long_header_test.cc
   Jeremy Barnes, 31 January 2011
   Copyright (c) 2011 Datacratic.  All rights reserved.

   Test that we can't crash the server sending long headers.
*/

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include <boost/test/unit_test.hpp>
#include "soa/service/http_endpoint.h"
#include "soa/service/active_endpoint.h"
#include "soa/service/passive_endpoint.h"
#include <sys/socket.h>
#include "jml/utils/guard.h"
#include "jml/utils/filter_streams.h"
#include "jml/arch/exception_handler.h"
#include "jml/utils/testing/watchdog.h"
#include "jml/utils/testing/fd_exhauster.h"
#include "test_connection_error.h"

using namespace std;
using namespace ML;
using namespace Datacratic;

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include <boost/test/unit_test.hpp>
#include "soa/service/http_endpoint.h"
#include "soa/service/active_endpoint.h"
#include "soa/service/passive_endpoint.h"
#include <sys/socket.h>
#include "jml/utils/guard.h"
#include "jml/arch/exception_handler.h"
#include "jml/utils/testing/watchdog.h"
#include "jml/utils/testing/fd_exhauster.h"
#include <poll.h>

using namespace std;
using namespace ML;
using namespace Datacratic;

BOOST_AUTO_TEST_CASE( test_accept_speed )
{
    Watchdog watchdog(5.0);

    string connectionError;

    PassiveEndpointT<SocketTransport> acceptor("acceptor");

    string error;

    struct TestHandler : HttpConnectionHandler {

        TestHandler(string & error)
            : bytesDone(0), error(error)
        {
        }

        int bytesDone;
        string & error;

        virtual void handleData(const std::string & data)
        {

            bytesDone += data.size();
            if (bytesDone > 1000000)
                throw ML::Exception("allowed infinite headers");
            HttpConnectionHandler::handleData(data);
        }

        virtual void handleError(const std::string & error)
        {
            cerr << "got error " << error << endl;
            this->error = error;
        }

        virtual void
        handleHttpHeader(const HttpHeader & header)
        {

            cerr << "got header " << header << endl;
        }

        virtual void handleHttpChunk(const HttpHeader & header,
                                     const std::string & chunkHeader,
                                     const std::string & chunk)
        {
            cerr << "chunkHeader " << chunkHeader << endl;
            //cerr << "chunk has " << chunk.length() << " bytes" << endl;
        }

    };

    acceptor.onMakeNewHandler = [&] ()
        {
            return ML::make_std_sp(new TestHandler(error));
        };

    int port = acceptor.init();

    cerr << "port = " << port << endl;

    BOOST_CHECK_EQUAL(acceptor.numConnections(), 0);

    Date before = Date::now();

    /* Open a connection */
    int s = socket(AF_INET, SOCK_STREAM, 0);
    if (s == -1)
        throw Exception("socket");

    //cerr << "i = " << i << " s = " << s << " sockets.size() = "
    //     << sockets.size() << endl;

    struct sockaddr_in addr = { AF_INET, htons(port), { INADDR_ANY } };
    //cerr << "before connect on " << s << endl;
    int res = connect(s, reinterpret_cast<const sockaddr *>(&addr),
                      sizeof(addr));
    //cerr << "after connect on " << s << endl;

    if (res == -1) {
        cerr << "connect error: " << strerror(errno) << endl;
        close(s);
    }

    /* Try to write 32MB of headers into the socket. */
    const char * buf = "header: 9012345678901234567890\r\n";

    int written = 0;
    int writeError = 0;

    for (unsigned i = 0;  i < 1000000;  ++i) {
        int res = write(s, buf, strlen(buf));
        if (res > 0)
            written += res;
        else if (res == 0)
            throw ML::Exception("nothing written");
        else {
            writeError = errno;
            cerr << strerror(errno) << endl;
            cerr << "error after writing " << written << " bytes"
                 << endl;
            break;
        }
    }

    // Check we didn't write more than 1MB before the error...
    BOOST_CHECK_LT(written, 1000000);
    BOOST_CHECK_EQUAL(writeError, ECONNRESET);
    BOOST_CHECK_NE(error.find("HTTP header exceeds"), string::npos);

    cerr << "wrote " << written << " bytes" << endl;

    close(s);

    acceptor.shutdown();
}
<commit_msg>Remove useless duplicated include<commit_after>/* http_long_header_test.cc
   Jeremy Barnes, 31 January 2011
   Copyright (c) 2011 Datacratic.  All rights reserved.

   Test that we can't crash the server sending long headers.
*/

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include <boost/test/unit_test.hpp>
#include "soa/service/http_endpoint.h"
#include "soa/service/active_endpoint.h"
#include "soa/service/passive_endpoint.h"
#include <sys/socket.h>
#include "jml/utils/guard.h"
#include "jml/arch/exception_handler.h"
#include "jml/utils/testing/watchdog.h"
#include "jml/utils/testing/fd_exhauster.h"
#include <poll.h>

using namespace std;
using namespace ML;
using namespace Datacratic;

BOOST_AUTO_TEST_CASE( test_accept_speed )
{
    Watchdog watchdog(5.0);

    string connectionError;

    PassiveEndpointT<SocketTransport> acceptor("acceptor");

    string error;

    struct TestHandler : HttpConnectionHandler {

        TestHandler(string & error)
            : bytesDone(0), error(error)
        {
        }

        int bytesDone;
        string & error;

        virtual void handleData(const std::string & data)
        {

            bytesDone += data.size();
            if (bytesDone > 1000000)
                throw ML::Exception("allowed infinite headers");
            HttpConnectionHandler::handleData(data);
        }

        virtual void handleError(const std::string & error)
        {
            cerr << "got error " << error << endl;
            this->error = error;
        }

        virtual void
        handleHttpHeader(const HttpHeader & header)
        {

            cerr << "got header " << header << endl;
        }

        virtual void handleHttpChunk(const HttpHeader & header,
                                     const std::string & chunkHeader,
                                     const std::string & chunk)
        {
            cerr << "chunkHeader " << chunkHeader << endl;
            //cerr << "chunk has " << chunk.length() << " bytes" << endl;
        }

    };

    acceptor.onMakeNewHandler = [&] ()
        {
            return ML::make_std_sp(new TestHandler(error));
        };

    int port = acceptor.init();

    cerr << "port = " << port << endl;

    BOOST_CHECK_EQUAL(acceptor.numConnections(), 0);

    Date before = Date::now();

    /* Open a connection */
    int s = socket(AF_INET, SOCK_STREAM, 0);
    if (s == -1)
        throw Exception("socket");

    //cerr << "i = " << i << " s = " << s << " sockets.size() = "
    //     << sockets.size() << endl;

    struct sockaddr_in addr = { AF_INET, htons(port), { INADDR_ANY } };
    //cerr << "before connect on " << s << endl;
    int res = connect(s, reinterpret_cast<const sockaddr *>(&addr),
                      sizeof(addr));
    //cerr << "after connect on " << s << endl;

    if (res == -1) {
        cerr << "connect error: " << strerror(errno) << endl;
        close(s);
    }

    /* Try to write 32MB of headers into the socket. */
    const char * buf = "header: 9012345678901234567890\r\n";

    int written = 0;
    int writeError = 0;

    for (unsigned i = 0;  i < 1000000;  ++i) {
        int res = write(s, buf, strlen(buf));
        if (res > 0)
            written += res;
        else if (res == 0)
            throw ML::Exception("nothing written");
        else {
            writeError = errno;
            cerr << strerror(errno) << endl;
            cerr << "error after writing " << written << " bytes"
                 << endl;
            break;
        }
    }

    // Check we didn't write more than 1MB before the error...
    BOOST_CHECK_LT(written, 1000000);
    BOOST_CHECK_EQUAL(writeError, ECONNRESET);
    BOOST_CHECK_NE(error.find("HTTP header exceeds"), string::npos);

    cerr << "wrote " << written << " bytes" << endl;

    close(s);

    acceptor.shutdown();
}
<|endoftext|>


<commit_before>#include "omxDefines.h"
#include "unsupported/Eigen/MatrixFunctions"

// For background, see
// http://epubs.siam.org/doi/abs/10.1137/090768539

void logm_eigen(int n, double *rz, double *out)
{
    Eigen::Map< Eigen::MatrixXd > inMat(rz, n, n);
    Eigen::Map< Eigen::MatrixXd > outMat(out, n, n);
    outMat = inMat.log();
}

void expm_eigen(int n, double *rz, double *out)
{
    Eigen::Map< Eigen::MatrixXd > inMat(rz, n, n);
    Eigen::Map< Eigen::MatrixXd > outMat(out, n, n);
    outMat = inMat.exp();
}
<commit_msg>Turn off Eigen bounds checking for matrix log/exp<commit_after>#undef OMX_BOUNDS_CHECK  // Very, very expensive here

#include "omxDefines.h"
#include "unsupported/Eigen/MatrixFunctions"

// For background, see
// http://epubs.siam.org/doi/abs/10.1137/090768539

void logm_eigen(int n, double *rz, double *out)
{
    Eigen::Map< Eigen::MatrixXd > inMat(rz, n, n);
    Eigen::Map< Eigen::MatrixXd > outMat(out, n, n);
    outMat = inMat.log();
}

void expm_eigen(int n, double *rz, double *out)
{
    Eigen::Map< Eigen::MatrixXd > inMat(rz, n, n);
    Eigen::Map< Eigen::MatrixXd > outMat(out, n, n);
    outMat = inMat.exp();
}
<|endoftext|>


<commit_before>#include "DMRecordTask.h"
#include "DMUtil.h"
#include "DMWriteTask.h"
#include "SkCommandLineFlags.h"
#include "SkRecording.h"

DEFINE_bool(skr, false, "If true, run SKR tests.");

namespace DM {

RecordTask::RecordTask(const Task& parent, skiagm::GM* gm, SkBitmap reference)
    : CpuTask(parent)
    , fName(UnderJoin(parent.name().c_str(), "skr"))
    , fGM(gm)
    , fReference(reference)
    {}

void RecordTask::draw() {
    // Record the GM into an SkRecord.
    EXPERIMENTAL::SkRecording recording(fReference.width(), fReference.height());
    fGM->draw(recording.canvas());
    SkAutoTDelete<const EXPERIMENTAL::SkPlayback> playback(recording.releasePlayback());

    // Draw the SkRecord back into a bitmap.
    SkBitmap bitmap;
    SetupBitmap(fReference.colorType(), fGM.get(), &bitmap);
    SkCanvas target(bitmap);
    playback->draw(&target);

    if (!BitmapsEqual(bitmap, fReference)) {
        this->fail();
        this->spawnChild(SkNEW_ARGS(WriteTask, (*this, bitmap)));
    }
}

bool RecordTask::shouldSkip() const {
    return !FLAGS_skr;
}

}  // namespace DM
<commit_msg>DM: Apply initial transform in --skr mode.<commit_after>#include "DMRecordTask.h"
#include "DMUtil.h"
#include "DMWriteTask.h"
#include "SkCommandLineFlags.h"
#include "SkRecording.h"

DEFINE_bool(skr, false, "If true, run SKR tests.");

namespace DM {

RecordTask::RecordTask(const Task& parent, skiagm::GM* gm, SkBitmap reference)
    : CpuTask(parent)
    , fName(UnderJoin(parent.name().c_str(), "skr"))
    , fGM(gm)
    , fReference(reference)
    {}

void RecordTask::draw() {
    // Record the GM into an SkRecord.
    EXPERIMENTAL::SkRecording recording(fReference.width(), fReference.height());
    recording.canvas()->concat(fGM->getInitialTransform());
    fGM->draw(recording.canvas());
    SkAutoTDelete<const EXPERIMENTAL::SkPlayback> playback(recording.releasePlayback());

    // Draw the SkRecord back into a bitmap.
    SkBitmap bitmap;
    SetupBitmap(fReference.colorType(), fGM.get(), &bitmap);
    SkCanvas target(bitmap);
    playback->draw(&target);

    if (!BitmapsEqual(bitmap, fReference)) {
        this->fail();
        this->spawnChild(SkNEW_ARGS(WriteTask, (*this, bitmap)));
    }
}

bool RecordTask::shouldSkip() const {
    return !FLAGS_skr;
}

}  // namespace DM
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <cstring>
#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
#include <map>
#include <set>

#include "server.h"
#include "duckchat.h"

// Server can accept connections.
// Server handles Login and Logout from users, and keeps records of which users are logged in.
// TODO Server handles Join and Leave from users, keeps records of which channels a user belongs to,
// and keeps records of which users are in a channel.
// TODO Server handles the Say message.
// TODO Server correctly handles List and Who.
// TODO Create copies of your client and server source. Modify them to send invalid packets to your good client
// and server, to see if you can make your client or server crash. Fix any bugs you find.

//std::string user;

class Channel {
public:
  std::string name;
  std::list<User *> users;

  Channel(std::string name): name(name) {};
};

class User {
public:
  std::string name;
  in_addr_t address;
  unsigned short port;
//  std::set<Channel *> channels;

  User(std::string name, in_addr_t address, unsigned short port): name(name), address(address), port(port) {};
};

std::map<std::string, User *> kUsers;
std::map<std::string, Channel *> kChannels;

void Error(const char *msg) {
  perror(msg);
  exit(1);
}

void ProcessRequest(void *buffer, in_addr_t user_address, unsigned short user_port) {
  struct request current_request;
  User *new_user;
  Channel *channel;

  memcpy(&current_request, buffer, sizeof(struct request));
  std::cout << "request type: " << current_request.req_type << std::endl;
  request_t request_type = current_request.req_type;

  switch(request_type) {
    case REQ_LOGIN:
      struct request_login login_request;
      memcpy(&login_request, buffer, sizeof(struct request_login));

      new_user = new User(login_request.req_username, user_address, user_port);
      kUsers.insert({std::string(login_request.req_username), new_user});

      std::cout << "server: " << login_request.req_username << " logs in" << std::endl;
      break;
    case REQ_LOGOUT:
      struct request_logout logout_request;
      memcpy(&logout_request, buffer, sizeof(struct request_logout));

      for (auto user : kUsers) {
        unsigned short current_port = user.second->port;
        in_addr_t current_address = user.second->address;

        if (current_port == user_port && current_address == user_address) {
          std::cout << "server: " << user.first << " logs out" << std::endl;
          kUsers.erase(user.first);
          break;
        }
      }
      break;
    case REQ_JOIN:
      struct request_join join_request;
      memcpy(&join_request, buffer, sizeof(struct request_join));
      bool isNewChannel = true;

      // If channel does exists in global map, set local channel to channel from kChannels
      for (auto ch : kChannels) {
        if (join_request.req_channel == ch.second->name) {
          isNewChannel = false;
          channel = ch.second;
          break;
        }
      }

      // If channel is new create a new channel
      if (isNewChannel) {
        channel = new Channel(join_request.req_channel);
      }

      for (auto user : kUsers) {
        unsigned short current_port = user.second->port;
        in_addr_t current_address = user.second->address;

        if (current_port == user_port && current_address == user_address) {
          std::cout << "server: " << user.first << " joins channel "<< channel->name << std::endl;

          channel->users.push_back(user);

          // Otherwise
          if (isNewChannel) {
            kChannels.insert({channel->name, channel});
          }

          // Test print
          for (auto u : channel->users) {
            std::cout << "user: " << u << std::endl;
          }
          break;
        }

      }
      break;
    default:
      break;
  }
}

int main(int argc, char *argv[]) {
  struct sockaddr_in server_addr;

  int server_socket;
  int receive_len;
  void* buffer[kBufferSize];
  int port;

//  user = "";

  if (argc < 2) {
    std::cerr << "server: no port provided" << std::endl;
    exit(1);
  }

  port = atoi(argv[1]);

  memset((char *) &server_addr, 0, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  server_addr.sin_port = htons(port);

  if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    Error("server: can't open socket\n");
  }

  if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
    Error("server: bind failed\n");
  }

  printf("server: waiting on port %d\n", port);
  while (1) {
    struct sockaddr_in client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
//    std::cout << "before recvfrom" << std::endl;
    receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len);
    if (receive_len > 0) {
      buffer[receive_len] = 0;

//      std::cout << "port " << client_addr.sin_port << std::endl;

      ProcessRequest(buffer, client_addr.sin_addr.s_addr, client_addr.sin_port);
    }
  }
}
<commit_msg>list to vector<commit_after>#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <cstring>
#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
#include <map>
#include <set>
#include <vector>

#include "server.h"
#include "duckchat.h"

// Server can accept connections.
// Server handles Login and Logout from users, and keeps records of which users are logged in.
// TODO Server handles Join and Leave from users, keeps records of which channels a user belongs to,
// and keeps records of which users are in a channel.
// TODO Server handles the Say message.
// TODO Server correctly handles List and Who.
// TODO Create copies of your client and server source. Modify them to send invalid packets to your good client
// and server, to see if you can make your client or server crash. Fix any bugs you find.

//std::string user;

class Channel {
public:
  std::string name;
  std::vector<User *> users;

  Channel(std::string name): name(name) {};
};

class User {
public:
  std::string name;
  in_addr_t address;
  unsigned short port;
//  std::set<Channel *> channels;

  User(std::string name, in_addr_t address, unsigned short port): name(name), address(address), port(port) {};
};

std::map<std::string, User *> kUsers;
std::map<std::string, Channel *> kChannels;

void Error(const char *msg) {
  perror(msg);
  exit(1);
}

void ProcessRequest(void *buffer, in_addr_t user_address, unsigned short user_port) {
  struct request current_request;
  User *new_user;
  Channel *channel;
  bool isNewChannel;

  memcpy(&current_request, buffer, sizeof(struct request));
  std::cout << "request type: " << current_request.req_type << std::endl;
  request_t request_type = current_request.req_type;

  switch(request_type) {
    case REQ_LOGIN:
      struct request_login login_request;
      memcpy(&login_request, buffer, sizeof(struct request_login));

      new_user = new User(login_request.req_username, user_address, user_port);
      kUsers.insert({std::string(login_request.req_username), new_user});

      std::cout << "server: " << login_request.req_username << " logs in" << std::endl;
      break;
    case REQ_LOGOUT:
      struct request_logout logout_request;
      memcpy(&logout_request, buffer, sizeof(struct request_logout));

      for (auto user : kUsers) {
        unsigned short current_port = user.second->port;
        in_addr_t current_address = user.second->address;

        if (current_port == user_port && current_address == user_address) {
          std::cout << "server: " << user.first << " logs out" << std::endl;
          kUsers.erase(user.first);
          break;
        }
      }
      break;
    case REQ_JOIN:
      struct request_join join_request;
      memcpy(&join_request, buffer, sizeof(struct request_join));
      isNewChannel = true;

      // If channel does exists in global map, set local channel to channel from kChannels
      for (auto ch : kChannels) {
        if (join_request.req_channel == ch.second->name) {
          isNewChannel = false;
          channel = ch.second;
          break;
        }
      }

      // If channel is new create a new channel
      if (isNewChannel) {
        channel = new Channel(join_request.req_channel);
      }

      for (auto user : kUsers) {
        unsigned short current_port = user.second->port;
        in_addr_t current_address = user.second->address;

        if (current_port == user_port && current_address == user_address) {
          std::cout << "server: " << user.first << " joins channel "<< channel->name << std::endl;

          channel->users.push_back(user);

          // Otherwise
          if (isNewChannel) {
            kChannels.insert({channel->name, channel});
          }

          // Test print
          for (auto u : channel->users) {
            std::cout << "user: " << u << std::endl;
          }
          break;
        }

      }
      break;
    default:
      break;
  }
}

int main(int argc, char *argv[]) {
  struct sockaddr_in server_addr;

  int server_socket;
  int receive_len;
  void* buffer[kBufferSize];
  int port;

//  user = "";

  if (argc < 2) {
    std::cerr << "server: no port provided" << std::endl;
    exit(1);
  }

  port = atoi(argv[1]);

  memset((char *) &server_addr, 0, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  server_addr.sin_port = htons(port);

  if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    Error("server: can't open socket\n");
  }

  if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
    Error("server: bind failed\n");
  }

  printf("server: waiting on port %d\n", port);
  while (1) {
    struct sockaddr_in client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
//    std::cout << "before recvfrom" << std::endl;
    receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len);
    if (receive_len > 0) {
      buffer[receive_len] = 0;

//      std::cout << "port " << client_addr.sin_port << std::endl;

      ProcessRequest(buffer, client_addr.sin_addr.s_addr, client_addr.sin_port);
    }
  }
}
<|endoftext|>


<commit_before>#include "menu/menu.h"
#include "menu/menu_option.h"
#include "util/bitmap.h"
#include "util/funcs.h"
#include "util/keyboard.h"
#include "util/sound.h"
#include "util/token.h"
#include "util/tokenreader.h"
#include "globals.h"
#include "init.h"
#include "music.h"

#include <queue>

Bitmap *Menu::work = Bitmap::Screen;

static std::string lastPlayed = "";

static std::queue<MenuOption *> backgrounds;

Menu::Menu() : music("")
{
}

void Menu::load(Token *token)throw( LoadException )
{
	try
	{
		if ( *token != "menu" )
			throw LoadException("Not a menu");

		while ( token->hasTokens() )
		{

			Token * tok;
			*token >> tok;
			if ( *tok == "music" )
			{
				// Set music
				*tok >> music;
			}
			else if ( *tok == "background" )
			{
				// Create new background and push onto the stack
				//background = new obj() <-- D:

				backgrounds.push(background);
			}
			else if ( *tok == "menu" )
			{
				// Create a menu option ie options, controller config, adventure, versus, credits, etc
			}
			else
			{
				cout<<"Unhandled menu attribute: "<<endl;
				tok->print(" ");
			}
		}

	}
	catch ( const TokenException & ex )
	{
		// delete current;
		string m( "Menu parse error: " );
		m += ex.getReason();
		throw LoadException( m );
	}
	catch ( const LoadException & ex )
	{
		// delete current;
		throw ex;
	}

	if(backgrounds.empty())throw LoadException("There should be at least one background in the entire menu!");

}

void Menu::load(const std::string &filename)throw( LoadException )
{
	// Must check for initial token, menu
	TokenReader tr( filename );

	// Token * current = tr.readToken();
	Token * token = tr.readToken();
	load(token);
}

void Menu::run() throw(ReturnException)
{

	Keyboard key;

	Bitmap screen_buffer( 320, 240 );
	bool done = false;
	bool endGame = false;

	if(menuOptions.empty())throw ReturnException();
	selectedOption = menuOptions.begin();

	while( !endGame )
	{
		Global::speed_counter = 0;
		Global::second_counter = 0;
		int game_time = 100;

		if(music != "" && music != lastPlayed)
		{
			Music::pause();
			Music::fadeIn( 0.3 );
			Music::loadSong( Util::getDataPath() + music );
			Music::play();
			lastPlayed = music;
		}
		while ( ! done && (*selectedOption)->getState() != MenuOption::Run ){

			bool draw = false;
			key.poll();

			if ( Global::speed_counter > 0 )
			{
				draw = true;
				// Keys

				// Logic
				std::vector <MenuOption *>::iterator b = menuOptions.begin();
				std::vector <MenuOption *>::iterator e = menuOptions.end();
				for(;b!=e;++b)
				{
					(*b)->logic();
				}

				Global::speed_counter = 0;
			}

			while ( Global::second_counter > 0 )
			{
				game_time--;
				Global::second_counter--;
				if ( game_time < 0 )
					game_time = 0;
			}

			if ( draw )
			{
				// Draw
				std::vector <MenuOption *>::iterator b = menuOptions.begin();
				std::vector <MenuOption *>::iterator e = menuOptions.end();
				for(;b!=e;++b)
				{
					(*b)->draw(work);
				}
			}

			while ( Global::speed_counter < 1 )
			{
				Util::rest( 1 );
				key.poll();
			}

			done |= key[ Keyboard::Key_ESC ];
		}

		// do we got an option to run, lets do it
		if((*selectedOption)->getState() == MenuOption::Run)
		{
			(*selectedOption)->run(endGame);
			// Reset it's state
			(*selectedOption)->setState(MenuOption::Selected);
			//  pop out any backgrounds pushed onto the stack reseting it to the old one if applicable
			if(backgrounds.size() >= 2)
			{
				delete backgrounds.front();
				backgrounds.pop();
				background = backgrounds.front();
			}
		}
	}
}

void Menu::setBitmap(Bitmap *bmp)
{
	work = bmp;
}

Menu::~Menu()
{
	// cleanup
	std::vector <MenuOption *>::iterator b = menuOptions.begin();
	std::vector <MenuOption *>::iterator e = menuOptions.end();
	for(;b!=e;++b)
	{
		if((*b))delete (*b);
	}
}

<commit_msg>menu backgrounds<commit_after>#include "menu/menu.h"
#include "menu/menu_option.h"
#include "util/bitmap.h"
#include "util/funcs.h"
#include "util/keyboard.h"
#include "util/sound.h"
#include "util/token.h"
#include "util/tokenreader.h"
#include "globals.h"
#include "init.h"
#include "music.h"

#include <queue>

Bitmap *Menu::work = Bitmap::Screen;

static std::string lastPlayed = "";

static std::queue<MenuOption *> backgrounds;

Menu::Menu() : music("")
{
}

void Menu::load(Token *token)throw( LoadException )
{
	try
	{
		if ( *token != "menu" )
			throw LoadException("Not a menu");

		while ( token->hasTokens() )
		{

			Token * tok;
			*token >> tok;
			if ( *tok == "music" )
			{
				// Set music
				*tok >> music;
			}
			else if ( *tok == "background" )
			{
				// Create new background and push onto the stack
				//background = new obj() <-- D:

				backgrounds.push(background);
			}
			else if ( *tok == "menu" )
			{
				// Create a menu option ie options, controller config, adventure, versus, credits, etc
			}
			else
			{
				cout<<"Unhandled menu attribute: "<<endl;
				tok->print(" ");
			}
		}

	}
	catch ( const TokenException & ex )
	{
		// delete current;
		string m( "Menu parse error: " );
		m += ex.getReason();
		throw LoadException( m );
	}
	catch ( const LoadException & ex )
	{
		// delete current;
		throw ex;
	}

	if(backgrounds.empty())throw LoadException("There should be at least one background in the entire menu!");

}

void Menu::load(const std::string &filename)throw( LoadException )
{
	// Must check for initial token, menu
	TokenReader tr( filename );

	// Token * current = tr.readToken();
	Token * token = tr.readToken();
	load(token);
}

void Menu::run() throw(ReturnException)
{

	Keyboard key;

	Bitmap screen_buffer( 320, 240 );
	bool done = false;
	bool endGame = false;

	if(menuOptions.empty())throw ReturnException();
	selectedOption = menuOptions.begin();

	while( !endGame )
	{
		Global::speed_counter = 0;
		Global::second_counter = 0;
		int game_time = 100;

		if(music != "" && music != lastPlayed)
		{
			Music::pause();
			Music::fadeIn( 0.3 );
			Music::loadSong( Util::getDataPath() + music );
			Music::play();
			lastPlayed = music;
		}
		while ( ! done && (*selectedOption)->getState() != MenuOption::Run ){

			bool draw = false;
			key.poll();

			if ( Global::speed_counter > 0 )
			{
				draw = true;
				// Keys

				// Logic
				background->logic();

				std::vector <MenuOption *>::iterator b = menuOptions.begin();
				std::vector <MenuOption *>::iterator e = menuOptions.end();
				for(;b!=e;++b)
				{
					(*b)->logic();
				}

				Global::speed_counter = 0;
			}

			while ( Global::second_counter > 0 )
			{
				game_time--;
				Global::second_counter--;
				if ( game_time < 0 )
					game_time = 0;
			}

			if ( draw )
			{
				// Draw
				background->draw(work);

				std::vector <MenuOption *>::iterator b = menuOptions.begin();
				std::vector <MenuOption *>::iterator e = menuOptions.end();
				for(;b!=e;++b)
				{
					(*b)->draw(work);
				}
			}

			while ( Global::speed_counter < 1 )
			{
				Util::rest( 1 );
				key.poll();
			}

			done |= key[ Keyboard::Key_ESC ];
		}

		// do we got an option to run, lets do it
		if((*selectedOption)->getState() == MenuOption::Run)
		{
			(*selectedOption)->run(endGame);
			// Reset it's state
			(*selectedOption)->setState(MenuOption::Selected);
			//  pop out any backgrounds pushed onto the stack reseting it to the old one if applicable
			if(backgrounds.size() >= 2)
			{
				delete backgrounds.front();
				backgrounds.pop();
				background = backgrounds.front();
			}
		}
	}
}

void Menu::setBitmap(Bitmap *bmp)
{
	work = bmp;
}

Menu::~Menu()
{
	// cleanup
	std::vector <MenuOption *>::iterator b = menuOptions.begin();
	std::vector <MenuOption *>::iterator e = menuOptions.end();
	for(;b!=e;++b)
	{
		if((*b))delete (*b);
	}

	while(!backgrounds.empty())
	{
		delete backgrounds.front();
		backgrounds.pop();
	}
}

<|endoftext|>


<commit_before>#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <cstring>
#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
#include <map>
#include <set>

#include "server.h"
#include "duckchat.h"

// TODO Handle domain
// Server can accept connections.
// Server handles Login and Logout from users, and keeps records of which users are logged in.
// Server handles Join and Leave from users, keeps records of which channels a user belongs to,
// and keeps records of which users are in a channel.
// TODO Server handles the Say message.
// TODO Server correctly handles List and Who.
// TODO Create copies of your client and server source. Modify them to send invalid packets to your good client
// and server, to see if you can make your client or server crash. Fix any bugs you find.

class Channel {
public:
  std::string name;
  std::list<User *> users;

  Channel(std::string name): name(name) {};
};

class User {
public:
  std::string name;
  in_addr_t address;
  unsigned short port;

  User(std::string name, in_addr_t address, unsigned short port): name(name), address(address), port(port) {};
};

std::map<std::string, User *> kUsers;
std::map<std::string, Channel *> kChannels;

void Error(const char *msg) {
  perror(msg);
  exit(1);
}

void ProcessRequest(int server_socket, void *buffer, in_addr_t request_address, unsigned short request_port) {
  struct request current_request;
  User *current_user;
  Channel *channel;
  std::string current_channel;
  std::list<User *>::const_iterator it;
  bool is_new_channel;
  bool is_channel;
  bool is_channel_user;

  memcpy(&current_request, buffer, sizeof(struct request));
//  std::cout << "request type: " << current_request.req_type << std::endl;
  request_t request_type = current_request.req_type;

  switch(request_type) {
    case REQ_LOGIN:
      struct request_login login_request;
      memcpy(&login_request, buffer, sizeof(struct request_login));

      current_user = new User(login_request.req_username, request_address, request_port);
      kUsers.insert({std::string(login_request.req_username), current_user});

      std::cout << "server: " << login_request.req_username << " logs in" << std::endl;
      break;

    case REQ_LOGOUT:
      struct request_logout logout_request;
      memcpy(&logout_request, buffer, sizeof(struct request_logout));

      for (auto user : kUsers) {
        unsigned short current_port = user.second->port;
        in_addr_t current_address = user.second->address;

        if (current_port == request_port && current_address == request_address) {
          std::cout << "server: " << user.first << " logs out" << std::endl;
          kUsers.erase(user.first);
          break;
        }
      }
      break;

    case REQ_LEAVE:
      struct request_leave leave_request;
      memcpy(&leave_request, buffer, sizeof(struct request_leave));
      current_channel = leave_request.req_channel;
      for (auto user : kUsers) {
        unsigned short current_port = user.second->port;
        in_addr_t current_address = user.second->address;

        if (current_port == request_port && current_address == request_address) {
          is_channel = false;
          for(auto ch : kChannels){
            if(ch.first == current_channel){
              std::cout << "channel found" << std::endl;
              is_channel = true;
              break;
            }
          }

          if(is_channel){
            channel = kChannels[current_channel];

            for (it = channel->users.begin(); it != channel->users.end(); ++it){
              if((*it)->name == user.first){
                break;
              }
            }

            if( it != channel->users.end()){
              channel->users.remove(*it);
              std::cout << user.first << " leaves channel " << channel->name << std::endl;
              if (channel->users.size() == 0) {
                kChannels.erase(channel->name);
                std::cout << "server: removing empty channel " << channel->name << std::endl;
              }
            }
            for (auto u : channel->users) {
              std::cout << "user: " << u->name << std::endl;
            }
            break;
          } else {
            std::cout << "server: " << user.first << " trying to leave non-existent channel " << channel->name << std::endl;
          }

        }
      }
      break;
    case REQ_JOIN:
      struct request_join join_request;
      memcpy(&join_request, buffer, sizeof(struct request_join));
      is_new_channel = true;

      // If channel does exists in global map, set local channel to channel from kChannels
      for (auto ch : kChannels) {
        if (join_request.req_channel == ch.second->name) {
          is_new_channel = false;
          channel = ch.second;
          break;
        }
      }

      // If channel is new create a new channel
      if (is_new_channel) {
        channel = new Channel(join_request.req_channel);
      }

      for (auto user : kUsers) {
        unsigned short current_port = user.second->port;
        in_addr_t current_address = user.second->address;
        std::cout << std::endl;
        std::cout << "port: " << current_port << " address "<< current_address << std::endl;
        std::cout << "port: " << request_port << " address "<< request_address << std::endl;
        std::cout << std::endl;
        if (current_port == request_port && current_address == request_address) {
          std::cout << "server: " << user.first << " joins channel "<< channel->name << std::endl;

          is_channel_user = false;
          for(auto u : channel->users){
            if(u->name == user.second->name){
              is_channel_user = true;
              break;
            }
          }

          if(!is_channel_user){
            channel->users.push_back(user.second);
          }

          // Otherwise
          if (is_new_channel) {
            kChannels.insert({channel->name, channel});
          }

          // Test print
          for (auto u : channel->users) {
            std::cout << "user: " << u->name << std::endl;
          }
          break;
        }

      }
      break;
    case REQ_SAY:
      struct request_say say_request;
      memcpy(&say_request, buffer, sizeof(struct request_say));

      for (auto user : kUsers) {
        unsigned short current_port = user.second->port;
        in_addr_t current_address = user.second->address;

        if (current_port == request_port && current_address == request_address) {
          current_user = user.second;
          std::cout << "user found : " << current_user->name << std::endl;
          break;
        }
      }

      for(auto user : kChannels[say_request.req_channel]->users){
        struct sockaddr_in client_addr;
        struct text_say say;
        memcpy(&say, buffer, sizeof(struct text_say));

        memset(&client_addr, 0, sizeof(struct sockaddr_in));
        client_addr.sin_family = AF_INET;
        client_addr.sin_port = user->port;
        client_addr.sin_addr.s_addr = user->address;

        // copy message into struct being sent
        strncpy(say.txt_channel, say_request.req_channel, CHANNEL_MAX);
        strncpy(say.txt_text, say_request.req_text, SAY_MAX);
        say.txt_type = TXT_SAY;
        strncpy(say.txt_username, current_user->name.c_str(), USERNAME_MAX);

        size_t message_size = sizeof(struct text_say);

        if (sendto(server_socket, &say, message_size, 0, (struct sockaddr*) &client_addr, sizeof(client_addr)) < 0) {
          Error("server: failed to send say\n");
        }
      }
      std::cout << current_user->name << " sends day message in " << say_request.req_channel << std::endl;
      break;
    default:
      break;
  }
}

int main(int argc, char *argv[]) {
  struct sockaddr_in server_addr;

  int server_socket;
  int receive_len;
  void* buffer[kBufferSize];
  int port;
//  std::string domain;

  if (argc < 3) {
    std::cerr << "Usage: ./server domain_name port_num" << std::endl;
    exit(1);
  }

//  domain = argv[1];
  port = atoi(argv[2]);

  memset((char *) &server_addr, 0, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  server_addr.sin_port = htons(port);

  if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    Error("server: can't open socket\n");
  }

  if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
    Error("server: bind failed\n");
  }

  printf("server: waiting on port %d\n", port);
  while (1) {
    struct sockaddr_in client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
    receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len);

    if (receive_len > 0) {
      buffer[receive_len] = 0;

      ProcessRequest(server_socket, buffer, client_addr.sin_addr.s_addr, client_addr.sin_port);
    }
  }
}
<commit_msg>checking to see if user exists before inserting<commit_after>#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <cstring>
#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
#include <map>
#include <set>

#include "server.h"
#include "duckchat.h"

// TODO Handle domain
// Server can accept connections.
// Server handles Login and Logout from users, and keeps records of which users are logged in.
// Server handles Join and Leave from users, keeps records of which channels a user belongs to,
// and keeps records of which users are in a channel.
// TODO Server handles the Say message.
// TODO Server correctly handles List and Who.
// TODO Create copies of your client and server source. Modify them to send invalid packets to your good client
// and server, to see if you can make your client or server crash. Fix any bugs you find.

class Channel {
public:
  std::string name;
  std::list<User *> users;

  Channel(std::string name): name(name) {};
};

class User {
public:
  std::string name;
  in_addr_t address;
  unsigned short port;

  User(std::string name, in_addr_t address, unsigned short port): name(name), address(address), port(port) {};
};

std::map<std::string, User *> kUsers;
std::map<std::string, Channel *> kChannels;

void Error(const char *msg) {
  perror(msg);
  exit(1);
}

void ProcessRequest(int server_socket, void *buffer, in_addr_t request_address, unsigned short request_port) {
  struct request current_request;
  User *current_user;
  Channel *channel;
  std::string current_channel;
  std::list<User *>::const_iterator it;
  std::map<std::string, User *>::const_iterator map_it;
  bool is_new_channel;
  bool is_channel;
  bool is_channel_user;
  bool is_user;

  memcpy(&current_request, buffer, sizeof(struct request));
//  std::cout << "request type: " << current_request.req_type << std::endl;
  request_t request_type = current_request.req_type;

  switch(request_type) {
    case REQ_LOGIN:
      struct request_login login_request;
      memcpy(&login_request, buffer, sizeof(struct request_login));

      current_user = new User(login_request.req_username, request_address, request_port);
      is_user = false;
      for (map_it = kUsers.begin(); map_it != kUsers.end(); ++map_it){
        if((*map_it).first == current_user->name){
          (*map_it).second == current_user;
          is_user = true;
          break;
        }
      }

      if(!is_user){
        kUsers.insert({std::string(login_request.req_username), current_user});
      }

      std::cout << "server: " << login_request.req_username << " logs in" << std::endl;
      break;

    case REQ_LOGOUT:
      struct request_logout logout_request;
      memcpy(&logout_request, buffer, sizeof(struct request_logout));

      for (auto user : kUsers) {
        unsigned short current_port = user.second->port;
        in_addr_t current_address = user.second->address;

        if (current_port == request_port && current_address == request_address) {
          std::cout << "server: " << user.first << " logs out" << std::endl;
          kUsers.erase(user.first);
          break;
        }
      }
      break;

    case REQ_LEAVE:
      struct request_leave leave_request;
      memcpy(&leave_request, buffer, sizeof(struct request_leave));
      current_channel = leave_request.req_channel;
      for (auto user : kUsers) {
        unsigned short current_port = user.second->port;
        in_addr_t current_address = user.second->address;

        if (current_port == request_port && current_address == request_address) {
          is_channel = false;
          for(auto ch : kChannels){
            if(ch.first == current_channel){
              std::cout << "channel found" << std::endl;
              is_channel = true;
              break;
            }
          }

          if(is_channel){
            channel = kChannels[current_channel];

            for (it = channel->users.begin(); it != channel->users.end(); ++it){
              if((*it)->name == user.first){
                break;
              }
            }

            if( it != channel->users.end()){
              channel->users.remove(*it);
              std::cout << user.first << " leaves channel " << channel->name << std::endl;
              if (channel->users.size() == 0) {
                kChannels.erase(channel->name);
                std::cout << "server: removing empty channel " << channel->name << std::endl;
              }
            }
            for (auto u : channel->users) {
              std::cout << "user: " << u->name << std::endl;
            }
            break;
          } else {
            std::cout << "server: " << user.first << " trying to leave non-existent channel " << channel->name << std::endl;
          }

        }
      }
      break;
    case REQ_JOIN:
      struct request_join join_request;
      memcpy(&join_request, buffer, sizeof(struct request_join));
      is_new_channel = true;

      // If channel does exists in global map, set local channel to channel from kChannels
      for (auto ch : kChannels) {
        if (join_request.req_channel == ch.second->name) {
          is_new_channel = false;
          channel = ch.second;
          break;
        }
      }

      // If channel is new create a new channel
      if (is_new_channel) {
        channel = new Channel(join_request.req_channel);
      }

      for (auto user : kUsers) {
        unsigned short current_port = user.second->port;
        in_addr_t current_address = user.second->address;
        std::cout << std::endl;
        std::cout << "port: " << current_port << " address "<< current_address << std::endl;
        std::cout << "port: " << request_port << " address "<< request_address << std::endl;
        std::cout << std::endl;
        if (current_port == request_port && current_address == request_address) {
          std::cout << "server: " << user.first << " joins channel "<< channel->name << std::endl;

          is_channel_user = false;
          for(auto u : channel->users){
            if(u->name == user.second->name){
              is_channel_user = true;
              break;
            }
          }

          if(!is_channel_user){
            channel->users.push_back(user.second);
          }

          // Otherwise
          if (is_new_channel) {
            kChannels.insert({channel->name, channel});
          }

          // Test print
          for (auto u : channel->users) {
            std::cout << "user: " << u->name << std::endl;
          }
          break;
        }

      }
      break;
    case REQ_SAY:
      struct request_say say_request;
      memcpy(&say_request, buffer, sizeof(struct request_say));

      for (auto user : kUsers) {
        unsigned short current_port = user.second->port;
        in_addr_t current_address = user.second->address;

        if (current_port == request_port && current_address == request_address) {
          current_user = user.second;
          std::cout << "user found : " << current_user->name << std::endl;
          break;
        }
      }

      for(auto user : kChannels[say_request.req_channel]->users){
        struct sockaddr_in client_addr;
        struct text_say say;
        memcpy(&say, buffer, sizeof(struct text_say));

        memset(&client_addr, 0, sizeof(struct sockaddr_in));
        client_addr.sin_family = AF_INET;
        client_addr.sin_port = user->port;
        client_addr.sin_addr.s_addr = user->address;

        // copy message into struct being sent
        strncpy(say.txt_channel, say_request.req_channel, CHANNEL_MAX);
        strncpy(say.txt_text, say_request.req_text, SAY_MAX);
        say.txt_type = TXT_SAY;
        strncpy(say.txt_username, current_user->name.c_str(), USERNAME_MAX);

        size_t message_size = sizeof(struct text_say);

        if (sendto(server_socket, &say, message_size, 0, (struct sockaddr*) &client_addr, sizeof(client_addr)) < 0) {
          Error("server: failed to send say\n");
        }
      }
      std::cout << current_user->name << " sends day message in " << say_request.req_channel << std::endl;
      break;
    default:
      break;
  }
}

int main(int argc, char *argv[]) {
  struct sockaddr_in server_addr;

  int server_socket;
  int receive_len;
  void* buffer[kBufferSize];
  int port;
//  std::string domain;

  if (argc < 3) {
    std::cerr << "Usage: ./server domain_name port_num" << std::endl;
    exit(1);
  }

//  domain = argv[1];
  port = atoi(argv[2]);

  memset((char *) &server_addr, 0, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  server_addr.sin_port = htons(port);

  if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    Error("server: can't open socket\n");
  }

  if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
    Error("server: bind failed\n");
  }

  printf("server: waiting on port %d\n", port);
  while (1) {
    struct sockaddr_in client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
    receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len);

    if (receive_len > 0) {
      buffer[receive_len] = 0;

      ProcessRequest(server_socket, buffer, client_addr.sin_addr.s_addr, client_addr.sin_port);
    }
  }
}
<|endoftext|>


<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

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

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

// C++ includes
#include <fstream>

// Local includes
#include "libmesh/libmesh_config.h"
#include "libmesh/ucd_io.h"
#include "libmesh/mesh_base.h"
#include "libmesh/face_quad4.h"
#include "libmesh/face_tri3.h"
#include "libmesh/cell_tet4.h"
#include "libmesh/cell_hex8.h"
#include "libmesh/cell_prism6.h"

#ifdef LIBMESH_HAVE_GZSTREAM
# include "gzstream.h" // For reading/writing compressed streams
#endif

namespace libMesh
{

// ------------------------------------------------------------
// UCDIO class members
void UCDIO::read (const std::string& file_name)
{
  if (file_name.rfind(".gz") < file_name.size())
    {
#ifdef LIBMESH_HAVE_GZSTREAM

      igzstream in_stream (file_name.c_str());
      this->read_implementation (in_stream);

#else

      libMesh::err << "ERROR:  You must have the zlib.h header "
		    << "files and libraries to read and write "
		    << "compressed streams."
		    << std::endl;
      libmesh_error();

#endif
      return;
    }

  else
    {
      std::ifstream in_stream (file_name.c_str());
      this->read_implementation (in_stream);
      return;
    }
}

void UCDIO::write (const std::string& file_name)
{
  if (file_name.rfind(".gz") < file_name.size())
    {
#ifdef LIBMESH_HAVE_GZSTREAM

      ogzstream out_stream (file_name.c_str());
      this->write_implementation (out_stream);

#else

      libMesh::err << "ERROR:  You must have the zlib.h header "
		    << "files and libraries to read and write "
		    << "compressed streams."
		    << std::endl;
      libmesh_error();

#endif
      return;
    }

  else
    {
      std::ofstream out_stream (file_name.c_str());
      this->write_implementation (out_stream);
      return;
    }
}

void UCDIO::read_implementation (std::istream& in)
{
  // This is a serial-only process for now;
  // the Mesh should be read on processor 0 and
  // broadcast later
  libmesh_assert_equal_to (MeshOutput<MeshBase>::mesh().processor_id(), 0);

  // Check input buffer
  libmesh_assert (in.good());

  MeshBase& mesh = MeshInput<MeshBase>::mesh();

  // Keep track of what kinds of elements this file contains
  elems_of_dimension.clear();
  elems_of_dimension.resize(4, false);

  this->skip_comment_lines (in, '#');

  unsigned int nNodes=0, nElem=0, dummy=0;

  in >> nNodes   // Read the number of nodes from the stream
     >> nElem    // Read the number of elements from the stream
     >> dummy
     >> dummy
     >> dummy;

  // Read the nodal coordinates. Note that UCD format always
  // stores (x,y,z), and in 2D z=0. We don't need to store this,
  // however.  So, we read in x,y,z for each node and make a point
  // in the proper way based on what dimension we're in
  {
    Point xyz;

    for (unsigned int i=0; i<nNodes; i++)
      {
	libmesh_assert (in.good());

	in >> dummy   // Point number
	   >> xyz(0)  // x-coordinate value
	   >> xyz(1)  // y-coordinate value
	   >> xyz(2); // z-coordinate value

	// Build the node
	mesh.add_point (xyz, i);
      }
  }

  // Read the elements from the stream. Notice that the UCD node-numbering
  // scheme is 1-based, and we just created a 0-based scheme above
  // (which is of course what we want). So, when we read in the nodal
  // connectivity for each element we need to take 1 off the value of
  // each node so that we get the right thing.
  {
    unsigned int material_id=0, node=0;
    std::string type;

    for (unsigned int i=0; i<nElem; i++)
      {
	Elem* elem = NULL;

	libmesh_assert (in.good());

	in >> dummy        // Cell number, means nothing to us
	   >> material_id  // doesn't mean anything at present, might later
	   >> type;        // string describing cell type:
	                   // either tri, quad, tet, hex, or prism for the
	                   // obvious cases

	                   // Now read the connectivity.
	if (type == "quad")
	  elem = new Quad4;
	else if (type == "tri")
	  elem = new Tri3;
	else if (type == "hex")
	  elem = new Hex8;
	else if (type == "tet")
	  elem = new Tet4;
	else if (type == "prism")
	  elem = new Prism6;
	else
	  libmesh_error();

	for (unsigned int n=0; n<elem->n_nodes(); n++)
	  {
	    libmesh_assert (in.good());

	    in >> node; // read the current node
	    node -= 1;  // UCD is 1-based, so subtract

	    libmesh_assert_less (node, mesh.n_nodes());

	    elem->set_node(n) =
	      mesh.node_ptr(node); // assign the node
	  }

        elems_of_dimension[elem->dim()] = true;

	// Add the element to the mesh
	elem->set_id(i);
	mesh.add_elem (elem);
      }

    // Set the mesh dimension to the largest encountered for an element
    for (unsigned int i=0; i!=4; ++i)
      if (elems_of_dimension[i])
        mesh.set_mesh_dimension(i);

#if LIBMESH_DIM < 3
    if (mesh.mesh_dimension() > LIBMESH_DIM)
      {
        libMesh::err << "Cannot open dimension " <<
		        mesh.mesh_dimension() <<
		        " mesh file when configured without " <<
                        mesh.mesh_dimension() << "D support." <<
                        std::endl;
        libmesh_error();
      }
#endif
  }
}

void UCDIO::write_implementation (std::ostream& out_stream)
{
  libmesh_assert (out_stream.good());

  const MeshBase& mesh = MeshOutput<MeshBase>::mesh();

  // UCD doesn't work in 1D
  libmesh_assert_not_equal_to (mesh.mesh_dimension(), 1);
  if(mesh.mesh_dimension() != 3)
    {
      libMesh::err << "Error: Can't write boundary elements for meshes of dimension less than 3"
		   << "Mesh dimension = " << mesh.mesh_dimension()
		   << std::endl;
      libmesh_error();
    }

  // Write header
  this->write_header(out_stream,mesh,mesh.n_elem(),0);

  // Write the node coordinates
  this->write_nodes(out_stream,mesh);

  // Write the elements
  this->write_interior_elems(out_stream,mesh);

  return;
}

void UCDIO::write_header(std::ostream& out_stream, const MeshBase& mesh,
			 dof_id_type n_elems, unsigned int n_vars )
{
  libmesh_assert (out_stream.good());
  // TODO: We used to print out the SVN revision here when we did keyword expansions...
  out_stream << "# For a description of the UCD format see the AVS Developer's guide.\n"
      << "#\n";

  // Write the mesh info
  out_stream << mesh.n_nodes() << " "
      << n_elems  << " "
      << n_vars << " "
      << " 0 0\n";
  return;
}

void UCDIO::write_nodes(std::ostream& out_stream, const MeshBase& mesh)
{
  MeshBase::const_node_iterator       it  = mesh.nodes_begin();
  const MeshBase::const_node_iterator end = mesh.nodes_end();

  unsigned int n=1; // 1-based node number for UCD

  // Write the node coordinates
  for (; it != end; ++it)
    {
      libmesh_assert (out_stream.good());

      out_stream << n++ << "\t";
      (*it)->write_unformatted(out_stream);
    }

  return;
}

void UCDIO::write_interior_elems(std::ostream& out_stream, const MeshBase& mesh)
{
  std::string type[] =
    { "edge",  "edge",  "edge",
      "tri",   "tri",
      "quad",  "quad",  "quad",
      "tet",   "tet",
      "hex",   "hex",   "hex",
      "prism", "prism", "prism",
      "pyramid" };

  MeshBase::const_element_iterator it  = mesh.elements_begin();
  const MeshBase::const_element_iterator end = mesh.elements_end();

  unsigned int e=1; // 1-based element number for UCD

  // Write element information
  for (; it != end; ++it)
    {
      libmesh_assert (out_stream.good());

      // PB: I believe these are the only supported ElemTypes.
      const ElemType etype = (*it)->type();
      if( (etype != TRI3) && (etype != QUAD4) &&
	  (etype != TET4) && (etype != HEX8) &&
          (etype != PRISM6) && (etype != PYRAMID5) )
	{
	  libMesh::err << "Error: Unsupported ElemType for UCDIO."
		       << std::endl;
	  libmesh_error();
	}

      out_stream << e++ << " 0 " << type[etype] << "\t";
      // (*it)->write_ucd_connectivity(out_stream);
      (*it)->write_connectivity(out_stream, UCD);
    }

  return;
}

void UCDIO::write_nodal_data(const std::string& fname,
			     const std::vector<Number>&soln,
			     const std::vector<std::string>& names)
{
  std::ofstream out_stream(fname.c_str());

  const MeshBase& mesh = MeshOutput<MeshBase>::mesh();

  // UCD doesn't work in 1D
  libmesh_assert (mesh.mesh_dimension() != 1);

  // Write header
  this->write_header(out_stream,mesh,mesh.n_elem(),names.size());

  // Write the node coordinates
  this->write_nodes(out_stream,mesh);

  // Write the elements
  this->write_interior_elems(out_stream,mesh);

  // Write the solution
  this->write_soln(out_stream,mesh,names,soln);

  return;
}

void UCDIO::write_soln(std::ostream& out_stream, const MeshBase& mesh,
		       const std::vector<std::string>& names,
		       const std::vector<Number>&soln)
{
  libmesh_assert (out_stream.good());

  // First write out how many variables and how many components per variable
  out_stream << names.size();
  for( unsigned int i = 0; i < names.size(); i++ )
    {
      libmesh_assert (out_stream.good());
      // Each named variable has only 1 component
      out_stream << " 1";
    }
  out_stream << std::endl;

  // Now write out variable names and units. Since we don't store units
  // We just write out dummy.
  for( std::vector<std::string>::const_iterator var = names.begin();
       var != names.end();
       var++)
    {
      libmesh_assert (out_stream.good());
      out_stream << (*var) << ", dummy" << std::endl;
    }

  // Now, for each node, write out the solution variables
  std::size_t nv = names.size();
  for( std::size_t n = 1; // 1-based node number for UCD
       n <= mesh.n_nodes(); n++)
    {
      libmesh_assert (out_stream.good());
      out_stream << n;

      for( std::size_t var = 0; var != nv; var++ )
	{
	  std::size_t idx = nv*(n-1) + var;

	  out_stream << " " << soln[idx];
	}
      out_stream << std::endl;
    }

  return;
}

} // namespace libMesh
<commit_msg>Make UCD_IO compatible with new solution vectors<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

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

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

// C++ includes
#include <fstream>

// Local includes
#include "libmesh/libmesh_config.h"
#include "libmesh/ucd_io.h"
#include "libmesh/mesh_base.h"
#include "libmesh/face_quad4.h"
#include "libmesh/face_tri3.h"
#include "libmesh/cell_tet4.h"
#include "libmesh/cell_hex8.h"
#include "libmesh/cell_prism6.h"

#ifdef LIBMESH_HAVE_GZSTREAM
# include "gzstream.h" // For reading/writing compressed streams
#endif

namespace libMesh
{

// ------------------------------------------------------------
// UCDIO class members
void UCDIO::read (const std::string& file_name)
{
  if (file_name.rfind(".gz") < file_name.size())
    {
#ifdef LIBMESH_HAVE_GZSTREAM

      igzstream in_stream (file_name.c_str());
      this->read_implementation (in_stream);

#else

      libMesh::err << "ERROR:  You must have the zlib.h header "
		    << "files and libraries to read and write "
		    << "compressed streams."
		    << std::endl;
      libmesh_error();

#endif
      return;
    }

  else
    {
      std::ifstream in_stream (file_name.c_str());
      this->read_implementation (in_stream);
      return;
    }
}

void UCDIO::write (const std::string& file_name)
{
  if (file_name.rfind(".gz") < file_name.size())
    {
#ifdef LIBMESH_HAVE_GZSTREAM

      ogzstream out_stream (file_name.c_str());
      this->write_implementation (out_stream);

#else

      libMesh::err << "ERROR:  You must have the zlib.h header "
		    << "files and libraries to read and write "
		    << "compressed streams."
		    << std::endl;
      libmesh_error();

#endif
      return;
    }

  else
    {
      std::ofstream out_stream (file_name.c_str());
      this->write_implementation (out_stream);
      return;
    }
}

void UCDIO::read_implementation (std::istream& in)
{
  // This is a serial-only process for now;
  // the Mesh should be read on processor 0 and
  // broadcast later
  libmesh_assert_equal_to (MeshOutput<MeshBase>::mesh().processor_id(), 0);

  // Check input buffer
  libmesh_assert (in.good());

  MeshBase& mesh = MeshInput<MeshBase>::mesh();

  // Keep track of what kinds of elements this file contains
  elems_of_dimension.clear();
  elems_of_dimension.resize(4, false);

  this->skip_comment_lines (in, '#');

  unsigned int nNodes=0, nElem=0, dummy=0;

  in >> nNodes   // Read the number of nodes from the stream
     >> nElem    // Read the number of elements from the stream
     >> dummy
     >> dummy
     >> dummy;

  // Read the nodal coordinates. Note that UCD format always
  // stores (x,y,z), and in 2D z=0. We don't need to store this,
  // however.  So, we read in x,y,z for each node and make a point
  // in the proper way based on what dimension we're in
  {
    Point xyz;

    for (unsigned int i=0; i<nNodes; i++)
      {
	libmesh_assert (in.good());

	in >> dummy   // Point number
	   >> xyz(0)  // x-coordinate value
	   >> xyz(1)  // y-coordinate value
	   >> xyz(2); // z-coordinate value

	// Build the node
	mesh.add_point (xyz, i);
      }
  }

  // Read the elements from the stream. Notice that the UCD node-numbering
  // scheme is 1-based, and we just created a 0-based scheme above
  // (which is of course what we want). So, when we read in the nodal
  // connectivity for each element we need to take 1 off the value of
  // each node so that we get the right thing.
  {
    unsigned int material_id=0, node=0;
    std::string type;

    for (unsigned int i=0; i<nElem; i++)
      {
	Elem* elem = NULL;

	libmesh_assert (in.good());

	in >> dummy        // Cell number, means nothing to us
	   >> material_id  // doesn't mean anything at present, might later
	   >> type;        // string describing cell type:
	                   // either tri, quad, tet, hex, or prism for the
	                   // obvious cases

	                   // Now read the connectivity.
	if (type == "quad")
	  elem = new Quad4;
	else if (type == "tri")
	  elem = new Tri3;
	else if (type == "hex")
	  elem = new Hex8;
	else if (type == "tet")
	  elem = new Tet4;
	else if (type == "prism")
	  elem = new Prism6;
	else
	  libmesh_error();

	for (unsigned int n=0; n<elem->n_nodes(); n++)
	  {
	    libmesh_assert (in.good());

	    in >> node; // read the current node
	    node -= 1;  // UCD is 1-based, so subtract

	    libmesh_assert_less (node, mesh.n_nodes());

	    elem->set_node(n) =
	      mesh.node_ptr(node); // assign the node
	  }

        elems_of_dimension[elem->dim()] = true;

	// Add the element to the mesh
	elem->set_id(i);
	mesh.add_elem (elem);
      }

    // Set the mesh dimension to the largest encountered for an element
    for (unsigned int i=0; i!=4; ++i)
      if (elems_of_dimension[i])
        mesh.set_mesh_dimension(i);

#if LIBMESH_DIM < 3
    if (mesh.mesh_dimension() > LIBMESH_DIM)
      {
        libMesh::err << "Cannot open dimension " <<
		        mesh.mesh_dimension() <<
		        " mesh file when configured without " <<
                        mesh.mesh_dimension() << "D support." <<
                        std::endl;
        libmesh_error();
      }
#endif
  }
}

void UCDIO::write_implementation (std::ostream& out_stream)
{
  libmesh_assert (out_stream.good());

  const MeshBase& mesh = MeshOutput<MeshBase>::mesh();

  // UCD doesn't work in 1D
  libmesh_assert_not_equal_to (mesh.mesh_dimension(), 1);
  if(mesh.mesh_dimension() != 3)
    {
      libMesh::err << "Error: Can't write boundary elements for meshes of dimension less than 3"
		   << "Mesh dimension = " << mesh.mesh_dimension()
		   << std::endl;
      libmesh_error();
    }

  // Write header
  this->write_header(out_stream,mesh,mesh.n_elem(),0);

  // Write the node coordinates
  this->write_nodes(out_stream,mesh);

  // Write the elements
  this->write_interior_elems(out_stream,mesh);

  return;
}

void UCDIO::write_header(std::ostream& out_stream, const MeshBase& mesh,
			 dof_id_type n_elems, unsigned int n_vars )
{
  libmesh_assert (out_stream.good());
  // TODO: We used to print out the SVN revision here when we did keyword expansions...
  out_stream << "# For a description of the UCD format see the AVS Developer's guide.\n"
      << "#\n";

  // Write the mesh info
  out_stream << mesh.n_nodes() << " "
      << n_elems  << " "
      << n_vars << " "
      << " 0 0\n";
  return;
}

void UCDIO::write_nodes(std::ostream& out_stream, const MeshBase& mesh)
{
  MeshBase::const_node_iterator       it  = mesh.nodes_begin();
  const MeshBase::const_node_iterator end = mesh.nodes_end();

  unsigned int n=1; // 1-based node number for UCD

  // Write the node coordinates
  for (; it != end; ++it)
    {
      libmesh_assert (out_stream.good());

      out_stream << n++ << "\t";
      (*it)->write_unformatted(out_stream);
    }

  return;
}

void UCDIO::write_interior_elems(std::ostream& out_stream, const MeshBase& mesh)
{
  std::string type[] =
    { "edge",  "edge",  "edge",
      "tri",   "tri",
      "quad",  "quad",  "quad",
      "tet",   "tet",
      "hex",   "hex",   "hex",
      "prism", "prism", "prism",
      "pyramid" };

  MeshBase::const_element_iterator it  = mesh.elements_begin();
  const MeshBase::const_element_iterator end = mesh.elements_end();

  unsigned int e=1; // 1-based element number for UCD

  // Write element information
  for (; it != end; ++it)
    {
      libmesh_assert (out_stream.good());

      // PB: I believe these are the only supported ElemTypes.
      const ElemType etype = (*it)->type();
      if( (etype != TRI3) && (etype != QUAD4) &&
	  (etype != TET4) && (etype != HEX8) &&
          (etype != PRISM6) && (etype != PYRAMID5) )
	{
	  libMesh::err << "Error: Unsupported ElemType for UCDIO."
		       << std::endl;
	  libmesh_error();
	}

      out_stream << e++ << " 0 " << type[etype] << "\t";
      // (*it)->write_ucd_connectivity(out_stream);
      (*it)->write_connectivity(out_stream, UCD);
    }

  return;
}

void UCDIO::write_nodal_data(const std::string& fname,
			     const std::vector<Number>&soln,
			     const std::vector<std::string>& names)
{
  const MeshBase& mesh = MeshOutput<MeshBase>::mesh();

  const dof_id_type n_elem = mesh.n_elem();

  // Only processor 0 does the writing
  if (mesh.processor_id())
    return;

  std::ofstream out_stream(fname.c_str());

  // UCD doesn't work in 1D
  libmesh_assert (mesh.mesh_dimension() != 1);

  // Write header
  this->write_header(out_stream,mesh,n_elem,names.size());

  // Write the node coordinates
  this->write_nodes(out_stream,mesh);

  // Write the elements
  this->write_interior_elems(out_stream,mesh);

  // Write the solution
  this->write_soln(out_stream,mesh,names,soln);

  return;
}

void UCDIO::write_soln(std::ostream& out_stream, const MeshBase& mesh,
		       const std::vector<std::string>& names,
		       const std::vector<Number>&soln)
{
  libmesh_assert (out_stream.good());

  // First write out how many variables and how many components per variable
  out_stream << names.size();
  for( unsigned int i = 0; i < names.size(); i++ )
    {
      libmesh_assert (out_stream.good());
      // Each named variable has only 1 component
      out_stream << " 1";
    }
  out_stream << std::endl;

  // Now write out variable names and units. Since we don't store units
  // We just write out dummy.
  for( std::vector<std::string>::const_iterator var = names.begin();
       var != names.end();
       var++)
    {
      libmesh_assert (out_stream.good());
      out_stream << (*var) << ", dummy" << std::endl;
    }

  // Now, for each node, write out the solution variables
  std::size_t nv = names.size();
  for( std::size_t n = 1; // 1-based node number for UCD
       n <= mesh.n_nodes(); n++)
    {
      libmesh_assert (out_stream.good());
      out_stream << n;

      for( std::size_t var = 0; var != nv; var++ )
	{
	  std::size_t idx = nv*(n-1) + var;

	  out_stream << " " << soln[idx];
	}
      out_stream << std::endl;
    }

  return;
}

} // namespace libMesh
<|endoftext|>