<commit_before>/*
 * imageresizer.cpp
 *
 *  Created on: Jul 8, 2016
 *      Author: Jason
 */

#include "common/base.h"
#include "imageresizer.h"
#include <stdexcept>

ImageResizer::ImageResizer()
:m_handle(NULL), m_result(NULL)
{

}

ImageResizer::~ImageResizer()
{

}

void ImageResizer::Create(int target_width, int target_height)
{
	if(eina_lock_new(&m_mutex)==EINA_FALSE)
	{
		throw std::runtime_error("fail to create eina_lock_new");
	}
	if(eina_condition_new(&m_cond, &m_mutex)==EINA_FALSE)
	{
		throw std::runtime_error("fail to create eina_lock_new");
	}

	int ret = image_util_transform_create(&m_handle);
	if(ret != IMAGE_UTIL_ERROR_NONE)
	{
		throw std::runtime_error(std::string("fail to image_util_transform_create: ")+to_string(ret));
	}
	ret = image_util_transform_set_resolution(m_handle, target_width, target_height);
}

void ImageResizer::Destroy()
{
	image_util_transform_destroy(m_handle);
	m_handle = NULL;
	eina_condition_free(&m_cond);
	eina_lock_free(&m_mutex);

}

bool ImageResizer::Resize(media_packet_h packet, media_packet_h* resized_packet)
{
	dlog_print(DLOG_DEBUG, "ImageResizer", "========================original packet===========================");
	print_packet_info(packet);
	int ret = image_util_transform_run(m_handle, packet, ImageResizer::resize_completed_cb, (void*)this);
	dlog_print(DLOG_DEBUG, "ImageResizer", "image_util_transform_run[%d]", ret);
	if(ret != IMAGE_UTIL_ERROR_NONE)
	{
		return false;
	}
	eina_condition_wait(&m_cond);
	*resized_packet = m_result;
	dlog_print(DLOG_DEBUG, "ImageResizer", "========================resized packet=================[%p], [%p]", *resized_packet, m_result);
	print_packet_info(*resized_packet);
	dlog_print(DLOG_DEBUG, "ImageResizer", "image_util_transform_run signaled");
	return true;
}

void ImageResizer::resize_completed(media_packet_h *dst, int error_code)
{
	m_result = *dst;
	dlog_print(DLOG_DEBUG, "ImageResizer", "condition signal dst[%p], error_code[%d]", *dst, error_code);
	eina_condition_signal(&m_cond);
}

void ImageResizer::resize_completed_cb(media_packet_h *dst, int error_code, void *user_data)
{
	dlog_print(DLOG_DEBUG, "ImageResizer", "resize_completed_cb is called [%p]", *dst );
	ImageResizer* resizer = (ImageResizer*)user_data;
	resizer->resize_completed(dst, error_code);
}

void ImageResizer::print_packet_info(media_packet_h packet)
{
	uint64_t	dts = 0;
	media_packet_get_dts(packet, &dts);
	dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_get_dts [%llu]", dts);

	uint64_t	duration = 0;
	media_packet_get_duration(packet, &duration);
	dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_get_duration [%llu]", dts);

	media_format_h fmt = NULL;
	media_format_mimetype_e mimetype;
	int width = 0, height = 0, avg_bps=0, max_bps = 0;
	int ret = media_packet_get_format(packet, &fmt);
	dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_get_format: [%p] [%d]=====", fmt, ret);
	media_format_get_video_info(fmt, &mimetype, &width, &height, &avg_bps, &max_bps);
	dlog_print(DLOG_DEBUG, "ImageResizer", "media_format_get_video_info: vidoe mimetype: %x, w:%d, h:%d, avg_bps:%d, max_bps:%d =====", (int)mimetype, width, height, avg_bps, max_bps);
	media_format_unref(fmt);

	bool codec_config = false;
	media_packet_is_codec_config(packet, &codec_config);
	dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_codec_config [%d]", (int)codec_config);

	bool is_encoded = false;
	media_packet_is_encoded(packet, &is_encoded);
	dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_encoded [%d]", (int)is_encoded);

	bool is_eos = false;
	media_packet_is_end_of_stream(packet, &is_eos);
	dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_end_of_stream [%d]", (int)is_eos);

	bool is_raw = false;
	media_packet_is_raw(packet, &is_raw);
	dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_raw [%d]", (int)is_raw);

	bool is_sync = false;
	media_packet_is_sync_frame(packet, &is_sync);
	dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_sync_frame [%d]", (int)is_sync);

	bool is_video = false;
	media_packet_is_video(packet, &is_video);
	dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_video [%d]", (int)is_video);

}

<commit_msg>fix the problem that image_transform does not copy the eos flag!!<commit_after>/*
 * imageresizer.cpp
 *
 *  Created on: Jul 8, 2016
 *      Author: Jason
 */

#include "common/base.h"
#include "imageresizer.h"
#include <stdexcept>

ImageResizer::ImageResizer()
:m_handle(NULL), m_result(NULL)
{

}

ImageResizer::~ImageResizer()
{

}

void ImageResizer::Create(int target_width, int target_height)
{
	if(eina_lock_new(&m_mutex)==EINA_FALSE)
	{
		throw std::runtime_error("fail to create eina_lock_new");
	}
	if(eina_condition_new(&m_cond, &m_mutex)==EINA_FALSE)
	{
		throw std::runtime_error("fail to create eina_lock_new");
	}

	int ret = image_util_transform_create(&m_handle);
	if(ret != IMAGE_UTIL_ERROR_NONE)
	{
		throw std::runtime_error(std::string("fail to image_util_transform_create: ")+to_string(ret));
	}
	ret = image_util_transform_set_resolution(m_handle, target_width, target_height);
}

void ImageResizer::Destroy()
{
	image_util_transform_destroy(m_handle);
	m_handle = NULL;
	eina_condition_free(&m_cond);
	eina_lock_free(&m_mutex);
}

bool ImageResizer::Resize(media_packet_h packet, media_packet_h* resized_packet)
{
	dlog_print(DLOG_DEBUG, "ImageResizer", "========================original packet===========================");
	print_packet_info(packet);
	bool is_eos = false;
	media_packet_is_end_of_stream(packet, &is_eos);
	int ret = image_util_transform_run(m_handle, packet, ImageResizer::resize_completed_cb, (void*)this);
	dlog_print(DLOG_DEBUG, "ImageResizer", "image_util_transform_run[%d]", ret);
	if(ret != IMAGE_UTIL_ERROR_NONE)
	{
		return false;
	}
	eina_condition_wait(&m_cond);
	*resized_packet = m_result;
	dlog_print(DLOG_DEBUG, "ImageResizer", "========================resized packet=================[%p], [%p]", *resized_packet, m_result);
	if(is_eos)
	{
		media_packet_set_flags(*resized_packet, MEDIA_PACKET_END_OF_STREAM);
	}
	print_packet_info(*resized_packet);
	dlog_print(DLOG_DEBUG, "ImageResizer", "image_util_transform_run signaled");
	return true;
}

void ImageResizer::resize_completed(media_packet_h *dst, int error_code)
{
	m_result = *dst;
	dlog_print(DLOG_DEBUG, "ImageResizer", "condition signal dst[%p], error_code[%d]", *dst, error_code);
	eina_condition_signal(&m_cond);
}

void ImageResizer::resize_completed_cb(media_packet_h *dst, int error_code, void *user_data)
{
	dlog_print(DLOG_DEBUG, "ImageResizer", "resize_completed_cb is called [%p]", *dst );
	ImageResizer* resizer = (ImageResizer*)user_data;
	resizer->resize_completed(dst, error_code);
}

void ImageResizer::print_packet_info(media_packet_h packet)
{
	uint64_t	dts = 0;
	media_packet_get_dts(packet, &dts);
	dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_get_dts [%llu]", dts);

	uint64_t	duration = 0;
	media_packet_get_duration(packet, &duration);
	dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_get_duration [%llu]", dts);

	media_format_h fmt = NULL;
	media_format_mimetype_e mimetype;
	int width = 0, height = 0, avg_bps=0, max_bps = 0;
	int ret = media_packet_get_format(packet, &fmt);
	dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_get_format: [%p] [%d]=====", fmt, ret);
	media_format_get_video_info(fmt, &mimetype, &width, &height, &avg_bps, &max_bps);
	dlog_print(DLOG_DEBUG, "ImageResizer", "media_format_get_video_info: vidoe mimetype: %x, w:%d, h:%d, avg_bps:%d, max_bps:%d =====", (int)mimetype, width, height, avg_bps, max_bps);
	media_format_unref(fmt);

	bool codec_config = false;
	media_packet_is_codec_config(packet, &codec_config);
	dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_codec_config [%d]", (int)codec_config);

	bool is_encoded = false;
	media_packet_is_encoded(packet, &is_encoded);
	dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_encoded [%d]", (int)is_encoded);

	bool is_eos = false;
	media_packet_is_end_of_stream(packet, &is_eos);
	dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_end_of_stream [%d]", (int)is_eos);

	bool is_raw = false;
	media_packet_is_raw(packet, &is_raw);
	dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_raw [%d]", (int)is_raw);

	bool is_sync = false;
	media_packet_is_sync_frame(packet, &is_sync);
	dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_sync_frame [%d]", (int)is_sync);

	bool is_video = false;
	media_packet_is_video(packet, &is_video);
	dlog_print(DLOG_DEBUG, "ImageResizer", "media_packet_is_video [%d]", (int)is_video);

}

<|endoftext|>


<commit_before>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright (C) 2011 - 2016                                                  *
 * Dominik Charousset <dominik.charousset (at) haw-hamburg.de>                *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#include "caf/config.hpp"

#define CAF_SUITE expected
#include "caf/test/unit_test.hpp"

#include "caf/sec.hpp"
#include "caf/expected.hpp"

using namespace std;
using namespace caf;

#define CHECK(x) CAF_CHECK(x);

#define CHECK_EQ(x, y)                                                         \
  CAF_CHECK(x == y);                                                           \
  CAF_CHECK(y == x);

#define CHECK_NEQ(x, y)                                                        \
  CAF_CHECK(x != y);                                                           \
  CAF_CHECK(y != x);

namespace {

using e_int = expected<int>;
using e_str = expected<std::string>;

} // namespace <anonymous>

CAF_TEST(both_engaged_equal) {
  e_int x{42};
  e_int y{42};
  CHECK(x);
  CHECK(y);
  CHECK_EQ(x, y);
  CHECK_EQ(x, 42);
  CHECK_EQ(y, 42);
}

CAF_TEST(both_engaged_not_equal) {
  e_int x{42};
  e_int y{24};
  CHECK(x);
  CHECK(y);
  CHECK_NEQ(x, y);
  CHECK_NEQ(x, sec::unexpected_message);
  CHECK_NEQ(y, sec::unexpected_message);
  CHECK_EQ(x, 42);
  CHECK_EQ(y, 24);
}

CAF_TEST(engaged_plus_not_engaged) {
  e_int x{42};
  e_int y{sec::unexpected_message};
  CHECK(x);
  CHECK(!y);
  CHECK_EQ(x, 42);
  CHECK_EQ(y, sec::unexpected_message);
  CHECK_NEQ(x, sec::unexpected_message);
  CHECK_NEQ(x, y);
  CHECK_NEQ(y, 42);
  CHECK_NEQ(y, sec::unsupported_sys_key);
}

CAF_TEST(both_not_engaged) {
  e_int x{sec::unexpected_message};
  e_int y{sec::unexpected_message};
  CHECK(!x);
  CHECK(!y);
  CHECK_EQ(x, y);
  CHECK_EQ(x, sec::unexpected_message);
  CHECK_EQ(y, sec::unexpected_message);
  CHECK_EQ(x.error(), y.error());
  CHECK_NEQ(x, sec::unsupported_sys_key);
  CHECK_NEQ(y, sec::unsupported_sys_key);
}

CAF_TEST(move_and_copy) {
  e_str x{sec::unexpected_message};
  e_str y{"hello"};
  x = "hello";
  CHECK_NEQ(x, sec::unexpected_message);
  CHECK_EQ(x, "hello");
  CHECK_EQ(x, y);
  y = "world";
  x = std::move(y);
  CHECK_EQ(x, "world");
  e_str z{std::move(x)};
  CHECK_EQ(z, "world");
  e_str z_cpy{z};
  CHECK_EQ(z_cpy, "world");
  CHECK_EQ(z, z_cpy);
  z = e_str{sec::unsupported_sys_key};
  CHECK_NEQ(z, z_cpy);
  CHECK_EQ(z, sec::unsupported_sys_key);
}
<commit_msg>Add test that constructs expected<T> from none_t<commit_after>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright (C) 2011 - 2016                                                  *
 * Dominik Charousset <dominik.charousset (at) haw-hamburg.de>                *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#include "caf/config.hpp"

#define CAF_SUITE expected
#include "caf/test/unit_test.hpp"

#include "caf/sec.hpp"
#include "caf/expected.hpp"

using namespace std;
using namespace caf;

#define CHECK(x) CAF_CHECK(x);

#define CHECK_EQ(x, y)                                                         \
  CAF_CHECK(x == y);                                                           \
  CAF_CHECK(y == x);

#define CHECK_NEQ(x, y)                                                        \
  CAF_CHECK(x != y);                                                           \
  CAF_CHECK(y != x);

namespace {

using e_int = expected<int>;
using e_str = expected<std::string>;

} // namespace <anonymous>

CAF_TEST(both_engaged_equal) {
  e_int x{42};
  e_int y{42};
  CHECK(x);
  CHECK(y);
  CHECK_EQ(x, y);
  CHECK_EQ(x, 42);
  CHECK_EQ(y, 42);
}

CAF_TEST(both_engaged_not_equal) {
  e_int x{42};
  e_int y{24};
  CHECK(x);
  CHECK(y);
  CHECK_NEQ(x, y);
  CHECK_NEQ(x, sec::unexpected_message);
  CHECK_NEQ(y, sec::unexpected_message);
  CHECK_EQ(x, 42);
  CHECK_EQ(y, 24);
}

CAF_TEST(engaged_plus_not_engaged) {
  e_int x{42};
  e_int y{sec::unexpected_message};
  CHECK(x);
  CHECK(!y);
  CHECK_EQ(x, 42);
  CHECK_EQ(y, sec::unexpected_message);
  CHECK_NEQ(x, sec::unexpected_message);
  CHECK_NEQ(x, y);
  CHECK_NEQ(y, 42);
  CHECK_NEQ(y, sec::unsupported_sys_key);
}

CAF_TEST(both_not_engaged) {
  e_int x{sec::unexpected_message};
  e_int y{sec::unexpected_message};
  CHECK(!x);
  CHECK(!y);
  CHECK_EQ(x, y);
  CHECK_EQ(x, sec::unexpected_message);
  CHECK_EQ(y, sec::unexpected_message);
  CHECK_EQ(x.error(), y.error());
  CHECK_NEQ(x, sec::unsupported_sys_key);
  CHECK_NEQ(y, sec::unsupported_sys_key);
}

CAF_TEST(move_and_copy) {
  e_str x{sec::unexpected_message};
  e_str y{"hello"};
  x = "hello";
  CHECK_NEQ(x, sec::unexpected_message);
  CHECK_EQ(x, "hello");
  CHECK_EQ(x, y);
  y = "world";
  x = std::move(y);
  CHECK_EQ(x, "world");
  e_str z{std::move(x)};
  CHECK_EQ(z, "world");
  e_str z_cpy{z};
  CHECK_EQ(z_cpy, "world");
  CHECK_EQ(z, z_cpy);
  z = e_str{sec::unsupported_sys_key};
  CHECK_NEQ(z, z_cpy);
  CHECK_EQ(z, sec::unsupported_sys_key);
}

CAF_TEST(construction_with_none) {
  e_int x{none};
  CHECK(!x);
  CHECK(!x.error());
}
<|endoftext|>


<commit_before>/*  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  Gearmand client and server library.
 *
 *  Copyright (C) 2011-2012 Data Differential, http://datadifferential.com/
 *  Copyright (C) 2008 Brian Aker, Eric Day
 *  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.
 *
 *      * The names of its contributors may not be used to endorse or
 *  promote products derived from this software without specific prior
 *  written permission.
 *
 *  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
 *  OWNER 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.
 *
 */

/**
 * @file
 * @brief Server function definitions
 */

#include <config.h>
#include <libgearman-server/common.h>

#include <cstring>
#include <memory>

#include <libgearman-server/list.h>

/*
 * Public definitions
 */

static gearman_server_function_st* gearman_server_function_create(gearman_server_st *server)
{
  gearman_server_function_st* function= new (std::nothrow) gearman_server_function_st;

  if (function == NULL)
  {
    gearmand_merror("new gearman_server_function_st", gearman_server_function_st, 0);
    return NULL;
  }

  function->worker_count= 0;
  function->job_count= 0;
  function->job_total= 0;
  function->job_running= 0;
  memset(function->max_queue_size, GEARMAN_DEFAULT_MAX_QUEUE_SIZE,
         sizeof(uint32_t) * GEARMAN_JOB_PRIORITY_MAX);
  function->function_name_size= 0;
  gearmand_server_list_add(server, function);
  function->function_name= NULL;
  function->worker_list= NULL;
  memset(function->job_list, 0,
         sizeof(gearman_server_job_st *) * GEARMAN_JOB_PRIORITY_MAX);
  memset(function->job_end, 0,
         sizeof(gearman_server_job_st *) * GEARMAN_JOB_PRIORITY_MAX);

  return function;
}

#ifndef __INTEL_COMPILER
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif

gearman_server_function_st *
gearman_server_function_get(gearman_server_st *server,
                            const char *function_name,
                            size_t function_name_size)
{
  gearman_server_function_st *function;

  for (function= server->function_list; function != NULL;
       function= function->next)
  {
    if (function->function_name_size == function_name_size and
        memcmp(function->function_name, function_name, function_name_size) == 0)
    {
      return function;
    }
  }

  function= gearman_server_function_create(server);
  if (function == NULL)
  {
    return NULL;
  }

  function->function_name= new char[function_name_size +1];
  if (function->function_name == NULL)
  {
    gearmand_merror("new[]", char,  function_name_size +1);
    gearman_server_function_free(server, function);
    return NULL;
  }

  memcpy(function->function_name, function_name, function_name_size);
  function->function_name[function_name_size]= 0;
  function->function_name_size= function_name_size;

  return function;
}

void gearman_server_function_free(gearman_server_st *server, gearman_server_function_st *function)
{
  delete function->function_name;

  gearmand_server_list_free(server, function);

  delete function;
}
<commit_msg>Bug fix for lp:1065852<commit_after>/*  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  Gearmand client and server library.
 *
 *  Copyright (C) 2011-2012 Data Differential, http://datadifferential.com/
 *  Copyright (C) 2008 Brian Aker, Eric Day
 *  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.
 *
 *      * The names of its contributors may not be used to endorse or
 *  promote products derived from this software without specific prior
 *  written permission.
 *
 *  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
 *  OWNER 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.
 *
 */

/**
 * @file
 * @brief Server function definitions
 */

#include <config.h>
#include <libgearman-server/common.h>

#include <cstring>
#include <memory>

#include <libgearman-server/list.h>

/*
 * Public definitions
 */

static gearman_server_function_st* gearman_server_function_create(gearman_server_st *server)
{
  gearman_server_function_st* function= new (std::nothrow) gearman_server_function_st;

  if (function == NULL)
  {
    gearmand_merror("new gearman_server_function_st", gearman_server_function_st, 0);
    return NULL;
  }

  function->worker_count= 0;
  function->job_count= 0;
  function->job_total= 0;
  function->job_running= 0;
  memset(function->max_queue_size, GEARMAN_DEFAULT_MAX_QUEUE_SIZE,
         sizeof(uint32_t) * GEARMAN_JOB_PRIORITY_MAX);
  function->function_name_size= 0;
  gearmand_server_list_add(server, function);
  function->function_name= NULL;
  function->worker_list= NULL;
  memset(function->job_list, 0,
         sizeof(gearman_server_job_st *) * GEARMAN_JOB_PRIORITY_MAX);
  memset(function->job_end, 0,
         sizeof(gearman_server_job_st *) * GEARMAN_JOB_PRIORITY_MAX);

  return function;
}

#ifndef __INTEL_COMPILER
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif

gearman_server_function_st *
gearman_server_function_get(gearman_server_st *server,
                            const char *function_name,
                            size_t function_name_size)
{
  gearman_server_function_st *function;

  for (function= server->function_list; function != NULL;
       function= function->next)
  {
    if (function->function_name_size == function_name_size and
        memcmp(function->function_name, function_name, function_name_size) == 0)
    {
      return function;
    }
  }

  function= gearman_server_function_create(server);
  if (function == NULL)
  {
    return NULL;
  }

  function->function_name= new char[function_name_size +1];
  if (function->function_name == NULL)
  {
    gearmand_merror("new[]", char,  function_name_size +1);
    gearman_server_function_free(server, function);
    return NULL;
  }

  memcpy(function->function_name, function_name, function_name_size);
  function->function_name[function_name_size]= 0;
  function->function_name_size= function_name_size;

  return function;
}

void gearman_server_function_free(gearman_server_st *server, gearman_server_function_st *function)
{
  delete [] function->function_name;

  gearmand_server_list_free(server, function);

  delete function;
}
<|endoftext|>


<commit_before>#include "inc/cxx/json.hpp"
#include "test/catch.hpp"
#include <type_traits>

TEST_CASE("can create cxx::json from std::initializer_list<cxx::json>")
{
  static_assert(std::is_assignable_v<cxx::json, std::initializer_list<cxx::json>>);
  cxx::json json;
  REQUIRE(cxx::holds_alternative<cxx::document>(json));

  json = {42, true, cxx::null, 3.14};
  REQUIRE(cxx::holds_alternative<cxx::array>(json));
  REQUIRE(json == cxx::array({42, true, cxx::null, 3.14}));
  REQUIRE(std::size(json) == 4);
}

TEST_CASE("can create cxx::json from std::initializer_list<cxx::document::value_type>")
{
  using namespace cxx::literals;
  static_assert(std::is_assignable_v<cxx::json, std::initializer_list<cxx::document::value_type>>);
  cxx::json json = 42;
  REQUIRE(cxx::holds_alternative<std::int64_t>(json));
  json = {
      // clang-format off
      {"lorem"_key, 42},
      {"ipsum"_key, "dolor"},
      {"sit"_key, cxx::null},
      {"amet"_key, 3.14},
      {"consectetur"_key, true}
      // clang-format on
  };
  REQUIRE(cxx::holds_alternative<cxx::document>(json));
  cxx::document const document = {
      // clang-format off
      {"lorem", 42},
      {"ipsum", "dolor"},
      {"sit", cxx::null},
      {"amet", 3.14},
      {"consectetur", true}
      // clang-format on
  };

  REQUIRE(std::size(json) == std::size(document));
  REQUIRE(json == document);
}
<commit_msg>assignment<commit_after>#include "inc/cxx/json.hpp"
#include "test/catch.hpp"
#include <type_traits>

TEST_CASE("cxx::json is copy assignable")
{
  static_assert(std::is_copy_assignable_v<cxx::json>);
  cxx::json const orig = 42;
  cxx::json json;
  REQUIRE_FALSE(cxx::holds_alternative<std::int64_t>(json));
  REQUIRE(json != orig);

  json = orig;
  REQUIRE(cxx::holds_alternative<std::int64_t>(json));
  REQUIRE(json == orig);
}

TEST_CASE("cxx::json is nothrow move assignable")
{
  static_assert(std::is_nothrow_move_assignable_v<cxx::json>);
  cxx::json orig = 42;
  cxx::json json;
  REQUIRE_FALSE(cxx::holds_alternative<std::int64_t>(json));
  REQUIRE(json != orig);

  json = std::move(orig);
  REQUIRE(cxx::holds_alternative<std::int64_t>(json));
  REQUIRE(json == 42);
}

TEST_CASE("can assign std::initializer_list<cxx::json> to cxx::json")
{
  static_assert(std::is_assignable_v<cxx::json, std::initializer_list<cxx::json>>);
  cxx::json json;
  REQUIRE(cxx::holds_alternative<cxx::document>(json));

  json = {42, true, cxx::null, 3.14};
  REQUIRE(cxx::holds_alternative<cxx::array>(json));
  REQUIRE(json == cxx::array({42, true, cxx::null, 3.14}));
  REQUIRE(std::size(json) == 4);
}

TEST_CASE("can assign std::initializer_list<cxx::document::value_type> to cxx::json")
{
  using namespace cxx::literals;
  static_assert(std::is_assignable_v<cxx::json, std::initializer_list<cxx::document::value_type>>);
  cxx::json json = 42;
  REQUIRE(cxx::holds_alternative<std::int64_t>(json));
  json = {
      // clang-format off
      {"lorem"_key, 42},
      {"ipsum"_key, "dolor"},
      {"sit"_key, cxx::null},
      {"amet"_key, 3.14},
      {"consectetur"_key, true}
      // clang-format on
  };
  REQUIRE(cxx::holds_alternative<cxx::document>(json));
  cxx::document const document = {
      // clang-format off
      {"lorem", 42},
      {"ipsum", "dolor"},
      {"sit", cxx::null},
      {"amet", 3.14},
      {"consectetur", true}
      // clang-format on
  };

  REQUIRE(std::size(json) == std::size(document));
  REQUIRE(json == document);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <functional>
#include <neu/activate_func/rectifier.hpp>
#include <neu/activate_func/sigmoid.hpp>
#include <neu/layer.hpp>
#include <neu/full_connected_layer.hpp>
#include <neu/activate_layer.hpp>
#include <neu/learning_rate_gen/fixed_learning_rate_gen.hpp>

int main() {
	std::cout << "hello world" << std::endl;

	/*
	auto fc1 = neu::make_full_connected_layer(1,1,1,
		neu::to_gpu_vector(neu::cpu_vector{10.f}),
		neu::to_gpu_vector(neu::cpu_vector{1.f}),
		neu::fixed_learning_rate_gen(0.01));
	auto fc1_layer = static_cast<neu::layer>(std::ref(fc1));
	*/
	auto ac1_layer = static_cast<neu::layer>(neu::make_activate_layer(1, 1, 1,
		neu::sigmoid()));

	ac1_layer.forward(neu::to_gpu_vector(neu::cpu_vector{10.f}));

	//std::cout << fc1_layer.get_next_input()[0] << std::endl;
	std::cout << ac1_layer.get_next_input()[0] << std::endl;
}
<commit_msg>rename test/layer/layer.cpp<commit_after><|endoftext|>


<commit_before>// $Id$

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

// This library is free software; you can redistribute 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

// library configuration
#include "libmesh_config.h"

// C++ includes
#include <algorithm> // for std::min
#include <map>       // for std::multimap
#include <sstream>   // for std::ostringstream

// Local includes
#include "boundary_info.h"
#include "elem.h"
#include "mesh_base.h"
#include "parallel.h"
#include "partitioner.h"
#include "point_locator_base.h"
#include "threads.h"

namespace libMesh
{

// ------------------------------------------------------------
// MeshBase class member functions
MeshBase::MeshBase (unsigned int d) :
  boundary_info  (new BoundaryInfo(*this)),
  _n_parts       (1),
  _dim           (d),
  _is_prepared   (false),
  _point_locator (NULL),
  _partitioner   (NULL)
{
  libmesh_assert (LIBMESH_DIM <= 3);
  libmesh_assert (LIBMESH_DIM >= _dim);
  libmesh_assert (libMesh::initialized());
}

MeshBase::MeshBase (const MeshBase& other_mesh) :
  boundary_info  (new BoundaryInfo(*this)), // no copy constructor defined for BoundaryInfo?
  _n_parts       (other_mesh._n_parts),
  _dim           (other_mesh._dim),
  _is_prepared   (other_mesh._is_prepared),
  _point_locator (NULL),
  _partitioner   (other_mesh._partitioner->clone())
{
}

MeshBase::~MeshBase()
{
  this->clear();

  libmesh_assert (!libMesh::closed());
}

void MeshBase::prepare_for_use (const bool skip_renumber_nodes_and_elements)
{
  // Renumber the nodes and elements so that they in contiguous
  // blocks.  By default, skip_renumber_nodes_and_elements is false,
  // however we may skip this step by passing
  // skip_renumber_nodes_and_elements==true to this function.
  //
  // Instances where you if prepare_for_use() should not renumber the nodes
  // and elements include reading in e.g. an xda/r or gmv file. In
  // this case, the ordering of the nodes may depend on an accompanying
  // solution, and the node ordering cannot be changed.
  if(!skip_renumber_nodes_and_elements)
    this->renumber_nodes_and_elements();

  // Let all the elements find their neighbors
  this->find_neighbors();

  // Partition the mesh.
  this->partition();

  // If we're using ParallelMesh, we'll want it parallelized.
  this->delete_remote_elements();

  if(!skip_renumber_nodes_and_elements)
    this->renumber_nodes_and_elements();

  // Reset our PointLocator.  This needs to happen any time the elements
  // in the underlying elements in the mesh have changed, so we do it here.
  this->clear_point_locator();

  // The mesh is now prepared for use.
  _is_prepared = true;
}

void MeshBase::clear ()
{
  // Reset the number of partitions
  _n_parts = 1;

  // Reset the _is_prepared flag
  _is_prepared = false;

  // Clear boundary information
  this->boundary_info->clear();

  // Clear our point locator.
  this->clear_point_locator();
}

unsigned int MeshBase::n_subdomains() const
{
  // This requires an inspection on every processor
  parallel_only();

  const_element_iterator       el  = this->active_elements_begin();
  const const_element_iterator end = this->active_elements_end();

  std::set<unsigned int> subdomain_ids;

  for (; el!=end; ++el)
    subdomain_ids.insert((*el)->subdomain_id());

  // Some subdomains may only live on other processors
  Parallel::set_union(subdomain_ids, 0);

  unsigned int n_sbd_ids = subdomain_ids.size();
  Parallel::broadcast(n_sbd_ids);

  return n_sbd_ids;
}

unsigned int MeshBase::n_nodes_on_proc (const unsigned int proc_id) const
{
  // We're either counting a processor's nodes or unpartitioned
  // nodes
  libmesh_assert (proc_id < libMesh::n_processors() ||
	  proc_id == DofObject::invalid_processor_id);

  return static_cast<unsigned int>(std::distance (this->pid_nodes_begin(proc_id),
						  this->pid_nodes_end  (proc_id)));
}

unsigned int MeshBase::n_elem_on_proc (const unsigned int proc_id) const
{
  // We're either counting a processor's elements or unpartitioned
  // elements
  libmesh_assert (proc_id < libMesh::n_processors() ||
	  proc_id == DofObject::invalid_processor_id);

  return static_cast<unsigned int>(std::distance (this->pid_elements_begin(proc_id),
						  this->pid_elements_end  (proc_id)));
}

unsigned int MeshBase::n_active_elem_on_proc (const unsigned int proc_id) const
{
  libmesh_assert (proc_id < libMesh::n_processors());
  return static_cast<unsigned int>(std::distance (this->active_pid_elements_begin(proc_id),
						  this->active_pid_elements_end  (proc_id)));
}

unsigned int MeshBase::n_sub_elem () const
{
  unsigned int ne=0;

  const_element_iterator       el  = this->elements_begin();
  const const_element_iterator end = this->elements_end();

  for (; el!=end; ++el)
    ne += (*el)->n_sub_elem();

  return ne;
}

unsigned int MeshBase::n_active_sub_elem () const
{
  unsigned int ne=0;

  const_element_iterator       el  = this->active_elements_begin();
  const const_element_iterator end = this->active_elements_end();

  for (; el!=end; ++el)
    ne += (*el)->n_sub_elem();

  return ne;
}

std::string MeshBase::get_info() const
{
  std::ostringstream out;

  out << " Mesh Information:"                                  << '\n'
      << "  mesh_dimension()="    << this->mesh_dimension()    << '\n'
      << "  spatial_dimension()=" << this->spatial_dimension() << '\n'
      << "  n_nodes()="           << this->n_nodes()           << '\n'
      << "    n_local_nodes()="   << this->n_local_nodes()     << '\n'
      << "  n_elem()="            << this->n_elem()            << '\n'
      << "    n_local_elem()="    << this->n_local_elem()      << '\n'
#ifdef LIBMESH_ENABLE_AMR
      << "    n_active_elem()="   << this->n_active_elem()     << '\n'
#endif
      << "  n_subdomains()="      << this->n_subdomains()      << '\n'
      << "  n_processors()="      << this->n_processors()      << '\n'
      << "  processor_id()="      << this->processor_id()      << '\n';

  return out.str();
}

void MeshBase::print_info(std::ostream& os) const
{
  os << this->get_info()
     << std::endl;
}

std::ostream& operator << (std::ostream& os, const MeshBase& m)
{
  m.print_info(os);
  return os;
}

void MeshBase::partition (const unsigned int n_parts)
{
  if (partitioner().get()) // "NULL" means don't partition
    partitioner()->partition (*this, n_parts);
}

unsigned int MeshBase::recalculate_n_partitions()
{
  const_element_iterator       el  = this->active_elements_begin();
  const const_element_iterator end = this->active_elements_end();

  unsigned int max_proc_id=0;

  for (; el!=end; ++el)
    max_proc_id = std::max(max_proc_id, static_cast<unsigned int>((*el)->processor_id()));

  // The number of partitions is one more than the max processor ID.
  _n_parts = max_proc_id+1;

  return _n_parts;
}

const PointLocatorBase & MeshBase::point_locator () const
{
  if (_point_locator.get() == NULL)
    {
      // PointLocator construction may not be safe within threads
      libmesh_assert(!Threads::in_threads);

      _point_locator.reset (PointLocatorBase::build(TREE, *this).release());
    }

  return *_point_locator;
}

void MeshBase::clear_point_locator ()
{
  _point_locator.reset(NULL);
}

} // namespace libMesh

<commit_msg>Copy associated BoundaryInfo when copying any Mesh<commit_after>// $Id$

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

// This library is free software; you can redistribute 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

// library configuration
#include "libmesh_config.h"

// C++ includes
#include <algorithm> // for std::min
#include <map>       // for std::multimap
#include <sstream>   // for std::ostringstream

// Local includes
#include "boundary_info.h"
#include "elem.h"
#include "mesh_base.h"
#include "parallel.h"
#include "partitioner.h"
#include "point_locator_base.h"
#include "threads.h"

namespace libMesh
{

// ------------------------------------------------------------
// MeshBase class member functions
MeshBase::MeshBase (unsigned int d) :
  boundary_info  (new BoundaryInfo(*this)),
  _n_parts       (1),
  _dim           (d),
  _is_prepared   (false),
  _point_locator (NULL),
  _partitioner   (NULL)
{
  libmesh_assert (LIBMESH_DIM <= 3);
  libmesh_assert (LIBMESH_DIM >= _dim);
  libmesh_assert (libMesh::initialized());
}

MeshBase::MeshBase (const MeshBase& other_mesh) :
  boundary_info  (new BoundaryInfo(*this)),
  _n_parts       (other_mesh._n_parts),
  _dim           (other_mesh._dim),
  _is_prepared   (other_mesh._is_prepared),
  _point_locator (NULL),
  _partitioner   (other_mesh._partitioner->clone())
{
  *boundary_info = *other_mesh.boundary_info;
}

MeshBase::~MeshBase()
{
  this->clear();

  libmesh_assert (!libMesh::closed());
}

void MeshBase::prepare_for_use (const bool skip_renumber_nodes_and_elements)
{
  // Renumber the nodes and elements so that they in contiguous
  // blocks.  By default, skip_renumber_nodes_and_elements is false,
  // however we may skip this step by passing
  // skip_renumber_nodes_and_elements==true to this function.
  //
  // Instances where you if prepare_for_use() should not renumber the nodes
  // and elements include reading in e.g. an xda/r or gmv file. In
  // this case, the ordering of the nodes may depend on an accompanying
  // solution, and the node ordering cannot be changed.
  if(!skip_renumber_nodes_and_elements)
    this->renumber_nodes_and_elements();

  // Let all the elements find their neighbors
  this->find_neighbors();

  // Partition the mesh.
  this->partition();

  // If we're using ParallelMesh, we'll want it parallelized.
  this->delete_remote_elements();

  if(!skip_renumber_nodes_and_elements)
    this->renumber_nodes_and_elements();

  // Reset our PointLocator.  This needs to happen any time the elements
  // in the underlying elements in the mesh have changed, so we do it here.
  this->clear_point_locator();

  // The mesh is now prepared for use.
  _is_prepared = true;
}

void MeshBase::clear ()
{
  // Reset the number of partitions
  _n_parts = 1;

  // Reset the _is_prepared flag
  _is_prepared = false;

  // Clear boundary information
  this->boundary_info->clear();

  // Clear our point locator.
  this->clear_point_locator();
}

unsigned int MeshBase::n_subdomains() const
{
  // This requires an inspection on every processor
  parallel_only();

  const_element_iterator       el  = this->active_elements_begin();
  const const_element_iterator end = this->active_elements_end();

  std::set<unsigned int> subdomain_ids;

  for (; el!=end; ++el)
    subdomain_ids.insert((*el)->subdomain_id());

  // Some subdomains may only live on other processors
  Parallel::set_union(subdomain_ids, 0);

  unsigned int n_sbd_ids = subdomain_ids.size();
  Parallel::broadcast(n_sbd_ids);

  return n_sbd_ids;
}

unsigned int MeshBase::n_nodes_on_proc (const unsigned int proc_id) const
{
  // We're either counting a processor's nodes or unpartitioned
  // nodes
  libmesh_assert (proc_id < libMesh::n_processors() ||
	  proc_id == DofObject::invalid_processor_id);

  return static_cast<unsigned int>(std::distance (this->pid_nodes_begin(proc_id),
						  this->pid_nodes_end  (proc_id)));
}

unsigned int MeshBase::n_elem_on_proc (const unsigned int proc_id) const
{
  // We're either counting a processor's elements or unpartitioned
  // elements
  libmesh_assert (proc_id < libMesh::n_processors() ||
	  proc_id == DofObject::invalid_processor_id);

  return static_cast<unsigned int>(std::distance (this->pid_elements_begin(proc_id),
						  this->pid_elements_end  (proc_id)));
}

unsigned int MeshBase::n_active_elem_on_proc (const unsigned int proc_id) const
{
  libmesh_assert (proc_id < libMesh::n_processors());
  return static_cast<unsigned int>(std::distance (this->active_pid_elements_begin(proc_id),
						  this->active_pid_elements_end  (proc_id)));
}

unsigned int MeshBase::n_sub_elem () const
{
  unsigned int ne=0;

  const_element_iterator       el  = this->elements_begin();
  const const_element_iterator end = this->elements_end();

  for (; el!=end; ++el)
    ne += (*el)->n_sub_elem();

  return ne;
}

unsigned int MeshBase::n_active_sub_elem () const
{
  unsigned int ne=0;

  const_element_iterator       el  = this->active_elements_begin();
  const const_element_iterator end = this->active_elements_end();

  for (; el!=end; ++el)
    ne += (*el)->n_sub_elem();

  return ne;
}

std::string MeshBase::get_info() const
{
  std::ostringstream out;

  out << " Mesh Information:"                                  << '\n'
      << "  mesh_dimension()="    << this->mesh_dimension()    << '\n'
      << "  spatial_dimension()=" << this->spatial_dimension() << '\n'
      << "  n_nodes()="           << this->n_nodes()           << '\n'
      << "    n_local_nodes()="   << this->n_local_nodes()     << '\n'
      << "  n_elem()="            << this->n_elem()            << '\n'
      << "    n_local_elem()="    << this->n_local_elem()      << '\n'
#ifdef LIBMESH_ENABLE_AMR
      << "    n_active_elem()="   << this->n_active_elem()     << '\n'
#endif
      << "  n_subdomains()="      << this->n_subdomains()      << '\n'
      << "  n_processors()="      << this->n_processors()      << '\n'
      << "  processor_id()="      << this->processor_id()      << '\n';

  return out.str();
}

void MeshBase::print_info(std::ostream& os) const
{
  os << this->get_info()
     << std::endl;
}

std::ostream& operator << (std::ostream& os, const MeshBase& m)
{
  m.print_info(os);
  return os;
}

void MeshBase::partition (const unsigned int n_parts)
{
  if (partitioner().get()) // "NULL" means don't partition
    partitioner()->partition (*this, n_parts);
}

unsigned int MeshBase::recalculate_n_partitions()
{
  const_element_iterator       el  = this->active_elements_begin();
  const const_element_iterator end = this->active_elements_end();

  unsigned int max_proc_id=0;

  for (; el!=end; ++el)
    max_proc_id = std::max(max_proc_id, static_cast<unsigned int>((*el)->processor_id()));

  // The number of partitions is one more than the max processor ID.
  _n_parts = max_proc_id+1;

  return _n_parts;
}

const PointLocatorBase & MeshBase::point_locator () const
{
  if (_point_locator.get() == NULL)
    {
      // PointLocator construction may not be safe within threads
      libmesh_assert(!Threads::in_threads);

      _point_locator.reset (PointLocatorBase::build(TREE, *this).release());
    }

  return *_point_locator;
}

void MeshBase::clear_point_locator ()
{
  _point_locator.reset(NULL);
}

} // namespace libMesh

<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <array>
#include <vector>
#include <set>
#include <map>
#include <random>
#include <chrono>
#include <functional>
#include <algorithm>

#include <cmath>

#define NF 16
#define SPLIT 20

using Entry = std::array<double, NF>;
using IntPair = std::pair<int, int>;

struct CompareSecond: std::binary_function<IntPair, IntPair, bool>
{
    bool operator()(const IntPair& a, const IntPair& b)
    {
        return a.second < b.second;
    }
};

int main(int argc, char** argv)
{
    // smoothing factor
    const double alpha = 1.0;
    // decision rule
    const int decision = 1;

    if (argc < 2)
        return 1;

    // preparing data
    int total = 0, correct = 0, totalClassified = 0;
    std::map<std::string, std::vector<Entry> > data;
    std::map<std::string, int> n;
    std::map<std::string, double> priors;
    std::map<std::string, std::vector<double> > multinomialLikelihoods;
    std::map<std::string, int> multinomialSums;
    std::map<std::string, Entry > sumX;
    std::map<std::string, std::vector<double> > means;
    std::map<std::string, std::vector<double> > variances;

    auto classify = [&](const std::string& label, const Entry& entry)
    {
        std::string predlabel;
        double maxlikelihood = 0.0;
        double denom = 0.0;
        std::vector<double> probs;
        for (auto it = priors.begin(); it != priors.end(); it++)
        {
            double numer = priors[it->first];
            const auto& firstMultinomialLikelihood = multinomialLikelihoods[it->first];
            const auto& firstMean = means[it->first];
            const auto& firstVariance = variances[it->first];
            for (int j = 0; j < NF; j++)
                switch (decision)
                {
                    case 2:
                        // Multinomial
                        if (entry[j])
                            numer *= pow(firstMultinomialLikelihood[j], entry[j]);
                        break;

                    case 3:
                        // Bernoulli
                        numer *= pow(firstMean[j], entry[j]) * pow(1.0 - firstMean[j], 1.0 - entry[j]);
                        break;

                    default:
                        // Gaussian
                        numer *= 1 / sqrt(2 * M_PI * firstVariance[j]) * exp((-1 * (entry[j] - firstMean[j]) * (entry[j] -firstMean[j])) / (2 * firstVariance[j]));
                        break;
                }

            if (numer > maxlikelihood)
            {
                maxlikelihood = numer;
                predlabel = it->first;
            }
            denom += numer;
            probs.push_back(numer);
        }

        std::cout << predlabel << "\t" << std::setw(1) << std::setprecision(3) << maxlikelihood/denom << "\t";
        if ("" == label)
            std::cout << "<no label>" << std::endl;
        else if (predlabel == label)
        {
            std::cout << "correct" << std::endl;
            correct++;
        }
        else
            std::cout << "incorrect" << std::endl;

        totalClassified++;
    };

    auto readFromFile = [&](const char* filename, bool isClassification)
    {
        std::ifstream file(argv[1]);
        if (!file.is_open())
            return 1;

        while (!file.eof())
        {
            std::string line;
            std::getline(file, line);
            if ("" == line)
                continue;
            std::istringstream linein(std::move(line));
            std::string label;
            std::getline(linein, label, ',');
            Entry entry;
            auto setField = [&entry, &label, &sumX, &multinomialSums, isClassification](int i, const std::string& field)
            {
                switch (field[0])
                {
                    case 'y':
                        entry[i] = 1.0;
                        break;

                    case 'n':
                        entry[i] = 0.0;
                        break;

                    case '?':
                        entry[i] = 0.5;
                        break;
                }
                if (!isClassification)
                {
                    sumX[label][i] += entry[i];
                    multinomialSums[label] += entry[i];
                }
            };
            for (int i = 0; i < NF; i++)
            {
                std::string field;
                std::getline(linein, field, ',');
                setField(i, field);
            }
            std::string field;
            std::getline(linein, field);
            setField(NF - 1, field);
            if (!isClassification)
            {
                data[label].push_back(std::move(entry));
                n[label]++;
                total++;
            }
            else
                classify(label, entry);
        }
    };

    readFromFile(argv[1], false);

    for (auto it = sumX.begin(); it != sumX.end(); it++)
    {
        priors[it->first] = (double)n[it->first] / total;

        std::cout << "Class " << it->first << ", prior: " << std::setw(1) << std::setprecision(3) << priors[it->first] << std::endl;
        std::cout << "feature\tmean\tvar\tstddev\tmnl" << std::endl;

        // calculate means
        std::vector<double> featureMeans(NF);
        for (int i = 0; i < NF; i++)
            featureMeans[i] = sumX[it->first][i] / n[it->first];

        // calculate variances
        std::vector<double> featureVariances(NF);
        const auto& firstData = data[it->first];
        for (int i = 0; i < firstData.size(); i++)
            for (int j = 0; j < NF; j++)
                featureVariances[j] += (firstData[i][j] - featureMeans[j]) * (firstData[i][j] - featureMeans[j]);
        for (int i = 0; i < NF; i++)
            featureVariances[i] /= firstData.size();

        const auto& firstSumX = sumX[it->first];
        auto firstMultinomialSum = multinomialSums[it->first];
        auto& firstMultinomialLikelihood = multinomialLikelihoods[it->first];
        // calculate multinomial likelihoods
        for (int i = 0; i < NF; i++)
        {
            double mnl = (firstSumX[i] + alpha) / (firstMultinomialSum + (alpha * featureMeans.size()));
            firstMultinomialLikelihood.push_back(mnl);
        }

        for (unsigned int i = 0; i < NF; i++)
            printf("%i\t%2.3f\t%2.3f\t%2.3f\t%2.3f\n",i+1,featureMeans[i],featureVariances[i],sqrt(featureVariances[i]),firstMultinomialLikelihood[i]);

        means[it->first] = std::move(featureMeans);
        variances[it->first] = std::move(featureVariances);
    }

    // classify
    std::cout << "Classifying:" << std::endl;
    std::cout << "class\tprob\tresult" << std::endl;

    readFromFile(argv[2], true);
    printf("Accuracy: %3.2f %% (%i/%i)\n", 100.0 * correct / totalClassified, correct, totalClassified);

    return 0;
}
<commit_msg>fixed some warnings enabled by `-Wall`<commit_after>#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <array>
#include <vector>
#include <set>
#include <map>
#include <random>
#include <chrono>
#include <functional>
#include <algorithm>

#include <cmath>

#define NF 16
#define SPLIT 20

using Entry = std::array<double, NF>;
using IntPair = std::pair<int, int>;

struct CompareSecond: std::binary_function<IntPair, IntPair, bool>
{
    bool operator()(const IntPair& a, const IntPair& b)
    {
        return a.second < b.second;
    }
};

int main(int argc, char** argv)
{
    // smoothing factor
    const double alpha = 1.0;
    // decision rule
    const int decision = 1;

    if (argc < 2)
        return 1;

    // preparing data
    int total = 0, correct = 0, totalClassified = 0;
    std::map<std::string, std::vector<Entry> > data;
    std::map<std::string, int> n;
    std::map<std::string, double> priors;
    std::map<std::string, std::vector<double> > multinomialLikelihoods;
    std::map<std::string, int> multinomialSums;
    std::map<std::string, Entry > sumX;
    std::map<std::string, std::vector<double> > means;
    std::map<std::string, std::vector<double> > variances;

    auto classify = [&](const std::string& label, const Entry& entry)
    {
        std::string predlabel;
        double maxlikelihood = 0.0;
        double denom = 0.0;
        std::vector<double> probs;
        for (auto it = priors.begin(); it != priors.end(); it++)
        {
            double numer = priors[it->first];
            const auto& firstMultinomialLikelihood = multinomialLikelihoods[it->first];
            const auto& firstMean = means[it->first];
            const auto& firstVariance = variances[it->first];
            for (int j = 0; j < NF; j++)
                switch (decision)
                {
                    case 2:
                        // Multinomial
                        if (entry[j])
                            numer *= pow(firstMultinomialLikelihood[j], entry[j]);
                        break;

                    case 3:
                        // Bernoulli
                        numer *= pow(firstMean[j], entry[j]) * pow(1.0 - firstMean[j], 1.0 - entry[j]);
                        break;

                    default:
                        // Gaussian
                        numer *= 1 / sqrt(2 * M_PI * firstVariance[j]) * exp((-1 * (entry[j] - firstMean[j]) * (entry[j] -firstMean[j])) / (2 * firstVariance[j]));
                        break;
                }

            if (numer > maxlikelihood)
            {
                maxlikelihood = numer;
                predlabel = it->first;
            }
            denom += numer;
            probs.push_back(numer);
        }

        std::cout << predlabel << "\t" << std::setw(1) << std::setprecision(3) << maxlikelihood/denom << "\t";
        if ("" == label)
            std::cout << "<no label>" << std::endl;
        else if (predlabel == label)
        {
            std::cout << "correct" << std::endl;
            correct++;
        }
        else
            std::cout << "incorrect" << std::endl;

        totalClassified++;
    };

    auto readFromFile = [&](const char* filename, bool isClassification)
    {
        std::ifstream file(argv[1]);
        if (!file.is_open())
            return 1;

        while (!file.eof())
        {
            std::string line;
            std::getline(file, line);
            if ("" == line)
                continue;
            std::istringstream linein(std::move(line));
            std::string label;
            std::getline(linein, label, ',');
            Entry entry;
            auto setField = [&entry, &label, &sumX, &multinomialSums, isClassification](int i, const std::string& field)
            {
                switch (field[0])
                {
                    case 'y':
                        entry[i] = 1.0;
                        break;

                    case 'n':
                        entry[i] = 0.0;
                        break;

                    case '?':
                        entry[i] = 0.5;
                        break;
                }
                if (!isClassification)
                {
                    sumX[label][i] += entry[i];
                    multinomialSums[label] += entry[i];
                }
            };
            for (int i = 0; i < NF; i++)
            {
                std::string field;
                std::getline(linein, field, ',');
                setField(i, field);
            }
            std::string field;
            std::getline(linein, field);
            setField(NF - 1, field);
            if (!isClassification)
            {
                data[label].push_back(std::move(entry));
                n[label]++;
                total++;
            }
            else
                classify(label, entry);
        }

        return 0;
    };

    int errcode = readFromFile(argv[1], false);
    if (errcode)
        return errcode;

    for (auto it = sumX.begin(); it != sumX.end(); it++)
    {
        priors[it->first] = (double)n[it->first] / total;

        std::cout << "Class " << it->first << ", prior: " << std::setw(1) << std::setprecision(3) << priors[it->first] << std::endl;
        std::cout << "feature\tmean\tvar\tstddev\tmnl" << std::endl;

        // calculate means
        std::vector<double> featureMeans(NF);
        for (int i = 0; i < NF; i++)
            featureMeans[i] = sumX[it->first][i] / n[it->first];

        // calculate variances
        std::vector<double> featureVariances(NF);
        const auto& firstData = data[it->first];
        for (int i = 0; i < (int)firstData.size(); i++)
            for (int j = 0; j < NF; j++)
                featureVariances[j] += (firstData[i][j] - featureMeans[j]) * (firstData[i][j] - featureMeans[j]);
        for (int i = 0; i < NF; i++)
            featureVariances[i] /= firstData.size();

        const auto& firstSumX = sumX[it->first];
        auto firstMultinomialSum = multinomialSums[it->first];
        auto& firstMultinomialLikelihood = multinomialLikelihoods[it->first];
        // calculate multinomial likelihoods
        for (int i = 0; i < NF; i++)
        {
            double mnl = (firstSumX[i] + alpha) / (firstMultinomialSum + (alpha * featureMeans.size()));
            firstMultinomialLikelihood.push_back(mnl);
        }

        for (unsigned int i = 0; i < NF; i++)
            printf("%i\t%2.3f\t%2.3f\t%2.3f\t%2.3f\n",i+1,featureMeans[i],featureVariances[i],sqrt(featureVariances[i]),firstMultinomialLikelihood[i]);

        means[it->first] = std::move(featureMeans);
        variances[it->first] = std::move(featureVariances);
    }

    // classify
    std::cout << "Classifying:" << std::endl;
    std::cout << "class\tprob\tresult" << std::endl;

    errcode = readFromFile(argv[2], true);
    if (errcode)
        return errcode;
    printf("Accuracy: %3.2f %% (%i/%i)\n", 100.0 * correct / totalClassified, correct, totalClassified);

    return 0;
}
<|endoftext|>


<commit_before>/*
Copyright 2015, Jernej Kovacic

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

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

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

#include "IntUtilGeneric.hpp"

/**
 * @file
 * @author Jernej Kovacic
 *
 * Implementation of auxiliary functions that handle integer variables.
 */

// no #include "IntUtilGeneric.hpp" !!!
#include <limits>

// A namespace with "private" functions and classes
namespace math {  namespace IntUtil {  namespace __private
{

/*
 * A set of clases that check whether an integer is negative.
 *
 * An integer value can only be negative if its type is signed. This could be
 * quickly checked by comparing (I)(-1) and (I)(0), however, if I is an unsigned type,
 * a compiler would raise a warning that "comparison of unsigned expression < 0 is
 * always false". One workaround this would be partial specialization. As C++ does
 * allow partial specialization of templated functions, thiswork around using an
 * additional templated static class has been introduced.
 */

template <typename I, bool isSigned>
struct __CheckSign
{
    /*
     * A "general" implementation of the class when isSigned equals 'true'
     */
    static inline bool isNeg(const I& n)
    {
        // As I is a signed type, 'n' must be compared to 0:
        return ( n < static_cast<I>(0) );
    }
};

// Partial specialization of __checkSignImpl for isSigned = false
template <typename I>
struct __CheckSign<I, false>
{
    /*
     * A specialization for isSigned == false, i.e. I is an unsigned integer type
     */
    static inline bool isNeg(const I& n)
    {
        // Since I is an unsigned type, 'n' can never be negative
        (void) n;
        return false;
    }
};

}}}  // namespace math::IntUtil::__private

/*
 * Checks the sign of 'n'.
 * Both, signed and unsigned, integer types are handled correctly.
 *
 * @param n - integer value to check
 *
 * @return 'true' if 'n' is strictly negative, 'false' otherwise
 */
template <typename I>
bool math::IntUtil::isNegative(const I& n)
{
    return
      math::IntUtil::__private::__CheckSign<I, std::numeric_limits<I>::is_signed>::isNeg(n);
}

/*
 * A simple integer implementation of abs
 *
 * @param n
 * @return absolute value of 'n'
 */
template <typename I>
inline I math::IntUtil::absolute(const I& n)
{
    return ( false==math::IntUtil::isNegative<I>(n) ? n : -n );
}
<commit_msg>error handling in int abs.<commit_after>/*
Copyright 2015, Jernej Kovacic

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

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

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

#include "IntUtilGeneric.hpp"

/**
 * @file
 * @author Jernej Kovacic
 *
 * Implementation of auxiliary functions that handle integer variables.
 */

// no #include "IntUtilGeneric.hpp" !!!
#include <limits>

// A namespace with "private" functions and classes
namespace math {  namespace IntUtil {  namespace __private
{

/*
 * A set of clases that check whether an integer is negative.
 *
 * An integer value can only be negative if its type is signed. This could be
 * quickly checked by comparing (I)(-1) and (I)(0), however, if I is an unsigned type,
 * a compiler would raise a warning that "comparison of unsigned expression < 0 is
 * always false". One workaround this would be partial specialization. As C++ does
 * allow partial specialization of templated functions, thiswork around using an
 * additional templated static class has been introduced.
 */

template <typename I, bool isSigned>
struct __CheckSign
{
    /*
     * A "general" implementation of the class when isSigned equals 'true'
     */
    static inline bool isNeg(const I& n)
    {
        // As I is a signed type, 'n' must be compared to 0:
        return ( n < static_cast<I>(0) );
    }
};

// Partial specialization of __checkSignImpl for isSigned = false
template <typename I>
struct __CheckSign<I, false>
{
    /*
     * A specialization for isSigned == false, i.e. I is an unsigned integer type
     */
    static inline bool isNeg(const I& n)
    {
        // Since I is an unsigned type, 'n' can never be negative
        (void) n;
        return false;
    }
};

}}}  // namespace math::IntUtil::__private

/*
 * Checks the sign of 'n'.
 * Both, signed and unsigned, integer types are handled correctly.
 *
 * @param n - integer value to check
 *
 * @return 'true' if 'n' is strictly negative, 'false' otherwise
 */
template <typename I>
bool math::IntUtil::isNegative(const I& n)
{
    return
      math::IntUtil::__private::__CheckSign<I, std::numeric_limits<I>::is_signed>::isNeg(n);
}

/*
 * A simple integer implementation of abs
 *
 * @param n
 * @return absolute value of 'n'
 */
template <typename I>
inline I math::IntUtil::absolute(const I& n)
{
    const bool neg = math::IntUtil::isNegative<I>(n);

    // TODO find better handling of this case!!!
    /*
     * If 'I' represents a signed type and 'n' equals I_MIN,
     * the function should return -I_MIN. However, in such a case,
     * I_MAX is typically less than -I_MIN  (I_MAX = I_MIN - 1) which
     * would result in an integer overflow (and possibly a core dump).
     * If this situation occurs, the function will return I_MAX.
     * Not really the correct handling but until a better solution is proposed...
     */
    if ( true==neg && std::numeric_limits<I>::min()==n )
    {
        return std::numeric_limits<I>::max();
    }

    return ( false==neg ? n : -n );
}
<|endoftext|>


<commit_before>/*
    Copyright (C) 1998,2000 by Jorrit Tyberghein
    This is the entry point for console executables

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "csutil/scf.h"

extern int csMain (int argc, char* argv[]);
extern int ApplicationShow;
HINSTANCE ModuleHandle;

#undef main
// The main entry for console applications
int main (int argc, char* argv[])
{
  // hInstance is really the handle of module
  ModuleHandle = GetModuleHandle (NULL);
  return csMain (argc, argv);
}

// The main entry for GUI applications
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
  LPSTR lpCmdLine, int nCmdShow)
{
  ModuleHandle = hInstance;
  ApplicationShow = nCmdShow;
  (void)lpCmdLine;
  (void)hPrevInstance;

  return
#ifdef COMP_BC
    csMain ( _argc,  _argv);
#else
    csMain (__argc, __argv);
#endif
}
<commit_msg>set ApplicationShow to SW_SHOWNORMAL in main (). For some reason the mingw links main and not WinMain for gui apps. In that case ApplicationShow was initialized to 0 which means HIDE which in turn was the reason the window was invisible when running with opengl/mingw. I remember that it worked before, so probably some linker options slightly changed when linking with mingw - i dont know.<commit_after>/*
    Copyright (C) 1998,2000 by Jorrit Tyberghein
    This is the entry point for console executables

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "csutil/scf.h"

extern int csMain (int argc, char* argv[]);
extern int ApplicationShow;
HINSTANCE ModuleHandle;

#undef main
// The main entry for console applications
int main (int argc, char* argv[])
{
  // hInstance is really the handle of module
  ModuleHandle = GetModuleHandle (NULL);
  ApplicationShow = SW_SHOWNORMAL;
  return csMain (argc, argv);
}

// The main entry for GUI applications
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
  LPSTR lpCmdLine, int nCmdShow)
{
  ModuleHandle = hInstance;
  ApplicationShow = nCmdShow;
  (void)lpCmdLine;
  (void)hPrevInstance;

  return
#ifdef COMP_BC
    csMain ( _argc,  _argv);
#else
    csMain (__argc, __argv);
#endif
}
<|endoftext|>


<commit_before>/* ****************************************************************************
*
* FILE                      workerStatus.cpp
*
* DESCRIPTION               extraction of machine information
*
*/
#include <stdio.h>              // FILE, fopen, ...
#include <errno.h>              // errno
#include <string.h>             // strerror

#include "logMsg.h"             // LM_*
#include "networkTraceLevels.h" // LMT_*

#include "samson.pb.h"          // WorkerStatus
#include "workerStatus.h"       // Own interface

namespace ss {

/* ****************************************************************************
*
* Definitions
*/
#define CPUINFO_PATH     "/proc/cpuinfo"
#define STAT_PATH        "/proc/stat"
#define NETDEV_PATH      "/proc/net/dev"

/* ****************************************************************************
*
* CpuTimes -
*/
typedef struct CpuTimes
{
    long  user;
    long  nice;
    long  system;
    long  idle;
    long  iowait;
    long  irq;
    long  softIrq;
    long  steal;
    long  guest;
} CpuTimes;

/* ****************************************************************************
*
* cLoad - measure the load of core 'coreNo'
*/
static int cLoad(int coreNo)
{
	FILE*            fP;
	char             line[160];
	static CpuTimes  oldticks[MAX_CORES + 1] = { { -1 } };
	CpuTimes         ticks;
	int              load;

	if (coreNo > MAX_CORES)
		LM_X(1, ("request for load on core %d - max core number is %d. Please redefine MAX_CORES and recompile", coreNo, MAX_CORES));

	fP = fopen(STAT_PATH, "r");
	if (fP == NULL)
		LM_RE(-1, ("fopen(%s): %s", STAT_PATH, strerror(errno)));

	char coreName[7];

	if (coreNo == MAX_CORES) /* Grand total */
		sprintf(coreName, "cpu ");
	else
		sprintf(coreName, "cpu%d ", coreNo);

	while (fgets(line, sizeof(line), fP) != NULL)
	{
		char coreName2[16];

		if (strncmp(line, coreName, strlen(coreName)) != 0)
			continue;

		sscanf(line, "%s %ld %ld %ld %ld %ld %ld %ld %ld",
			   coreName2,
			   &ticks.user,
			   &ticks.nice,
			   &ticks.system,
			   &ticks.idle,
			   &ticks.iowait,
			   &ticks.irq,
			   &ticks.softIrq,
			   &ticks.steal);

		/* Do I have an old measurement?  - if not, I cannot measure the CPU load ... */
		if (oldticks[coreNo].user == -1)
			return 0;

		CpuTimes* oldP = &oldticks[coreNo];

		long long total     = ticks.user + ticks.nice + ticks.system + ticks.idle + ticks.iowait + ticks.irq + ticks.softIrq + ticks.steal;
		long long oldTotal  = oldP->user + oldP->nice + oldP->system + oldP->idle + oldP->iowait + oldP->irq + oldP->softIrq + oldP->steal;
		long long totalDiff = total - oldTotal;

		if (totalDiff != 0)
		{
			long long idleDiff       = ticks.idle - oldticks[coreNo].idle;
			long long idlePercentage = (100 * idleDiff) / totalDiff;

			load = 100 - idlePercentage;
		}
		else
			load = 0;

		// Remember what was just measured for the next time
		oldticks[coreNo] = ticks;

		return load;
	}

	LM_W(("core %d not found ...", coreNo));
	return 0;
}

/* ****************************************************************************
*
* cores -
*/
static int cores(void)
{
	FILE* fP;
	char  line[160];
	int   coreNo = -2;

	fP = fopen(CPUINFO_PATH, "r");
	if (fP == NULL)
		LM_RE(-1, ("fopen(%s): %s", CPUINFO_PATH, strerror(errno)));

	while (fgets(line, sizeof(line), fP) != NULL)
	{
		char* colon;

		if (strncmp(line, "processor", 9) != 0)
			continue;

		colon = strchr(line, ':');
		if (colon == NULL)
			continue;
		++colon;
		coreNo = atoi(colon);
	}

	fclose(fP);
	return coreNo + 1;
}

/* ****************************************************************************
*
* coreInfo -
*/
static void coreInfo(int coreNo, CoreInfo* ciP)
{
	ciP->load = cLoad(coreNo);

	FILE* fP;
	char  line[160];
	int   cNo = -1;

	fP = fopen(CPUINFO_PATH, "r");
	if (fP == NULL)
		LM_RVE(("fopen(%s): %s", CPUINFO_PATH, strerror(errno)));

	while (fgets(line, sizeof(line), fP) != NULL)
	{
		char* colon;

		if (strncmp(line, "processor", 9) == 0)
		{
			colon = strchr(line, ':');
			if (colon == NULL)
				continue;
			++colon;
			cNo = atoi(colon);

			if (cNo > coreNo)
				return;
		}
		else if (cNo == coreNo)
		{
			if (strncmp(line, "cpu MHz", 7) == 0)
			{
				colon = strchr(line, ':');
				if (colon == NULL)
					continue;
				++colon;
				ciP->mhz = atoi(colon);
			}
			else if (strncmp(line, "bogomips", 8) == 0)
			{
				colon = strchr(line, ':');
				if (colon == NULL)
					continue;
				++colon;
				ciP->bogomips = atoi(colon);
			}
			else if (strncmp(line, "cache size", 10) == 0)
			{
				colon = strchr(line, ':');
				if (colon == NULL)
					continue;
				++colon;
				ciP->cacheSize = atoi(colon);
			}
		}
	}

	fclose(fP);
}

/* ****************************************************************************
*
* netifs -
*/
static int netifs(void)
{
	FILE* fP;
	char  line[160];
	int   ifs = 0;

	fP = fopen(NETDEV_PATH, "r");
	if (fP == NULL)
		LM_RE(-1, ("fopen(%s): %s", CPUINFO_PATH, strerror(errno)));

	while (fgets(line, sizeof(line), fP) != NULL)
	{
		char* colon;

		colon = strchr(line, ':');
		if (colon == NULL)
			continue;
		++ifs;
	}

	fclose(fP);
	return ifs;
}

/* ****************************************************************************
*
* cpuInfo -
*/
static void cpuInfo(CpuInfo* ciP)
{
	int cIx;

	ciP->cores = cores();
	ciP->load  = cLoad(MAX_CORES);

	for (cIx = 0; cIx < ciP->cores; cIx++)
	{
		memset(&ciP->coreInfo[cIx], 0, sizeof(ciP->coreInfo[cIx]));
		coreInfo(cIx, &ciP->coreInfo[cIx]);
	}
}

/* ****************************************************************************
*
* netifInfo -
*/
static void netifInfo(int ifIndex, NetIf* nifP, time_t now, time_t lastTime)
{
	FILE*          fP;
	char           line[160];
	int            lineNo            = 0;
	static NetIf   netif[MAX_NETIFS] = { { { 0 }, 0 } };
	unsigned long  intervalInSecs    = now - lastTime;

	fP = fopen(NETDEV_PATH, "r");
	if (fP == NULL)
		LM_RVE(("fopen(%s): %s", NETDEV_PATH, strerror(errno)));

	while (fgets(line, sizeof(line), fP) != NULL)
	{
		++lineNo;

		if (lineNo - 3 != ifIndex)
		{
			continue;
		}

		char* colon;

		colon = strchr(line, ':');
		if (colon == NULL)
		{
			LM_W(("no colon in '%s'", line));
			continue;
		}
		*colon = 0;
		++colon;

		strcpy(nifP->name, line);
		sscanf(colon, "%ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld",
			   &nifP->rcvBytes, &nifP->rcvPackets, &nifP->rcvErrors,     &nifP->rcvDrop,
			   &nifP->rcvFifo,  &nifP->rcvFrame,   &nifP->rcvCompressed, &nifP->rcvMulticast,
			   &nifP->sndBytes, &nifP->sndPackets, &nifP->sndErrs,       &nifP->sndDrop,
			   &nifP->sndFifo,  &nifP->sndColls,   &nifP->sndCarrier,    &nifP->sndCompressed);

		if (lastTime == 0)
		{
			nifP->rcvSpeed  = 0;
			nifP->sndSpeed  = 0;
		}
		else
		{
			if (netif[ifIndex].rcvBytes != 0)
				nifP->rcvSpeed = (nifP->rcvBytes - netif[ifIndex].rcvBytes) / intervalInSecs;
			if (netif[ifIndex].sndBytes != 0)
				nifP->sndSpeed = (nifP->sndBytes - netif[ifIndex].sndBytes) / intervalInSecs;
		}

		netif[ifIndex] = *nifP;
		fclose(fP);

		return;
	}
}

/* ****************************************************************************
*
* netInfo -
*/
static void netInfo(NetIfInfo* niP)
{
	int            nIx;
	time_t         now  = time(NULL);
	static time_t  then = 0;

	niP->ifaces = netifs();

	for (nIx = 0; nIx < niP->ifaces; nIx++)
	{
		memset(&niP->iface[nIx], 0, sizeof(niP->iface[nIx]));
		strcpy(niP->iface[nIx].name, "nada");
		netifInfo(nIx, &niP->iface[nIx], now, then);
	}

	then = now;
}

/* ****************************************************************************
*
* workerStatus -
*/
void workerStatus(WorkerStatus* wsP)
{
	cpuInfo(&wsP->cpuInfo);
	netInfo(&wsP->netInfo);
}

}
<commit_msg>new feature - closing files after using them ...<commit_after>/* ****************************************************************************
*
* FILE                      workerStatus.cpp
*
* DESCRIPTION               extraction of machine information
*
*/
#include <stdio.h>              // FILE, fopen, ...
#include <errno.h>              // errno
#include <string.h>             // strerror

#include "logMsg.h"             // LM_*
#include "networkTraceLevels.h" // LMT_*

#include "samson.pb.h"          // WorkerStatus
#include "workerStatus.h"       // Own interface

namespace ss {

/* ****************************************************************************
*
* Definitions
*/
#define CPUINFO_PATH     "/proc/cpuinfo"
#define STAT_PATH        "/proc/stat"
#define NETDEV_PATH      "/proc/net/dev"

/* ****************************************************************************
*
* CpuTimes -
*/
typedef struct CpuTimes
{
    long  user;
    long  nice;
    long  system;
    long  idle;
    long  iowait;
    long  irq;
    long  softIrq;
    long  steal;
    long  guest;
} CpuTimes;

/* ****************************************************************************
*
* cLoad - measure the load of core 'coreNo'
*/
static int cLoad(int coreNo)
{
	FILE*            fP;
	char             line[160];
	static CpuTimes  oldticks[MAX_CORES + 1] = { { -1 } };
	CpuTimes         ticks;
	int              load;

	if (coreNo > MAX_CORES)
		LM_X(1, ("request for load on core %d - max core number is %d. Please redefine MAX_CORES and recompile", coreNo, MAX_CORES));

	fP = fopen(STAT_PATH, "r");
	if (fP == NULL)
		LM_RE(-1, ("fopen(%s): %s", STAT_PATH, strerror(errno)));

	char coreName[7];

	if (coreNo == MAX_CORES) /* Grand total */
		sprintf(coreName, "cpu ");
	else
		sprintf(coreName, "cpu%d ", coreNo);

	while (fgets(line, sizeof(line), fP) != NULL)
	{
		char coreName2[16];

		if (strncmp(line, coreName, strlen(coreName)) != 0)
			continue;

		sscanf(line, "%s %ld %ld %ld %ld %ld %ld %ld %ld",
			   coreName2,
			   &ticks.user,
			   &ticks.nice,
			   &ticks.system,
			   &ticks.idle,
			   &ticks.iowait,
			   &ticks.irq,
			   &ticks.softIrq,
			   &ticks.steal);

		/* Do I have an old measurement?  - if not, I cannot measure the CPU load ... */
		if (oldticks[coreNo].user == -1)
		{
			fclose(fP);
			return 0;
		}

		CpuTimes* oldP = &oldticks[coreNo];

		long long total     = ticks.user + ticks.nice + ticks.system + ticks.idle + ticks.iowait + ticks.irq + ticks.softIrq + ticks.steal;
		long long oldTotal  = oldP->user + oldP->nice + oldP->system + oldP->idle + oldP->iowait + oldP->irq + oldP->softIrq + oldP->steal;
		long long totalDiff = total - oldTotal;

		if (totalDiff != 0)
		{
			long long idleDiff       = ticks.idle - oldticks[coreNo].idle;
			long long idlePercentage = (100 * idleDiff) / totalDiff;

			load = 100 - idlePercentage;
		}
		else
			load = 0;

		// Remember what was just measured for the next time
		oldticks[coreNo] = ticks;

		fclose(fP);
		return load;
	}

	LM_W(("core %d not found ...", coreNo));
	fclose(fP);
	return 0;
}

/* ****************************************************************************
*
* cores -
*/
static int cores(void)
{
	FILE* fP;
	char  line[160];
	int   coreNo = -2;

	fP = fopen(CPUINFO_PATH, "r");
	if (fP == NULL)
		LM_RE(-1, ("fopen(%s): %s", CPUINFO_PATH, strerror(errno)));

	while (fgets(line, sizeof(line), fP) != NULL)
	{
		char* colon;

		if (strncmp(line, "processor", 9) != 0)
			continue;

		colon = strchr(line, ':');
		if (colon == NULL)
			continue;
		++colon;
		coreNo = atoi(colon);
	}

	fclose(fP);
	return coreNo + 1;
}

/* ****************************************************************************
*
* coreInfo -
*/
static void coreInfo(int coreNo, CoreInfo* ciP)
{
	ciP->load = cLoad(coreNo);

	FILE* fP;
	char  line[160];
	int   cNo = -1;

	fP = fopen(CPUINFO_PATH, "r");
	if (fP == NULL)
		LM_RVE(("fopen(%s): %s", CPUINFO_PATH, strerror(errno)));

	while (fgets(line, sizeof(line), fP) != NULL)
	{
		char* colon;

		if (strncmp(line, "processor", 9) == 0)
		{
			colon = strchr(line, ':');
			if (colon == NULL)
				continue;
			++colon;
			cNo = atoi(colon);

			if (cNo > coreNo)
			{
				fclose(fP);
				return;
			}
		}
		else if (cNo == coreNo)
		{
			if (strncmp(line, "cpu MHz", 7) == 0)
			{
				colon = strchr(line, ':');
				if (colon == NULL)
					continue;
				++colon;
				ciP->mhz = atoi(colon);
			}
			else if (strncmp(line, "bogomips", 8) == 0)
			{
				colon = strchr(line, ':');
				if (colon == NULL)
					continue;
				++colon;
				ciP->bogomips = atoi(colon);
			}
			else if (strncmp(line, "cache size", 10) == 0)
			{
				colon = strchr(line, ':');
				if (colon == NULL)
					continue;
				++colon;
				ciP->cacheSize = atoi(colon);
			}
		}
	}

	fclose(fP);
}

/* ****************************************************************************
*
* netifs -
*/
static int netifs(void)
{
	FILE* fP;
	char  line[160];
	int   ifs = 0;

	fP = fopen(NETDEV_PATH, "r");
	if (fP == NULL)
		LM_RE(-1, ("fopen(%s): %s", CPUINFO_PATH, strerror(errno)));

	while (fgets(line, sizeof(line), fP) != NULL)
	{
		char* colon;

		colon = strchr(line, ':');
		if (colon == NULL)
			continue;
		++ifs;
	}

	fclose(fP);
	return ifs;
}

/* ****************************************************************************
*
* cpuInfo -
*/
static void cpuInfo(CpuInfo* ciP)
{
	int cIx;

	ciP->cores = cores();
	ciP->load  = cLoad(MAX_CORES);

	for (cIx = 0; cIx < ciP->cores; cIx++)
	{
		memset(&ciP->coreInfo[cIx], 0, sizeof(ciP->coreInfo[cIx]));
		coreInfo(cIx, &ciP->coreInfo[cIx]);
	}
}

/* ****************************************************************************
*
* netifInfo -
*/
static void netifInfo(int ifIndex, NetIf* nifP, time_t now, time_t lastTime)
{
	FILE*          fP;
	char           line[160];
	int            lineNo            = 0;
	static NetIf   netif[MAX_NETIFS] = { { { 0 }, 0 } };
	unsigned long  intervalInSecs    = now - lastTime;

	fP = fopen(NETDEV_PATH, "r");
	if (fP == NULL)
		LM_RVE(("fopen(%s): %s", NETDEV_PATH, strerror(errno)));

	while (fgets(line, sizeof(line), fP) != NULL)
	{
		++lineNo;

		if (lineNo - 3 != ifIndex)
		{
			continue;
		}

		char* colon;

		colon = strchr(line, ':');
		if (colon == NULL)
		{
			LM_W(("no colon in '%s'", line));
			continue;
		}
		*colon = 0;
		++colon;

		strcpy(nifP->name, line);
		sscanf(colon, "%ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld",
			   &nifP->rcvBytes, &nifP->rcvPackets, &nifP->rcvErrors,     &nifP->rcvDrop,
			   &nifP->rcvFifo,  &nifP->rcvFrame,   &nifP->rcvCompressed, &nifP->rcvMulticast,
			   &nifP->sndBytes, &nifP->sndPackets, &nifP->sndErrs,       &nifP->sndDrop,
			   &nifP->sndFifo,  &nifP->sndColls,   &nifP->sndCarrier,    &nifP->sndCompressed);

		if (lastTime == 0)
		{
			nifP->rcvSpeed  = 0;
			nifP->sndSpeed  = 0;
		}
		else
		{
			if (netif[ifIndex].rcvBytes != 0)
				nifP->rcvSpeed = (nifP->rcvBytes - netif[ifIndex].rcvBytes) / intervalInSecs;
			if (netif[ifIndex].sndBytes != 0)
				nifP->sndSpeed = (nifP->sndBytes - netif[ifIndex].sndBytes) / intervalInSecs;
		}

		netif[ifIndex] = *nifP;
		fclose(fP);

		return;
	}

	fclose(fP);
}

/* ****************************************************************************
*
* netInfo -
*/
static void netInfo(NetIfInfo* niP)
{
	int            nIx;
	time_t         now  = time(NULL);
	static time_t  then = 0;

	niP->ifaces = netifs();

	for (nIx = 0; nIx < niP->ifaces; nIx++)
	{
		memset(&niP->iface[nIx], 0, sizeof(niP->iface[nIx]));
		strcpy(niP->iface[nIx].name, "nada");
		netifInfo(nIx, &niP->iface[nIx], now, then);
	}

	then = now;
}

/* ****************************************************************************
*
* workerStatus -
*/
void workerStatus(WorkerStatus* wsP)
{
	cpuInfo(&wsP->cpuInfo);
	netInfo(&wsP->netInfo);
}

}
<|endoftext|>


<commit_before><commit_msg>Use the proper variable name to enhance the redability (#5602)<commit_after><|endoftext|>


<commit_before>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#define SUITE scope_linked

#include "vast/scope_linked.hpp"

#include "test.hpp"
#include "fixtures/actor_system.hpp"

using namespace vast;

namespace {

caf::behavior dummy() {
  return {
    [] {
      // nop
    }
  };
}

} // namespace <anonymous>

FIXTURE_SCOPE(scope_linked_tests, fixtures::deterministic_actor_system)

TEST(exit message on exit) {
  caf::actor hdl;
  { // "lifetime scope" for our dummy
    scope_linked_actor sla{sys.spawn(dummy)};
    hdl = sla.get();
  }
  expect((caf::exit_msg), from(_).to(hdl));
}

FIXTURE_SCOPE_END()
<commit_msg>Clarify non-obvious test with comments<commit_after>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#define SUITE scope_linked

#include "vast/scope_linked.hpp"

#include "test.hpp"
#include "fixtures/actor_system.hpp"

using namespace vast;

namespace {

caf::behavior dummy() {
  return {
    [] {
      // nop
    }
  };
}

} // namespace <anonymous>

FIXTURE_SCOPE(scope_linked_tests, fixtures::deterministic_actor_system)

TEST(exit message on exit) {
  // Spawn dummy, assign it to a scope_linked handle (sla) and make sure it
  // gets killed when sla goes out of scope.
  caf::actor hdl;
  { // "lifetime scope" for our dummy
    scope_linked_actor sla{sys.spawn(dummy)};
    // Store the actor handle in the outer scope, otherwise we can't check for
    // a message to the dummy.
    hdl = sla.get();
  }
  // The sla handle must send an exit_msg when going out of scope.
  expect((caf::exit_msg), from(_).to(hdl));
}

FIXTURE_SCOPE_END()
<|endoftext|>