<commit_before>#include <Halide.h>
#include <stdio.h>
#include <stdlib.h>

#include <functional>

using namespace Halide;

int test_per_channel_select() {

    Func gpu("gpu"), cpu("cpu");
    Var x("x"), y("y"), c("c");

    gpu(x, y, c) = cast<uint8_t>(select(c == 0, 128,
                                        c == 1, x,
                                        c == 2, y,
                                        x*y));
    gpu.bound(c, 0, 4);
    gpu.glsl(x, y, c);
    gpu.compute_root();

    cpu(x, y, c) = gpu(x, y, c);

    Image<uint8_t> out(10, 10, 4);
    cpu.realize(out);

    // Verify the result
    for (int y=0; y!=out.height(); ++y) {
        for (int x=0; x!=out.width(); ++x) {
            for (int c=0; c!=out.channels(); ++c) {
                uint8_t expected;
                switch (c) {
                    case 0: expected = 128; break;
                    case 1: expected = x; break;
                    case 2: expected = y; break;
                    default: expected = x*y; break;
                }
                uint8_t actual  = out(x,y,c);

                if (expected != actual) {
                    fprintf(stderr, "Incorrect pixel (%d, %d, %d, %d) at x=%d y=%d.\n",
                            out(x, y, 0), out(x, y, 1), out(x, y, 2), out(x, y, 3),
                            x, y);
                    return 1;
                }
            }
        }
    }

    return 0;
}

int test_flag_scalar_select() {

    Func gpu("gpu"), cpu("cpu");
    Var x("x"), y("y"), c("c");

    int flag_value = 0;

    Param<int> flag("flag");
    flag.set(flag_value);

    gpu(x, y, c) = cast<uint8_t>(select(flag != 0, 128,
                                        255));
    gpu.bound(c, 0, 4);
    gpu.glsl(x, y, c);
    gpu.compute_root();

    // This should trigger a copy_to_host operation
    cpu(x, y, c) = gpu(x, y, c);

    Image<uint8_t> out(10, 10, 4);
    cpu.realize(out);

    // Verify the result
    for (int y=0; y!=out.height(); ++y) {
        for (int x=0; x!=out.width(); ++x) {
            for (int c=0; c!=out.channels(); ++c) {
                uint8_t expected = !flag_value ? 255 : 128;
                uint8_t actual  = out(x,y,c);

                if (expected != actual) {
                    fprintf(stderr, "Incorrect pixel (%d, %d, %d, %d) at x=%d y=%d.\n",
                            out(x, y, 0), out(x, y, 1), out(x, y, 2), out(x, y, 3),
                            x, y);
                    return 1;
                }
            }
        }
    }

    return 0;
}

int test_flag_pixel_select() {

    Func gpu("gpu"), cpu("cpu");
    Var x("x"), y("y"), c("c");

    int flag_value = 0;

    Param<int> flag("flag");
    flag.set(flag_value);

    Image<uint8_t> image(10, 10, 4);
    for (int y=0; y<image.height(); y++) {
        for (int x=0; x<image.width(); x++) {
            for (int c=0; c<image.channels(); c++) {
                image(x, y, c) = 128;
            }
        }
    }

    gpu(x, y, c) = cast<uint8_t>(select(flag != 0, image(x,y,c),
                                        255));
    gpu.bound(c, 0, 4);
    gpu.glsl(x, y, c);
    gpu.compute_root();

    // This should trigger a copy_to_host operation
    cpu(x, y, c) = gpu(x, y, c);

    Image<uint8_t> out(10, 10, 4);
    cpu.realize(out);

    // Verify the result
    for (int y=0; y!=out.height(); ++y) {
        for (int x=0; x!=out.width(); ++x) {
            for (int c=0; c!=out.channels(); ++c) {
                uint8_t expected = !flag_value ? 255 : 128;
                uint8_t actual  = out(x,y,c);

                if (expected != actual) {
                    fprintf(stderr, "Incorrect pixel (%d, %d, %d, %d) at x=%d y=%d.\n",
                            out(x, y, 0), out(x, y, 1), out(x, y, 2), out(x, y, 3),
                            x, y);
                    return 1;
                }
            }
        }
    }

    return 0;
}

int main() {

    // This test must be run with an OpenGL target
    const Target &target = get_jit_target_from_environment();
    if (!target.has_feature(Target::OpenGL))  {
        fprintf(stderr,"ERROR: This test must be run with an OpenGL target, e.g. by setting HL_JIT_TARGET=host-opengl.\n");
        return 1;
    }

    int err = 0;

    err |= test_per_channel_select();
    err |= test_flag_scalar_select();
    err |= test_flag_pixel_select();

    if (err) {
        printf("FAILED\n");
        return 1;
    }

    printf("Success!\n");
    return 0;
}
<commit_msg>Removed unnecessary include<commit_after>#include <Halide.h>
#include <stdio.h>
#include <stdlib.h>

using namespace Halide;

int test_per_channel_select() {

    Func gpu("gpu"), cpu("cpu");
    Var x("x"), y("y"), c("c");

    gpu(x, y, c) = cast<uint8_t>(select(c == 0, 128,
                                        c == 1, x,
                                        c == 2, y,
                                        x*y));
    gpu.bound(c, 0, 4);
    gpu.glsl(x, y, c);
    gpu.compute_root();

    cpu(x, y, c) = gpu(x, y, c);

    Image<uint8_t> out(10, 10, 4);
    cpu.realize(out);

    // Verify the result
    for (int y=0; y!=out.height(); ++y) {
        for (int x=0; x!=out.width(); ++x) {
            for (int c=0; c!=out.channels(); ++c) {
                uint8_t expected;
                switch (c) {
                    case 0: expected = 128; break;
                    case 1: expected = x; break;
                    case 2: expected = y; break;
                    default: expected = x*y; break;
                }
                uint8_t actual  = out(x,y,c);

                if (expected != actual) {
                    fprintf(stderr, "Incorrect pixel (%d, %d, %d, %d) at x=%d y=%d.\n",
                            out(x, y, 0), out(x, y, 1), out(x, y, 2), out(x, y, 3),
                            x, y);
                    return 1;
                }
            }
        }
    }

    return 0;
}

int test_flag_scalar_select() {

    Func gpu("gpu"), cpu("cpu");
    Var x("x"), y("y"), c("c");

    int flag_value = 0;

    Param<int> flag("flag");
    flag.set(flag_value);

    gpu(x, y, c) = cast<uint8_t>(select(flag != 0, 128,
                                        255));
    gpu.bound(c, 0, 4);
    gpu.glsl(x, y, c);
    gpu.compute_root();

    // This should trigger a copy_to_host operation
    cpu(x, y, c) = gpu(x, y, c);

    Image<uint8_t> out(10, 10, 4);
    cpu.realize(out);

    // Verify the result
    for (int y=0; y!=out.height(); ++y) {
        for (int x=0; x!=out.width(); ++x) {
            for (int c=0; c!=out.channels(); ++c) {
                uint8_t expected = !flag_value ? 255 : 128;
                uint8_t actual  = out(x,y,c);

                if (expected != actual) {
                    fprintf(stderr, "Incorrect pixel (%d, %d, %d, %d) at x=%d y=%d.\n",
                            out(x, y, 0), out(x, y, 1), out(x, y, 2), out(x, y, 3),
                            x, y);
                    return 1;
                }
            }
        }
    }

    return 0;
}

int test_flag_pixel_select() {

    Func gpu("gpu"), cpu("cpu");
    Var x("x"), y("y"), c("c");

    int flag_value = 0;

    Param<int> flag("flag");
    flag.set(flag_value);

    Image<uint8_t> image(10, 10, 4);
    for (int y=0; y<image.height(); y++) {
        for (int x=0; x<image.width(); x++) {
            for (int c=0; c<image.channels(); c++) {
                image(x, y, c) = 128;
            }
        }
    }

    gpu(x, y, c) = cast<uint8_t>(select(flag != 0, image(x,y,c),
                                        255));
    gpu.bound(c, 0, 4);
    gpu.glsl(x, y, c);
    gpu.compute_root();

    // This should trigger a copy_to_host operation
    cpu(x, y, c) = gpu(x, y, c);

    Image<uint8_t> out(10, 10, 4);
    cpu.realize(out);

    // Verify the result
    for (int y=0; y!=out.height(); ++y) {
        for (int x=0; x!=out.width(); ++x) {
            for (int c=0; c!=out.channels(); ++c) {
                uint8_t expected = !flag_value ? 255 : 128;
                uint8_t actual  = out(x,y,c);

                if (expected != actual) {
                    fprintf(stderr, "Incorrect pixel (%d, %d, %d, %d) at x=%d y=%d.\n",
                            out(x, y, 0), out(x, y, 1), out(x, y, 2), out(x, y, 3),
                            x, y);
                    return 1;
                }
            }
        }
    }

    return 0;
}

int main() {

    // This test must be run with an OpenGL target
    const Target &target = get_jit_target_from_environment();
    if (!target.has_feature(Target::OpenGL))  {
        fprintf(stderr,"ERROR: This test must be run with an OpenGL target, e.g. by setting HL_JIT_TARGET=host-opengl.\n");
        return 1;
    }

    int err = 0;

    err |= test_per_channel_select();
    err |= test_flag_scalar_select();
    err |= test_flag_pixel_select();

    if (err) {
        printf("FAILED\n");
        return 1;
    }

    printf("Success!\n");
    return 0;
}
<|endoftext|>


<commit_before>#ifndef QUEUES_H_INCLUDED
#define QUEUES_H_INCLUDED

#include <wiz/global.h>
#include <wiz/wizardError.h>
#include <wiz/newarrays.h>

/// #define QUEUES_DEBUG

namespace wiz{
class QueueEmptyError : public wiz::Error
{
public:
    QueueEmptyError() : wiz::Error( "queueEmptyError" )
    {

    }
};
class QueueFullError : public wiz::Error
{
public:
    QueueFullError() : wiz::Error( "queueFullError" )
    {

    }
};

// check array Queue, array stack?
template <typename T>
class Queue //: public wizObject
{
private:
    class Element
    {
    public:
        Element* next;
        T data;
    public:
        explicit Element( const T d = T() )
        {
            data = d;
            next =  nullptr;
        }
    };
private:
    Element* Head; //
    Element* Rear; //
public:
    explicit Queue() : Head( nullptr ), Rear( nullptr ) { Head = new Element(); Rear = Head; }

    virtual ~Queue(){
        clear();
        delete Head; Head = Rear = nullptr;
    }
    void clear()
    {
        while( !isEmpty() ){
           deleteq();
        }
     }
    bool isEmpty() const
    {
        return nullptr == Head->next; /// size == 0, empty..
    }
    bool empty() const { return isEmpty(); }
    //
    void addq( const T& p ) /// push
    {
        Element* temp = new Element(p); //
        //
        Rear->next = temp;//
        temp->next = nullptr;// auto look def of Element
        Rear = Rear->next; //
    }//
    void push( const T& p ) { addq( p ); }
    T deleteq(){ /// pop
        if( isEmpty() )
        {
            throw QueueEmptyError();
        }
        //
        Element* temp = Head->next;//
        Head->next = temp->next;
        //Rear 처리
        if( nullptr == Head->next )
            Rear = Head;
        T returnTemp = temp->data;
        delete temp;
        return returnTemp;
    }
    T pop() { return deleteq(); }
    Queue& operator<<( const T& p ){
        addq( p ); //
        return *this;
    }
private:
    void copy( const Queue<T>& q )
    {
        //this->clear();

        Element* qTemp = q.Head->next;

        while( qTemp != nullptr )
        {
            addq( qTemp->data );
            qTemp = qTemp->next;
        }
    }
public:
    //
    Queue( const Queue<T>& q ) : Head( nullptr ), Rear( nullptr )
    {// clear();
        Head = new Element(); Rear = Head;
        copy( q );
    }
    Queue& operator=( const Queue<T>& q )
    {
        if( Head == q.Head ) { return *this; }

        clear();

        // head, rear reser..!!
        copy( q );

        return *this;
    }
    Queue( Queue<T>&& q )
    {
        Head->next = q.Head->next;
        Rear = q.Rear;

        /// do-empty..
        q.Head->next = nullptr;
        q.Rear = q.Head;
    }
    Queue<T>& operator=( Queue<T>&& q )
    {
        if( Head == q.Head ) { return *this; }
        this->clear();
        Head->next = q.Head->next;
        Rear = q.Rear;

q.Head->next = nullptr;
q.Rear = q.Head;
return *this;
	}
};

// Queue using Array
template <class T>
class ArrayQueue
{
public:
	ArrayQueue(const ArrayQueue<T>& aq)
		:que(aq.que), start(aq.start), num(aq.num)
	{
		//
	}
	ArrayQueue(ArrayQueue<T>&& aq)
	{
		que = std::move(aq.que);
		start = aq.start;
		num = aq.num;

		aq.que = Array<T>(2);
		aq.start = 0;
		aq.num = 0;
	}
	ArrayQueue<T>& operator=(ArrayQueue<T>&& aq)
	{
		if (que == aq.que) { return *this; }
		this->que.DoEmpty();
		que = std::move(aq.que);
		start = aq.start;
		num = aq.num;

		aq.que = Array<T>(2);
		aq.start = 0;
		aq.num = 0;
		return *this;
	}
	ArrayQueue<T>& operator=(const ArrayQueue<T>& aq)
	{
		if (que == aq.que) { return *this; }
		que.DoEmpty();
		this->que = aq.que;
		this->start = aq.start;
		this->num = aq.num;
		return *this;
	}
private:
	Array<T> que;
	int start;
	int num;
public:
	explicit ArrayQueue(const int max = 2) : start(0), num(0)
	{
#ifdef QUEUES_DEBUG
		// max > 0
		wiz::checkUnderError(0, max, 1);
#endif
		que = Array<T>(max);
	}
	virtual ~ArrayQueue()
	{
	}
public:
	const T& operator[](const int idx) const
	{
		return que[(start + idx) & (que.size() - 1)];
	}
	T& operator[](const int idx)
	{
		return que[(start + idx) & (que.size() - 1)];
	}
public:
	void push(const ArrayQueue<T>& val) {
		if (val.empty()) { return; }
		int newSize = this->que.size();

		while (newSize - num < val.size()) {
			newSize = newSize * 2;
		}
		if (newSize != this->que.size()) {
			// expand array queue.
			ArrayQueue<T> temp(newSize);
			temp.start = 0;
			//
			for (int i = 0; i < this->size(); ++i) {
				temp[i] = std::move((*this)[i]);
			}

			const int iend = val.num;
			for (int i = 0; i < iend; ++i) {
				temp[i + this->num] = val[i];
			}

			temp.num = this->num + val.num;
			*this = std::move(temp);
		}
		else {
			for (int i = 0; i < val.size(); ++i) {
				this->push(val.que[i]);
			}
		}
	}
	void push(ArrayQueue<T>&& val) { // chk..
		if (val.empty()) { return; }
		int newSize = this->que.size();

		while (newSize - num < val.size()) {
			newSize = newSize * 2;
		}
		if (newSize != this->que.size()) {
			// expand array queue.
			ArrayQueue temp(newSize);
			temp.start = 0;
			//
			for (int i = 0; i < this->size(); ++i) {
				temp[i] = std::move((*this)[i]);
			}

			const int iend = val.num;
			for (int i = 0; i < iend; ++i) {
				temp[i + this->num] = std::move(val[i]);
			}

			temp.num = this->num + val.num;
			*this = std::move(temp);
		}
		else {
			for (int i = 0; i < val.size(); ++i) {
				this->push(std::move(val[i]));
			}
		}
	}
    void push( const T& val )
    {
        if( isFull() )
        {
            // expand array queue.
            ArrayQueue temp( que.size() * 2 );
            //
			for (int i = 0; i < que.size(); ++i) {
				temp[i] = std::move(que[(start + i) & (que.size()-1)]);
			}
			temp.start = 0;
			temp.num = que.size();

            *this = std::move( temp );
        }
        que[(start+num) & (que.size()-1)] = val;
        num++;
    }

	void push(T&& val)
	{
		if (isFull())
		{
			// expand array queue.
			ArrayQueue temp(que.size() * 2);
			//
			for (int i = 0; i < que.size(); ++i) {
				temp[i] = std::move(que[(start + i) & (que.size()-1)]);
			}
			temp.start = 0;
			temp.num = que.size();

			*this = std::move(temp);
		}
		que[(start + num) & (que.size()-1)] = std::move(val);
		num++;
	}

	void pop(T* t = nullptr) {
		if (isEmpty()) { throw QueueEmptyError(); }

		T temp = std::move(que[start]);

		//que[start] = T();

		start = (start + 1) & (que.size() - 1); // % que.size(), 2^n.
		num--;

		if (nullptr != t) {
			*t = move(temp);
		}
	}

	T pop_back()
	{
		if (isEmpty()) { throw QueueEmptyError(); }
		T temp = std::move((*this)[num - 1]);

		//(*this)[num - 1] = T();

		num--;

		return temp;
	}

    bool isFull()const
    {
        return num >= ( que.size() );
    }

    bool isEmpty()const
    {
        return 0 == num;
    }
    int size()const{ return num; }
    bool empty()const { return isEmpty(); }
    int getNumMax()const { return que.size(); }
    int getNum()const { return num; }
    Array<T> toArray()const
    {
        Array<T> temp;

        if( num > 0 )
        {
            temp = Array<T>( num );
            int count=0;

            for( int i=0; i < num; i++ )
            {
                temp[i] = que[ ( start + i ) % (que.size()) ];
            }
        }

        return temp;
    }

    ArrayQueue<T>& operator<<( const T& data )
    {
        push( data );

        return *this;
    }
};

}
#endif // QUEUES_H_INCLUDED
<commit_msg>Delete QUEUES.H<commit_after><|endoftext|>


<commit_before>// @(#)root/utils:$Name:  $:$Id: rlibmap.cxx,v 1.12 2004/05/17 17:40:00 rdm Exp $
// Author: Fons Rademakers   05/12/2003

/*************************************************************************
 * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

// This program generates a map between class name and shared library.
// Its output is in TEnv format.
// Usage: rlibmap [-f] [-o <mapfile>] -l <sofile> -d <depsofiles>
//                 -c <linkdeffiles>
// -f: output full library path name (not needed when ROOT library
//     search path is used)
// -o: write output to specified file, otherwise to stdout
// -r: replace existing entries in the specified file
// -l: library containing the classes in the specified linkdef files
// -d: libraries on which the -l library depends
// -c: linkdef files containing the list of classes defined in the -l library

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string>
#include <vector>
#ifndef WIN32
#   include <unistd.h>
#else
#   define ssize_t int
#   include <io.h>
#   include <sys/types.h>
#endif

#ifdef __APPLE__
#include <AvailabilityMacros.h>
#endif
#if (defined(__FreeBSD__) && (__FreeBSD__ < 4)) || \
    (defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_10_3) || \
     (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_3)))
#include <sys/file.h>
#define lockf(fd, op, sz)   flock((fd), (op))
#ifndef F_LOCK
#define F_LOCK             (LOCK_EX | LOCK_NB)
#endif
#ifndef F_ULOCK
#define F_ULOCK             LOCK_UN
#endif
#endif

#if defined(__CYGWIN__) && defined(__GNUC__)
#define F_LOCK F_WRLCK
#define F_ULOCK F_UNLCK
static int fcntl_lockf(int fd, int op, off_t off)
{
   flock fl;
   fl.l_whence = SEEK_SET;
   fl.l_start  = off;
   fl.l_len    = 0;       // whole file
   fl.l_pid    = getpid();
   fl.l_type   = op;
   return fcntl(fd, F_SETLK, &fl);
}
#define lockf fcntl_lockf
#endif

const char *usage = "Usage: %s [-f] [<-r|-o> <mapfile>] -l <sofile> -d <depsofiles> -c <linkdeffiles>\n";

namespace std {}
using namespace std;

#ifdef WIN32
#include <windows.h>

#define ftruncate(fd, size)  win32_ftruncate(fd, size)

//______________________________________________________________________________
int win32_ftruncate(int fd, ssize_t size)
{
   HANDLE hfile;
   int curpos;

   if (fd < 0) return -1;

   hfile = (HANDLE) _get_osfhandle(fd);
   curpos = ::SetFilePointer(hfile, 0, 0, FILE_CURRENT);
   if (curpos == 0xFFFFFFFF ||
       ::SetFilePointer(hfile, size, 0, FILE_BEGIN) == 0xFFFFFFFF ||
       !::SetEndOfFile(hfile)) {
         int error = ::GetLastError();

      switch (error) {
         case ERROR_INVALID_HANDLE:
            errno = EBADF;
            break;
         default:
            errno = EIO;
         break;
      }
      return -1;
   }
   return 0;
}

#endif // WIN32

//______________________________________________________________________________
char *Compress(const char *str)
{
   // Remove all blanks from the string str. The returned string has to be
   // deleted by the user.

   if (!str) return 0;

   const char *p = str;
   // allocate 20 extra characters in case of eg, vector<vector<T>>
   char *s, *s1 = new char[strlen(str)+20];
   s = s1;

   while (*p) {
      if (*p != ' ')
         *s++ = *p;
      p++;
   }
   *s = '\0';

   return s1;
}

//______________________________________________________________________________
int RemoveLib(const string &solib, bool fullpath, FILE *fp)
{
   // Remove entries from the map file for the specified solib.

   fseek(fp, 0, SEEK_SET);

   // get file size
   struct stat sbuf;
   fstat(fileno(fp), &sbuf);
   size_t siz = sbuf.st_size;

   if (!siz) return 0;

   const char *libbase = solib.c_str();
   if (!fullpath) {
      if ((libbase = strrchr(libbase, '/')))
         libbase++;
   }

   // read file and remove lines matching specified libs
   char *fbuf = new char[siz+1];
   char *fptr = fbuf;

   while (fgets(fptr, siz - size_t(fptr-fbuf), fp)) {

      char *line = new char[strlen(fptr)+1];
      strcpy(line, fptr);
      strtok(line, " ");
      char *lib = strtok(0, " \n");
      if (lib && strcmp(lib, libbase)) {
         fptr += strlen(fptr);
         if (*(fptr-1) != '\n') {
            *fptr = '\n';
            fptr++;
         }
      }
      delete [] line;

      // fgets() should return 0 in this case but doesn't
      if (siz - size_t(fptr - fbuf) <= 0)
         break;
   }

   ftruncate(fileno(fp), 0);

   // write remaining lines back
   if (fptr != fbuf) {
      fseek(fp, 0, SEEK_SET);
      fwrite(fbuf, 1, size_t(fptr-fbuf), fp);
   }

   delete [] fbuf;

   fseek(fp, 0, SEEK_END);

   return 0;
}

//______________________________________________________________________________
int LibMap(const string &solib, const vector<string> &solibdeps,
           const vector<string> &linkdefs, bool fullpath, FILE *fp)
{
   // Write libmap. Returns -1 in case of error.

   vector<string> classes;

   vector<string>::const_iterator lk;
   for (lk = linkdefs.begin(); lk != linkdefs.end(); lk++) {
      const char *linkdef = lk->c_str();
      FILE *lfp;
      char pragma[1024];
      if ((lfp = fopen(linkdef, "r"))) {
         while (fgets(pragma, 1024, lfp)) {
            if (!strcmp(strtok(pragma, " "), "#pragma") &&
                !strcmp(strtok(0,      " "), "link")    &&
                !strcmp(strtok(0,      " "), "C++")     &&
                !strcmp(strtok(0,      " "), "class")) {
               char *cls = strtok(0, "-!+;");
               // just in case remove trailing space and tab
               while (*cls == ' ') cls++;
               int len = strlen(cls) - 1;
               while (cls[len] == ' ' || cls[len] == '\t')
                  cls[len--] = '\0';
               //no space between tmpl arguments allowed
               cls = Compress(cls);

               // don't include "vector<string>" and "std::pair<" classes
               if (!strncmp(cls, "vector<string>", 14) ||
                   !strncmp(cls, "std::pair<", 10))
                  continue;

               // replace "::" by "@@" since TEnv uses ":" as delimeter
               char *s = cls;
               while (*s) {
                  if (*s == ':') *s = '@';
                  s++;
               }
               classes.push_back(cls);
            }
         }
         fclose(lfp);
      } else {
         fprintf(stderr, "cannot open linkdef file %s\n", linkdef);
      }
   }

   const char *libbase = solib.c_str();
   if (!fullpath) {
      if ((libbase = strrchr(libbase, '/')))
         libbase++;
   }

   vector<string>::const_iterator it;
   for (it = classes.begin(); it != classes.end(); it++) {
      fprintf(fp, "Library.%-35s %s", ((*it)+":").c_str(), libbase);

      if (solibdeps.size() > 0) {
         vector<string>::const_iterator depit;
         for (depit = solibdeps.begin(); depit != solibdeps.end(); depit++) {
            const char *deplib = depit->c_str();
            if (!fullpath) {
               if ((deplib = strrchr(deplib, '/')))
                  deplib++;
            }
            fprintf(fp, " %s", deplib);
         }
      }
      fprintf(fp, "\n");
   }

   return 0;
}

//______________________________________________________________________________
int main(int argc, char **argv)
{
   string         solib;
   vector<string> solibdeps;
   vector<string> linkdefs;
   bool fullpath = false;
   bool replace  = false;
   FILE *fp      = stdout;

   if (argc > 1) {
      int ic = 1;
      if (!strcmp(argv[ic], "-?") || !strcmp(argv[ic], "-h")) {
         fprintf(stderr, usage, argv[0]);
         return 1;
      }
      if (!strcmp(argv[ic], "-f")) {
         fullpath = true;
         ic++;
      }
      if (!strcmp(argv[ic], "-o")) {
         ic++;
         fp = fopen(argv[ic], "w");
         if (!fp) {
            fprintf(stderr, "cannot open output file %s\n", argv[ic]);
            return 1;
         }
         ic++;
      }
      if (!strcmp(argv[ic], "-r")) {
         replace = true;
         ic++;
         fp = fopen(argv[ic], "a+");
         if (!fp) {
            fprintf(stderr, "cannot open output file %s\n", argv[ic]);
            return 1;
         }
         ic++;
      }
      if (!strcmp(argv[ic], "-l")) {
         ic++;
         solib = argv[ic];
#ifdef __APPLE__
         string::size_type i = solib.find(".dylib");
         if (i != string::npos)
            solib.replace(i, 6, ".so");
#endif
         ic++;
      }
      if (!strcmp(argv[ic], "-d")) {
         ic++;
         for (int i = ic; i < argc && argv[i][0] != '-'; i++) {
            string dl = argv[i];
#ifdef __APPLE__
            string::size_type i = dl.find(".dylib");
            if (i != string::npos)
               dl.replace(i, 6, ".so");
#endif
            solibdeps.push_back(dl);
            ic++;
         }
      }
      if (!strcmp(argv[ic], "-c")) {
         ic++;
         for (int i = ic; i < argc; i++) {
            linkdefs.push_back(argv[i]);
            ic++;
         }
      }
   } else {
      fprintf(stderr, usage, argv[0]);
      return 1;
   }

   if (replace) {
#if !defined(WIN32) && !defined(__CYGWIN__)
      // lock file
      if (lockf(fileno(fp), F_LOCK, (off_t)1) == -1) {
         fprintf(stderr, "rlibmap: error locking output file\n");
         fclose(fp);
         return 1;
      }
#endif

      // remove entries for solib to be processed
      RemoveLib(solib, fullpath, fp);
   }

   LibMap(solib, solibdeps, linkdefs, fullpath, fp);

   if (replace) {
#if !defined(WIN32) && !defined(__CYGWIN__)
      // remove lock
      lseek(fileno(fp), 0, SEEK_SET);
      if (lockf(fileno(fp), F_ULOCK, (off_t)1) == -1) {
         fprintf(stderr, "rlibmap: error unlocking output file\n");
         fclose(fp);
         return 1;
      }
#endif
   }

   if (fp != stdout)
      fclose(fp);

   return 0;
}
<commit_msg>disable use of lockf on FreeBSD.<commit_after>// @(#)root/utils:$Name:  $:$Id: rlibmap.cxx,v 1.13 2004/05/19 16:12:58 rdm Exp $
// Author: Fons Rademakers   05/12/2003

/*************************************************************************
 * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

// This program generates a map between class name and shared library.
// Its output is in TEnv format.
// Usage: rlibmap [-f] [-o <mapfile>] -l <sofile> -d <depsofiles>
//                 -c <linkdeffiles>
// -f: output full library path name (not needed when ROOT library
//     search path is used)
// -o: write output to specified file, otherwise to stdout
// -r: replace existing entries in the specified file
// -l: library containing the classes in the specified linkdef files
// -d: libraries on which the -l library depends
// -c: linkdef files containing the list of classes defined in the -l library

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string>
#include <vector>
#ifndef WIN32
#   include <unistd.h>
#else
#   define ssize_t int
#   include <io.h>
#   include <sys/types.h>
#endif

#ifdef __APPLE__
#include <AvailabilityMacros.h>
#endif
#if (defined(__FreeBSD__) && (__FreeBSD__ < 4)) || \
    (defined(__APPLE__) && (!defined(MAC_OS_X_VERSION_10_3) || \
     (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_3)))
#include <sys/file.h>
#define lockf(fd, op, sz)   flock((fd), (op))
#ifndef F_LOCK
#define F_LOCK             (LOCK_EX | LOCK_NB)
#endif
#ifndef F_ULOCK
#define F_ULOCK             LOCK_UN
#endif
#endif

#if defined(__CYGWIN__) && defined(__GNUC__)
#define F_LOCK F_WRLCK
#define F_ULOCK F_UNLCK
static int fcntl_lockf(int fd, int op, off_t off)
{
   flock fl;
   fl.l_whence = SEEK_SET;
   fl.l_start  = off;
   fl.l_len    = 0;       // whole file
   fl.l_pid    = getpid();
   fl.l_type   = op;
   return fcntl(fd, F_SETLK, &fl);
}
#define lockf fcntl_lockf
#endif

const char *usage = "Usage: %s [-f] [<-r|-o> <mapfile>] -l <sofile> -d <depsofiles> -c <linkdeffiles>\n";

namespace std {}
using namespace std;

#ifdef WIN32
#include <windows.h>

#define ftruncate(fd, size)  win32_ftruncate(fd, size)

//______________________________________________________________________________
int win32_ftruncate(int fd, ssize_t size)
{
   HANDLE hfile;
   int curpos;

   if (fd < 0) return -1;

   hfile = (HANDLE) _get_osfhandle(fd);
   curpos = ::SetFilePointer(hfile, 0, 0, FILE_CURRENT);
   if (curpos == 0xFFFFFFFF ||
       ::SetFilePointer(hfile, size, 0, FILE_BEGIN) == 0xFFFFFFFF ||
       !::SetEndOfFile(hfile)) {
         int error = ::GetLastError();

      switch (error) {
         case ERROR_INVALID_HANDLE:
            errno = EBADF;
            break;
         default:
            errno = EIO;
         break;
      }
      return -1;
   }
   return 0;
}

#endif // WIN32

//______________________________________________________________________________
char *Compress(const char *str)
{
   // Remove all blanks from the string str. The returned string has to be
   // deleted by the user.

   if (!str) return 0;

   const char *p = str;
   // allocate 20 extra characters in case of eg, vector<vector<T>>
   char *s, *s1 = new char[strlen(str)+20];
   s = s1;

   while (*p) {
      if (*p != ' ')
         *s++ = *p;
      p++;
   }
   *s = '\0';

   return s1;
}

//______________________________________________________________________________
int RemoveLib(const string &solib, bool fullpath, FILE *fp)
{
   // Remove entries from the map file for the specified solib.

   fseek(fp, 0, SEEK_SET);

   // get file size
   struct stat sbuf;
   fstat(fileno(fp), &sbuf);
   size_t siz = sbuf.st_size;

   if (!siz) return 0;

   const char *libbase = solib.c_str();
   if (!fullpath) {
      if ((libbase = strrchr(libbase, '/')))
         libbase++;
   }

   // read file and remove lines matching specified libs
   char *fbuf = new char[siz+1];
   char *fptr = fbuf;

   while (fgets(fptr, siz - size_t(fptr-fbuf), fp)) {

      char *line = new char[strlen(fptr)+1];
      strcpy(line, fptr);
      strtok(line, " ");
      char *lib = strtok(0, " \n");
      if (lib && strcmp(lib, libbase)) {
         fptr += strlen(fptr);
         if (*(fptr-1) != '\n') {
            *fptr = '\n';
            fptr++;
         }
      }
      delete [] line;

      // fgets() should return 0 in this case but doesn't
      if (siz - size_t(fptr - fbuf) <= 0)
         break;
   }

   ftruncate(fileno(fp), 0);

   // write remaining lines back
   if (fptr != fbuf) {
      fseek(fp, 0, SEEK_SET);
      fwrite(fbuf, 1, size_t(fptr-fbuf), fp);
   }

   delete [] fbuf;

   fseek(fp, 0, SEEK_END);

   return 0;
}

//______________________________________________________________________________
int LibMap(const string &solib, const vector<string> &solibdeps,
           const vector<string> &linkdefs, bool fullpath, FILE *fp)
{
   // Write libmap. Returns -1 in case of error.

   vector<string> classes;

   vector<string>::const_iterator lk;
   for (lk = linkdefs.begin(); lk != linkdefs.end(); lk++) {
      const char *linkdef = lk->c_str();
      FILE *lfp;
      char pragma[1024];
      if ((lfp = fopen(linkdef, "r"))) {
         while (fgets(pragma, 1024, lfp)) {
            if (!strcmp(strtok(pragma, " "), "#pragma") &&
                !strcmp(strtok(0,      " "), "link")    &&
                !strcmp(strtok(0,      " "), "C++")     &&
                !strcmp(strtok(0,      " "), "class")) {
               char *cls = strtok(0, "-!+;");
               // just in case remove trailing space and tab
               while (*cls == ' ') cls++;
               int len = strlen(cls) - 1;
               while (cls[len] == ' ' || cls[len] == '\t')
                  cls[len--] = '\0';
               //no space between tmpl arguments allowed
               cls = Compress(cls);

               // don't include "vector<string>" and "std::pair<" classes
               if (!strncmp(cls, "vector<string>", 14) ||
                   !strncmp(cls, "std::pair<", 10))
                  continue;

               // replace "::" by "@@" since TEnv uses ":" as delimeter
               char *s = cls;
               while (*s) {
                  if (*s == ':') *s = '@';
                  s++;
               }
               classes.push_back(cls);
            }
         }
         fclose(lfp);
      } else {
         fprintf(stderr, "cannot open linkdef file %s\n", linkdef);
      }
   }

   const char *libbase = solib.c_str();
   if (!fullpath) {
      if ((libbase = strrchr(libbase, '/')))
         libbase++;
   }

   vector<string>::const_iterator it;
   for (it = classes.begin(); it != classes.end(); it++) {
      fprintf(fp, "Library.%-35s %s", ((*it)+":").c_str(), libbase);

      if (solibdeps.size() > 0) {
         vector<string>::const_iterator depit;
         for (depit = solibdeps.begin(); depit != solibdeps.end(); depit++) {
            const char *deplib = depit->c_str();
            if (!fullpath) {
               if ((deplib = strrchr(deplib, '/')))
                  deplib++;
            }
            fprintf(fp, " %s", deplib);
         }
      }
      fprintf(fp, "\n");
   }

   return 0;
}

//______________________________________________________________________________
int main(int argc, char **argv)
{
   string         solib;
   vector<string> solibdeps;
   vector<string> linkdefs;
   bool fullpath = false;
   bool replace  = false;
   FILE *fp      = stdout;

   if (argc > 1) {
      int ic = 1;
      if (!strcmp(argv[ic], "-?") || !strcmp(argv[ic], "-h")) {
         fprintf(stderr, usage, argv[0]);
         return 1;
      }
      if (!strcmp(argv[ic], "-f")) {
         fullpath = true;
         ic++;
      }
      if (!strcmp(argv[ic], "-o")) {
         ic++;
         fp = fopen(argv[ic], "w");
         if (!fp) {
            fprintf(stderr, "cannot open output file %s\n", argv[ic]);
            return 1;
         }
         ic++;
      }
      if (!strcmp(argv[ic], "-r")) {
         replace = true;
         ic++;
         fp = fopen(argv[ic], "a+");
         if (!fp) {
            fprintf(stderr, "cannot open output file %s\n", argv[ic]);
            return 1;
         }
         ic++;
      }
      if (!strcmp(argv[ic], "-l")) {
         ic++;
         solib = argv[ic];
#ifdef __APPLE__
         string::size_type i = solib.find(".dylib");
         if (i != string::npos)
            solib.replace(i, 6, ".so");
#endif
         ic++;
      }
      if (!strcmp(argv[ic], "-d")) {
         ic++;
         for (int i = ic; i < argc && argv[i][0] != '-'; i++) {
            string dl = argv[i];
#ifdef __APPLE__
            string::size_type i = dl.find(".dylib");
            if (i != string::npos)
               dl.replace(i, 6, ".so");
#endif
            solibdeps.push_back(dl);
            ic++;
         }
      }
      if (!strcmp(argv[ic], "-c")) {
         ic++;
         for (int i = ic; i < argc; i++) {
            linkdefs.push_back(argv[i]);
            ic++;
         }
      }
   } else {
      fprintf(stderr, usage, argv[0]);
      return 1;
   }

   if (replace) {
#if !defined(WIN32) && !defined(__CYGWIN__) && !defined(__FreeBSD__)
      // lock file
      if (lockf(fileno(fp), F_LOCK, (off_t)1) == -1) {
         fprintf(stderr, "rlibmap: error locking output file\n");
         fclose(fp);
         return 1;
      }
#endif

      // remove entries for solib to be processed
      RemoveLib(solib, fullpath, fp);
   }

   LibMap(solib, solibdeps, linkdefs, fullpath, fp);

   if (replace) {
#if !defined(WIN32) && !defined(__CYGWIN__) && !defined(__FreeBSD__)
      // remove lock
      lseek(fileno(fp), 0, SEEK_SET);
      if (lockf(fileno(fp), F_ULOCK, (off_t)1) == -1) {
         fprintf(stderr, "rlibmap: error unlocking output file\n");
         fclose(fp);
         return 1;
      }
#endif
   }

   if (fp != stdout)
      fclose(fp);

   return 0;
}
<|endoftext|>


<commit_before><commit_msg>bool improvements<commit_after><|endoftext|>


<commit_before>#include "core/generator_maze.h"
#include "core/generator_cell.h"

#include "core/random.h"
#include "core/imageops.h"

#include "core/debug.h"

#include <iostream>

// later when doing floodfill
// #include "core/colorbrewer.h"

void maze()
{
  auto random = Random {};
  auto maze = generator::Maze::FromWidthHeight(30, 10);

  auto gen   = generator::RecursiveBacktracker{};
  gen.maze = &maze;
  gen.random = &random;
  gen.Setup();

  auto drawer = generator::Drawer {};
  drawer.maze = &maze;
  drawer.tracker = &gen;
  drawer.cell_size = 1;
  drawer.wall_size = 1;

  while(gen.HasMoreWork())
  {
    gen.Work();
  }

  drawer.Draw();
  debug::MemoryChunkToFile(drawer.image.Write(ImageWriteFormat::PNG), "maze.png");

  auto table = ImageToStringTable(drawer.image,
    {
      {'#', drawer.wall_color},
      {'/', drawer.cell_color},
      {' ', drawer.wall_color},
      {' ', drawer.cell_visited_color},
      {'O', drawer.unit_color}
    }
  );

  for(int r=0; r<table.Height(); r+=1)
  {
    for(int c=0; c<table.Width(); c+=1)
    {
      std::cout << table.Value(c, r);
    }
    std::cout << "\n";
  }
}

void cell()
{
  auto random = Random {};
  auto world = generator::World::FromWidthHeight(80, 80);

  generator::CellularAutomata cell;
  cell.world = &world;
  cell.random = &random;
  cell.Setup();

  auto drawer = generator::CellularAutomataDrawer {};
  drawer.world = &world;

  while(cell.HasMoreWork())
  {
    cell.Work();
  }

  drawer.Draw();
  debug::MemoryChunkToFile(drawer.image.Write(ImageWriteFormat::PNG), "maze.png");
}

void main()
{
  // maze();
  cell();
}
<commit_msg>return value on main<commit_after>#include "core/generator_maze.h"
#include "core/generator_cell.h"

#include "core/random.h"
#include "core/imageops.h"

#include "core/debug.h"

#include <iostream>

// later when doing floodfill
// #include "core/colorbrewer.h"

void maze()
{
  auto random = Random {};
  auto maze = generator::Maze::FromWidthHeight(30, 10);

  auto gen   = generator::RecursiveBacktracker{};
  gen.maze = &maze;
  gen.random = &random;
  gen.Setup();

  auto drawer = generator::Drawer {};
  drawer.maze = &maze;
  drawer.tracker = &gen;
  drawer.cell_size = 1;
  drawer.wall_size = 1;

  while(gen.HasMoreWork())
  {
    gen.Work();
  }

  drawer.Draw();
  debug::MemoryChunkToFile(drawer.image.Write(ImageWriteFormat::PNG), "maze.png");

  auto table = ImageToStringTable(drawer.image,
    {
      {'#', drawer.wall_color},
      {'/', drawer.cell_color},
      {' ', drawer.wall_color},
      {' ', drawer.cell_visited_color},
      {'O', drawer.unit_color}
    }
  );

  for(int r=0; r<table.Height(); r+=1)
  {
    for(int c=0; c<table.Width(); c+=1)
    {
      std::cout << table.Value(c, r);
    }
    std::cout << "\n";
  }
}

void cell()
{
  auto random = Random {};
  auto world = generator::World::FromWidthHeight(80, 80);

  generator::CellularAutomata cell;
  cell.world = &world;
  cell.random = &random;
  cell.Setup();

  auto drawer = generator::CellularAutomataDrawer {};
  drawer.world = &world;

  while(cell.HasMoreWork())
  {
    cell.Work();
  }

  drawer.Draw();
  debug::MemoryChunkToFile(drawer.image.Write(ImageWriteFormat::PNG), "maze.png");
}

int main()
{
  // maze();
  cell();

  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "vm/globals.h"
#if defined(TARGET_OS_MACOS)

#include "vm/os.h"

#include <errno.h>  // NOLINT
#include <limits.h>  // NOLINT
#include <mach/mach.h>  // NOLINT
#include <mach/clock.h>  // NOLINT
#include <mach/mach_time.h>  // NOLINT
#include <sys/time.h>  // NOLINT
#include <sys/resource.h>  // NOLINT
#include <unistd.h>  // NOLINT
#if TARGET_OS_IOS
#include <sys/sysctl.h>  // NOLINT
#include <syslog.h>  // NOLINT
#endif

#include "platform/utils.h"
#include "vm/isolate.h"
#include "vm/zone.h"

namespace dart {

const char* OS::Name() {
  return "macos";
}

intptr_t OS::ProcessId() {
  return static_cast<intptr_t>(getpid());
}

static bool LocalTime(int64_t seconds_since_epoch, tm* tm_result) {
  time_t seconds = static_cast<time_t>(seconds_since_epoch);
  if (seconds != seconds_since_epoch) return false;
  struct tm* error_code = localtime_r(&seconds, tm_result);
  return error_code != NULL;
}

const char* OS::GetTimeZoneName(int64_t seconds_since_epoch) {
  tm decomposed;
  bool succeeded = LocalTime(seconds_since_epoch, &decomposed);
  // If unsuccessful, return an empty string like V8 does.
  return (succeeded && (decomposed.tm_zone != NULL)) ? decomposed.tm_zone : "";
}

int OS::GetTimeZoneOffsetInSeconds(int64_t seconds_since_epoch) {
  tm decomposed;
  bool succeeded = LocalTime(seconds_since_epoch, &decomposed);
  // Even if the offset was 24 hours it would still easily fit into 32 bits.
  // If unsuccessful, return zero like V8 does.
  return succeeded ? static_cast<int>(decomposed.tm_gmtoff) : 0;
}

int OS::GetLocalTimeZoneAdjustmentInSeconds() {
  // TODO(floitsch): avoid excessive calls to tzset?
  tzset();
  // Even if the offset was 24 hours it would still easily fit into 32 bits.
  // Note that Unix and Dart disagree on the sign.
  return static_cast<int>(-timezone);
}

int64_t OS::GetCurrentTimeMillis() {
  return GetCurrentTimeMicros() / 1000;
}

int64_t OS::GetCurrentTimeMicros() {
  // gettimeofday has microsecond resolution.
  struct timeval tv;
  if (gettimeofday(&tv, NULL) < 0) {
    UNREACHABLE();
    return 0;
  }
  return (static_cast<int64_t>(tv.tv_sec) * 1000000) + tv.tv_usec;
}

int64_t OS::GetCurrentTraceMicros() {
#if TARGET_OS_IOS
  // On iOS mach_absolute_time stops while the device is sleeping. Instead use
  // now - KERN_BOOTTIME to get a time difference that is not impacted by clock
  // changes. KERN_BOOTTIME will be updated by the system whenever the system
  // clock change.
  struct timeval boottime;
  int mib[2] = {CTL_KERN, KERN_BOOTTIME};
  size_t size = sizeof(boottime);
  int kr = sysctl(mib, sizeof(mib) / sizeof(mib[0]), &boottime, &size, NULL, 0);
  ASSERT(KERN_SUCCESS == kr);
  int64_t now = GetCurrentTimeMicros();
  int64_t origin = boottime.tv_sec * kMicrosecondsPerSecond;
  origin += boottime.tv_usec;
  return now - origin;
#else
  static mach_timebase_info_data_t timebase_info;
  if (timebase_info.denom == 0) {
    // Zero-initialization of statics guarantees that denom will be 0 before
    // calling mach_timebase_info.  mach_timebase_info will never set denom to
    // 0 as that would be invalid, so the zero-check can be used to determine
    // whether mach_timebase_info has already been called.  This is
    // recommended by Apple's QA1398.
    kern_return_t kr = mach_timebase_info(&timebase_info);
    ASSERT(KERN_SUCCESS == kr);
  }

  // timebase_info converts absolute time tick units into nanoseconds.  Convert
  // to microseconds.
  int64_t result = mach_absolute_time() / kNanosecondsPerMicrosecond;
  result *= timebase_info.numer;
  result /= timebase_info.denom;
  return result;
#endif  // TARGET_OS_IOS
}

void* OS::AlignedAllocate(intptr_t size, intptr_t alignment) {
  const int kMinimumAlignment = 16;
  ASSERT(Utils::IsPowerOfTwo(alignment));
  ASSERT(alignment >= kMinimumAlignment);
  // Temporary workaround until xcode is upgraded.
  // Mac guarantees malloc returns a 16 byte aligned memory chunk.
  // Currently we only allocate with 16-bye alignment.
  ASSERT(alignment == 16);
  // TODO(johnmccutchan): Remove hack and switch to posix_memalign.
  return malloc(size);
}

void OS::AlignedFree(void* ptr) {
  free(ptr);
}

intptr_t OS::ActivationFrameAlignment() {
#if TARGET_OS_IOS
#if TARGET_ARCH_ARM
  // Even if we generate code that maintains a stronger alignment, we cannot
  // assert the stronger stack alignment because C++ code will not maintain it.
  return 8;
#elif TARGET_ARCH_ARM64
  return 16;
#endif
#else  // TARGET_OS_IOS
  // OS X activation frames must be 16 byte-aligned; see "Mac OS X ABI
  // Function Call Guide".
  return 16;
#endif  // TARGET_OS_IOS
}

intptr_t OS::PreferredCodeAlignment() {
  ASSERT(32 <= OS::kMaxPreferredCodeAlignment);
  return 32;
}

bool OS::AllowStackFrameIteratorFromAnotherThread() {
  return false;
}

int OS::NumberOfAvailableProcessors() {
  return sysconf(_SC_NPROCESSORS_ONLN);
}

void OS::Sleep(int64_t millis) {
  int64_t micros = millis * kMicrosecondsPerMillisecond;
  SleepMicros(micros);
}

void OS::SleepMicros(int64_t micros) {
  struct timespec req;  // requested.
  struct timespec rem;  // remainder.
  int64_t seconds = micros / kMicrosecondsPerSecond;
  if (seconds > kMaxInt32) {
    // Avoid truncation of overly large sleep values.
    seconds = kMaxInt32;
  }
  micros = micros - seconds * kMicrosecondsPerSecond;
  int64_t nanos = micros * kNanosecondsPerMicrosecond;
  req.tv_sec = static_cast<int32_t>(seconds);
  req.tv_nsec = static_cast<long>(nanos);  // NOLINT (long used in timespec).
  while (true) {
    int r = nanosleep(&req, &rem);
    if (r == 0) {
      break;
    }
    // We should only ever see an interrupt error.
    ASSERT(errno == EINTR);
    // Copy remainder into requested and repeat.
    req = rem;
  }
}

void OS::DebugBreak() {
  __builtin_trap();
}

char* OS::StrNDup(const char* s, intptr_t n) {
  // strndup has only been added to Mac OS X in 10.7. We are supplying
  // our own copy here if needed.
#if !defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || \
    __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ <= 1060
  intptr_t len = strlen(s);
  if ((n < 0) || (len < 0)) {
    return NULL;
  }
  if (n < len) {
    len = n;
  }
  char* result = reinterpret_cast<char*>(malloc(len + 1));
  if (result == NULL) {
    return NULL;
  }
  result[len] = '\0';
  return reinterpret_cast<char*>(memmove(result, s, len));
#else  // !defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || ...
  return strndup(s, n);
#endif  // !defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || ...
}

void OS::Print(const char* format, ...) {
#if TARGET_OS_IOS
  va_list args;
  va_start(args, format);
  vsyslog(LOG_INFO, format, args);
  va_end(args);
#else
  va_list args;
  va_start(args, format);
  VFPrint(stdout, format, args);
  va_end(args);
#endif
}

void OS::VFPrint(FILE* stream, const char* format, va_list args) {
  vfprintf(stream, format, args);
  fflush(stream);
}

int OS::SNPrint(char* str, size_t size, const char* format, ...) {
  va_list args;
  va_start(args, format);
  int retval = VSNPrint(str, size, format, args);
  va_end(args);
  return retval;
}

int OS::VSNPrint(char* str, size_t size, const char* format, va_list args) {
  int retval = vsnprintf(str, size, format, args);
  if (retval < 0) {
    FATAL1("Fatal error in OS::VSNPrint with format '%s'", format);
  }
  return retval;
}

char* OS::SCreate(Zone* zone, const char* format, ...) {
  va_list args;
  va_start(args, format);
  char* buffer = VSCreate(zone, format, args);
  va_end(args);
  return buffer;
}

char* OS::VSCreate(Zone* zone, const char* format, va_list args) {
  // Measure.
  va_list measure_args;
  va_copy(measure_args, args);
  intptr_t len = VSNPrint(NULL, 0, format, measure_args);
  va_end(measure_args);

  char* buffer;
  if (zone) {
    buffer = zone->Alloc<char>(len + 1);
  } else {
    buffer = reinterpret_cast<char*>(malloc(len + 1));
  }
  ASSERT(buffer != NULL);

  // Print.
  va_list print_args;
  va_copy(print_args, args);
  VSNPrint(buffer, len + 1, format, print_args);
  va_end(print_args);
  return buffer;
}

bool OS::StringToInt64(const char* str, int64_t* value) {
  ASSERT(str != NULL && strlen(str) > 0 && value != NULL);
  int32_t base = 10;
  char* endptr;
  int i = 0;
  if (str[0] == '-') {
    i = 1;
  }
  if ((str[i] == '0') &&
      (str[i + 1] == 'x' || str[i + 1] == 'X') &&
      (str[i + 2] != '\0')) {
    base = 16;
  }
  errno = 0;
  *value = strtoll(str, &endptr, base);
  return ((errno == 0) && (endptr != str) && (*endptr == 0));
}

void OS::RegisterCodeObservers() {
}

void OS::PrintErr(const char* format, ...) {
#if TARGET_OS_IOS
  va_list args;
  va_start(args, format);
  vsyslog(LOG_ERR, format, args);
  va_end(args);
#else
  va_list args;
  va_start(args, format);
  VFPrint(stderr, format, args);
  va_end(args);
#endif
}

void OS::InitOnce() {
  // TODO(5411554): For now we check that initonce is called only once,
  // Once there is more formal mechanism to call InitOnce we can move
  // this check there.
  static bool init_once_called = false;
  ASSERT(init_once_called == false);
  init_once_called = true;
}

void OS::Shutdown() {
}

void OS::Abort() {
  abort();
}

void OS::Exit(int code) {
  exit(code);
}

}  // namespace dart

#endif  // defined(TARGET_OS_MACOS)
<commit_msg>Return correct ActivationFrameAlignment for iOS simulator variants<commit_after>// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "vm/globals.h"
#if defined(TARGET_OS_MACOS)

#include "vm/os.h"

#include <errno.h>  // NOLINT
#include <limits.h>  // NOLINT
#include <mach/mach.h>  // NOLINT
#include <mach/clock.h>  // NOLINT
#include <mach/mach_time.h>  // NOLINT
#include <sys/time.h>  // NOLINT
#include <sys/resource.h>  // NOLINT
#include <unistd.h>  // NOLINT
#if TARGET_OS_IOS
#include <sys/sysctl.h>  // NOLINT
#include <syslog.h>  // NOLINT
#endif

#include "platform/utils.h"
#include "vm/isolate.h"
#include "vm/zone.h"

namespace dart {

const char* OS::Name() {
  return "macos";
}

intptr_t OS::ProcessId() {
  return static_cast<intptr_t>(getpid());
}

static bool LocalTime(int64_t seconds_since_epoch, tm* tm_result) {
  time_t seconds = static_cast<time_t>(seconds_since_epoch);
  if (seconds != seconds_since_epoch) return false;
  struct tm* error_code = localtime_r(&seconds, tm_result);
  return error_code != NULL;
}

const char* OS::GetTimeZoneName(int64_t seconds_since_epoch) {
  tm decomposed;
  bool succeeded = LocalTime(seconds_since_epoch, &decomposed);
  // If unsuccessful, return an empty string like V8 does.
  return (succeeded && (decomposed.tm_zone != NULL)) ? decomposed.tm_zone : "";
}

int OS::GetTimeZoneOffsetInSeconds(int64_t seconds_since_epoch) {
  tm decomposed;
  bool succeeded = LocalTime(seconds_since_epoch, &decomposed);
  // Even if the offset was 24 hours it would still easily fit into 32 bits.
  // If unsuccessful, return zero like V8 does.
  return succeeded ? static_cast<int>(decomposed.tm_gmtoff) : 0;
}

int OS::GetLocalTimeZoneAdjustmentInSeconds() {
  // TODO(floitsch): avoid excessive calls to tzset?
  tzset();
  // Even if the offset was 24 hours it would still easily fit into 32 bits.
  // Note that Unix and Dart disagree on the sign.
  return static_cast<int>(-timezone);
}

int64_t OS::GetCurrentTimeMillis() {
  return GetCurrentTimeMicros() / 1000;
}

int64_t OS::GetCurrentTimeMicros() {
  // gettimeofday has microsecond resolution.
  struct timeval tv;
  if (gettimeofday(&tv, NULL) < 0) {
    UNREACHABLE();
    return 0;
  }
  return (static_cast<int64_t>(tv.tv_sec) * 1000000) + tv.tv_usec;
}

int64_t OS::GetCurrentTraceMicros() {
#if TARGET_OS_IOS
  // On iOS mach_absolute_time stops while the device is sleeping. Instead use
  // now - KERN_BOOTTIME to get a time difference that is not impacted by clock
  // changes. KERN_BOOTTIME will be updated by the system whenever the system
  // clock change.
  struct timeval boottime;
  int mib[2] = {CTL_KERN, KERN_BOOTTIME};
  size_t size = sizeof(boottime);
  int kr = sysctl(mib, sizeof(mib) / sizeof(mib[0]), &boottime, &size, NULL, 0);
  ASSERT(KERN_SUCCESS == kr);
  int64_t now = GetCurrentTimeMicros();
  int64_t origin = boottime.tv_sec * kMicrosecondsPerSecond;
  origin += boottime.tv_usec;
  return now - origin;
#else
  static mach_timebase_info_data_t timebase_info;
  if (timebase_info.denom == 0) {
    // Zero-initialization of statics guarantees that denom will be 0 before
    // calling mach_timebase_info.  mach_timebase_info will never set denom to
    // 0 as that would be invalid, so the zero-check can be used to determine
    // whether mach_timebase_info has already been called.  This is
    // recommended by Apple's QA1398.
    kern_return_t kr = mach_timebase_info(&timebase_info);
    ASSERT(KERN_SUCCESS == kr);
  }

  // timebase_info converts absolute time tick units into nanoseconds.  Convert
  // to microseconds.
  int64_t result = mach_absolute_time() / kNanosecondsPerMicrosecond;
  result *= timebase_info.numer;
  result /= timebase_info.denom;
  return result;
#endif  // TARGET_OS_IOS
}

void* OS::AlignedAllocate(intptr_t size, intptr_t alignment) {
  const int kMinimumAlignment = 16;
  ASSERT(Utils::IsPowerOfTwo(alignment));
  ASSERT(alignment >= kMinimumAlignment);
  // Temporary workaround until xcode is upgraded.
  // Mac guarantees malloc returns a 16 byte aligned memory chunk.
  // Currently we only allocate with 16-bye alignment.
  ASSERT(alignment == 16);
  // TODO(johnmccutchan): Remove hack and switch to posix_memalign.
  return malloc(size);
}

void OS::AlignedFree(void* ptr) {
  free(ptr);
}

intptr_t OS::ActivationFrameAlignment() {
#if TARGET_OS_IOS
#if TARGET_ARCH_ARM
  // Even if we generate code that maintains a stronger alignment, we cannot
  // assert the stronger stack alignment because C++ code will not maintain it.
  return 8;
#elif TARGET_ARCH_ARM64
  return 16;
#elif TARGET_ARCH_IA32
  return 16;  // iOS simulator
#elif TARGET_ARCH_X64
  return 16;  // iOS simulator
#else
#error Unimplemented
#endif
#else  // TARGET_OS_IOS
  // OS X activation frames must be 16 byte-aligned; see "Mac OS X ABI
  // Function Call Guide".
  return 16;
#endif  // TARGET_OS_IOS
}

intptr_t OS::PreferredCodeAlignment() {
  ASSERT(32 <= OS::kMaxPreferredCodeAlignment);
  return 32;
}

bool OS::AllowStackFrameIteratorFromAnotherThread() {
  return false;
}

int OS::NumberOfAvailableProcessors() {
  return sysconf(_SC_NPROCESSORS_ONLN);
}

void OS::Sleep(int64_t millis) {
  int64_t micros = millis * kMicrosecondsPerMillisecond;
  SleepMicros(micros);
}

void OS::SleepMicros(int64_t micros) {
  struct timespec req;  // requested.
  struct timespec rem;  // remainder.
  int64_t seconds = micros / kMicrosecondsPerSecond;
  if (seconds > kMaxInt32) {
    // Avoid truncation of overly large sleep values.
    seconds = kMaxInt32;
  }
  micros = micros - seconds * kMicrosecondsPerSecond;
  int64_t nanos = micros * kNanosecondsPerMicrosecond;
  req.tv_sec = static_cast<int32_t>(seconds);
  req.tv_nsec = static_cast<long>(nanos);  // NOLINT (long used in timespec).
  while (true) {
    int r = nanosleep(&req, &rem);
    if (r == 0) {
      break;
    }
    // We should only ever see an interrupt error.
    ASSERT(errno == EINTR);
    // Copy remainder into requested and repeat.
    req = rem;
  }
}

void OS::DebugBreak() {
  __builtin_trap();
}

char* OS::StrNDup(const char* s, intptr_t n) {
  // strndup has only been added to Mac OS X in 10.7. We are supplying
  // our own copy here if needed.
#if !defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || \
    __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ <= 1060
  intptr_t len = strlen(s);
  if ((n < 0) || (len < 0)) {
    return NULL;
  }
  if (n < len) {
    len = n;
  }
  char* result = reinterpret_cast<char*>(malloc(len + 1));
  if (result == NULL) {
    return NULL;
  }
  result[len] = '\0';
  return reinterpret_cast<char*>(memmove(result, s, len));
#else  // !defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || ...
  return strndup(s, n);
#endif  // !defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || ...
}

void OS::Print(const char* format, ...) {
#if TARGET_OS_IOS
  va_list args;
  va_start(args, format);
  vsyslog(LOG_INFO, format, args);
  va_end(args);
#else
  va_list args;
  va_start(args, format);
  VFPrint(stdout, format, args);
  va_end(args);
#endif
}

void OS::VFPrint(FILE* stream, const char* format, va_list args) {
  vfprintf(stream, format, args);
  fflush(stream);
}

int OS::SNPrint(char* str, size_t size, const char* format, ...) {
  va_list args;
  va_start(args, format);
  int retval = VSNPrint(str, size, format, args);
  va_end(args);
  return retval;
}

int OS::VSNPrint(char* str, size_t size, const char* format, va_list args) {
  int retval = vsnprintf(str, size, format, args);
  if (retval < 0) {
    FATAL1("Fatal error in OS::VSNPrint with format '%s'", format);
  }
  return retval;
}

char* OS::SCreate(Zone* zone, const char* format, ...) {
  va_list args;
  va_start(args, format);
  char* buffer = VSCreate(zone, format, args);
  va_end(args);
  return buffer;
}

char* OS::VSCreate(Zone* zone, const char* format, va_list args) {
  // Measure.
  va_list measure_args;
  va_copy(measure_args, args);
  intptr_t len = VSNPrint(NULL, 0, format, measure_args);
  va_end(measure_args);

  char* buffer;
  if (zone) {
    buffer = zone->Alloc<char>(len + 1);
  } else {
    buffer = reinterpret_cast<char*>(malloc(len + 1));
  }
  ASSERT(buffer != NULL);

  // Print.
  va_list print_args;
  va_copy(print_args, args);
  VSNPrint(buffer, len + 1, format, print_args);
  va_end(print_args);
  return buffer;
}

bool OS::StringToInt64(const char* str, int64_t* value) {
  ASSERT(str != NULL && strlen(str) > 0 && value != NULL);
  int32_t base = 10;
  char* endptr;
  int i = 0;
  if (str[0] == '-') {
    i = 1;
  }
  if ((str[i] == '0') &&
      (str[i + 1] == 'x' || str[i + 1] == 'X') &&
      (str[i + 2] != '\0')) {
    base = 16;
  }
  errno = 0;
  *value = strtoll(str, &endptr, base);
  return ((errno == 0) && (endptr != str) && (*endptr == 0));
}

void OS::RegisterCodeObservers() {
}

void OS::PrintErr(const char* format, ...) {
#if TARGET_OS_IOS
  va_list args;
  va_start(args, format);
  vsyslog(LOG_ERR, format, args);
  va_end(args);
#else
  va_list args;
  va_start(args, format);
  VFPrint(stderr, format, args);
  va_end(args);
#endif
}

void OS::InitOnce() {
  // TODO(5411554): For now we check that initonce is called only once,
  // Once there is more formal mechanism to call InitOnce we can move
  // this check there.
  static bool init_once_called = false;
  ASSERT(init_once_called == false);
  init_once_called = true;
}

void OS::Shutdown() {
}

void OS::Abort() {
  abort();
}

void OS::Exit(int code) {
  exit(code);
}

}  // namespace dart

#endif  // defined(TARGET_OS_MACOS)
<|endoftext|>


<commit_before><commit_msg>sal: fix build with clang and --enable-crashdump<commit_after><|endoftext|>


<commit_before>/*! CreditMetrics.cpp : Defines the entry point for the console application.
	Note: The given .csv files are not formatted consistently. The .csv parsers below are
	designed to handle the inconsistencies present in the files in a somewhat
	general manner by removing extra characters and white space.
*/
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include <boost/numeric/ublas/matrix.hpp>
using namespace std;

static inline string& trim(string& s) {
	//left
	s.erase(s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace))));
	//right
	s.erase(find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end());
	return s;
}
static inline int convertInt(string strInt)
{
	trim(strInt);
	return ::atoi(strInt.c_str());
}
static inline double convertDouble(string strDouble)
{
	trim(strDouble);
	return ::atof(strDouble.c_str());
}
static inline double convertPercent(string strPercent)
{
	replace(strPercent.begin(), strPercent.end(), '%', ' ');
	return convertDouble(strPercent) / 100;
}

template <class R> class CSV : public vector<R>
{
public:
	CSV(const string& filename, size_t skipLines)
	{
		ifstream file(filename);
		if (!file.good())
		{
			throw runtime_error("File does not exist");
		}
		while (!file.eof())
		{
			string strline;
			getline(file, strline);
			if (skipLines > 0)
			{
				skipLines--;
				continue;
			}
			if (strline.empty())
			{
				continue;
			}
			stringstream streamline(strline);
			vector<string> cells;
			while (!streamline.eof())
			{
				string cell;
				getline(streamline, cell, ',');
				if (cell != "")
				{
					cells.push_back(cell);
				}
			}
			if (cells.empty())
			{
				continue;
			}
			push_back(R(cells));
		}
	}
	const string toString()
	{
		string ret;
		for (size_t i = 0, n = size(); i < n; i++)
			ret = ret + at(i).toString() + "\n";
		return ret;
	}
};
class IssuerEntry
{
public:
	IssuerEntry(const vector<string>& cells):
		name(cells.at(0)),
		rating(cells.at(1)),
		industry(cells.at(2))
	{}
	const string name;
	const string rating;
	const string industry;
	const string toString() const
	{
		return string()
			+ name + "," + rating + "," + industry;
	}
};
class IssuerData : public CSV<IssuerEntry>
{
public:
	IssuerData() : CSV("issuers.csv", 1) { }
	IssuerEntry* getByName(string name)
	{
		for (size_t i = 0, n = size(); i < n; i++)
		{
			IssuerEntry& issuer = at(i);
			if(issuer.name == name)
				return &issuer;
		}
		return nullptr;
	}
};
class PortfolioEntry
{
public:
	PortfolioEntry(const vector<string>& cells) :
		name(cells.at(0)),
		instrumentType(cells.at(1)),
		cusip(cells.at(2)),
		notional(convertNotional(cells.at(3))),
		maturity(cells.at(4)),
		coupon(convertPercent(cells.at(5))),
		couponsPerYear(convertInt(cells.at(6))),
		price(convertPrice(cells.at(7))),
		yield(convertPercent(cells.at(8))),
		cleanPrice(convertPrice(cells.at(9))),
		exprr(convertPercent(cells.at(10)))
	{}
	const string name, instrumentType, cusip, maturity;
	const int notional, couponsPerYear;
	const double coupon, price, yield, cleanPrice,exprr;
	const string toString() const
	{
		return string()
			+ name + "," + instrumentType + ","
			+ cusip + "," + to_string(notional) + ","
			+ maturity + "," + to_string(coupon) + ","
			+ to_string(couponsPerYear) + "," + to_string(price) + ","
			+ to_string(yield) + "," + to_string(cleanPrice) + ","
			+ to_string(exprr);
	}
private:
	int convertNotional(string strNotional)
	{
		return convertInt(strNotional);
	}
	double convertPrice(string strPrice)
	{
		replace(strPrice.begin(), strPrice.end(), '$', ' ');
		return convertDouble(strPrice);
	}
};
class PortfolioData : public CSV<PortfolioEntry>
{
public:
	PortfolioData() : CSV("portfolio_for_project.csv", 1) { }
	PortfolioEntry* getByName(string name)
	{
		for (size_t i = 0, n = size(); i < n; i++)
		{
			PortfolioEntry& issuer = at(i);
			if (issuer.name == name)
				return &issuer;
		}
		return nullptr;
	}
	/*! Response for Part B, Step 2) Reported Value
		\return The reported value of the portfolio in millions of dollars
	*/
	double getReportedValue()
	{
		double marketValue = 0;
		for (size_t i = 0, n = size(); i < n; i++)
		{
			PortfolioEntry& row = at(i);
			double targetValue;
			if (row.instrumentType == "CDS")
				targetValue = row.cleanPrice;
			else
				targetValue = row.price;
			marketValue = marketValue + (row.notional*targetValue / 100);
		}
		return marketValue;
	}
	/*! Response for Part B, Step 2) Theoretical Value
	\return The theoretical value of the portfolio in millions of dollars
	*/
	double getTheorValue()
	{
		double theorValue = 0;
		for (size_t i = 0, n = size(); i < n; i++)
		{
			PortfolioEntry& row = at(i);
			theorValue = theorValue + (row.notional*row.cleanPrice / 100);
		}
		return theorValue;
	}
};
class YieldEntry
{
public:
	YieldEntry(const vector<string>& cells):
		term(convertDouble(cells.at(0))),
		aaa(convertPercent(cells.at(1))),
		aa(convertPercent(cells.at(2))),
		a(convertPercent(cells.at(3))),
		bbb(convertPercent(cells.at(4))),
		bb(convertPercent(cells.at(5))),
		b(convertPercent(cells.at(6))),
		ccc(convertPercent(cells.at(7))),
		govt(convertPercent(cells.at(8)))
	{}
	const double term, aaa, aa, a, bbb, bb, b, ccc, govt;
	const string toString() const
	{
		return string()
			+ to_string(term) + "," + to_string(aaa) + ","
			+ to_string(aa) + "," + to_string(a) + ","
			+ to_string(bbb) + "," + to_string(bb) + ","
			+ to_string(b) + "," + to_string(ccc) + ","
			+ to_string(govt);
	}
};
class YieldData : public CSV<YieldEntry>
{
public:
	YieldData() : CSV("yield_curve_for_project.csv", 1) { }
	YieldEntry* getByTerm(double term)
	{
		for (size_t i = 0, n = size(); i < n; i++)
		{
			YieldEntry& yield = at(i);
			if (yield.term == term)
				return &yield;
		}
		return nullptr;
	}
};
class MatrixRow : public vector<double>
{
public:
	MatrixRow(const vector<string>& cells)
	{
		for (size_t i = 1, n = cells.size(); i < n; i++)
		{
			push_back(convertDouble(cells.at(i)));
		}
	}
	using vector::vector;
	string toString()
	{
		string ret;
		for (size_t i = 0, n = size(); i < n; i++)
		{
			if (i > 0)
				ret = ret + ",";
			ret = ret + to_string(at(i));
		}
		return ret;
	}
};
class Matrix : public CSV<MatrixRow>
{
public:
	Matrix(const string& filename, size_t skipLines) : CSV(filename, skipLines) {}
};
int main(int argc, char* argv[])
{
	try
	{
		IssuerData issuerData;
		// cout << issuerData.toString();
		PortfolioData portfolioData;
		// cout << portfolioData.toString();
		YieldData yieldData;
		// cout << yieldData.toString();
		Matrix correlationMatrix("correlation_matrix_for_project.csv", 1);
		// cout << correlationMatrix.toString();
		Matrix transitionMatrix("transition_matrix_for_project.csv", 3);
		MatrixRow row{ 0,0,0,0,0,0,0,1 };
		transitionMatrix.push_back(row);
		// cout << transitionMatrix.toString();
		cout << portfolioData.getReportedValue() << "\n";
		cout << portfolioData.getTheorValue();
	}
	catch (const exception &e)
	{
		cerr << "error: " << e.what() << "\n";
	}
	getchar();
}<commit_msg>Created routine to produce matrix of possible prices for each instrument<commit_after>/*! CreditMetrics.cpp : Defines the entry point for the console application.
	Note: The given .csv files are not formatted consistently. The .csv parsers below are
	designed to handle the inconsistencies present in the files in a somewhat
	general manner by removing extra characters and white space.
*/
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include <random>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
using namespace std;

static inline string& trim(string& s) {
	//left
	s.erase(s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace))));
	//right
	s.erase(find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end());
	return s;
}
static inline int convertInt(string strInt)
{
	trim(strInt);
	return ::atoi(strInt.c_str());
}
static inline double convertDouble(string strDouble)
{
	trim(strDouble);
	return ::atof(strDouble.c_str());
}
static inline double convertPercent(string strPercent)
{
	replace(strPercent.begin(), strPercent.end(), '%', ' ');
	return convertDouble(strPercent) / 100;
}

template <class R> class CSV : public vector<R>
{
public:
	CSV(const string& filename, size_t skipLines)
	{
		ifstream file(filename);
		if (!file.good())
		{
			throw runtime_error("File does not exist");
		}
		while (!file.eof())
		{
			string strline;
			getline(file, strline);
			if (skipLines > 0)
			{
				skipLines--;
				continue;
			}
			if (strline.empty())
			{
				continue;
			}
			stringstream streamline(strline);
			vector<string> cells;
			while (!streamline.eof())
			{
				string cell;
				getline(streamline, cell, ',');
				if (cell != "")
				{
					cells.push_back(cell);
				}
			}
			if (cells.empty())
			{
				continue;
			}
			push_back(R(cells));
		}
	}
	const string toString()
	{
		string ret;
		for (size_t i = 0, n = size(); i < n; i++)
			ret = ret + at(i).toString() + "\n";
		return ret;
	}
};
class IssuerEntry
{
public:
	IssuerEntry(const vector<string>& cells):
		name(cells.at(0)),
		rating(cells.at(1)),
		industry(cells.at(2))
	{}
	const string name;
	const string rating;
	const string industry;
	const string toString() const
	{
		return string()
			+ name + "," + rating + "," + industry;
	}
};
class IssuerData : public CSV<IssuerEntry>
{
public:
	IssuerData() : CSV("issuers.csv", 1) { }
	IssuerEntry* getByName(string name)
	{
		for (size_t i = 0, n = size(); i < n; i++)
		{
			IssuerEntry& issuer = at(i);
			if(issuer.name == name)
				return &issuer;
		}
		return nullptr;
	}
};
class PortfolioEntry
{
public:
	PortfolioEntry(const vector<string>& cells) :
		name(cells.at(0)),
		instrumentType(cells.at(1)),
		cusip(cells.at(2)),
		notional(convertNotional(cells.at(3))),
		maturity(cells.at(4)),
		coupon(convertPercent(cells.at(5))),
		couponsPerYear(convertInt(cells.at(6))),
		price(convertPrice(cells.at(7))),
		yield(convertPercent(cells.at(8))),
		cleanPrice(convertPrice(cells.at(9))),
		exprr(convertPercent(cells.at(10)))
	{}
	const string name, instrumentType, cusip, maturity;
	const int notional, couponsPerYear;
	const double coupon, price, yield, cleanPrice,exprr;
	const string toString() const
	{
		return string()
			+ name + "," + instrumentType + ","
			+ cusip + "," + to_string(notional) + ","
			+ maturity + "," + to_string(coupon) + ","
			+ to_string(couponsPerYear) + "," + to_string(price) + ","
			+ to_string(yield) + "," + to_string(cleanPrice) + ","
			+ to_string(exprr);
	}
private:
	int convertNotional(string strNotional)
	{
		return convertInt(strNotional);
	}
	double convertPrice(string strPrice)
	{
		replace(strPrice.begin(), strPrice.end(), '$', ' ');
		return convertDouble(strPrice);
	}
};
class PortfolioData : public CSV<PortfolioEntry>
{
public:
	PortfolioData() : CSV("portfolio_for_project.csv", 1) { }
	PortfolioEntry* getByName(string name)
	{
		for (size_t i = 0, n = size(); i < n; i++)
		{
			PortfolioEntry& issuer = at(i);
			if (issuer.name == name)
				return &issuer;
		}
		return nullptr;
	}
	/*! Response for Part B, Step 2) Reported Value
		\return The reported value of the portfolio in millions of dollars
	*/
	double getReportedValue()
	{
		double marketValue = 0;
		for (size_t i = 0, n = size(); i < n; i++)
		{
			PortfolioEntry& row = at(i);
			double targetValue;
			if (row.instrumentType == "CDS")
				targetValue = row.cleanPrice;
			else
				targetValue = row.price;
			marketValue = marketValue + (row.notional*targetValue / 100);
		}
		return marketValue;
	}
	/*! Response for Part B, Step 2) Theoretical Value
	\return The theoretical value of the portfolio in millions of dollars
	*/
	double getTheorValue()
	{
		double theorValue = 0;
		for (size_t i = 0, n = size(); i < n; i++)
		{
			PortfolioEntry& row = at(i);
			theorValue = theorValue + (row.notional*row.cleanPrice / 100);
		}
		return theorValue;
	}
};
class YieldEntry
{
public:
	YieldEntry(const vector<string>& cells):
		term(convertDouble(cells.at(0))),
		aaa(convertPercent(cells.at(1))),
		aa(convertPercent(cells.at(2))),
		a(convertPercent(cells.at(3))),
		bbb(convertPercent(cells.at(4))),
		bb(convertPercent(cells.at(5))),
		b(convertPercent(cells.at(6))),
		ccc(convertPercent(cells.at(7))),
		govt(convertPercent(cells.at(8)))
	{}
	const double term, aaa, aa, a, bbb, bb, b, ccc, govt;
	const string toString() const
	{
		return string()
			+ to_string(term) + "," + to_string(aaa) + ","
			+ to_string(aa) + "," + to_string(a) + ","
			+ to_string(bbb) + "," + to_string(bb) + ","
			+ to_string(b) + "," + to_string(ccc) + ","
			+ to_string(govt);
	}
};
class YieldData : public CSV<YieldEntry>
{
public:
	YieldData() : CSV("yield_curve_for_project.csv", 1) { }
	YieldEntry* getByTerm(double term)
	{
		for (size_t i = 0, n = size(); i < n; i++)
		{
			YieldEntry& yield = at(i);
			if (yield.term == term)
				return &yield;
		}
		return nullptr;
	}
};
class MatrixRow : public vector<double>
{
public:
	MatrixRow(const vector<string>& cells)
	{
		for (size_t i = 1, n = cells.size(); i < n; i++)
		{
			push_back(convertDouble(cells.at(i)));
		}
	}
	using vector::vector;
	string toString()
	{
		string ret;
		for (size_t i = 0, n = size(); i < n; i++)
		{
			if (i > 0)
				ret = ret + ",";
			ret = ret + to_string(at(i));
		}
		return ret;
	}
};
class Matrix : public CSV<MatrixRow>
{
public:
	Matrix(const string& filename, size_t skipLines) : CSV(filename, skipLines) {}
};
int main(int argc, char* argv[])
{
	try
	{
		random_device rd;
		mt19937 gen(rd());
		uniform_real_distribution<> dis(0, 1);

		IssuerData issuerData;
		// cout << issuerData.toString();
		PortfolioData portfolioData;
		// cout << portfolioData.toString();
		YieldData yieldData;
		// cout << yieldData.toString();
		Matrix correlationMatrix("correlation_matrix_for_project.csv", 1);
		// cout << correlationMatrix.toString();
		Matrix transitionMatrix("transition_matrix_for_project.csv", 3);
		MatrixRow row{ 0,0,0,0,0,0,0,1 };
		transitionMatrix.push_back(row);
		// cout << transitionMatrix.toString();
		cout << portfolioData.getReportedValue() << endl;
		cout << portfolioData.getTheorValue() << endl;

		boost::numeric::ublas::matrix<double> m(portfolioData.size(), 8);
		for (size_t i = 0, n1 = m.size1(); i < n1; i++)
		{
			PortfolioEntry& row = portfolioData.at(i);
			// To do: clean this up?
			if (row.instrumentType == "CDS")
			{
				for (size_t j = 0, n2 = m.size2() - 1; j < n2; j++)
					m(i, j) = dis(gen);
			}
			else
			{
				for (size_t j = 0, n2 = m.size2() - 1; j < n2; j++)
					m(i, j) = row.cleanPrice;
			}
			m(i, m.size2() - 1) = row.exprr * 100;
		}
		cout << m << endl;
	}
	catch (const exception &e)
	{
		cerr << "error: " << e.what() << "\n";
	}
	getchar();
}<|endoftext|>


<commit_before>#include "Main.h"

//获取基本信息
void handlerGetDeviceBaseInfo(struct bufferevent * bufEvent,Json::Value &data){
    char buffer[100];
    //获取内存大小
    struct sysinfo memInfo;
    sysinfo(&memInfo);
    //获取磁盘大小
    struct statfs diskInfo;
    statfs(DISK_SIZE_PATH, &diskInfo);
    //格式化数据
    double totalMemSize = (double)memInfo.totalram/(1024.0*1024.0);
    double usedMemSize = (double)(memInfo.totalram-memInfo.freeram)/(1024.0*1024.0);
    double totalDiskSize = (double)(diskInfo.f_bsize*diskInfo.f_blocks)/(1024.0*1024.0);
    double usedDiskSize = (double)(diskInfo.f_bsize*diskInfo.f_blocks-diskInfo.f_bsize*diskInfo.f_bfree)/(1024.0*1024.0);
    //构造返回JSON
    Json::Value root;
    Json::Value re_data;
    root["is_app"] = false;
    root["protocol"] = API_DEVICE_BASE_INFO;
    //总内存大小
    sprintf(buffer,"%.2f",totalMemSize);
    re_data["mem_total"] = string(buffer);
    memset(buffer,0,100);
    //使用内存
    sprintf(buffer,"%.2f",usedMemSize);
    re_data["mem_used"] = string(buffer);
    memset(buffer,0,100);
    //总硬盘大小
    sprintf(buffer,"%.2f",totalDiskSize);
    re_data["disk_total"] = string(buffer);
    memset(buffer,0,100);
    //使用硬盘大小
    sprintf(buffer,"%.2f",usedDiskSize);
    re_data["disk_used"] = string(buffer);
    memset(buffer,0,100);
    //返回数据
    root["data"] = re_data;
    bufferevent_write(bufEvent, root.toStyledString().c_str(), root.toStyledString().length());
}
//键盘按下
void handlerKeyDown(struct bufferevent * bufEvent,Json::Value &data){
    Json::Value key_map = data["data"];
    int key;
    stringstream stream;
    stream << key_map["key"].toStyledString();
    stream >> key;
    switch(key){
        case 119://W
        case 115://S
        case 97://A
        case 100://D
        case 105://I
        case 107://K
        case 106://J
        case 108://L
            printf("key down:%d\n", key);
        break;
        default:
            printf("key not find:%d\n", key);
        break;
    }
}
//获取MAC地址
string getMacAddress(){
    char buff[32];
    memset (buff ,'\0', sizeof(buff));
    string cmd = "ip addr |grep -A 2 "+network_card_name+" | awk 'NR>1'|awk 'NR<2'|awk '{print $2}'";
    // 通过管道来回去系统命令返回的值
    FILE *fstream = popen(cmd.c_str(), "r");
    if(fstream == NULL) {
        perror("popen");
        exit(0);
    }
    if(NULL == fgets(buff, sizeof(buff), fstream)){
        printf("not find mac address !!!\n");
        exit(0);
    }
    pclose(fstream);
    string mac;
    mac = string(buff);
    mac = mac.substr(0, mac.length()-1);
    return mac;
}
//调用方法
void callFunc(struct bufferevent * bufEvent,Json::Value &request_data,const string func){
    if(func.length() == 0){
        return;
    }
    if (client_api_list.count(func)) {
        (*(client_api_list[func]))(bufEvent,request_data);
    }
}

void sendDeviceInfo(struct bufferevent * bufEvent){
    Json::Value root;
    Json::Value data;
    //获取MAC地址
    data["mac"] = getMacAddress();
    data["name"] = device_name;
    root["protocol"] = API_DEVICE_INFO;
    root["is_app"] = false;
    root["data"] = data;
    string json = root.toStyledString();
    bufferevent_write(bufEvent, json.c_str(), json.length());
}

//读操作
void ReadEventCb(struct bufferevent *bufEvent, void *args){
   Json::Reader reader;
    Json::Value data;
    //获取输入缓存
    struct evbuffer * pInput = bufferevent_get_input(bufEvent);
    //获取输入缓存数据的长度
    int len = evbuffer_get_length(pInput);
    //获取数据
    char* body = new char[len+1];
    memset(body,0,sizeof(char)*(len+1));
    evbuffer_remove(pInput, body, len);
    if(reader.parse(body, data)){
        string func = data["protocol"].asString();
        callFunc(bufEvent,data,func);
    }
    delete[] body;
    return ;
}
//写操作
void WriteEventCb(struct bufferevent *bufEvent, void *args){

}
//关闭
void SignalEventCb(struct bufferevent * bufEvent, short sEvent, void * args){
    //请求的连接过程已经完成
    if(BEV_EVENT_CONNECTED == sEvent){
        bufferevent_enable(bufEvent, EV_READ);
        //设置读超时时间 10s
        struct timeval tTimeout = {10, 0};
        bufferevent_set_timeouts( bufEvent, &tTimeout, NULL);
        string mac = getMacAddress();
        if(mac.length() == 0){
            printf("MAC地址获取错误请检查网卡配置\n");
            event_base_loopexit(baseEvent, NULL);
            exit(0);
        }
        //发送基本信息
        sendDeviceInfo(bufEvent);
    }
    //写操作发生事件
    if(BEV_EVENT_WRITING & sEvent){}
    //操作时发生错误
    if (sEvent & BEV_EVENT_ERROR){
        perror("event");
        event_base_loopexit(baseEvent, NULL);
    }
    //结束指示
    if (sEvent & BEV_EVENT_EOF){
        perror("event");
        event_base_loopexit(baseEvent, NULL);
    }
    //读取发生事件或者超时处理
    if(0 != (sEvent & (BEV_EVENT_TIMEOUT|BEV_EVENT_READING)) ){
        //发送心跳包
        //
        //重新注册可读事件
        bufferevent_enable(bufEvent, EV_READ);
    }
    return ;
}
//设置配置文件
void setConfig(const char* config_path){
    Config config;
    //检测配置文件是否存在
    if(!config.FileExist(config_path)){
      printf("config: not find config file\n");
      exit(0);
    }
    //读取配置
    config.ReadFile(config_path);
    api_host = config.Read("SERVER_HOST", api_host);
    api_port = config.Read("API_PORT", api_port);
    network_card_name = config.Read("NETWORK_CARD", network_card_name);
    device_name = config.Read("DEVICE_NAME", device_name);
}
//开始
void startRun(const char* ip,int port){
    //创建事件驱动句柄
    baseEvent = event_base_new();
    //创建socket类型的bufferevent
    struct bufferevent* bufferEvent = bufferevent_socket_new(baseEvent, -1, 0);
    //构造服务器地址
    struct sockaddr_in sin;
    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = inet_addr(api_host.c_str());
    sin.sin_port = htons(api_port);
    //连接服务器
    if( bufferevent_socket_connect(bufferEvent, (struct sockaddr*)&sin, sizeof(sin)) < 0){
        perror("socket");
        return;
    }
    //设置回调函数, 及回调函数的参数
    bufferevent_setcb(bufferEvent, ReadEventCb, WriteEventCb, SignalEventCb,NULL);
    //开始事件循环
    event_base_dispatch(baseEvent);
    //事件循环结束 资源清理
    bufferevent_free(bufferEvent);
    event_base_free(baseEvent);
}
//初始化API列表
void initApiList() {
  client_api_list[API_DEVICE_BASE_INFO] = &handlerGetDeviceBaseInfo;
  client_api_list[API_DEVICE_KEY_DOWN] = &handlerKeyDown;
}

int main(){
    //加载API列表
    initApiList();
    //加载配置文件
    setConfig(CONFIG_PATH);
    //启动sockt
    startRun(api_host.c_str(),api_port);
    return 0;
}
<commit_msg>String to int<commit_after>#include "Main.h"

//获取基本信息
void handlerGetDeviceBaseInfo(struct bufferevent * bufEvent,Json::Value &data){
    char buffer[100];
    //获取内存大小
    struct sysinfo memInfo;
    sysinfo(&memInfo);
    //获取磁盘大小
    struct statfs diskInfo;
    statfs(DISK_SIZE_PATH, &diskInfo);
    //格式化数据
    double totalMemSize = (double)memInfo.totalram/(1024.0*1024.0);
    double usedMemSize = (double)(memInfo.totalram-memInfo.freeram)/(1024.0*1024.0);
    double totalDiskSize = (double)(diskInfo.f_bsize*diskInfo.f_blocks)/(1024.0*1024.0);
    double usedDiskSize = (double)(diskInfo.f_bsize*diskInfo.f_blocks-diskInfo.f_bsize*diskInfo.f_bfree)/(1024.0*1024.0);
    //构造返回JSON
    Json::Value root;
    Json::Value re_data;
    root["is_app"] = false;
    root["protocol"] = API_DEVICE_BASE_INFO;
    //总内存大小
    sprintf(buffer,"%.2f",totalMemSize);
    re_data["mem_total"] = string(buffer);
    memset(buffer,0,100);
    //使用内存
    sprintf(buffer,"%.2f",usedMemSize);
    re_data["mem_used"] = string(buffer);
    memset(buffer,0,100);
    //总硬盘大小
    sprintf(buffer,"%.2f",totalDiskSize);
    re_data["disk_total"] = string(buffer);
    memset(buffer,0,100);
    //使用硬盘大小
    sprintf(buffer,"%.2f",usedDiskSize);
    re_data["disk_used"] = string(buffer);
    memset(buffer,0,100);
    //返回数据
    root["data"] = re_data;
    bufferevent_write(bufEvent, root.toStyledString().c_str(), root.toStyledString().length());
}
//键盘按下
void handlerKeyDown(struct bufferevent * bufEvent,Json::Value &data){
    Json::Value key_map = data["data"];
    string key = key_map["key"].toStyledString();
    if(key.compare("119") == 0){
        printf("key down:%s\n", key.c_str());
    }else if(key.compare("115") == 0){
        printf("key down:%s\n", key.c_str());
    }else if(key.compare("97") == 0){
        printf("key down:%s\n", key.c_str());
    }else if(key.compare("100") == 0){
        printf("key down:%s\n", key.c_str());
    }else if(key.compare("105") == 0){
        printf("key down:%s\n", key.c_str());
    }else if(key.compare("107") == 0){
        printf("key down:%s\n", key.c_str());
    }else if(key.compare("106") == 0){
        printf("key down:%s\n", key.c_str());
    }else if(key.compare("108") == 0){
        printf("key down:%s\n", key.c_str());
    }else{
        printf("key not find:%s\n", key.c_str());
    }
}
//获取MAC地址
string getMacAddress(){
    char buff[32];
    memset (buff ,'\0', sizeof(buff));
    string cmd = "ip addr |grep -A 2 "+network_card_name+" | awk 'NR>1'|awk 'NR<2'|awk '{print $2}'";
    // 通过管道来回去系统命令返回的值
    FILE *fstream = popen(cmd.c_str(), "r");
    if(fstream == NULL) {
        perror("popen");
        exit(0);
    }
    if(NULL == fgets(buff, sizeof(buff), fstream)){
        printf("not find mac address !!!\n");
        exit(0);
    }
    pclose(fstream);
    string mac;
    mac = string(buff);
    mac = mac.substr(0, mac.length()-1);
    return mac;
}
//调用方法
void callFunc(struct bufferevent * bufEvent,Json::Value &request_data,const string func){
    if(func.length() == 0){
        return;
    }
    if (client_api_list.count(func)) {
        (*(client_api_list[func]))(bufEvent,request_data);
    }
}

void sendDeviceInfo(struct bufferevent * bufEvent){
    Json::Value root;
    Json::Value data;
    //获取MAC地址
    data["mac"] = getMacAddress();
    data["name"] = device_name;
    root["protocol"] = API_DEVICE_INFO;
    root["is_app"] = false;
    root["data"] = data;
    string json = root.toStyledString();
    bufferevent_write(bufEvent, json.c_str(), json.length());
}

//读操作
void ReadEventCb(struct bufferevent *bufEvent, void *args){
   Json::Reader reader;
    Json::Value data;
    //获取输入缓存
    struct evbuffer * pInput = bufferevent_get_input(bufEvent);
    //获取输入缓存数据的长度
    int len = evbuffer_get_length(pInput);
    //获取数据
    char* body = new char[len+1];
    memset(body,0,sizeof(char)*(len+1));
    evbuffer_remove(pInput, body, len);
    if(reader.parse(body, data)){
        string func = data["protocol"].asString();
        callFunc(bufEvent,data,func);
    }
    delete[] body;
    return ;
}
//写操作
void WriteEventCb(struct bufferevent *bufEvent, void *args){

}
//关闭
void SignalEventCb(struct bufferevent * bufEvent, short sEvent, void * args){
    //请求的连接过程已经完成
    if(BEV_EVENT_CONNECTED == sEvent){
        bufferevent_enable(bufEvent, EV_READ);
        //设置读超时时间 10s
        struct timeval tTimeout = {10, 0};
        bufferevent_set_timeouts( bufEvent, &tTimeout, NULL);
        string mac = getMacAddress();
        if(mac.length() == 0){
            printf("MAC地址获取错误请检查网卡配置\n");
            event_base_loopexit(baseEvent, NULL);
            exit(0);
        }
        //发送基本信息
        sendDeviceInfo(bufEvent);
    }
    //写操作发生事件
    if(BEV_EVENT_WRITING & sEvent){}
    //操作时发生错误
    if (sEvent & BEV_EVENT_ERROR){
        perror("event");
        event_base_loopexit(baseEvent, NULL);
    }
    //结束指示
    if (sEvent & BEV_EVENT_EOF){
        perror("event");
        event_base_loopexit(baseEvent, NULL);
    }
    //读取发生事件或者超时处理
    if(0 != (sEvent & (BEV_EVENT_TIMEOUT|BEV_EVENT_READING)) ){
        //发送心跳包
        //
        //重新注册可读事件
        bufferevent_enable(bufEvent, EV_READ);
    }
    return ;
}
//设置配置文件
void setConfig(const char* config_path){
    Config config;
    //检测配置文件是否存在
    if(!config.FileExist(config_path)){
      printf("config: not find config file\n");
      exit(0);
    }
    //读取配置
    config.ReadFile(config_path);
    api_host = config.Read("SERVER_HOST", api_host);
    api_port = config.Read("API_PORT", api_port);
    network_card_name = config.Read("NETWORK_CARD", network_card_name);
    device_name = config.Read("DEVICE_NAME", device_name);
}
//开始
void startRun(const char* ip,int port){
    //创建事件驱动句柄
    baseEvent = event_base_new();
    //创建socket类型的bufferevent
    struct bufferevent* bufferEvent = bufferevent_socket_new(baseEvent, -1, 0);
    //构造服务器地址
    struct sockaddr_in sin;
    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = inet_addr(api_host.c_str());
    sin.sin_port = htons(api_port);
    //连接服务器
    if( bufferevent_socket_connect(bufferEvent, (struct sockaddr*)&sin, sizeof(sin)) < 0){
        perror("socket");
        return;
    }
    //设置回调函数, 及回调函数的参数
    bufferevent_setcb(bufferEvent, ReadEventCb, WriteEventCb, SignalEventCb,NULL);
    //开始事件循环
    event_base_dispatch(baseEvent);
    //事件循环结束 资源清理
    bufferevent_free(bufferEvent);
    event_base_free(baseEvent);
}
//初始化API列表
void initApiList() {
  client_api_list[API_DEVICE_BASE_INFO] = &handlerGetDeviceBaseInfo;
  client_api_list[API_DEVICE_KEY_DOWN] = &handlerKeyDown;
}

int main(){
    //加载API列表
    initApiList();
    //加载配置文件
    setConfig(CONFIG_PATH);
    //启动sockt
    startRun(api_host.c_str(),api_port);
    return 0;
}
<|endoftext|>


<commit_before>/*===================================[ Algorithmen und Datenstrukturen]================================================================*
 *

 *
 * @Version:		1.0.0
 * @Author:			Achim Grolimund (achim.grolimund@hf-ict.info)
 * @Date:			01.1.2017
 *
 * @Description:

 *
 * Beispiel:

 *
 * Anmerkung:
 *
 *
 *==============================================[ EOF RDM ]=============================================================================*/

#define DEBUG
#include <bits/stdc++.h>

#include "C:/Users/achim/Documents/Programming/C++/HF-ICT-AAD/myFunks/myFunks/myfunks.h"
#include "C:/Users/achim/Documents/Programming/C++/HF-ICT-AAD/myFunks/myFunks/debug.h"

using namespace std;

int kgv(int,int);
int ggtRek(int,int);

int main()
{
	cout<<kgv(12,18)<<endl; //36

	return 0;
}

int kgv(int zahl1, int zahl2)
{
   return (zahl1*zahl2)/ggtRek(zahl1, zahl2);
}

//<-- GGT Berechnen Rekursiv -->
int ggtRek(int a, int b){
	if(b==0) return a;
	return ggtRek(b,a%b);
}
<commit_msg>update<commit_after>/*===================================[ Algorithmen und Datenstrukturen]================================================================*
 *

 *
 * @Version:		1.0.0
 * @Author:			Achim Grolimund (achim.grolimund@hf-ict.info)
 * @Date:			01.1.2017
 *
 * @Description:

 *
 * Beispiel:

 *
 * Anmerkung:
 *
 *
 *==============================================[ EOF RDM ]=============================================================================*/

#define DEBUG
#include <bits/stdc++.h>

#include "C:/Users/achim/Documents/Programming/C++/HF-ICT-AAD/myFunks/myFunks/myfunks.h"
#include "C:/Users/achim/Documents/Programming/C++/HF-ICT-AAD/myFunks/myFunks/debug.h"

using namespace std;

int kgv(int,int);
int ggtRek(int,int);

int main()
{

	auto start = myFunks::myTime::start();
	std::this_thread::sleep_for (std::chrono::seconds(1));
	cout<<kgv(12,18)<<endl; //36
	myFunks::myTime::stop(start);

	return 0;
}

int kgv(int zahl1, int zahl2)
{
   return (zahl1*zahl2)/ggtRek(zahl1, zahl2);
}

//<-- GGT Berechnen Rekursiv -->
int ggtRek(int a, int b){
	if(b==0) return a;
	return ggtRek(b,a%b);
}
<|endoftext|>


<commit_before>#include "distributions/joint_GMM.h"
#include "distributions/joint_gaussian.h"
#include "vector"
#include "bmp_image.h"
#include "dataset/distr_array.h"
#include "io/edda_vtk_reader.h"
#include "io/edda_vtk_writer.h"
#include "io/edda_reader.h"
#include "io/edda_writer.h"
#include "distributions/histogram.h"
#include "dataset/distr_array.h"

using namespace edda;
using namespace std;
using namespace edda::dist;

//using image to test joint Gaussian GMM
int main()
{
	//load testing image from disk
	BMPImage image("test_img.bmp");

	//down-sampled block size
	int blockSize = 20;
	int nVar = 3;//number of variables, rgb is 3 variables
	int nGmmComp = 2;//number of Gaussian compoenents

	//output image means and resampled image
	BMPImage optImage("test_img.bmp");//output image, randomly give a image file

	//number of row and col after down-sampleing
	int dsVs = image.height / blockSize;
	int dsUs = image.width / blockSize;

	//Joint GMM array
	shared_ary<JointGMM> array(new JointGMM[dsVs*dsUs], dsVs*dsUs);
	thrust::default_random_engine rng;//random engine for getJointSample()

	Real* varR = (Real*)malloc(sizeof(Real)*blockSize*blockSize);
	Real* varG = (Real*)malloc(sizeof(Real)*blockSize*blockSize);
	Real* varB = (Real*)malloc(sizeof(Real)*blockSize*blockSize);

	//loop: go through each block
	for (int dsV = 0; dsV < dsVs; dsV++){
		for (int dsU = 0; dsU < dsUs; dsU++){
			printf("%d %d\n", dsV, dsU);
			//prepare training vectors to OpenCV EM
			int cnt = 0;
			for (int v = dsV*blockSize; v<(dsV + 1)*blockSize; v++) {//row
				for (int u = dsU*blockSize; u<(dsU + 1)*blockSize; u++) {//col
					varR[cnt] = (Real)(image.bitmapImage[(v*image.width + u) * 3 + 0]);
					varG[cnt] = (Real)(image.bitmapImage[(v*image.width + u) * 3 + 1]);
					varB[cnt] = (Real)(image.bitmapImage[(v*image.width + u) * 3 + 2]);
					cnt++;
				}
			}

			//EM in Edda
			std::vector<Real*> trainSamples;
			trainSamples.push_back(varR);
			trainSamples.push_back(varG);
			trainSamples.push_back(varB);
			array[dsV*dsUs + dsU] = eddaComputeJointGMM(trainSamples, blockSize*blockSize, nGmmComp);

			//resample this block and write to image
			for (int i = 0; i < blockSize; i++){
				for (int j = 0; j < blockSize; j++){
					std::vector<Real> sample = getJointSample(array[dsV*dsUs + dsU], rng);

					int rawV = dsV*blockSize + i;//u and v in the original image resolution
					int rawU = dsU*blockSize + j;

					//trim value to 0-255, it possible to sample any value from gaussian
					//and store back to image buffer
					for (int k = 0; k < nVar; k++){
						if (sample[k] < 0)  sample[k] = 0;
						if (sample[k] > 255)sample[k] = 255;

						optImage.bitmapImage[(rawV*image.width + rawU) * 3 + k] = sample[k];
					}
				}
			}
		}
	}

	//shared_ptr<Dataset<std::vector<Real>> > dataset = make_Dataset<std::vector<Real>>(
	//	new RegularCartesianGrid(1, 1, dsVs*dsUs),
	//	array
	//	);

	// safe to free data, after constructing the distribution
	free(varR);
	free(varG);
	free(varB);

	//write three images to disk
	optImage.writeImage(std::string("jointGMMTestOutput.bmp").c_str());//this is the output file name

	std::cout << "Press any key to finish" << std::endl;
	getchar();

}<commit_msg>Minor fix for test_jointGMM.cpp<commit_after>#include "distributions/joint_GMM.h"
#include "distributions/joint_gaussian.h"
#include "vector"
#include "bmp_image.h"
#include "dataset/distr_array.h"
#include "io/edda_vtk_reader.h"
#include "io/edda_vtk_writer.h"
#include "io/edda_reader.h"
#include "io/edda_writer.h"
#include "distributions/histogram.h"
#include "dataset/distr_array.h"

using namespace edda;
using namespace std;
using namespace edda::dist;

//using image to test joint Gaussian GMM
int main()
{
	//load testing image from disk
	BMPImage image("test_img.bmp");

	//down-sampled block size
	int blockSize = 20;
	int nVar = 3;//number of variables, rgb is 3 variables
	int nGmmComp = 2;//number of Gaussian compoenents

	//output image means and resampled image
	BMPImage optImage("test_img.bmp");//output image, randomly give a image file

	//number of row and col after down-sampleing
	int dsVs = image.height / blockSize;
	int dsUs = image.width / blockSize;

	//Joint GMM array
	shared_ary<JointGMM> array(new JointGMM[dsVs*dsUs], dsVs*dsUs);
	thrust::default_random_engine rng;//random engine for getJointSample()

	Real* varR = (Real*)malloc(sizeof(Real)*blockSize*blockSize);
	Real* varG = (Real*)malloc(sizeof(Real)*blockSize*blockSize);
	Real* varB = (Real*)malloc(sizeof(Real)*blockSize*blockSize);

	//loop: go through each block
	for (int dsV = 0; dsV < dsVs; dsV++){
		for (int dsU = 0; dsU < dsUs; dsU++){
			printf("%d %d\n", dsV, dsU);
			//prepare training vectors to OpenCV EM
			int cnt = 0;
			for (int v = dsV*blockSize; v<(dsV + 1)*blockSize; v++) {//row
				for (int u = dsU*blockSize; u<(dsU + 1)*blockSize; u++) {//col
					varR[cnt] = (Real)(image.bitmapImage[(v*image.width + u) * 3 + 0]);
					varG[cnt] = (Real)(image.bitmapImage[(v*image.width + u) * 3 + 1]);
					varB[cnt] = (Real)(image.bitmapImage[(v*image.width + u) * 3 + 2]);
					cnt++;
				}
			}

			//EM in Edda
			std::vector<Real*> trainSamples;
			trainSamples.push_back(varR);
			trainSamples.push_back(varG);
			trainSamples.push_back(varB);
			array[dsV*dsUs + dsU] = eddaComputeJointGMM(trainSamples, blockSize*blockSize, nGmmComp);

			//resample this block and write to image
			for (int i = 0; i < blockSize; i++){
				for (int j = 0; j < blockSize; j++){
					std::vector<Real> sample = getJointSample(array[dsV*dsUs + dsU], rng);

					int rawV = dsV*blockSize + i;//u and v in the original image resolution
					int rawU = dsU*blockSize + j;

					//trim value to 0-255, it possible to sample any value from gaussian
					//and store back to image buffer
					for (int k = 0; k < nVar; k++){
						if (sample[k] < 0)  sample[k] = 0;
						if (sample[k] > 255)sample[k] = 255;

						optImage.bitmapImage[(rawV*image.width + rawU) * 3 + k] = sample[k];
					}
				}
			}
		}
	}

	//shared_ptr<Dataset<std::vector<Real>> > dataset = make_Dataset<std::vector<Real>>(
	//	new RegularCartesianGrid(1, 1, dsVs*dsUs),
	//	array
	//	);

	// safe to free data, after constructing the distribution
	free(varR);
	free(varG);
	free(varB);

	//write three images to disk
	optImage.writeImage(std::string("jointGMMTestOutputggg.bmp").c_str());//this is the output file name

	std::cout << "Press any key to finish" << std::endl;
	getchar();

}<|endoftext|>