<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: bessel.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 23:21:02 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SCA_BESSEL_HXX
#define SCA_BESSEL_HXX

#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

namespace sca {
namespace analysis {

// ============================================================================
//     BESSEL functions
// ============================================================================

/** Returns the result for the unmodified BESSEL function of first kind (J), n-th order, at point x. */
double BesselJ( double x, sal_Int32 n ) throw( ::com::sun::star::lang::IllegalArgumentException );

/** Returns the result for the modified BESSEL function of first kind (I), n-th order, at point x. */
double BesselI( double x, sal_Int32 n ) throw( ::com::sun::star::lang::IllegalArgumentException );

/** Returns the result for the unmodified BESSEL function of second kind (Y), n-th order, at point x. */
double BesselY( double x, sal_Int32 n ) throw( ::com::sun::star::lang::IllegalArgumentException );

/** Returns the result for the modified BESSEL function of second kind (K), n-th order, at point x. */
double BesselK( double x, sal_Int32 n ) throw( ::com::sun::star::lang::IllegalArgumentException );

// ============================================================================

} // namespace analysis
} // namespace sca

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.3.132); FILE MERGED 2008/04/01 15:31:30 thb 1.3.132.3: #i85898# Stripping all external header guards 2008/04/01 12:37:08 thb 1.3.132.2: #i85898# Stripping all external header guards 2008/03/31 17:23:11 rt 1.3.132.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: bessel.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef SCA_BESSEL_HXX
#define SCA_BESSEL_HXX

#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <sal/types.h>

namespace sca {
namespace analysis {

// ============================================================================
//     BESSEL functions
// ============================================================================

/** Returns the result for the unmodified BESSEL function of first kind (J), n-th order, at point x. */
double BesselJ( double x, sal_Int32 n ) throw( ::com::sun::star::lang::IllegalArgumentException );

/** Returns the result for the modified BESSEL function of first kind (I), n-th order, at point x. */
double BesselI( double x, sal_Int32 n ) throw( ::com::sun::star::lang::IllegalArgumentException );

/** Returns the result for the unmodified BESSEL function of second kind (Y), n-th order, at point x. */
double BesselY( double x, sal_Int32 n ) throw( ::com::sun::star::lang::IllegalArgumentException );

/** Returns the result for the modified BESSEL function of second kind (K), n-th order, at point x. */
double BesselK( double x, sal_Int32 n ) throw( ::com::sun::star::lang::IllegalArgumentException );

// ============================================================================

} // namespace analysis
} // namespace sca

#endif

<|endoftext|>


<commit_before>// $Id: path.C,v 1.4 1999/10/30 12:53:31 oliver Exp $

#include <BALL/COMMON/global.h>
#include <BALL/COMMON/path.h>
#include <fstream>
#include <stdlib.h>

using std::ifstream;

namespace BALL
{

	string					Path::path_ = BALL_PATH"/data/";
	bool						Path::path_array_valid_ = false;
	bool						Path::environment_checked_ = false;
	vector<string>	Path::path_array_;

	string Path::getDataPath()
	{
		return path_;
	}

	void Path::setDataPath(const string& path)
	{
		path_array_valid_ = false;
		path_ = path;
	}

	string Path::getDefaultDataPath()
	{
		return BALL_PATH"/data/";
	}

	void Path::buildPathArray_()
	{
		// everything is valid - return directly
		if (path_array_valid_)
		{
			return;
		}

		// remove old path array
		path_array_.clear();

		// check whether the environment variable BALL_DATA_PATH is set
		if (!environment_checked_)
		{
			char*	ball_data_path = getenv("BALL_DATA_PATH");
			if (ball_data_path != 0)
			{
				path_ = string(ball_data_path) + ":" + path_;
			}

			// don`t try this again
			environment_checked_ = true;
		}

		// segment the path string and insert each path
		// into the path array. append slashes where neccessary
		string tmp = path_ + ":";
		Size position;
		while ((position = tmp.find(":")) != string::npos)
		{
			// extract the next path...
			string path = tmp.substr(0, position);

			// append a '/' if neccessary (just to be sure...)
			if (path[path.size() - 1] != '/')
			{
				path.append("/");
			}

			// store the path...
			path_array_.push_back(path);
			tmp.erase(0, position + 1);
		}

		// remember we don't have to do this again - computation on demand!
		path_array_valid_ = true;
	}

	string Path::find(const string& name)
	{
		string	result = findStrict(name);

		if (result == string(""))
		{
			// if the full (path-specified) name could not be found,
			// only try the basename (remove leading directories)
			string tmp = name;
			tmp.erase(0, tmp.rfind("/") + 1);
			if (tmp != name)
			{
				result = findStrict(tmp);
			}
		}

		// return the path. "" means nothing found
		return result;
	}

	string Path::findStrict(const string& name)
	{
		// rebuild the path array (only if not already done so!)
		buildPathArray_();

		vector<string>::iterator	path_it = path_array_.begin();
		string filename;

		// first, try the path itself
		ifstream file(name.c_str());
		if (file.is_open())
		{
			file.close();
			return name;
		}
		file.close();

		// iterate over all path entries and check for
		// a file of the desired name...
		for (; path_it != path_array_.end(); ++path_it)
		{
			filename = *path_it + name;
			file.open(filename.c_str());

			// if the file could be opened, we return its name
			if (file.is_open())
			{
				file.close();
				return filename;
			}
			file.close();
		}

		// we didn't find anything - return an empty string
		return string("");
	}

} // namespace BALL
<commit_msg>fixed: the open/close file mechanisms didn't work under Tru64<commit_after>// $Id: path.C,v 1.5 2000/03/27 19:42:24 oliver Exp $

#include <BALL/COMMON/global.h>
#include <BALL/COMMON/path.h>
#include <BALL/SYSTEM/file.h>
#include <fstream>
#include <stdlib.h>

using std::ifstream;

namespace BALL
{

	string					Path::path_ = BALL_PATH"/data/";
	bool						Path::path_array_valid_ = false;
	bool						Path::environment_checked_ = false;
	vector<string>	Path::path_array_;

	string Path::getDataPath()
	{
		return path_;
	}

	void Path::setDataPath(const string& path)
	{
		path_array_valid_ = false;
		path_ = path;
	}

	string Path::getDefaultDataPath()
	{
		return BALL_PATH"/data/";
	}

	void Path::buildPathArray_()
	{
		// everything is valid - return directly
		if (path_array_valid_)
		{
			return;
		}

		// remove old path array
		path_array_.clear();

		// check whether the environment variable BALL_DATA_PATH is set
		if (!environment_checked_)
		{
			char*	ball_data_path = getenv("BALL_DATA_PATH");
			if (ball_data_path != 0)
			{
				path_ = string(ball_data_path) + ":" + path_;
			}

			// don`t try this again
			environment_checked_ = true;
		}

		// segment the path string and insert each path
		// into the path array. append slashes where neccessary
		string tmp = path_ + ":";
		Size position;
		while ((position = tmp.find(":")) != string::npos)
		{
			// extract the next path...
			string path = tmp.substr(0, position);

			// append a '/' if neccessary (just to be sure...)
			if (path[path.size() - 1] != '/')
			{
				path.append("/");
			}

			// store the path...
			path_array_.push_back(path);
			tmp.erase(0, position + 1);
		}

		// remember we don't have to do this again - computation on demand!
		path_array_valid_ = true;
	}

	string Path::find(const string& name)
	{
		string	result = findStrict(name);

		if (result == string(""))
		{
			// if the full (path-specified) name could not be found,
			// only try the basename (remove leading directories)
			string tmp = name;
			tmp.erase(0, tmp.rfind("/") + 1);
			if (tmp != name)
			{
				result = findStrict(tmp);
			}
		}

		// return the path. "" means nothing found
		return result;
	}

	string Path::findStrict(const string& name)
	{
		// rebuild the path array (only if not already done so!)
		buildPathArray_();

		vector<string>::iterator	path_it = path_array_.begin();
		string filename;

		// first, try the path itself
		if (File::isAccessible(name))
		{
			return name;
		}

		// iterate over all path entries and check for
		// a file of the desired name...
		for (; path_it != path_array_.end(); ++path_it)
		{
			filename = *path_it + name;

			// if the file could be opened, we return its name
			if (File::isAccessible(filename))
			{
				return filename;
			}
		}

		// we didn't find anything - return an empty string
		return string("");
	}

} // namespace BALL
<|endoftext|>


<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
//
// 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 "util.h"

#ifdef _WIN32
#include <windows.h>
#include <io.h>
#endif

#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>

#ifndef _WIN32
#include <sys/time.h>
#endif

#include <vector>

#if defined(__APPLE__) || defined(__FreeBSD__)
#include <sys/sysctl.h>
#elif defined(linux)
#include <sys/sysinfo.h>
#endif

#include "edit_distance.h"
#include "metrics.h"

void Fatal(const char* msg, ...) {
  va_list ap;
  fprintf(stderr, "ninja: fatal: ");
  va_start(ap, msg);
  vfprintf(stderr, msg, ap);
  va_end(ap);
  fprintf(stderr, "\n");
#ifdef _WIN32
  // On Windows, some tools may inject extra threads.
  // exit() may block on locks held by those threads, so forcibly exit.
  fflush(stderr);
  fflush(stdout);
  ExitProcess(1);
#else
  exit(1);
#endif
}

void Warning(const char* msg, ...) {
  va_list ap;
  fprintf(stderr, "ninja: warning: ");
  va_start(ap, msg);
  vfprintf(stderr, msg, ap);
  va_end(ap);
  fprintf(stderr, "\n");
}

void Error(const char* msg, ...) {
  va_list ap;
  fprintf(stderr, "ninja: error: ");
  va_start(ap, msg);
  vfprintf(stderr, msg, ap);
  va_end(ap);
  fprintf(stderr, "\n");
}

bool CanonicalizePath(string* path, string* err) {
  METRIC_RECORD("canonicalize str");
  size_t len = path->size();
  char* str = 0;
  if (len > 0)
    str = &(*path)[0];
  if (!CanonicalizePath(str, &len, err))
    return false;
  path->resize(len);
  return true;
}

bool CanonicalizePath(char* path, size_t* len, string* err) {
  // WARNING: this function is performance-critical; please benchmark
  // any changes you make to it.
  METRIC_RECORD("canonicalize path");
  if (*len == 0) {
    *err = "empty path";
    return false;
  }

  const int kMaxPathComponents = 30;
  char* components[kMaxPathComponents];
  int component_count = 0;

  char* start = path;
  char* dst = start;
  const char* src = start;
  const char* end = start + *len;

  if (*src == '/') {
#ifdef _WIN32
    // network path starts with //
    if (*len > 1 && *(src + 1) == '/') {
      src += 2;
      dst += 2;
    } else {
      ++src;
      ++dst;
    }
#else
    ++src;
    ++dst;
#endif
  }

  while (src < end) {
    if (*src == '.') {
      if (src + 1 == end || src[1] == '/') {
        // '.' component; eliminate.
        src += 2;
        continue;
      } else if (src[1] == '.' && (src + 2 == end || src[2] == '/')) {
        // '..' component.  Back up if possible.
        if (component_count > 0) {
          dst = components[component_count - 1];
          src += 3;
          --component_count;
        } else {
          *dst++ = *src++;
          *dst++ = *src++;
          *dst++ = *src++;
        }
        continue;
      }
    }

    if (*src == '/') {
      src++;
      continue;
    }

    if (component_count == kMaxPathComponents)
      Fatal("path has too many components");
    components[component_count] = dst;
    ++component_count;

    while (*src != '/' && src != end)
      *dst++ = *src++;
    *dst++ = *src++;  // Copy '/' or final \0 character as well.
  }

  if (dst == start) {
    *err = "path canonicalizes to the empty path";
    return false;
  }

  *len = dst - start - 1;
  return true;
}

int ReadFile(const string& path, string* contents, string* err) {
  FILE* f = fopen(path.c_str(), "r");
  if (!f) {
    err->assign(strerror(errno));
    return -errno;
  }

  char buf[64 << 10];
  size_t len;
  while ((len = fread(buf, 1, sizeof(buf), f)) > 0) {
    contents->append(buf, len);
  }
  if (ferror(f)) {
    err->assign(strerror(errno));  // XXX errno?
    contents->clear();
    fclose(f);
    return -errno;
  }
  fclose(f);
  return 0;
}

void SetCloseOnExec(int fd) {
#ifndef _WIN32
  int flags = fcntl(fd, F_GETFD);
  if (flags < 0) {
    perror("fcntl(F_GETFD)");
  } else {
    if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0)
      perror("fcntl(F_SETFD)");
  }
#else
  HANDLE hd = (HANDLE) _get_osfhandle(fd);
  if (! SetHandleInformation(hd, HANDLE_FLAG_INHERIT, 0)) {
    fprintf(stderr, "SetHandleInformation(): %s", GetLastErrorString().c_str());
  }
#endif  // ! _WIN32
}

const char* SpellcheckStringV(const string& text,
                              const vector<const char*>& words) {
  const bool kAllowReplacements = true;
  const int kMaxValidEditDistance = 3;

  int min_distance = kMaxValidEditDistance + 1;
  const char* result = NULL;
  for (vector<const char*>::const_iterator i = words.begin();
       i != words.end(); ++i) {
    int distance = EditDistance(*i, text, kAllowReplacements,
                                kMaxValidEditDistance);
    if (distance < min_distance) {
      min_distance = distance;
      result = *i;
    }
  }
  return result;
}

const char* SpellcheckString(const string& text, ...) {
  va_list ap;
  va_start(ap, text);
  vector<const char*> words;
  const char* word;
  while ((word = va_arg(ap, const char*)))
    words.push_back(word);
  return SpellcheckStringV(text, words);
}

#ifdef _WIN32
string GetLastErrorString() {
  DWORD err = GetLastError();

  char* msg_buf;
  FormatMessageA(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        err,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (char*)&msg_buf,
        0,
        NULL);
  string msg = msg_buf;
  LocalFree(msg_buf);
  return msg;
}

void Win32Fatal(const char* function) {
  Fatal("%s: %s", function, GetLastErrorString().c_str());
}
#endif

static bool islatinalpha(int c) {
  // isalpha() is locale-dependent.
  return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}

string StripAnsiEscapeCodes(const string& in) {
  string stripped;
  stripped.reserve(in.size());

  for (size_t i = 0; i < in.size(); ++i) {
    if (in[i] != '\33') {
      // Not an escape code.
      stripped.push_back(in[i]);
      continue;
    }

    // Only strip CSIs for now.
    if (i + 1 >= in.size()) break;
    if (in[i + 1] != '[') continue;  // Not a CSI.
    i += 2;

    // Skip everything up to and including the next [a-zA-Z].
    while (i < in.size() && !islatinalpha(in[i]))
      ++i;
  }
  return stripped;
}

#if defined(linux)
int GetProcessorCount() {
  return get_nprocs();
}
#elif defined(__APPLE__) || defined(__FreeBSD__)
int GetProcessorCount() {
  int processors;
  size_t processors_size = sizeof(processors);
  int name[] = {CTL_HW, HW_NCPU};
  if (sysctl(name, sizeof(name) / sizeof(int),
             &processors, &processors_size,
             NULL, 0) < 0) {
    return 0;
  }
  return processors;
}
#elif defined(_WIN32)
int GetProcessorCount() {
  SYSTEM_INFO info;
  GetSystemInfo(&info);
  return info.dwNumberOfProcessors;
}
#endif

#ifdef _WIN32
double GetLoadAverage() {
  // TODO(nicolas.despres@gmail.com): Find a way to implement it on Windows.
  // Remember to also update Usage() when this is fixed.
  return -0.0f;
}
#else
double GetLoadAverage() {
  double loadavg[3] = { 0.0f, 0.0f, 0.0f };
  if (getloadavg(loadavg, 3) < 0) {
    // Maybe we should return an error here or the availability of
    // getloadavg(3) should be checked when ninja is configured.
    return -0.0f;
  }
  return loadavg[0];
}
#endif // _WIN32

string ElideMiddle(const string& str, size_t width) {
  const int kMargin = 3;  // Space for "...".
  string result = str;
  if (result.size() + kMargin > width) {
    size_t elide_size = (width - kMargin) / 2;
    result = result.substr(0, elide_size)
      + "..."
      + result.substr(result.size() - elide_size, elide_size);
  }
  return result;
}
<commit_msg>add GetProcessorCount() implementation for Solaris<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
//
// 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 "util.h"

#ifdef _WIN32
#include <windows.h>
#include <io.h>
#endif

#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>

#ifndef _WIN32
#include <sys/time.h>
#endif

#include <vector>

#if defined(__APPLE__) || defined(__FreeBSD__)
#include <sys/sysctl.h>
#elif defined(__SVR4) && defined(__sun)
#include <unistd.h>
#include <sys/loadavg.h>
#elif defined(linux)
#include <sys/sysinfo.h>
#endif

#include "edit_distance.h"
#include "metrics.h"

void Fatal(const char* msg, ...) {
  va_list ap;
  fprintf(stderr, "ninja: fatal: ");
  va_start(ap, msg);
  vfprintf(stderr, msg, ap);
  va_end(ap);
  fprintf(stderr, "\n");
#ifdef _WIN32
  // On Windows, some tools may inject extra threads.
  // exit() may block on locks held by those threads, so forcibly exit.
  fflush(stderr);
  fflush(stdout);
  ExitProcess(1);
#else
  exit(1);
#endif
}

void Warning(const char* msg, ...) {
  va_list ap;
  fprintf(stderr, "ninja: warning: ");
  va_start(ap, msg);
  vfprintf(stderr, msg, ap);
  va_end(ap);
  fprintf(stderr, "\n");
}

void Error(const char* msg, ...) {
  va_list ap;
  fprintf(stderr, "ninja: error: ");
  va_start(ap, msg);
  vfprintf(stderr, msg, ap);
  va_end(ap);
  fprintf(stderr, "\n");
}

bool CanonicalizePath(string* path, string* err) {
  METRIC_RECORD("canonicalize str");
  size_t len = path->size();
  char* str = 0;
  if (len > 0)
    str = &(*path)[0];
  if (!CanonicalizePath(str, &len, err))
    return false;
  path->resize(len);
  return true;
}

bool CanonicalizePath(char* path, size_t* len, string* err) {
  // WARNING: this function is performance-critical; please benchmark
  // any changes you make to it.
  METRIC_RECORD("canonicalize path");
  if (*len == 0) {
    *err = "empty path";
    return false;
  }

  const int kMaxPathComponents = 30;
  char* components[kMaxPathComponents];
  int component_count = 0;

  char* start = path;
  char* dst = start;
  const char* src = start;
  const char* end = start + *len;

  if (*src == '/') {
#ifdef _WIN32
    // network path starts with //
    if (*len > 1 && *(src + 1) == '/') {
      src += 2;
      dst += 2;
    } else {
      ++src;
      ++dst;
    }
#else
    ++src;
    ++dst;
#endif
  }

  while (src < end) {
    if (*src == '.') {
      if (src + 1 == end || src[1] == '/') {
        // '.' component; eliminate.
        src += 2;
        continue;
      } else if (src[1] == '.' && (src + 2 == end || src[2] == '/')) {
        // '..' component.  Back up if possible.
        if (component_count > 0) {
          dst = components[component_count - 1];
          src += 3;
          --component_count;
        } else {
          *dst++ = *src++;
          *dst++ = *src++;
          *dst++ = *src++;
        }
        continue;
      }
    }

    if (*src == '/') {
      src++;
      continue;
    }

    if (component_count == kMaxPathComponents)
      Fatal("path has too many components");
    components[component_count] = dst;
    ++component_count;

    while (*src != '/' && src != end)
      *dst++ = *src++;
    *dst++ = *src++;  // Copy '/' or final \0 character as well.
  }

  if (dst == start) {
    *err = "path canonicalizes to the empty path";
    return false;
  }

  *len = dst - start - 1;
  return true;
}

int ReadFile(const string& path, string* contents, string* err) {
  FILE* f = fopen(path.c_str(), "r");
  if (!f) {
    err->assign(strerror(errno));
    return -errno;
  }

  char buf[64 << 10];
  size_t len;
  while ((len = fread(buf, 1, sizeof(buf), f)) > 0) {
    contents->append(buf, len);
  }
  if (ferror(f)) {
    err->assign(strerror(errno));  // XXX errno?
    contents->clear();
    fclose(f);
    return -errno;
  }
  fclose(f);
  return 0;
}

void SetCloseOnExec(int fd) {
#ifndef _WIN32
  int flags = fcntl(fd, F_GETFD);
  if (flags < 0) {
    perror("fcntl(F_GETFD)");
  } else {
    if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0)
      perror("fcntl(F_SETFD)");
  }
#else
  HANDLE hd = (HANDLE) _get_osfhandle(fd);
  if (! SetHandleInformation(hd, HANDLE_FLAG_INHERIT, 0)) {
    fprintf(stderr, "SetHandleInformation(): %s", GetLastErrorString().c_str());
  }
#endif  // ! _WIN32
}

const char* SpellcheckStringV(const string& text,
                              const vector<const char*>& words) {
  const bool kAllowReplacements = true;
  const int kMaxValidEditDistance = 3;

  int min_distance = kMaxValidEditDistance + 1;
  const char* result = NULL;
  for (vector<const char*>::const_iterator i = words.begin();
       i != words.end(); ++i) {
    int distance = EditDistance(*i, text, kAllowReplacements,
                                kMaxValidEditDistance);
    if (distance < min_distance) {
      min_distance = distance;
      result = *i;
    }
  }
  return result;
}

const char* SpellcheckString(const string& text, ...) {
  va_list ap;
  va_start(ap, text);
  vector<const char*> words;
  const char* word;
  while ((word = va_arg(ap, const char*)))
    words.push_back(word);
  return SpellcheckStringV(text, words);
}

#ifdef _WIN32
string GetLastErrorString() {
  DWORD err = GetLastError();

  char* msg_buf;
  FormatMessageA(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        err,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (char*)&msg_buf,
        0,
        NULL);
  string msg = msg_buf;
  LocalFree(msg_buf);
  return msg;
}

void Win32Fatal(const char* function) {
  Fatal("%s: %s", function, GetLastErrorString().c_str());
}
#endif

static bool islatinalpha(int c) {
  // isalpha() is locale-dependent.
  return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}

string StripAnsiEscapeCodes(const string& in) {
  string stripped;
  stripped.reserve(in.size());

  for (size_t i = 0; i < in.size(); ++i) {
    if (in[i] != '\33') {
      // Not an escape code.
      stripped.push_back(in[i]);
      continue;
    }

    // Only strip CSIs for now.
    if (i + 1 >= in.size()) break;
    if (in[i + 1] != '[') continue;  // Not a CSI.
    i += 2;

    // Skip everything up to and including the next [a-zA-Z].
    while (i < in.size() && !islatinalpha(in[i]))
      ++i;
  }
  return stripped;
}

#if defined(linux)
int GetProcessorCount() {
  return get_nprocs();
}
#elif defined(__APPLE__) || defined(__FreeBSD__)
int GetProcessorCount() {
  int processors;
  size_t processors_size = sizeof(processors);
  int name[] = {CTL_HW, HW_NCPU};
  if (sysctl(name, sizeof(name) / sizeof(int),
             &processors, &processors_size,
             NULL, 0) < 0) {
    return 0;
  }
  return processors;
}
#elif defined(_WIN32)
int GetProcessorCount() {
  SYSTEM_INFO info;
  GetSystemInfo(&info);
  return info.dwNumberOfProcessors;
}
#else
// This is what get_nprocs() should be doing in the Linux implementation
// above, but in a more standard way.
int GetProcessorCount() {
  return sysconf(_SC_NPROCESSORS_ONLN);
}
#endif

#ifdef _WIN32
double GetLoadAverage() {
  // TODO(nicolas.despres@gmail.com): Find a way to implement it on Windows.
  // Remember to also update Usage() when this is fixed.
  return -0.0f;
}
#else
double GetLoadAverage() {
  double loadavg[3] = { 0.0f, 0.0f, 0.0f };
  if (getloadavg(loadavg, 3) < 0) {
    // Maybe we should return an error here or the availability of
    // getloadavg(3) should be checked when ninja is configured.
    return -0.0f;
  }
  return loadavg[0];
}
#endif // _WIN32

string ElideMiddle(const string& str, size_t width) {
  const int kMargin = 3;  // Space for "...".
  string result = str;
  if (result.size() + kMargin > width) {
    size_t elide_size = (width - kMargin) / 2;
    result = result.substr(0, elide_size)
      + "..."
      + result.substr(result.size() - elide_size, elide_size);
  }
  return result;
}
<|endoftext|>


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

#pragma once

#include <string>
#include <vector>
#include <algorithm>
#include "ecsState.generated.hpp"

namespace ezecs {

  typedef Delegate<bool(const entityId& id)> entNotifyHandler;
  static bool doNothing(const entityId&) { return true; }

  struct IdRegistry {
    std::vector<entityId> ids;
    entNotifyHandler discoverHandler;
    entNotifyHandler forgetHandler;
    IdRegistry(entNotifyHandler&& discoverHandler = DELEGATE_NOCLASS(doNothing),
               entNotifyHandler&& forgetHandler   = DELEGATE_NOCLASS(doNothing))
               : discoverHandler(discoverHandler), forgetHandler(forgetHandler) { }
  };

  template<typename Derived_System>
  class System
  {
    private:
      bool paused = false;
      Derived_System& sys();

    protected:
      State* state;
      std::vector<IdRegistry> registries;

    public:
      System(State* state);
      ~System();
      bool init();
      void tick(double dt);
      void pause();
      void resume();
      void clean();
      bool isPaused();
  };

  template<typename Derived_System>
  System<Derived_System>::System(State* state)
      : state(state) { }
  template<typename Derived_System>
  System<Derived_System>::~System() {
    //TODO: Remove callbacks from State
    printf("%s is destructing\n", typeid(Derived_System).name());
  }
  template<typename Derived_System>
  Derived_System& System<Derived_System>::sys() {
    return *static_cast<Derived_System*>(this);
  }
  static void discover(const entityId& id, void* data) {
    IdRegistry* registry = reinterpret_cast<IdRegistry*>(data);
    if (registry->discoverHandler(id)) {
      registry->ids.push_back(id);
    }
  }
  static void forget(const entityId& id, void* data) {
    IdRegistry* registry = reinterpret_cast<IdRegistry*>(data);
    std::vector<entityId>::iterator position = std::find(registry->ids.begin(), registry->ids.end(), id);
    if (position != registry->ids.end()) {
      if (registry->forgetHandler(id)) {
        registry->ids.erase(position);
      }
    }
  }
  template<typename Derived_System>
  bool System<Derived_System>::init() {
    registries.resize(sys().requiredComponents.size());
    for (size_t i = 0; i < sys().requiredComponents.size(); ++i) {
      state->listenForLikeEntities(
           sys().requiredComponents[i],
           EntNotifyDelegate{ DELEGATE_NOCLASS(discover), sys().requiredComponents[i], &registries[i] },
           EntNotifyDelegate{ DELEGATE_NOCLASS(forget), sys().requiredComponents[i], &registries[i] }
      );
    }
    return sys().onInit();
  }
  template<typename Derived_System>
  void System<Derived_System>::tick(double dt) {
    sys().onTick(dt);
  }
  template<typename Derived_System>
  void System<Derived_System>::pause(){
    if (!paused){
      paused = true;
    }
  }
  template<typename Derived_System>
  void System<Derived_System>::resume(){
    if (paused){
      paused = false;
    }
  }
  template<typename Derived_System>
  void System<Derived_System>::clean(){
    sys().onClean();
    for (auto registry : registries) {
      registry.ids.clear();
    }
  }
  template<typename Derived_System>
  bool System<Derived_System>::isPaused(){
    return paused;
  }
}
<commit_msg>System is named on destruction<commit_after>/*
 * Copyright (c) 2016 Galen Cochrane
 * Galen Cochrane <galencochrane@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#pragma once

#include <string>
#include <vector>
#include <algorithm>
#include "ecsState.generated.hpp"

namespace ezecs {

  typedef Delegate<bool(const entityId& id)> entNotifyHandler;
  static bool passThrough(const entityId &) { return true; }

  struct IdRegistry {
    std::vector<entityId> ids;
    entNotifyHandler discoverHandler;
    entNotifyHandler forgetHandler;
    IdRegistry(entNotifyHandler&& discoverHandler = DELEGATE_NOCLASS(passThrough),
               entNotifyHandler&& forgetHandler   = DELEGATE_NOCLASS(passThrough))
               : discoverHandler(discoverHandler), forgetHandler(forgetHandler) { }
  };

  template<typename Derived_System>
  class System
  {
    private:
      bool paused = false;
      Derived_System& sys();

    protected:
      std::string name = "Generic System";
      State* state;
      std::vector<IdRegistry> registries;

    public:
      System(State* state);
      virtual ~System();
      bool init();
      void tick(double dt);
      void pause();
      void resume();
      void clean();
      bool isPaused();
  };

  template<typename Derived_System>
  System<Derived_System>::System(State* state)
      : state(state) { }
  template<typename Derived_System>
  System<Derived_System>::~System() {
    //TODO: Remove callbacks from State
    printf("%s is destructing\n", name.c_str());
  }
  template<typename Derived_System>
  Derived_System& System<Derived_System>::sys() {
    return *static_cast<Derived_System*>(this);
  }
  static void discover(const entityId& id, void* data) {
    IdRegistry* registry = reinterpret_cast<IdRegistry*>(data);
    if (registry->discoverHandler(id)) {
      registry->ids.push_back(id);
    }
  }
  static void forget(const entityId& id, void* data) {
    IdRegistry* registry = reinterpret_cast<IdRegistry*>(data);
    std::vector<entityId>::iterator position = std::find(registry->ids.begin(), registry->ids.end(), id);
    if (position != registry->ids.end()) {
      if (registry->forgetHandler(id)) {
        registry->ids.erase(position);
      }
    }
  }
  template<typename Derived_System>
  bool System<Derived_System>::init() {
    registries.resize(sys().requiredComponents.size());
    for (size_t i = 0; i < sys().requiredComponents.size(); ++i) {
      state->listenForLikeEntities(
           sys().requiredComponents[i],
           EntNotifyDelegate{ DELEGATE_NOCLASS(discover), sys().requiredComponents[i], &registries[i] },
           EntNotifyDelegate{ DELEGATE_NOCLASS(forget), sys().requiredComponents[i], &registries[i] }
      );
    }
    return sys().onInit();
  }
  template<typename Derived_System>
  void System<Derived_System>::tick(double dt) {
    sys().onTick(dt);
  }
  template<typename Derived_System>
  void System<Derived_System>::pause(){
    if (!paused){
      paused = true;
    }
  }
  template<typename Derived_System>
  void System<Derived_System>::resume(){
    if (paused){
      paused = false;
    }
  }
  template<typename Derived_System>
  void System<Derived_System>::clean(){
    sys().onClean();
    for (auto registry : registries) {
      registry.ids.clear();
    }
  }
  template<typename Derived_System>
  bool System<Derived_System>::isPaused(){
    return paused;
  }
}
<|endoftext|>


<commit_before>#include "ghost/config.h"

#if GHOST_HAVE_MPI
#include <mpi.h> //mpi.h has to be included before stdio.h
#endif
#include <cstdlib>
#include <iostream>
#include <stdio.h>

#include "ghost/complex.h"
#include "ghost/util.h"
#include "ghost/vec.h"
#include "ghost/math.h"
#include "ghost/constants.h"
#include "ghost/affinity.h"

template <typename v_t> void ghost_normalizeVector_tmpl(ghost_vec_t *vec)
{
    ghost_vidx_t v;
    v_t *s = (v_t *)ghost_malloc(vec->traits->nvecs*sizeof(v_t));
    ghost_dotProduct(vec,vec,s);

    for (v=0; v<vec->traits->nvecs; v++)
    {
        s[v] = (v_t)sqrt(s[v]);
        s[v] = (v_t)(((v_t)1.)/s[v]);
    }
    vec->vscale(vec,s);

}

template <typename v_t> void ghost_vec_dotprod_tmpl(ghost_vec_t *vec, ghost_vec_t *vec2, void *res)
{ // the parallelization is done manually because reduction does not work with ghost_complex numbers
    if (vec->traits->nrows != vec2->traits->nrows) {
        WARNING_LOG("The input vectors of the dot product have different numbers of rows");
    }
    if (vec->traits->nvecs != vec2->traits->nvecs) {
        WARNING_LOG("The input vectors of the dot product have different numbers of columns");
    }
    ghost_vidx_t i,v;
    ghost_vidx_t nr = MIN(vec->traits->nrows,vec2->traits->nrows);

    int nthreads;
#pragma omp parallel
#pragma omp single
    nthreads = ghost_ompGetNumThreads();

    v_t *partsums = (v_t *)ghost_malloc(16*nthreads*sizeof(v_t));
    for (v=0; v<MIN(vec->traits->nvecs,vec2->traits->nvecs); v++) {
        v_t sum = 0;
        for (i=0; i<nthreads*16; i++) partsums[i] = (v_t)0.;

#pragma omp parallel for schedule(runtime)
        for (i=0; i<nr; i++) {
            partsums[ghost_ompGetThreadNum()*16] +=
                *(v_t *)VECVAL(vec2,vec2->val,v,i)*
                conjugate((v_t *)(VECVAL(vec,vec->val,v,i)));
        }

        for (i=0; i<nthreads; i++) sum += partsums[i*16];

        ((v_t *)res)[v] = sum;
    }
    free(partsums);

}

template <typename v_t> void ghost_vec_vaxpy_tmpl(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale)
{
    ghost_vidx_t i,v;
    v_t *s = (v_t *)scale;
    ghost_vidx_t nr = MIN(vec->traits->nrows,vec2->traits->nrows);

    for (v=0; v<MIN(vec->traits->nvecs,vec2->traits->nvecs); v++) {
#pragma omp parallel for schedule(runtime)
        for (i=0; i<nr; i++) {
            *(v_t *)VECVAL(vec,vec->val,v,i) += *(v_t *)VECVAL(vec2,vec2->val,v,i) * s[v];
        }
    }
}

template <typename v_t> void ghost_vec_vaxpby_tmpl(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale, void *b_)
{
    ghost_vidx_t i,v;
    v_t *s = (v_t *)scale;
    v_t *b = (v_t *)b_;
    ghost_vidx_t nr = MIN(vec->traits->nrows,vec2->traits->nrows);

    for (v=0; v<MIN(vec->traits->nvecs,vec2->traits->nvecs); v++) {
#pragma omp parallel for schedule(runtime)
        for (i=0; i<nr; i++) {
            *(v_t *)VECVAL(vec,vec->val,v,i) = *(v_t *)VECVAL(vec2,vec2->val,v,i) * s[v] +
                *(v_t *)VECVAL(vec,vec->val,v,i) * b[v];
        }
    }
}

template<typename v_t> void ghost_vec_vscale_tmpl(ghost_vec_t *vec, void *scale)
{
    ghost_vidx_t i,v;
    v_t *s = (v_t *)scale;

    for (v=0; v<vec->traits->nvecs; v++) {
#pragma omp parallel for schedule(runtime)
        for (i=0; i<vec->traits->nrows; i++) {
            *(v_t *)VECVAL(vec,vec->val,v,i) *= s[v];
        }
    }
}

// thread-safe type generic random function, returns pseudo-random numbers between -1 and 1.
template <typename v_t>
void my_rand(unsigned int* state, v_t* result)
{
    // default implementation
    static const v_t scal = (v_t)2.0/(v_t)RAND_MAX;
    static const v_t shift=(v_t)(-1.0);
    *result=(v_t)rand_r(state)*scal+shift;
}

template <typename float_type>
void my_rand(unsigned int* state, std::complex<float_type>* result)
{
    float_type* ft_res = (float_type*)result;
    my_rand(state,&ft_res[0]);
    my_rand(state,&ft_res[1]);
}

template <typename float_type>
void my_rand(unsigned int* state, ghost_complex<float_type>* result)
{
    my_rand(state,result);
    my_rand(state,((char *)result)+sizeof(float_type));
}

template <typename v_t> void ghost_vec_fromRand_tmpl(ghost_vec_t *vec)
{
    ghost_vec_malloc(vec);
    DEBUG_LOG(1,"Filling vector with random values");
    ghost_vidx_t i,v;

#pragma omp parallel private (v,i)
    {
    unsigned int* state = ghost_getRandState();
        for (v=0; v<vec->traits->nvecs; v++)
        {
#pragma omp for schedule(runtime)
            for (i=0; i<vec->traits->nrows; i++)
            {
                my_rand(state,(v_t *)VECVAL(vec,vec->val,v,i));
            }
        }
    }
    vec->upload(vec);
}

template <typename v_t> void ghost_vec_print_tmpl(ghost_vec_t *vec)
{
    char prefix[16];
#ifdef GHOST_HAVE_MPI
    if (vec->context != NULL && vec->context->mpicomm != MPI_COMM_NULL) {
        int rank = ghost_getRank(vec->context->mpicomm);
        int ndigits = (int)floor(log10(abs(rank))) + 1;
        snprintf(prefix,4+ndigits,"PE%d: ",rank);
    } else {
        snprintf(prefix,1,"");
    }
#else
    snprintf(prefix,1,"");
#endif

    ghost_vidx_t i,v;
    std::cout.setf(std::ios::fixed, std::ios::floatfield);
    for (i=0; i<vec->traits->nrows; i++) {
        std::cout << prefix << "\t";
        for (v=0; v<vec->traits->nvecs; v++) {
            v_t val = 0.;
            if (vec->traits->flags & GHOST_VEC_DEVICE)
            {
#if GHOST_HAVE_CUDA
                CU_copyDeviceToHost(&val,&(((v_t *)vec->CU_val)[v*vec->traits->nrowspadded+i]),sizeof(v_t));
#endif
            }
            else if (vec->traits->flags & GHOST_VEC_HOST)
            {
                val = *(v_t *)VECVAL(vec,vec->val,v,i);
            }
            std::cout << val << "\t";
        }
        std::cout << std::endl;
    }
}

extern "C" void d_ghost_printVector(ghost_vec_t *vec)
{ return ghost_vec_print_tmpl< double >(vec); }

extern "C" void s_ghost_printVector(ghost_vec_t *vec)
{ return ghost_vec_print_tmpl< float >(vec); }

extern "C" void z_ghost_printVector(ghost_vec_t *vec)
{ return ghost_vec_print_tmpl< ghost_complex<double> >(vec); }

extern "C" void c_ghost_printVector(ghost_vec_t *vec)
{ return ghost_vec_print_tmpl< ghost_complex<float> >(vec); }

extern "C" void d_ghost_normalizeVector(ghost_vec_t *vec)
{ return ghost_normalizeVector_tmpl< double >(vec); }

extern "C" void s_ghost_normalizeVector(ghost_vec_t *vec)
{ return ghost_normalizeVector_tmpl< float >(vec); }

extern "C" void z_ghost_normalizeVector(ghost_vec_t *vec)
{ return ghost_normalizeVector_tmpl< ghost_complex<double> >(vec); }

extern "C" void c_ghost_normalizeVector(ghost_vec_t *vec)
{ return ghost_normalizeVector_tmpl< ghost_complex<float> >(vec); }

extern "C" void d_ghost_vec_dotprod(ghost_vec_t *vec, ghost_vec_t *vec2, void *res)
{ return ghost_vec_dotprod_tmpl< double >(vec,vec2,res); }

extern "C" void s_ghost_vec_dotprod(ghost_vec_t *vec, ghost_vec_t *vec2, void *res)
{ return ghost_vec_dotprod_tmpl< float >(vec,vec2,res); }

extern "C" void z_ghost_vec_dotprod(ghost_vec_t *vec, ghost_vec_t *vec2, void *res)
{ return ghost_vec_dotprod_tmpl< ghost_complex<double> >(vec,vec2,res); }

extern "C" void c_ghost_vec_dotprod(ghost_vec_t *vec, ghost_vec_t *vec2, void *res)
{ return ghost_vec_dotprod_tmpl< ghost_complex<float> >(vec,vec2,res); }

extern "C" void d_ghost_vec_vscale(ghost_vec_t *vec, void *scale)
{ return ghost_vec_vscale_tmpl< double >(vec, scale); }

extern "C" void s_ghost_vec_vscale(ghost_vec_t *vec, void *scale)
{ return ghost_vec_vscale_tmpl< float  >(vec, scale); }

extern "C" void z_ghost_vec_vscale(ghost_vec_t *vec, void *scale)
{ return ghost_vec_vscale_tmpl< ghost_complex<double> >(vec, scale); }

extern "C" void c_ghost_vec_vscale(ghost_vec_t *vec, void *scale)
{ return ghost_vec_vscale_tmpl< ghost_complex<float> >(vec, scale); }

extern "C" void d_ghost_vec_vaxpy(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale)
{ return ghost_vec_vaxpy_tmpl< double >(vec, vec2, scale); }

extern "C" void s_ghost_vec_vaxpy(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale)
{ return ghost_vec_vaxpy_tmpl< float >(vec, vec2, scale); }

extern "C" void z_ghost_vec_vaxpy(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale)
{ return ghost_vec_vaxpy_tmpl< ghost_complex<double> >(vec, vec2, scale); }

extern "C" void c_ghost_vec_vaxpy(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale)
{ return ghost_vec_vaxpy_tmpl< ghost_complex<float> >(vec, vec2, scale); }

extern "C" void d_ghost_vec_vaxpby(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale, void *b)
{ return ghost_vec_vaxpby_tmpl< double >(vec, vec2, scale, b); }

extern "C" void s_ghost_vec_vaxpby(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale, void *b)
{ return ghost_vec_vaxpby_tmpl< float >(vec, vec2, scale, b); }

extern "C" void z_ghost_vec_vaxpby(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale, void *b)
{ return ghost_vec_vaxpby_tmpl< ghost_complex<double> >(vec, vec2, scale, b); }

extern "C" void c_ghost_vec_vaxpby(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale, void *b)
{ return ghost_vec_vaxpby_tmpl< ghost_complex<float> >(vec, vec2, scale, b); }

extern "C" void d_ghost_vec_fromRand(ghost_vec_t *vec)
{ return ghost_vec_fromRand_tmpl< double >(vec); }

extern "C" void s_ghost_vec_fromRand(ghost_vec_t *vec)
{ return ghost_vec_fromRand_tmpl< float >(vec); }

extern "C" void z_ghost_vec_fromRand(ghost_vec_t *vec)
{ return ghost_vec_fromRand_tmpl< ghost_complex<double> >(vec); }

extern "C" void c_ghost_vec_fromRand(ghost_vec_t *vec)
{ return ghost_vec_fromRand_tmpl< ghost_complex<float> >(vec); }

<commit_msg>fixed infinite loop which occured in some occations<commit_after>#include "ghost/config.h"

#if GHOST_HAVE_MPI
#include <mpi.h> //mpi.h has to be included before stdio.h
#endif
#include <cstdlib>
#include <iostream>
#include <stdio.h>

#include "ghost/complex.h"
#include "ghost/util.h"
#include "ghost/vec.h"
#include "ghost/math.h"
#include "ghost/constants.h"
#include "ghost/affinity.h"

template <typename v_t> void ghost_normalizeVector_tmpl(ghost_vec_t *vec)
{
    ghost_vidx_t v;
    v_t *s = (v_t *)ghost_malloc(vec->traits->nvecs*sizeof(v_t));
    ghost_dotProduct(vec,vec,s);

    for (v=0; v<vec->traits->nvecs; v++)
    {
        s[v] = (v_t)sqrt(s[v]);
        s[v] = (v_t)(((v_t)1.)/s[v]);
    }
    vec->vscale(vec,s);

}

template <typename v_t> void ghost_vec_dotprod_tmpl(ghost_vec_t *vec, ghost_vec_t *vec2, void *res)
{ // the parallelization is done manually because reduction does not work with ghost_complex numbers
    if (vec->traits->nrows != vec2->traits->nrows) {
        WARNING_LOG("The input vectors of the dot product have different numbers of rows");
    }
    if (vec->traits->nvecs != vec2->traits->nvecs) {
        WARNING_LOG("The input vectors of the dot product have different numbers of columns");
    }
    ghost_vidx_t i,v;
    ghost_vidx_t nr = MIN(vec->traits->nrows,vec2->traits->nrows);

    int nthreads;
#pragma omp parallel
#pragma omp single
    nthreads = ghost_ompGetNumThreads();

    v_t *partsums = (v_t *)ghost_malloc(16*nthreads*sizeof(v_t));
    for (v=0; v<MIN(vec->traits->nvecs,vec2->traits->nvecs); v++) {
        v_t sum = 0;
        for (i=0; i<nthreads*16; i++) partsums[i] = (v_t)0.;

#pragma omp parallel for schedule(runtime)
        for (i=0; i<nr; i++) {
            partsums[ghost_ompGetThreadNum()*16] +=
                *(v_t *)VECVAL(vec2,vec2->val,v,i)*
                conjugate((v_t *)(VECVAL(vec,vec->val,v,i)));
        }

        for (i=0; i<nthreads; i++) sum += partsums[i*16];

        ((v_t *)res)[v] = sum;
    }
    free(partsums);

}

template <typename v_t> void ghost_vec_vaxpy_tmpl(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale)
{
    ghost_vidx_t i,v;
    v_t *s = (v_t *)scale;
    ghost_vidx_t nr = MIN(vec->traits->nrows,vec2->traits->nrows);

    for (v=0; v<MIN(vec->traits->nvecs,vec2->traits->nvecs); v++) {
#pragma omp parallel for schedule(runtime)
        for (i=0; i<nr; i++) {
            *(v_t *)VECVAL(vec,vec->val,v,i) += *(v_t *)VECVAL(vec2,vec2->val,v,i) * s[v];
        }
    }
}

template <typename v_t> void ghost_vec_vaxpby_tmpl(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale, void *b_)
{
    ghost_vidx_t i,v;
    v_t *s = (v_t *)scale;
    v_t *b = (v_t *)b_;
    ghost_vidx_t nr = MIN(vec->traits->nrows,vec2->traits->nrows);

    for (v=0; v<MIN(vec->traits->nvecs,vec2->traits->nvecs); v++) {
#pragma omp parallel for schedule(runtime)
        for (i=0; i<nr; i++) {
            *(v_t *)VECVAL(vec,vec->val,v,i) = *(v_t *)VECVAL(vec2,vec2->val,v,i) * s[v] +
                *(v_t *)VECVAL(vec,vec->val,v,i) * b[v];
        }
    }
}

template<typename v_t> void ghost_vec_vscale_tmpl(ghost_vec_t *vec, void *scale)
{
    ghost_vidx_t i,v;
    v_t *s = (v_t *)scale;

    for (v=0; v<vec->traits->nvecs; v++) {
#pragma omp parallel for schedule(runtime)
        for (i=0; i<vec->traits->nrows; i++) {
            *(v_t *)VECVAL(vec,vec->val,v,i) *= s[v];
        }
    }
}

// thread-safe type generic random function, returns pseudo-random numbers between -1 and 1.
template <typename v_t>
void my_rand(unsigned int* state, v_t* result)
{
    // default implementation
    static const v_t scal = (v_t)2.0/(v_t)RAND_MAX;
    static const v_t shift=(v_t)(-1.0);
    *result=(v_t)rand_r(state)*scal+shift;
}

template <typename float_type>
void my_rand(unsigned int* state, std::complex<float_type>* result)
{
    float_type* ft_res = (float_type*)result;
    my_rand(state,&ft_res[0]);
    my_rand(state,&ft_res[1]);
}

template <typename float_type>
void my_rand(unsigned int* state, ghost_complex<float_type>* result)
{
    my_rand<float_type>(state,(float_type *)result);
    my_rand<float_type>(state,((float_type *)result)+1);
}

template <typename v_t> void ghost_vec_fromRand_tmpl(ghost_vec_t *vec)
{
    ghost_vec_malloc(vec);
    DEBUG_LOG(1,"Filling vector with random values");
    ghost_vidx_t i,v;

#pragma omp parallel private (v,i)
    {
    unsigned int* state = ghost_getRandState();
        for (v=0; v<vec->traits->nvecs; v++)
        {
#pragma omp for schedule(runtime)
            for (i=0; i<vec->traits->nrows; i++)
            {
                my_rand(state,(v_t *)VECVAL(vec,vec->val,v,i));
            }
        }
    }
    vec->upload(vec);
}

template <typename v_t> void ghost_vec_print_tmpl(ghost_vec_t *vec)
{
    char prefix[16];
#ifdef GHOST_HAVE_MPI
    if (vec->context != NULL && vec->context->mpicomm != MPI_COMM_NULL) {
        int rank = ghost_getRank(vec->context->mpicomm);
        int ndigits = (int)floor(log10(abs(rank))) + 1;
        snprintf(prefix,4+ndigits,"PE%d: ",rank);
    } else {
        snprintf(prefix,1,"");
    }
#else
    snprintf(prefix,1,"");
#endif

    ghost_vidx_t i,v;
    std::cout.setf(std::ios::fixed, std::ios::floatfield);
    for (i=0; i<vec->traits->nrows; i++) {
        std::cout << prefix << "\t";
        for (v=0; v<vec->traits->nvecs; v++) {
            v_t val = 0.;
            if (vec->traits->flags & GHOST_VEC_DEVICE)
            {
#if GHOST_HAVE_CUDA
                CU_copyDeviceToHost(&val,&(((v_t *)vec->CU_val)[v*vec->traits->nrowspadded+i]),sizeof(v_t));
#endif
            }
            else if (vec->traits->flags & GHOST_VEC_HOST)
            {
                val = *(v_t *)VECVAL(vec,vec->val,v,i);
            }
            std::cout << val << "\t";
        }
        std::cout << std::endl;
    }
}

extern "C" void d_ghost_printVector(ghost_vec_t *vec)
{ return ghost_vec_print_tmpl< double >(vec); }

extern "C" void s_ghost_printVector(ghost_vec_t *vec)
{ return ghost_vec_print_tmpl< float >(vec); }

extern "C" void z_ghost_printVector(ghost_vec_t *vec)
{ return ghost_vec_print_tmpl< ghost_complex<double> >(vec); }

extern "C" void c_ghost_printVector(ghost_vec_t *vec)
{ return ghost_vec_print_tmpl< ghost_complex<float> >(vec); }

extern "C" void d_ghost_normalizeVector(ghost_vec_t *vec)
{ return ghost_normalizeVector_tmpl< double >(vec); }

extern "C" void s_ghost_normalizeVector(ghost_vec_t *vec)
{ return ghost_normalizeVector_tmpl< float >(vec); }

extern "C" void z_ghost_normalizeVector(ghost_vec_t *vec)
{ return ghost_normalizeVector_tmpl< ghost_complex<double> >(vec); }

extern "C" void c_ghost_normalizeVector(ghost_vec_t *vec)
{ return ghost_normalizeVector_tmpl< ghost_complex<float> >(vec); }

extern "C" void d_ghost_vec_dotprod(ghost_vec_t *vec, ghost_vec_t *vec2, void *res)
{ return ghost_vec_dotprod_tmpl< double >(vec,vec2,res); }

extern "C" void s_ghost_vec_dotprod(ghost_vec_t *vec, ghost_vec_t *vec2, void *res)
{ return ghost_vec_dotprod_tmpl< float >(vec,vec2,res); }

extern "C" void z_ghost_vec_dotprod(ghost_vec_t *vec, ghost_vec_t *vec2, void *res)
{ return ghost_vec_dotprod_tmpl< ghost_complex<double> >(vec,vec2,res); }

extern "C" void c_ghost_vec_dotprod(ghost_vec_t *vec, ghost_vec_t *vec2, void *res)
{ return ghost_vec_dotprod_tmpl< ghost_complex<float> >(vec,vec2,res); }

extern "C" void d_ghost_vec_vscale(ghost_vec_t *vec, void *scale)
{ return ghost_vec_vscale_tmpl< double >(vec, scale); }

extern "C" void s_ghost_vec_vscale(ghost_vec_t *vec, void *scale)
{ return ghost_vec_vscale_tmpl< float  >(vec, scale); }

extern "C" void z_ghost_vec_vscale(ghost_vec_t *vec, void *scale)
{ return ghost_vec_vscale_tmpl< ghost_complex<double> >(vec, scale); }

extern "C" void c_ghost_vec_vscale(ghost_vec_t *vec, void *scale)
{ return ghost_vec_vscale_tmpl< ghost_complex<float> >(vec, scale); }

extern "C" void d_ghost_vec_vaxpy(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale)
{ return ghost_vec_vaxpy_tmpl< double >(vec, vec2, scale); }

extern "C" void s_ghost_vec_vaxpy(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale)
{ return ghost_vec_vaxpy_tmpl< float >(vec, vec2, scale); }

extern "C" void z_ghost_vec_vaxpy(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale)
{ return ghost_vec_vaxpy_tmpl< ghost_complex<double> >(vec, vec2, scale); }

extern "C" void c_ghost_vec_vaxpy(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale)
{ return ghost_vec_vaxpy_tmpl< ghost_complex<float> >(vec, vec2, scale); }

extern "C" void d_ghost_vec_vaxpby(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale, void *b)
{ return ghost_vec_vaxpby_tmpl< double >(vec, vec2, scale, b); }

extern "C" void s_ghost_vec_vaxpby(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale, void *b)
{ return ghost_vec_vaxpby_tmpl< float >(vec, vec2, scale, b); }

extern "C" void z_ghost_vec_vaxpby(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale, void *b)
{ return ghost_vec_vaxpby_tmpl< ghost_complex<double> >(vec, vec2, scale, b); }

extern "C" void c_ghost_vec_vaxpby(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale, void *b)
{ return ghost_vec_vaxpby_tmpl< ghost_complex<float> >(vec, vec2, scale, b); }

extern "C" void d_ghost_vec_fromRand(ghost_vec_t *vec)
{ return ghost_vec_fromRand_tmpl< double >(vec); }

extern "C" void s_ghost_vec_fromRand(ghost_vec_t *vec)
{ return ghost_vec_fromRand_tmpl< float >(vec); }

extern "C" void z_ghost_vec_fromRand(ghost_vec_t *vec)
{ return ghost_vec_fromRand_tmpl< ghost_complex<double> >(vec); }

extern "C" void c_ghost_vec_fromRand(ghost_vec_t *vec)
{ return ghost_vec_fromRand_tmpl< ghost_complex<float> >(vec); }

<|endoftext|>


<commit_before>#pragma once
#include <silicium/html/tree.hpp>
#include <boost/intrusive/options.hpp>

namespace
{

	//----------------TITLE tag----------------
	template <class Element>
	auto html(Element &&content)
	{
		return Si::html::tag("html", std::forward<Element>(content));
	}

	template <class Element>
	auto head(Element &&content)
	{
		return Si::html::tag("head", std::forward<Element>(content));
	}

	template <class Element>
	auto body(Element &&content)
	{
		return Si::html::tag("body", std::forward<Element>(content));
	}

	//----------------TITLE tag----------------
	auto title(std::string const &content)
	{
		using namespace Si::html;
		return tag("title", text(content));
	}

	//----------------H1 tag----------------
	template <class Element>
	auto h1(Element &&content)
	{
		using namespace Si::html;
		return tag("h1", std::forward<Element>(content));
	}

	//----------------H2 tag----------------
	template <class Element>
	auto h2(Element &&content)
	{
		using namespace Si::html;
		return tag("h2", std::forward<Element>(content));
	}

	//----------------H3 tag----------------
	template <class Element>
	auto h3(Element &&content)
	{
		using namespace Si::html;
		return tag("h3", std::forward<Element>(content));
	}

	//----------------H4 tag----------------
	template <class Element>
	auto h4(Element &&content)
	{
		using namespace Si::html;
		return tag("h4", std::forward<Element>(content));
	}

	//----------------MENU tag----------------
	template <class Element>
	auto menu(Element &&content)
	{
		return Si::html::tag("menu", std::forward<Element>(content));
	}

	//----------------FOOTER tag----------------
	template <class Element>
	auto footer(Element &&content)
	{
		return Si::html::tag("footer", std::forward<Element>(content));
	}

	//----------------P tag----------------
	auto p(std::string const &content)
	{
		using namespace Si::html;
		return tag("p", text(content));
	}

	template <class Element, class Attributes>
	auto p(Attributes &&attributes, Element &&content)
	{
		return Si::html::tag("p", std::forward<Attributes>(attributes),
		                     std::forward<Element>(content));
	}

	//----------------DIV tag----------------
	template <class Element>
	auto div(Element &&content)
	{
		return Si::html::tag("div", std::forward<Element>(content));
	}

	template <class Element, class Attributes>
	auto div(Attributes &&attributes, Element &&content)
	{
		return Si::html::tag("div", std::forward<Attributes>(attributes),
		                     std::forward<Element>(content));
	}

	//----------------SPAN tag----------------
	template <class Element>
	auto span(Element &&content)
	{
		return Si::html::tag("span", std::forward<Element>(content));
	}

	template <class Element, class Attributes>
	auto span(Attributes &&attributes, Element &&content)
	{
		return Si::html::tag("span", std::forward<Attributes>(attributes),
		                     std::forward<Element>(content));
	}

	//----------------table tags----------------
	template <class Element>
	auto table(Element &&content)
	{
		return Si::html::tag("table", std::forward<Element>(content));
	}

	template <class Element>
	auto table(std::string const &summary, Element &&content)
	{
		return Si::html::tag("table", Si::html::attribute("summary", summary),
		                     std::forward<Element>(content));
	}

	template <class Element>
	auto thead(Element &&content)
	{
		return Si::html::tag("thead", std::forward<Element>(content));
	}
	template <class Element>
	auto tbody(Element &&content)
	{
		return Si::html::tag("tbody", std::forward<Element>(content));
	}
	template <class Element>
	auto tfoot(Element &&content)
	{
		return Si::html::tag("tfoot", std::forward<Element>(content));
	}

	//----------------TD tag----------------
	template <class Element>
	auto td(Element &&content)
	{
		return Si::html::tag("td", std::forward<Element>(content));
	}

	//----------------UL tag----------------
	template <class Element>
	auto ul(Element &&content)
	{
		return Si::html::tag("ul", std::forward<Element>(content));
	}

	template <class Element, class Attributes>
	auto ul(Attributes &&attributes, Element &&content)
	{
		return Si::html::tag("ul", std::forward<Attributes>(attributes),
		                     std::forward<Element>(content));
	}
	//----------------LI tag----------------
	template <class Element>
	auto li(Element &&content)
	{
		return Si::html::tag("li", std::forward<Element>(content));
	}

	//----------------PRE tag----------------
	template <class Element>
	auto pre(Element &&content)
	{
		return Si::html::tag("pre", std::forward<Element>(content));
	}

	template <class Element, class Attributes>
	auto pre(Attributes &&attributes, Element &&content)
	{
		return Si::html::tag("pre", std::forward<Attributes>(attributes),
		                     std::forward<Element>(content));
	}

	template <class Attributes>
	auto br(Attributes &&attributes)
	{
		using namespace Si::html;
		return tag("br", std::forward<Attributes>(attributes), empty);
	}

	//----------------classes attrib----------------
	auto cl(std::string const &content)
	{
		return Si::html::attribute("class", content);
	}

	//----------------href attrib----------------
	auto href(std::string const &content)
	{
		return Si::html::attribute("href", content);
	}

	// PSEUDO TAG: link (emulates the a-tag)
	template <std::size_t N>
	auto link(std::string const &protocol,
	          char const(&address_without_protocol)[N],
	          std::string const &caption)
	{
		using namespace Si::html;
		return dynamic(
		    [protocol, &address_without_protocol, caption](code_sink &sink)
		    {
			    if (protocol == "http://" || protocol == "https://")
			    {
				    tag("a", href(protocol + address_without_protocol) +
				                 attribute("target", "_blank"),
				        text(caption))
				        .generate(sink);
			    }
			    else
			    {
				    tag("a", href(protocol + address_without_protocol),
				        text(caption))
				        .generate(sink);
			    }
			});
	}

	template <std::size_t N>
	auto link(std::string const &protocol,
	          char const(&address_without_protocol)[N])
	{
		return link(protocol, address_without_protocol,
		            address_without_protocol);
	}

	// PSEUDO ATTRIBUTE: anchor_attributes (emulates a jump mark on a page)
	template <std::size_t N>
	auto anchor_attributes(char const(&name)[N])
	{
		using namespace Si::html;
		return attribute("name", name) + href(std::string("#") + name);
	}
}
<commit_msg>avoid unused function warning<commit_after>#pragma once
#include <silicium/html/tree.hpp>

//----------------TITLE tag----------------
template <class Element>
auto html(Element &&content)
{
	return Si::html::tag("html", std::forward<Element>(content));
}

template <class Element>
auto head(Element &&content)
{
	return Si::html::tag("head", std::forward<Element>(content));
}

template <class Element>
auto body(Element &&content)
{
	return Si::html::tag("body", std::forward<Element>(content));
}

//----------------TITLE tag----------------
inline auto title(std::string const &content)
{
	using namespace Si::html;
	return tag("title", text(content));
}

//----------------H1 tag----------------
template <class Element>
auto h1(Element &&content)
{
	using namespace Si::html;
	return tag("h1", std::forward<Element>(content));
}

//----------------H2 tag----------------
template <class Element>
auto h2(Element &&content)
{
	using namespace Si::html;
	return tag("h2", std::forward<Element>(content));
}

//----------------H3 tag----------------
template <class Element>
auto h3(Element &&content)
{
	using namespace Si::html;
	return tag("h3", std::forward<Element>(content));
}

//----------------H4 tag----------------
template <class Element>
auto h4(Element &&content)
{
	using namespace Si::html;
	return tag("h4", std::forward<Element>(content));
}

//----------------MENU tag----------------
template <class Element>
auto menu(Element &&content)
{
	return Si::html::tag("menu", std::forward<Element>(content));
}

//----------------FOOTER tag----------------
template <class Element>
auto footer(Element &&content)
{
	return Si::html::tag("footer", std::forward<Element>(content));
}

//----------------P tag----------------
inline auto p(std::string const &content)
{
	using namespace Si::html;
	return tag("p", text(content));
}

template <class Element, class Attributes>
auto p(Attributes &&attributes, Element &&content)
{
	return Si::html::tag("p", std::forward<Attributes>(attributes),
	                     std::forward<Element>(content));
}

//----------------DIV tag----------------
template <class Element>
auto div(Element &&content)
{
	return Si::html::tag("div", std::forward<Element>(content));
}

template <class Element, class Attributes>
auto div(Attributes &&attributes, Element &&content)
{
	return Si::html::tag("div", std::forward<Attributes>(attributes),
	                     std::forward<Element>(content));
}

//----------------SPAN tag----------------
template <class Element>
auto span(Element &&content)
{
	return Si::html::tag("span", std::forward<Element>(content));
}

template <class Element, class Attributes>
auto span(Attributes &&attributes, Element &&content)
{
	return Si::html::tag("span", std::forward<Attributes>(attributes),
	                     std::forward<Element>(content));
}

//----------------table tags----------------
template <class Element>
auto table(Element &&content)
{
	return Si::html::tag("table", std::forward<Element>(content));
}

template <class Element>
auto table(std::string const &summary, Element &&content)
{
	return Si::html::tag("table", Si::html::attribute("summary", summary),
	                     std::forward<Element>(content));
}

template <class Element>
auto thead(Element &&content)
{
	return Si::html::tag("thead", std::forward<Element>(content));
}

template <class Element>
auto tbody(Element &&content)
{
	return Si::html::tag("tbody", std::forward<Element>(content));
}

template <class Element>
auto tfoot(Element &&content)
{
	return Si::html::tag("tfoot", std::forward<Element>(content));
}

//----------------TD tag----------------
template <class Element>
auto td(Element &&content)
{
	return Si::html::tag("td", std::forward<Element>(content));
}

//----------------UL tag----------------
template <class Element>
auto ul(Element &&content)
{
	return Si::html::tag("ul", std::forward<Element>(content));
}

template <class Element, class Attributes>
auto ul(Attributes &&attributes, Element &&content)
{
	return Si::html::tag("ul", std::forward<Attributes>(attributes),
	                     std::forward<Element>(content));
}

//----------------LI tag----------------
template <class Element>
auto li(Element &&content)
{
	return Si::html::tag("li", std::forward<Element>(content));
}

//----------------PRE tag----------------
template <class Element>
auto pre(Element &&content)
{
	return Si::html::tag("pre", std::forward<Element>(content));
}

template <class Element, class Attributes>
auto pre(Attributes &&attributes, Element &&content)
{
	return Si::html::tag("pre", std::forward<Attributes>(attributes),
	                     std::forward<Element>(content));
}

template <class Attributes>
auto br(Attributes &&attributes)
{
	using namespace Si::html;
	return tag("br", std::forward<Attributes>(attributes), empty);
}

//----------------classes attrib----------------
inline auto cl(std::string const &content)
{
	return Si::html::attribute("class", content);
}

//----------------href attrib----------------
inline auto href(std::string const &content)
{
	return Si::html::attribute("href", content);
}

// PSEUDO TAG: link (emulates the a-tag)
template <std::size_t N>
auto link(std::string const &protocol, char const(&address_without_protocol)[N],
          std::string const &caption)
{
	using namespace Si::html;
	return dynamic(
	    [protocol, &address_without_protocol, caption](code_sink &sink)
	    {
		    if (protocol == "http://" || protocol == "https://")
		    {
			    tag("a", href(protocol + address_without_protocol) +
			                 attribute("target", "_blank"),
			        text(caption))
			        .generate(sink);
		    }
		    else
		    {
			    tag("a", href(protocol + address_without_protocol),
			        text(caption))
			        .generate(sink);
		    }
		});
}

template <std::size_t N>
auto link(std::string const &protocol, char const(&address_without_protocol)[N])
{
	return link(protocol, address_without_protocol, address_without_protocol);
}

// PSEUDO ATTRIBUTE: anchor_attributes (emulates a jump mark on a page)
template <std::size_t N>
auto anchor_attributes(char const(&name)[N])
{
	using namespace Si::html;
	return attribute("name", name) + href(std::string("#") + name);
}
<|endoftext|>


<commit_before>#ifndef _http_Message__
#define _http_Message__

// Copyright(c) Andre Caron <andre.l.caron@gmail.com>, 2011
//
// This document is covered by the an Open Source Initiative approved license. A
// copy of the license should have been provided alongside this software package
// (see "LICENSE.txt"). If not, terms of the license are available online at
// "http://www.opensource.org/licenses/mit".

#include <http_parser.h>

#include <map>
#include <string>

namespace http {

    class Flags;

        /*!
         * @brief Common denominator of @c Request and @c Response classes.
         *
         * This classes is an implementation detail and should not be
         * instantiated directly.  You should use its services through instances
         * of the the @c Request and @c Response classes instead.
         */
    class Message
    {
        /* nested types. */
    private:
        typedef std::map<std::string, std::string> Headers;

        /* class methods. */
    private:
        static int on_message_begin ( ::http_parser * parser );

        static int on_message_complete ( ::http_parser * parser );

        static int on_header_field
            ( ::http_parser * parser, const char * data, size_t size );

        static int on_header_value
            ( ::http_parser * parser, const char * data, size_t size );

        static int on_headers_complete ( ::http_parser * parser );

        static int on_body
            ( ::http_parser * parser, const char * data, size_t size );

        /* data. */
    protected:
        ::http_parser_settings mySettings;
        ::http_parser myParser;

            // Accumulate info, then push to map.
        std::string myCurrentField;
        std::string myCurrentValue;
        std::map<std::string, std::string> myHeaders;

            // Accumulate whole body.
        std::string myBody;

            // Signal when message is complete.
        bool myComplete;
        bool myHeadersComplete;

        /* construction. */
    protected:
            /*!
             * @brief Build a fresh, independant HTTP parser.
             */
        Message ();

    private:
           // Not copyable.
        Message ( const Message& );

        /* methods. */
    public:
            /*!
             * @brief Empty all request content, but keep allocated buffers.
             */
        void clear ();

            /*!
             * @brief Feed data to the parser.
             * @param data Address of first byte to read.
             * @param size Number of bytes to read, starting at @a data.
             * @return Number of bytes processed.
             *
             * @see complete()
             */
        std::size_t feed ( const void * data, ::size_t size );

            /*!
             * @brief Feed data to the parser.
             * @param data Address of first byte to read.
             * @param size Number of bytes to read, starting at @a data.
             * @return Number of bytes processed.
             *
             * @see complete()
             */
        std::size_t feed ( const char * data, ::size_t size );

           /*!
            * @brief Check if the request has been completely parsed.
            */
        bool complete () const;

           /*!
            * @brief Check if the request headers have been completely parsed.
            */
        bool headers_complete () const;

            /*!
             * @brief Obtain the HTTP version used by the remote peer.
             * @return A numeric error code (should be 1 for now).
             */
        int major_version () const;

            /*!
             * @brief Obtain the HTTP revision used by the remote peer.
             * @return A numeric error code (should be 0 or 1 for now).
             */
        int minor_version () const;

            /*!
             * @brief Obtain parser flags.
             * @return Flags documenting the parsed request/response object.
             */
        const Flags flags () const;

            /*!
             * @brief Check if the request included a header named @a field.
             * @param field Name of header to check.
             *
             * @warning This value is unspecified until @c headerscomplete()
             *  returns @c true.
             */
        bool has_header ( const std::string& field ) const;

            /*!
             * @brief Obtain the value of the header named @a field.
             * @param field Name of header to check.
             * @return An empty string if the header was not present, the header
             *  value otherwise.
             *
             * @warning This value is unspecified until @c headerscomplete()
             *  returns @c true.
             */
        std::string header ( const std::string& field ) const;

            /*!
             * @brief Obtain the entire request body.
             *
             * @warning This value is undefined until @c complete() returns
             *  @c true.
             */
        const std::string& body () const;

        /* operators. */
    private:
           // Not copyable.
        Message& operator= ( const Message& );
    };

}

#endif /* _http_Message__ */
<commit_msg>Make http::Message copyable<commit_after>#ifndef _http_Message__
#define _http_Message__

// Copyright(c) Andre Caron <andre.l.caron@gmail.com>, 2011
//
// This document is covered by the an Open Source Initiative approved license. A
// copy of the license should have been provided alongside this software package
// (see "LICENSE.txt"). If not, terms of the license are available online at
// "http://www.opensource.org/licenses/mit".

#include <http_parser.h>

#include <map>
#include <string>

namespace http {

    class Flags;

        /*!
         * @brief Common denominator of @c Request and @c Response classes.
         *
         * This classes is an implementation detail and should not be
         * instantiated directly.  You should use its services through instances
         * of the the @c Request and @c Response classes instead.
         */
    class Message
    {
        /* nested types. */
    private:
        typedef std::map<std::string, std::string> Headers;

        /* class methods. */
    private:
        static int on_message_begin ( ::http_parser * parser );

        static int on_message_complete ( ::http_parser * parser );

        static int on_header_field
            ( ::http_parser * parser, const char * data, size_t size );

        static int on_header_value
            ( ::http_parser * parser, const char * data, size_t size );

        static int on_headers_complete ( ::http_parser * parser );

        static int on_body
            ( ::http_parser * parser, const char * data, size_t size );

        /* data. */
    protected:
        ::http_parser_settings mySettings;
        ::http_parser myParser;

            // Accumulate info, then push to map.
        std::string myCurrentField;
        std::string myCurrentValue;
        std::map<std::string, std::string> myHeaders;

            // Accumulate whole body.
        std::string myBody;

            // Signal when message is complete.
        bool myComplete;
        bool myHeadersComplete;

        /* construction. */
    protected:
            /*!
             * @brief Build a fresh, independant HTTP parser.
             */
        Message ();

    private:
           // Not copyable.
        //Message ( const Message& );

        /* methods. */
    public:
            /*!
             * @brief Empty all request content, but keep allocated buffers.
             */
        void clear ();

            /*!
             * @brief Feed data to the parser.
             * @param data Address of first byte to read.
             * @param size Number of bytes to read, starting at @a data.
             * @return Number of bytes processed.
             *
             * @see complete()
             */
        std::size_t feed ( const void * data, ::size_t size );

            /*!
             * @brief Feed data to the parser.
             * @param data Address of first byte to read.
             * @param size Number of bytes to read, starting at @a data.
             * @return Number of bytes processed.
             *
             * @see complete()
             */
        std::size_t feed ( const char * data, ::size_t size );

           /*!
            * @brief Check if the request has been completely parsed.
            */
        bool complete () const;

           /*!
            * @brief Check if the request headers have been completely parsed.
            */
        bool headers_complete () const;

            /*!
             * @brief Obtain the HTTP version used by the remote peer.
             * @return A numeric error code (should be 1 for now).
             */
        int major_version () const;

            /*!
             * @brief Obtain the HTTP revision used by the remote peer.
             * @return A numeric error code (should be 0 or 1 for now).
             */
        int minor_version () const;

            /*!
             * @brief Obtain parser flags.
             * @return Flags documenting the parsed request/response object.
             */
        const Flags flags () const;

            /*!
             * @brief Check if the request included a header named @a field.
             * @param field Name of header to check.
             *
             * @warning This value is unspecified until @c headerscomplete()
             *  returns @c true.
             */
        bool has_header ( const std::string& field ) const;

            /*!
             * @brief Obtain the value of the header named @a field.
             * @param field Name of header to check.
             * @return An empty string if the header was not present, the header
             *  value otherwise.
             *
             * @warning This value is unspecified until @c headerscomplete()
             *  returns @c true.
             */
        std::string header ( const std::string& field ) const;

            /*!
             * @brief Obtain the entire request body.
             *
             * @warning This value is undefined until @c complete() returns
             *  @c true.
             */
        const std::string& body () const;

        /* operators. */
    private:
           // Not copyable.
        Message& operator= ( const Message& );
    };

}

#endif /* _http_Message__ */
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2227
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1319819 by johtaylo@johtaylo-jtincrementor-increment on 2016/09/28 03:00:08<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2228
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>