<commit_before>#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <unordered_map>

#include <Mandelbrot.h>
#include <../constants.h>
#include <vector>

using namespace std;

double scale(double, double, double, double, double);

int main()
{
    SDL_Renderer *renderer;
    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_Window *w;
    SDL_CreateWindowAndRenderer(SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN, &w, &renderer);
    SDL_SetWindowTitle(w, "Test");

    TTF_Init();
    TTF_Font* font = TTF_OpenFont("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 12);
    SDL_Color White = { 255, 255, 255};

    if (!font)
    {
        printf("%s", TTF_GetError());
        return 0;
    }

    Mandelbrot m;

    enum Style {
        Banded, Smooth, STYLE_SIZE
    };

    enum Palette {
        Linear, Pre1, PALETTE_SIZE
    };

    string StyleNames[] = { "Banded", "Smooth", "NULL" };
    string PaletteNames[] = { "Linear", "Pre 1", "NULL" };

    const int gradientScale = 256;
    const float stops[] = { 0, 0.16, 0.42, 0.6425, 0.8575, 1 };
    SDL_Color stopcols[] = { { 0, 7, 100}, { 32, 107, 203}, { 237, 255, 255}, { 255, 170, 0}, { 0, 2, 0} };
    SDL_Color *gradient = new SDL_Color[gradientScale];

    SDL_Color linearColor = { 255, 0, 0 };

    for (int i = 0, n = 0; i < gradientScale; i++)
    {
        float f = (float)i / gradientScale;
        if (f > stops[n + 1]) n++;
        gradient[i] = { scale(f, stops[n], stops[n + 1], stopcols[n].r, stopcols[(n + 1) % 5].r), scale(f, stops[n], stops[n + 1], stopcols[n].g, stopcols[(n + 1) % 5].g), scale(f, stops[n], stops[n + 1], stopcols[n].b, stopcols[(n + 1) % 5].b) };
    }

    unordered_map<SDL_Keycode, bool> keys;
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    SDL_RenderClear(renderer);
    SDL_RenderPresent(renderer);

    int lx = -1, ly = -1;
    int mx = 0, my = 0;
    int lastiter = m.iter;
    Style style = Banded;
    Palette palette = Linear;
    double *vals = new double[SCREEN_HEIGHT * SCREEN_WIDTH]();

    bool redraw = false;
    bool recalc = true;
    long double loffx = 0, loffy = 0;
    SDL_Event e;
    while (true)
    {
        while (SDL_PollEvent(&e))
        {
            if (e.type == SDL_QUIT) return 0;
            else if (e.type == SDL_KEYDOWN && !keys[e.key.keysym.sym])
            {
                keys[e.key.keysym.sym] = true;
                switch (e.key.keysym.sym)
                {
                    case SDLK_ESCAPE: return 0;
                    case SDLK_r: recalc = true; break;
                    case SDLK_t: redraw = true; break;
                    case SDLK_s: style = (Style)((style + 1) % STYLE_SIZE);
                        redraw = true;
                        break;
                    case SDLK_a: palette = (Palette)((palette + 1) % PALETTE_SIZE);
                        redraw = true;
                        break;
                }
            }
            else if (e.type == SDL_KEYUP && keys[e.key.keysym.sym]) keys[e.key.keysym.sym] = false;
            else if (e.type == SDL_MOUSEMOTION)
            {
                if (keys[e.button.button])
                {
                    m.offx = loffx + (lx - mx) * m.zoom;
                    m.offy = loffy + (ly - my) * m.zoom;
                    //loffx = m.offx;
                   //loffy = m.offy;
                }
                mx = e.button.x;
                my = e.button.y;
                //redraw = true;
            }
            else if (e.type == SDL_MOUSEBUTTONDOWN && !keys[e.button.button])
            {
                lx = mx;
                ly = my;
                keys[e.button.button] = true;
            }
            else if (e.type == SDL_MOUSEBUTTONUP)
            {
                loffx = m.offx;
                loffy = m.offy;
                keys[e.button.button] = false;
            }
            else if (e.type == SDL_MOUSEWHEEL)
            {
                if (e.wheel.y > 0)
                {
                    loffx = m.offx = loffx + (mx * m.zoom) - ((SCREEN_WIDTH / 2.0) * m.zoom);
                    loffy = m.offy = loffy + (my * m.zoom) - ((SCREEN_HEIGHT / 2.0) * m.zoom);
                    m.zoom /= 1.1 * e.wheel.y;
                    SDL_WarpMouseInWindow(w, SCREEN_WIDTH / 2.0, SCREEN_HEIGHT / 2.0);
                    recalc = true;
                }
                else if (e.wheel.y < 0)
                {
                    m.zoom *= -1.1 * e.wheel.y;
                    //loffx = m.offx = loffx + (lx - mx) * m.zoom;
                    //loffy = m.offy = loffy + (ly - my) * m.zoom;
                    recalc = true;
                }
            }

            if (keys[SDLK_KP_PLUS] && e.key.keysym.sym == SDLK_KP_PLUS)
            {
                if (keys[SDLK_i]) m.iter++;
                if (keys[SDLK_KP_1]) linearColor.r = min(255, linearColor.r + 1);
                if (keys[SDLK_KP_2]) linearColor.g = min(255, linearColor.g + 1);
                if (keys[SDLK_KP_3]) linearColor.b = min(255, linearColor.b + 1);

                if (m.iter > MAX_ITER) m.iter = MAX_ITER;
            }

            if (keys[SDLK_KP_MINUS] && e.key.keysym.sym == SDLK_KP_MINUS)
            {
                if (keys[SDLK_i]) m.iter--;
                if (keys[SDLK_KP_1]) linearColor.r = max(0, linearColor.r - 1);
                if (keys[SDLK_KP_2]) linearColor.g = max(0, linearColor.g - 1);
                if (keys[SDLK_KP_3]) linearColor.b = max(0, linearColor.b - 1);

                if (m.iter < 2) m.iter = 2;
            }

            if (m.iter != lastiter)
            {
                recalc = true;
                lastiter = m.iter;
            }
        }

        if (recalc)
        {
            m.Update(vals);
            redraw = true;
        }

        if (redraw)
        {
            SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
            SDL_RenderClear(renderer);
            for (int y = 0; y < SCREEN_HEIGHT; y++)
            {
                for (int x = 0; x < SCREEN_WIDTH; x++)
                {
                    double n = vals[y * SCREEN_WIDTH + x];
                    if (n < 0) continue;
                    int k = (int)n;
                    if (style == Banded)
                    {
                        switch (palette)
                        {
                            case Linear:
                                SDL_SetRenderDrawColor(renderer,
                                    scale(k, 0, m.iter, 0, linearColor.r),
                                    scale(k, 0, m.iter, 0, linearColor.g),
                                    scale(k, 0, m.iter, 0, linearColor.b), 255);
                                break;
                            case Pre1:
                                SDL_SetRenderDrawColor(renderer,
                                    gradient[k % gradientScale].r,
                                    gradient[k % gradientScale].g,
                                    gradient[k % gradientScale].b, 255);
                                break;
                        }
                    }
                    else if (style == Smooth)
                    {
                        switch (palette)
                        {
                            case Linear:
                            {
                                SDL_Color a = { scale(k, 0, m.iter, 0, linearColor.r),
                                    scale(k, 0, m.iter, 0, linearColor.g),
                                    scale(k, 0, m.iter, 0, linearColor.b) };
                                SDL_Color b = { scale(k + 1, 0, m.iter, 0, linearColor.r),
                                    scale(k + 1, 0, m.iter, 0, linearColor.g),
                                    scale(k + 1, 0, m.iter, 0, linearColor.b) };
                                SDL_SetRenderDrawColor(renderer,
                                    scale(n - (int)n, 0, 1, a.r, b.r),
                                    scale(n - (int)n, 0, 1, a.g, b.g),
                                    scale(n - (int)n, 0, 1, a.b, b.b) , 255);
                                break;
                            }
                            case Pre1:
                                SDL_SetRenderDrawColor(renderer,
                                    scale(n - (int)n, 0, 1, gradient[k % gradientScale].r, gradient[(k + 1) % gradientScale].r),
                                    scale(n - (int)n, 0, 1, gradient[k % gradientScale].g, gradient[(k + 1) % gradientScale].g),
                                    scale(n - (int)n, 0, 1, gradient[k % gradientScale].b, gradient[(k + 1) % gradientScale].b), 255);
                                break;
                        }
                    }
                    SDL_RenderDrawPoint(renderer, x, y);
                }
            }

            string s = "Palette: " + PaletteNames[palette] + "\n" +
                        "Style: " + StyleNames[style] + "\n" +
                        "Iters: " + to_string(m.iter);

            SDL_Surface* txt = TTF_RenderText_Blended_Wrapped(font, s.c_str(), White, 500);
            SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, txt);
            SDL_Rect r; r.x = 10; r.y = 5;
            SDL_QueryTexture(tex, NULL, NULL, &r.w, &r.h);
            SDL_RenderCopy(renderer, tex, NULL, &r);
            SDL_FreeSurface(txt);
            if (palette == Linear)
            {
                s = "{ " + to_string(linearColor.r) + ", " + to_string(linearColor.g) + ", " + to_string(linearColor.b) + " }";
                txt = TTF_RenderText_Blended_Wrapped(font, s.c_str(), linearColor, 500);
                tex = SDL_CreateTextureFromSurface(renderer, txt);
                SDL_Rect r; r.x = 120; r.y = 5;
                SDL_QueryTexture(tex, NULL, NULL, &r.w, &r.h);
                SDL_RenderCopy(renderer, tex, NULL, &r);
                SDL_FreeSurface(txt);
            }
            else if (palette == Pre1)
            {
                for (int i = 0; i < gradientScale; i++)
                {
                    SDL_SetRenderDrawColor(renderer, gradient[i].r, gradient[i].g, gradient[i].b, 255);
                    SDL_RenderDrawLine(renderer, i + 120, 5, i + 120, 15);
                }
            }

            SDL_RenderPresent(renderer);
            redraw = false;
        }
    }
}

double scale(double v, double vl, double vh, double nl, double nh)
{
    return nl + (nh - nl) * (v - vl) / (vh - vl);
}
<commit_msg>Converted single-gradient variable to arrays for easy expansion (WIP)<commit_after>#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <unordered_map>

#include <Mandelbrot.h>
#include <../constants.h>
#include <vector>

using namespace std;

double scale(double, double, double, double, double);

int main()
{
    SDL_Renderer *renderer;
    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_Window *w;
    SDL_CreateWindowAndRenderer(SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN, &w, &renderer);
    SDL_SetWindowTitle(w, "Test");

    TTF_Init();
    TTF_Font* font = TTF_OpenFont("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 12);
    SDL_Color White = { 255, 255, 255};

    if (!font)
    {
        printf("%s", TTF_GetError());
        return 0;
    }

    Mandelbrot m;

    enum Style {
        Banded, Smooth, STYLE_SIZE
    };

    enum Palette {
        Linear, Pre1, Pre2, PALETTE_SIZE
    };

    string StyleNames[] = { "Banded", "Smooth", "NULL" };
    string PaletteNames[] = { "Linear", "Ultra Fractal", "Fire", "NULL" };

    const int gradientScale = 256;
    vector<float> stops[] { { 0, 0.16, 0.42, 0.6425, 0.8575, 1 }, { 0,  };
    vector<SDL_Color> stopcols[] = { { { 0, 7, 100}, { 32, 107, 203}, { 237, 255, 255}, { 255, 170, 0}, { 0, 2, 0} } };
    vector<SDL_Color*> gradient;

    SDL_Color linearColor = { 255, 0, 0 };

    for (int p = 0; p < PALETTE_SIZE - 1; p++)
    {
        gradient.push_back(new SDL_Color[gradientScale]);
        for (int i = 0, n = 0; i < gradientScale; i++)
        {
            float f = (float)i / gradientScale;
            if (f > stops[p][n + 1]) n++;
            gradient[p][i] = {
                scale(f, stops[p][n], stops[p][n + 1], stopcols[p][n].r, stopcols[p][(n + 1) % 5].r),
                scale(f, stops[p][n], stops[p][n + 1], stopcols[p][n].g, stopcols[p][(n + 1) % 5].g),
                scale(f, stops[p][n], stops[p][n + 1], stopcols[p][n].b, stopcols[p][(n + 1) % 5].b)
            };
        }
    }

    unordered_map<SDL_Keycode, bool> keys;
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    SDL_RenderClear(renderer);
    SDL_RenderPresent(renderer);

    int lx = -1, ly = -1;
    int mx = 0, my = 0;
    int lastiter = m.iter;
    Style style = Banded;
    Palette palette = Linear;
    double *vals = new double[SCREEN_HEIGHT * SCREEN_WIDTH]();

    bool redraw = false;
    bool recalc = true;
    long double loffx = 0, loffy = 0;
    SDL_Event e;
    while (true)
    {
        while (SDL_PollEvent(&e))
        {
            if (e.type == SDL_QUIT) return 0;
            else if (e.type == SDL_KEYDOWN && !keys[e.key.keysym.sym])
            {
                keys[e.key.keysym.sym] = true;
                switch (e.key.keysym.sym)
                {
                    case SDLK_ESCAPE: return 0;
                    case SDLK_r: recalc = true; break;
                    case SDLK_t: redraw = true; break;
                    case SDLK_s: style = (Style)((style + 1) % STYLE_SIZE);
                        redraw = true;
                        break;
                    case SDLK_a: palette = (Palette)((palette + 1) % PALETTE_SIZE);
                        redraw = true;
                        break;
                }
            }
            else if (e.type == SDL_KEYUP && keys[e.key.keysym.sym]) keys[e.key.keysym.sym] = false;
            else if (e.type == SDL_MOUSEMOTION)
            {
                if (keys[e.button.button])
                {
                    m.offx = loffx + (lx - mx) * m.zoom;
                    m.offy = loffy + (ly - my) * m.zoom;
                    //loffx = m.offx;
                   //loffy = m.offy;
                }
                mx = e.button.x;
                my = e.button.y;
                //redraw = true;
            }
            else if (e.type == SDL_MOUSEBUTTONDOWN && !keys[e.button.button])
            {
                lx = mx;
                ly = my;
                keys[e.button.button] = true;
            }
            else if (e.type == SDL_MOUSEBUTTONUP)
            {
                loffx = m.offx;
                loffy = m.offy;
                keys[e.button.button] = false;
            }
            else if (e.type == SDL_MOUSEWHEEL)
            {
                if (e.wheel.y > 0)
                {
                    loffx = m.offx = loffx + (mx * m.zoom) - ((SCREEN_WIDTH / 2.0) * m.zoom);
                    loffy = m.offy = loffy + (my * m.zoom) - ((SCREEN_HEIGHT / 2.0) * m.zoom);
                    m.zoom /= 1.1 * e.wheel.y;
                    SDL_WarpMouseInWindow(w, SCREEN_WIDTH / 2.0, SCREEN_HEIGHT / 2.0);
                    recalc = true;
                }
                else if (e.wheel.y < 0)
                {
                    m.zoom *= -1.1 * e.wheel.y;
                    //loffx = m.offx = loffx + (lx - mx) * m.zoom;
                    //loffy = m.offy = loffy + (ly - my) * m.zoom;
                    recalc = true;
                }
            }

            if (keys[SDLK_KP_PLUS] && e.key.keysym.sym == SDLK_KP_PLUS)
            {
                if (keys[SDLK_i]) m.iter++;
                if (keys[SDLK_KP_1]) linearColor.r = min(255, linearColor.r + 1);
                if (keys[SDLK_KP_2]) linearColor.g = min(255, linearColor.g + 1);
                if (keys[SDLK_KP_3]) linearColor.b = min(255, linearColor.b + 1);

                if (m.iter > MAX_ITER) m.iter = MAX_ITER;
            }

            if (keys[SDLK_KP_MINUS] && e.key.keysym.sym == SDLK_KP_MINUS)
            {
                if (keys[SDLK_i]) m.iter--;
                if (keys[SDLK_KP_1]) linearColor.r = max(0, linearColor.r - 1);
                if (keys[SDLK_KP_2]) linearColor.g = max(0, linearColor.g - 1);
                if (keys[SDLK_KP_3]) linearColor.b = max(0, linearColor.b - 1);

                if (m.iter < 2) m.iter = 2;
            }

            if (m.iter != lastiter)
            {
                recalc = true;
                lastiter = m.iter;
            }
        }

        if (recalc)
        {
            m.Update(vals);
            redraw = true;
        }

        if (redraw)
        {
            SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
            SDL_RenderClear(renderer);
            for (int y = 0; y < SCREEN_HEIGHT; y++)
            {
                for (int x = 0; x < SCREEN_WIDTH; x++)
                {
                    double n = vals[y * SCREEN_WIDTH + x];
                    if (n < 0) continue;
                    int k = (int)n;
                    if (style == Banded)
                    {
                        switch (palette)
                        {
                            case Linear:
                                SDL_SetRenderDrawColor(renderer,
                                    scale(k, 0, m.iter, 0, linearColor.r),
                                    scale(k, 0, m.iter, 0, linearColor.g),
                                    scale(k, 0, m.iter, 0, linearColor.b), 255);
                                break;
                            case Pre1:
                                SDL_SetRenderDrawColor(renderer,
                                    gradient[palette][k % gradientScale].r,
                                    gradient[palette][k % gradientScale].g,
                                    gradient[palette][k % gradientScale].b, 255);
                                break;
                        }
                    }
                    else if (style == Smooth)
                    {
                        switch (palette)
                        {
                            case Linear:
                            {
                                SDL_Color a = { scale(k, 0, m.iter, 0, linearColor.r),
                                    scale(k, 0, m.iter, 0, linearColor.g),
                                    scale(k, 0, m.iter, 0, linearColor.b) };
                                SDL_Color b = { scale(k + 1, 0, m.iter, 0, linearColor.r),
                                    scale(k + 1, 0, m.iter, 0, linearColor.g),
                                    scale(k + 1, 0, m.iter, 0, linearColor.b) };
                                SDL_SetRenderDrawColor(renderer,
                                    scale(n - (int)n, 0, 1, a.r, b.r),
                                    scale(n - (int)n, 0, 1, a.g, b.g),
                                    scale(n - (int)n, 0, 1, a.b, b.b) , 255);
                                break;
                            }
                            case Pre1:
                                SDL_SetRenderDrawColor(renderer,
                                    scale(n - (int)n, 0, 1, gradient[palette][k % gradientScale].r, gradient[palette][(k + 1) % gradientScale].r),
                                    scale(n - (int)n, 0, 1, gradient[palette][k % gradientScale].g, gradient[palette][(k + 1) % gradientScale].g),
                                    scale(n - (int)n, 0, 1, gradient[palette][k % gradientScale].b, gradient[palette][(k + 1) % gradientScale].b), 255);
                                break;
                        }
                    }
                    SDL_RenderDrawPoint(renderer, x, y);
                }
            }

            string s = "Palette: " + PaletteNames[palette] + "\n" +
                        "Style: " + StyleNames[style] + "\n" +
                        "Iters: " + to_string(m.iter);

            SDL_Surface* txt = TTF_RenderText_Blended_Wrapped(font, s.c_str(), White, 500);
            SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, txt);
            SDL_Rect r; r.x = 10; r.y = 5;
            SDL_QueryTexture(tex, NULL, NULL, &r.w, &r.h);
            SDL_RenderCopy(renderer, tex, NULL, &r);
            SDL_FreeSurface(txt);
            if (palette == Linear)
            {
                s = "{ " + to_string(linearColor.r) + ", " + to_string(linearColor.g) + ", " + to_string(linearColor.b) + " }";
                txt = TTF_RenderText_Blended_Wrapped(font, s.c_str(), linearColor, 500);
                tex = SDL_CreateTextureFromSurface(renderer, txt);
                SDL_Rect r; r.x = 120; r.y = 5;
                SDL_QueryTexture(tex, NULL, NULL, &r.w, &r.h);
                SDL_RenderCopy(renderer, tex, NULL, &r);
                SDL_FreeSurface(txt);
            }
            else if (palette == Pre1)
            {
                for (int i = 0; i < gradientScale; i++)
                {
                    SDL_SetRenderDrawColor(renderer, gradient[palette][i].r, gradient[palette][i].g, gradient[palette][i].b, 255);
                    SDL_RenderDrawLine(renderer, i + 120, 5, i + 120, 15);
                }
            }

            SDL_RenderPresent(renderer);
            redraw = false;
        }
    }
}

double scale(double v, double vl, double vh, double nl, double nh)
{
    return nl + (nh - nl) * (v - vl) / (vh - vl);
}
<|endoftext|>


<commit_before>9fc2bd28-ad58-11e7-8a97-ac87a332f658<commit_msg>Bug fixes and performance improvements<commit_after>a02d9e54-ad58-11e7-a0b1-ac87a332f658<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

int main()
{
    cout << "Hello World!" << endl;
    return 0;
}

<commit_msg>Test Qt built-in tools<commit_after>#include <iostream>

using namespace std;

int main()
{
    cout << "~" << endl;
    return 0;
}

<|endoftext|>


<commit_before>39e2c7a1-ad58-11e7-9573-ac87a332f658<commit_msg>fix for the previous fix<commit_after>3a5e8bb8-ad58-11e7-ae9d-ac87a332f658<|endoftext|>


<commit_before>#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <netcdf.h>
#include <cudpp.h>
#include <cutil.h>

#include "cuda_test.h"
#include "cpu_test.h"
#include "cuda_defs.h"

#define ERRCODE 2
#define ERR(e) {printf("Error: %s\n", nc_strerror(e)); exit(ERRCODE);}

#define TIME 1
#define LAT 190
#define LON 384
#define VARNAME "TMP_2maboveground"

void unpack_data(char *filename, float *data_in);

int main()
{

	unsigned int start = 1985;
	unsigned int end = 2009;
	unsigned int tsamples = ((end-start) + 1)*12;
	unsigned int nf = 9;

	unsigned int nSamples = 10;
        unsigned int dim = tsamples * LAT * LON;

	char filename[23];
	float *data = NULL;
	CPUMALLOC((void**)&data, sizeof(float)*nSamples*dim);
	printf("%d\n", nSamples*dim);

	int moffset, yoffset, foffset;
	for (int y =start; y<=end; y++){
		yoffset = (LAT*LON*12) * (y-start);
		for (int m = 1; m<=12; m++){
			sprintf(filename, "../data/TMP_%d%02d_a.nc", y, m);
			moffset = LAT*LON*(m-1);
			unpack_data(filename, (data+yoffset+moffset));
		}
	}

	char ffilename[25];
	for (int f = 1; f<=9; f++){
		foffset = dim*f;
		for (int y =start; y<=end; y++){
			yoffset = (LAT*LON*12) * (y-start);
        	 	for (int m = 1; m<=12; m++){
                		sprintf(ffilename, "../data/TMP_%d%02d_f%02d.nc", y, m, f);
				moffset = LAT*LON*(m-1);
				unpack_data(ffilename, (data+(foffset+yoffset+moffset)));
    	            }
        	}
	}
	assert((foffset+yoffset+moffset+LAT*LON)==(dim*nSamples));

	/*  Allocate enough space.. */
	testall(data, nSamples, dim);
       // test_kdtree(data, nSamples, dim);
	return 0;
}

void unpack_data(char *filename, float *data_in){
	//netCDF fileit and data var
	int ncid, varid;

	//loop inds and error_handling
	int ld, la, ln, retval;

	/** Open the file. NC_NOWRITE tells netCDF
  	we want read-only access  to the file.*/
  	if((retval = nc_open(filename, NC_NOWRITE, &ncid)))
		ERR(retval);

	/** Get the varid of the data variable,
 	    based on its name. */
   	if ((retval = nc_inq_varid(ncid, VARNAME, &varid)))
		ERR(retval);

	/* Read the data. */
   	if ((retval = nc_get_var_float(ncid, varid, data_in)))
      		ERR(retval);

   	/* Close the file, freeing all resources. */
   	if ((retval = nc_close(ncid)))
     		 ERR(retval);

   	printf("*** SUCCESS reading %s!\n", filename);
}

<commit_msg>transpose implemented/verified<commit_after>#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <netcdf.h>
#include <cudpp.h>
#include <cutil.h>

#include "cuda_test.h"
#include "cpu_test.h"
#include "cuda_defs.h"

#define ERRCODE 2
#define ERR(e) {printf("Error: %s\n", nc_strerror(e)); exit(ERRCODE);}

#define TIME 1
#define LAT 190
#define LON 384
#define VARNAME "TMP_2maboveground"

void unpack_data(char *filename, float *data_in);
int main()
{

	unsigned int start = 1985;
	unsigned int end = 2009;
	unsigned int tsamples = ((end-start) + 1)*12;
	unsigned int nf = 9;

	unsigned int dim = 9;
        unsigned int nSamples = tsamples * LAT * LON;

	char filename[23];
	float *data = NULL;
	float *dataT = NULL;
	CPUMALLOC((void**)&data, sizeof(float)*nSamples*dim);
	CPUMALLOC((void**)&dataT, sizeof(float)*nSamples*dim);

	printf("%d\n", nSamples*dim);

	int moffset, yoffset, foffset;
	/**
 	char filename[23];
	for (int y =start; y<=end; y++){
		yoffset = (LAT*LON*12) * (y-start);
		for (int m = 1; m<=12; m++){
			sprintf(filename, "../data/TMP_%d%02d_a.nc", y, m);
			moffset = LAT*LON*(m-1);
			unpack_data(filename, (data+yoffset+moffset));
		}
	}
	**/

	char ffilename[25];
	for (int f = 1; f<=9; f++){
		foffset = nSamples*(f-1);
		for (int y =start; y<=end; y++){
			yoffset = (LAT*LON*12) * (y-start);
        	 	for (int m = 1; m<=12; m++){
                		sprintf(ffilename, "../data/TMP_%d%02d_f%02d.nc", y, m, f);
				moffset = LAT*LON*(m-1);
				unpack_data(ffilename, (data+(foffset+yoffset+moffset)));
    	            }
        	}
	}
	assert((foffset+yoffset+moffset+LAT*LON)==(dim*nSamples));
	//Transpose
	//http://stackoverflow.com/a/16743203/1267531
	for(int n=0; n<(nSamples*dim); n++){
		dataT[n] = data[nSamples*(n%dim) +(n/dim)];
	}
	/*  Allocate enough space.. */
	testall(dataT, nSamples, dim);
       // test_kdtree(data, nSamples, dim);
	return 0;
}

void unpack_data(char *filename, float *data_in){
	//netCDF fileit and data var
	int ncid, varid;

	//loop inds and error_handling
	int ld, la, ln, retval;

	/** Open the file. NC_NOWRITE tells netCDF
  	we want read-only access  to the file.*/
  	if((retval = nc_open(filename, NC_NOWRITE, &ncid)))
		ERR(retval);

	/** Get the varid of the data variable,
 	    based on its name. */
   	if ((retval = nc_inq_varid(ncid, VARNAME, &varid)))
		ERR(retval);

	/* Read the data. */
   	if ((retval = nc_get_var_float(ncid, varid, data_in)))
      		ERR(retval);

   	/* Close the file, freeing all resources. */
   	if ((retval = nc_close(ncid)))
     		 ERR(retval);

   	printf("*** SUCCESS reading %s!\n", filename);
}

<|endoftext|>


<commit_before>7e69b9c0-4b02-11e5-a4c9-28cfe9171a43<commit_msg>master branch<commit_after>7e73d9f0-4b02-11e5-b98d-28cfe9171a43<|endoftext|>


<commit_before>/**
 * @author wezside
 * Based on the code from Bildr (http://bildr.org/2011/02/74hc595/)
 */

#include "Arduino.h"

//How many of the shift registers - change this
#define number_of_74hc595s 1

//do not touch
#define numOfRegisterPins number_of_74hc595s * 8

#define SPEED 30

int SER_Pin = 8;   //pin 14 on the 75HC595
int RCLK_Pin = 9;  //pin 12 on the 75HC595
int SRCLK_Pin = 10; //pin 11 on the 75HC595

int anime = 0;
int counter = 0;
int shift_right_counter = 4;
int shift_left_counter = 0;

// 0110 1001 1111 1001
char a[] = {0, 0, 0, 0};
char a_copy[] = {6, 9, 15, 9};

// Registers or Shift register pins
boolean registers[numOfRegisterPins];

// Forward declarations
void clearRegisters();
void writeRegisters();
void row(int i);
void col(int i);

void setup()
{
	Serial.begin(115200);

	pinMode(SER_Pin, OUTPUT);
	pinMode(RCLK_Pin, OUTPUT);
	pinMode(SRCLK_Pin, OUTPUT);

	// Reset all register pins
	clearRegisters();
	writeRegisters();
}

//set all register pins to LOW
void clearRegisters()
{
	for(int i = numOfRegisterPins - 1; i >=  0; i--)
	{
		registers[i] = LOW;
	}
}

//Set and display registers
//Only call AFTER all values are set how you would like (slow otherwise)
void writeRegisters()
{
	digitalWrite(RCLK_Pin, LOW);
	for(int i = numOfRegisterPins - 1; i >=  0; i--)
	{
		digitalWrite(SRCLK_Pin, LOW);
		int val = registers[i];
		digitalWrite(SER_Pin, val);
		digitalWrite(SRCLK_Pin, HIGH);

	}
	digitalWrite(RCLK_Pin, HIGH);
}

void setRegisterPin(int index, int value)
{
	registers[index] = value;
}

void loop()
{
	clearRegisters();
	writeRegisters();

	// Wrap around for row counter
	if (counter == 4) counter = 0;

	// Light up the row with index
	row(counter);

	// Animate in (right to left)
	if (anime % SPEED == 0 && shift_right_counter != -1)
	{
		// For each of the rows
		for (int i = 0; i < 4; ++i)
		{
			a[i] = a_copy[i] >> shift_right_counter;
		}
		shift_right_counter--;
	}

	// Animate out (right to left)
	if (anime % SPEED == 0 && shift_left_counter <= 4 && shift_right_counter == -1)
	{
		// For each of the rows
		for (int i = 0; i < 4; ++i)
		{
			a[i] = a_copy[i] << shift_left_counter;
		}
		shift_left_counter++;
	}

	// Animation frame counter
	anime++;

	for (int i = 0; i < 4; ++i)
	{
		if (!(a[counter] & 1 << i)) col(i);
	}
	writeRegisters();
	delay(5);

	if (counter < 4) counter ++;
	else counter = 0;
}

void row(int i)
{
	setRegisterPin(i, HIGH);
}

void col(int i)
{
	setRegisterPin(i + 4, HIGH);
}	<commit_msg>Refactored methods<commit_after>/**
 * @author wezside
 * Based on the code from Bildr (http://bildr.org/2011/02/74hc595/)
 */

#include "Arduino.h"

//How many of the shift registers - change this
#define number_of_74hc595s 1

//do not touch
#define numOfRegisterPins number_of_74hc595s * 8

// Lower will be faster must be larger than 0
#define SPEED 30

int SER_Pin = 8;   //pin 14 on the 75HC595
int RCLK_Pin = 9;  //pin 12 on the 75HC595
int SRCLK_Pin = 10; //pin 11 on the 75HC595

int anime = 0;
int counter = 0;
int shift_right_counter = 4;
int shift_left_counter = 0;

// 0110 1001 1111 1001
char a[] = {0, 0, 0, 0};
char a_copy[] = {6, 9, 15, 9};

// Registers or Shift register pins
boolean registers[numOfRegisterPins];

// Forward declarations
void clearRegisters();
void writeRegisters();
void row(int i);
void col(int i);

void setup()
{
	Serial.begin(115200);

	pinMode(SER_Pin, OUTPUT);
	pinMode(RCLK_Pin, OUTPUT);
	pinMode(SRCLK_Pin, OUTPUT);

	// Reset all register pins
	clearRegisters();
	writeRegisters();
}

//set all register pins to LOW
void clearRegisters()
{
	for(int i = numOfRegisterPins - 1; i >=  0; i--)
	{
		registers[i] = LOW;
	}
}

//Set and display registers
//Only call AFTER all values are set how you would like (slow otherwise)
void writeRegisters()
{
	digitalWrite(RCLK_Pin, LOW);
	for(int i = numOfRegisterPins - 1; i >=  0; i--)
	{
		digitalWrite(SRCLK_Pin, LOW);
		int val = registers[i];
		digitalWrite(SER_Pin, val);
		digitalWrite(SRCLK_Pin, HIGH);

	}
	digitalWrite(RCLK_Pin, HIGH);
}

void setRegisterPin(int index, int value)
{
	registers[index] = value;
}

void row(int i)
{
	setRegisterPin(i, HIGH);
}

void col(int i)
{
	setRegisterPin(i + 4, HIGH);
}

void loop()
{
	clearRegisters();
	writeRegisters();

	// Wrap around for row counter
	if (counter == 4) counter = 0;

	// Light up the row with index
	row(counter);

	// Animate in (right to left)
	if (anime % SPEED == 0 && shift_right_counter != -1)
	{
		// For each of the rows
		for (int i = 0; i < 4; ++i)
		{
			a[i] = a_copy[i] >> shift_right_counter;
		}
		shift_right_counter--;
	}

	// Animate out (right to left)
	if (anime % SPEED == 0 && shift_left_counter <= 4 && shift_right_counter == -1)
	{
		// For each of the rows
		for (int i = 0; i < 4; ++i)
		{
			a[i] = a_copy[i] << shift_left_counter;
		}
		shift_left_counter++;
	}

	// Animation frame counter
	anime++;

	for (int i = 0; i < 4; ++i)
	{
		if (!(a[counter] & 1 << i)) col(i);
	}
	writeRegisters();
	delay(5);

	if (counter < 4) counter ++;
	else counter = 0;
}
<|endoftext|>


<commit_before>89642733-ad5c-11e7-aa74-ac87a332f658<commit_msg>bug fix<commit_after>89fe7226-ad5c-11e7-b1cb-ac87a332f658<|endoftext|>


<commit_before>0a226ba1-2748-11e6-bc56-e0f84713e7b8<commit_msg>We apologise for the previous fix. Those responsible have been sacked<commit_after>0a2d5197-2748-11e6-befe-e0f84713e7b8<|endoftext|>


<commit_before>#include "Iir.h"

#include <stdio.h>

#include "assert_print.h"

void assert_double(double a, double b) {
	const double d = fabs(a-b);
	if (d < 1E-5) {
		fprintf(stderr,"%e == %e, err = %e\n",a,b,d);
		return;
	}
	char tmp[1024];
	sprintf(tmp,"Mismatch: %e != %e\n",a,b);
	fprintf(stderr,"%s",tmp);
	throw tmp;
}

void test1 () {
        const int nSOS = 1;
        const double coeff[nSOS][6] =
		{{ 0.02008337,  0.04016673,  0.02008337,
		   1.,         -1.56101808,  0.64135154}};
        Iir::Custom::SOSCascade<nSOS,Iir::DirectFormI> cust(coeff);
	assert_double(cust.filter(-1.0f),-2.00833656e-02);
	assert_double(cust.filter(0.5f),-6.14755450e-02);
	assert_double(cust.filter(1.0f),-6.30005740e-02);
}

void test2 () {
        const int nSOS = 1;
        const double coeff[nSOS][6] =
		{{ 0.02008337,  0.04016673,  0.02008337,
		   1.,         -1.56101808,  0.64135154}};
        Iir::Custom::SOSCascade<nSOS,Iir::DirectFormII> cust(coeff);
	assert_double(cust.filter(-1.0f),-2.00833656e-02);
	assert_double(cust.filter(0.5f),-6.14755450e-02);
	assert_double(cust.filter(1.0f),-6.30005740e-02);
}

void test3() {
        const int nSOS = 2;
        const double coeff[nSOS][6] =
		{{1.78260999e-03,  3.56521998e-03,  1.78260999e-03,
		  1.00000000e+00,  -1.25544047e+00, 4.09013783e-01},
		 {1.00000000e+00,  2.00000000e+00,  1.00000000e+00,
		  1.00000000e+00,  -1.51824184e+00, 7.03962657e-01}};
        Iir::Custom::SOSCascade<nSOS,Iir::DirectFormI> cust(coeff);
	assert_double(cust.filter(-1.0f),-1.782610e-03);
	assert_double(cust.filter(0.5f),-1.118353e-02);
	assert_double(cust.filter(-1.0f),-3.455084e-02);
	assert_double(cust.filter(0.5f),-7.277369e-02);
	assert_double(cust.filter(-0.3f),-1.197387e-01);
	assert_double(cust.filter(3.0f),-1.588640e-01);
	assert_double(cust.filter(-1E-5f),-1.587363e-01);
}

void test4() {
        const int nSOS = 2;
        const double coeff[nSOS][6] =
		{{1.78260999e-03,  3.56521998e-03,  1.78260999e-03,
		  1.00000000e+00,  -1.25544047e+00, 4.09013783e-01},
		 {1.00000000e+00,  2.00000000e+00,  1.00000000e+00,
		  1.00000000e+00,  -1.51824184e+00, 7.03962657e-01}};
        Iir::Custom::SOSCascade<nSOS,Iir::DirectFormII> cust(coeff);
	assert_double(cust.filter(-1.0f),-1.782610e-03);
	assert_double(cust.filter(0.5f),-1.118353e-02);
	assert_double(cust.filter(-1.0f),-3.455084e-02);
	assert_double(cust.filter(0.5f),-7.277369e-02);
	assert_double(cust.filter(-0.3f),-1.197387e-01);
	assert_double(cust.filter(3.0f),-1.588640e-01);
	assert_double(cust.filter(-1E-5f),-1.587363e-01);
}

int main (int,char**)
{
	test1();
	test2();
	test3();
	test4();

	return 0;
}
<commit_msg>Got rid of float specifiers in the constants<commit_after>#include "Iir.h"

#include <stdio.h>

#include "assert_print.h"

void assert_double(double a, double b) {
	const double d = fabs(a-b);
	if (d < 1E-5) {
		fprintf(stderr,"%e == %e, err = %e\n",a,b,d);
		return;
	}
	char tmp[1024];
	sprintf(tmp,"Mismatch: %e != %e\n",a,b);
	fprintf(stderr,"%s",tmp);
	throw tmp;
}

void test1 () {
        const int nSOS = 1;
        const double coeff[nSOS][6] =
		{{ 0.02008337,  0.04016673,  0.02008337,
		   1.,         -1.56101808,  0.64135154}};
        Iir::Custom::SOSCascade<nSOS,Iir::DirectFormI> cust(coeff);
	assert_double(cust.filter(-1.0),-2.00833656e-02);
	assert_double(cust.filter(0.5),-6.14755450e-02);
	assert_double(cust.filter(1.0),-6.30005740e-02);
}

void test2 () {
        const int nSOS = 1;
        const double coeff[nSOS][6] =
		{{ 0.02008337,  0.04016673,  0.02008337,
		   1.,         -1.56101808,  0.64135154}};
        Iir::Custom::SOSCascade<nSOS,Iir::DirectFormII> cust(coeff);
	assert_double(cust.filter(-1.0),-2.00833656e-02);
	assert_double(cust.filter(0.5),-6.14755450e-02);
	assert_double(cust.filter(1.0),-6.30005740e-02);
}

void test3() {
        const int nSOS = 2;
        const double coeff[nSOS][6] =
		{{1.78260999e-03,  3.56521998e-03,  1.78260999e-03,
		  1.00000000e+00,  -1.25544047e+00, 4.09013783e-01},
		 {1.00000000e+00,  2.00000000e+00,  1.00000000e+00,
		  1.00000000e+00,  -1.51824184e+00, 7.03962657e-01}};
        Iir::Custom::SOSCascade<nSOS,Iir::DirectFormI> cust(coeff);
	assert_double(cust.filter(-1.0),-1.782610e-03);
	assert_double(cust.filter(0.5),-1.118353e-02);
	assert_double(cust.filter(-1.0),-3.455084e-02);
	assert_double(cust.filter(0.5),-7.277369e-02);
	assert_double(cust.filter(-0.3),-1.197387e-01);
	assert_double(cust.filter(3.0),-1.588640e-01);
	assert_double(cust.filter(-1.0E-5),-1.587363e-01);
}

void test4() {
        const int nSOS = 2;
        const double coeff[nSOS][6] =
		{{1.78260999e-03,  3.56521998e-03,  1.78260999e-03,
		  1.00000000e+00,  -1.25544047e+00, 4.09013783e-01},
		 {1.00000000e+00,  2.00000000e+00,  1.00000000e+00,
		  1.00000000e+00,  -1.51824184e+00, 7.03962657e-01}};
        Iir::Custom::SOSCascade<nSOS,Iir::DirectFormII> cust(coeff);
	assert_double(cust.filter(-1.0),-1.782610e-03);
	assert_double(cust.filter(0.5),-1.118353e-02);
	assert_double(cust.filter(-1.0),-3.455084e-02);
	assert_double(cust.filter(0.5),-7.277369e-02);
	assert_double(cust.filter(-0.3),-1.197387e-01);
	assert_double(cust.filter(3.0),-1.588640e-01);
	assert_double(cust.filter(-1.0E-5),-1.587363e-01);
}

int main (int,char**)
{
	test1();
	test2();
	test3();
	test4();

	return 0;
}
<|endoftext|>


<commit_before>/*  This file is part of the Vc library.

    Copyright (C) 2009 Matthias Kretz <kretz@kde.org>

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

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

    You should have received a copy of the GNU Lesser General Public
    License along with Vc.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <Vc/Vc>
#include "unittest.h"
#include <iostream>
#include "vectormemoryhelper.h"
#include <cmath>
#include <algorithm>

using namespace Vc;

#ifdef isfinite
#undef isfinite
#endif
#ifdef isnan
#undef isnan
#endif

template<typename Vec> void testAbs()
{
    for (int i = 0; i < 0x7fff; ++i) {
        Vec a(i);
        Vec b(-i);
        COMPARE(a, Vc::abs(a));
        COMPARE(a, Vc::abs(b));
    }
}

template<typename Vec> void testLog()
{
    setFuzzyness<float>(1.2e-7f);
    setFuzzyness<double>(3e-16);
    typedef typename Vec::IndexType I;
    const I indexesFromZero(IndexesFromZero);
    Vec a(indexesFromZero);
    a *= 0.1;
    const Vec end(1000);
    for (; a < end; a += Vec::Size) {
        Vec b = Vc::log(a);

        const typename Vec::EntryType two = 2.;

        for (int i = 0; i < Vec::Size; ++i) {
            FUZZY_COMPARE(b[i], static_cast<typename Vec::EntryType>(std::log(a[i])));
        }

        const Vec a2 = a * a;
        FUZZY_COMPARE(Vc::log(a2), two * Vc::log(a));
    }
    setFuzzyness<float>(0.f);
    setFuzzyness<double>(0.);
}

template<typename Vec>
void testMax()
{
    typedef typename Vec::EntryType T;
    VectorMemoryHelper<Vec> mem(3);
    T *data = mem;
    for (int i = 0; i < Vec::Size; ++i) {
        data[i] = i;
        data[i + Vec::Size] = Vec::Size + 1 - i;
        data[i + 2 * Vec::Size] = std::max(data[i], data[i + Vec::Size]);
    }
    Vec a(&data[0]);
    Vec b(&data[Vec::Size]);
    Vec c(&data[2 * Vec::Size]);

    COMPARE(Vc::max(a, b), c);
}

#define FillHelperMemory(code) \
    VectorMemoryHelper<Vec> mem(2); \
    T *data = mem; \
    T *reference = &data[Vec::Size]; \
    for (int ii = 0; ii < Vec::Size; ++ii) { \
        const T i = static_cast<T>(ii); \
        data[ii] = i; \
        reference[ii] = code; \
    } do {} while (false)

template<typename Vec> void testSqrt()
{
    typedef typename Vec::EntryType T;
    FillHelperMemory(std::sqrt(i));
    Vec a(data);
    Vec b(reference);

    FUZZY_COMPARE(Vc::sqrt(a), b);
}

template<typename Vec> void testRSqrt()
{
    typedef typename Vec::EntryType T;
    const T one = 1;
    FillHelperMemory(one / std::sqrt(i));
    Vec a(data);
    Vec b(reference);

    // RSQRTPS is documented as having a relative error <= 1.5 * 2^-12
    setFuzzyness<float>(0.0003662109375f);
    FUZZY_COMPARE(Vc::rsqrt(a), b);
    setFuzzyness<float>(0.f);
}

template<typename Vec> void testAtan()
{
    typedef typename Vec::EntryType T;
    setFuzzyness<float>(0.005f);
    for (int offset = -1000; offset < 1000; offset += 10) {
        FillHelperMemory(std::atan((i + offset) * 0.1));
        Vec a(data);
        Vec b(reference);

        FUZZY_COMPARE(Vc::atan((a + offset) * 0.1), b);
    }
    setFuzzyness<float>(0.0f);
}

template<typename Vec> void testAtan2()
{
    typedef typename Vec::EntryType T;
    setFuzzyness<float>(0.005f);
    for (int xoffset = -100; xoffset < 100; xoffset += 10) {
        for (int yoffset = -100; yoffset < 100; yoffset += 10) {
            FillHelperMemory(std::atan2(i + xoffset, i + yoffset));
            Vec a(data);
            Vec b(reference);

            //std::cout << a + xoffset << a + yoffset << std::endl;
            FUZZY_COMPARE(Vc::atan2(a + xoffset, a + yoffset), b);
        }
    }
    setFuzzyness<float>(0.0f);
}

template<typename Vec> void testInf()
{
    typedef typename Vec::EntryType T;
    const T one = 1;
    const Vec zero(Zero);
    VERIFY(Vc::isfinite(zero));
    VERIFY(Vc::isfinite(Vec(one)));
    VERIFY(!Vc::isfinite(one / zero));
}

template<typename Vec> void testNaN()
{
    typedef typename Vec::EntryType T;
    const T one = 1;
    const Vec zero(Zero);
    VERIFY(!Vc::isnan(zero));
    VERIFY(!Vc::isnan(Vec(one)));
    const Vec inf = one / zero;
    VERIFY(Vc::isnan(Vec(inf * zero)));
}

template<typename Vec> void testReduceMin()
{
    typedef typename Vec::EntryType T;
    const T one = 1;
    VectorMemoryHelper<Vec> mem(Vec::Size);
    T *data = mem;
    for (int i = 0; i < Vec::Size * Vec::Size; ++i) {
        data[i] = i % (Vec::Size + 1) + one;
    }
    for (int i = 0; i < Vec::Size; ++i, data += Vec::Size) {
        const Vec a(&data[0]);
        //std::cout << a << std::endl;
        COMPARE(a.min(), one);
    }
}

int main()
{
    runTest(testAbs<int_v>);
    runTest(testAbs<float_v>);
    runTest(testAbs<double_v>);
    runTest(testAbs<short_v>);
    runTest(testAbs<sfloat_v>);

    runTest(testLog<float_v>);
    runTest(testLog<double_v>);
    runTest(testLog<sfloat_v>);

    runTest(testMax<int_v>);
    runTest(testMax<uint_v>);
    runTest(testMax<float_v>);
    runTest(testMax<double_v>);
    runTest(testMax<short_v>);
    runTest(testMax<ushort_v>);
    runTest(testMax<sfloat_v>);

    runTest(testSqrt<float_v>);
    runTest(testSqrt<double_v>);
    runTest(testSqrt<sfloat_v>);

    runTest(testRSqrt<float_v>);
    runTest(testRSqrt<double_v>);
    runTest(testRSqrt<sfloat_v>);

    runTest(testAtan<float_v>);
    runTest(testAtan<sfloat_v>);

    runTest(testAtan2<float_v>);
    runTest(testAtan2<sfloat_v>);

    runTest(testInf<float_v>);
    runTest(testInf<double_v>);
    runTest(testInf<sfloat_v>);

    runTest(testNaN<float_v>);
    runTest(testNaN<double_v>);
    runTest(testNaN<sfloat_v>);

    runTest(testReduceMin<float_v>);
    runTest(testReduceMin<sfloat_v>);
    runTest(testReduceMin<double_v>);
    runTest(testReduceMin<int_v>);
    runTest(testReduceMin<uint_v>);
    runTest(testReduceMin<short_v>);
    runTest(testReduceMin<ushort_v>);

    return 0;
}
<commit_msg>improve coverage, test atan(double_v), minimize fuzzyness<commit_after>/*  This file is part of the Vc library.

    Copyright (C) 2009 Matthias Kretz <kretz@kde.org>

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

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

    You should have received a copy of the GNU Lesser General Public
    License along with Vc.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <Vc/Vc>
#include "unittest.h"
#include <iostream>
#include "vectormemoryhelper.h"
#include <cmath>
#include <algorithm>

using namespace Vc;

#ifdef isfinite
#undef isfinite
#endif
#ifdef isnan
#undef isnan
#endif

template<typename Vec> void testAbs()
{
    for (int i = 0; i < 0x7fff; ++i) {
        Vec a(i);
        Vec b(-i);
        COMPARE(a, Vc::abs(a));
        COMPARE(a, Vc::abs(b));
    }
}

template<typename Vec> void testLog()
{
    setFuzzyness<float>(1.2e-7f);
    setFuzzyness<double>(3e-16);
    typedef typename Vec::IndexType I;
    const I indexesFromZero(IndexesFromZero);
    Vec a(indexesFromZero);
    a *= 0.1;
    const Vec end(1000);
    for (; a < end; a += Vec::Size) {
        Vec b = Vc::log(a);

        const typename Vec::EntryType two = 2.;

        for (int i = 0; i < Vec::Size; ++i) {
            FUZZY_COMPARE(b[i], static_cast<typename Vec::EntryType>(std::log(a[i])));
        }

        const Vec a2 = a * a;
        FUZZY_COMPARE(Vc::log(a2), two * Vc::log(a));
    }
    setFuzzyness<float>(0.f);
    setFuzzyness<double>(0.);
}

template<typename Vec>
void testMax()
{
    typedef typename Vec::EntryType T;
    VectorMemoryHelper<Vec> mem(3);
    T *data = mem;
    for (int i = 0; i < Vec::Size; ++i) {
        data[i] = i;
        data[i + Vec::Size] = Vec::Size + 1 - i;
        data[i + 2 * Vec::Size] = std::max(data[i], data[i + Vec::Size]);
    }
    Vec a(&data[0]);
    Vec b(&data[Vec::Size]);
    Vec c(&data[2 * Vec::Size]);

    COMPARE(Vc::max(a, b), c);
}

#define FillHelperMemory(code) \
    VectorMemoryHelper<Vec> mem(2); \
    T *data = mem; \
    T *reference = &data[Vec::Size]; \
    for (int ii = 0; ii < Vec::Size; ++ii) { \
        const T i = static_cast<T>(ii); \
        data[ii] = i; \
        reference[ii] = code; \
    } do {} while (false)

template<typename Vec> void testSqrt()
{
    typedef typename Vec::EntryType T;
    FillHelperMemory(std::sqrt(i));
    Vec a(data);
    Vec b(reference);

    FUZZY_COMPARE(Vc::sqrt(a), b);
}

template<typename Vec> void testRSqrt()
{
    typedef typename Vec::EntryType T;
    const T one = 1;
    FillHelperMemory(one / std::sqrt(i));
    Vec a(data);
    Vec b(reference);

    // RSQRTPS is documented as having a relative error <= 1.5 * 2^-12
    setFuzzyness<float>(0.0003662109375f);
    FUZZY_COMPARE(Vc::rsqrt(a), b);
    setFuzzyness<float>(0.f);
}

template<typename Vec> void testAtan()
{
    typedef typename Vec::EntryType T;
    setFuzzyness<float>(8e-5f);
    setFuzzyness<double>(2e-8);
    for (int offset = -1000; offset < 1000; offset += 10) {
        FillHelperMemory(std::atan((i + offset) * 0.1));
        Vec a(data);
        Vec b(reference);

        FUZZY_COMPARE(Vc::atan((a + offset) * 0.1), b);
    }
}

template<typename Vec> void testAtan2()
{
    typedef typename Vec::EntryType T;
    setFuzzyness<float>(8e-5f);
    setFuzzyness<double>(3e-8);
    for (int xoffset = -100; xoffset < 1000; xoffset += 10) {
        for (int yoffset = -100; yoffset < 1000; yoffset += 10) {
            FillHelperMemory(std::atan2((i + xoffset) * 0.15, (i + yoffset) * 0.15));
            Vec a(data);
            Vec b(reference);

            //std::cout << (a + xoffset) * 0.15 << (a + yoffset) * 0.15 << std::endl;
            FUZZY_COMPARE(Vc::atan2((a + xoffset) * 0.15, (a + yoffset) * 0.15), b);
        }
    }
}

template<typename Vec> void testInf()
{
    typedef typename Vec::EntryType T;
    const T one = 1;
    const Vec zero(Zero);
    VERIFY(Vc::isfinite(zero));
    VERIFY(Vc::isfinite(Vec(one)));
    VERIFY(!Vc::isfinite(one / zero));
}

template<typename Vec> void testNaN()
{
    typedef typename Vec::EntryType T;
    const T one = 1;
    const Vec zero(Zero);
    VERIFY(!Vc::isnan(zero));
    VERIFY(!Vc::isnan(Vec(one)));
    const Vec inf = one / zero;
    VERIFY(Vc::isnan(Vec(inf * zero)));
}

template<typename Vec> void testReduceMin()
{
    typedef typename Vec::EntryType T;
    const T one = 1;
    VectorMemoryHelper<Vec> mem(Vec::Size);
    T *data = mem;
    for (int i = 0; i < Vec::Size * Vec::Size; ++i) {
        data[i] = i % (Vec::Size + 1) + one;
    }
    for (int i = 0; i < Vec::Size; ++i, data += Vec::Size) {
        const Vec a(&data[0]);
        //std::cout << a << std::endl;
        COMPARE(a.min(), one);
    }
}

int main()
{
    runTest(testAbs<int_v>);
    runTest(testAbs<float_v>);
    runTest(testAbs<double_v>);
    runTest(testAbs<short_v>);
    runTest(testAbs<sfloat_v>);

    runTest(testLog<float_v>);
    runTest(testLog<double_v>);
    runTest(testLog<sfloat_v>);

    runTest(testMax<int_v>);
    runTest(testMax<uint_v>);
    runTest(testMax<float_v>);
    runTest(testMax<double_v>);
    runTest(testMax<short_v>);
    runTest(testMax<ushort_v>);
    runTest(testMax<sfloat_v>);

    runTest(testSqrt<float_v>);
    runTest(testSqrt<double_v>);
    runTest(testSqrt<sfloat_v>);

    runTest(testRSqrt<float_v>);
    runTest(testRSqrt<double_v>);
    runTest(testRSqrt<sfloat_v>);

    runTest(testAtan<float_v>);
    runTest(testAtan<sfloat_v>);
    runTest(testAtan<double_v>);

    runTest(testAtan2<float_v>);
    runTest(testAtan2<sfloat_v>);
    runTest(testAtan2<double_v>);

    runTest(testInf<float_v>);
    runTest(testInf<double_v>);
    runTest(testInf<sfloat_v>);

    runTest(testNaN<float_v>);
    runTest(testNaN<double_v>);
    runTest(testNaN<sfloat_v>);

    runTest(testReduceMin<float_v>);
    runTest(testReduceMin<sfloat_v>);
    runTest(testReduceMin<double_v>);
    runTest(testReduceMin<int_v>);
    runTest(testReduceMin<uint_v>);
    runTest(testReduceMin<short_v>);
    runTest(testReduceMin<ushort_v>);

    return 0;
}
<|endoftext|>


<commit_before>#include <path.h>
#include "yatf/include/yatf.h"

using namespace yacppl;

TEST(path, empty_path_is_empty_string) {
    path p;
    REQUIRE(p == "");
}

TEST(path, path_constructed_from_string_is_valid) {
    path p("/root/dir");
    REQUIRE_EQ((const char *)p, "/root/dir");
    path p2("some_dir/another_dir");
    REQUIRE_EQ((const char *)p2, "some_dir/another_dir");
    path p3("/");
    REQUIRE_EQ((const char *)p3, "/");
}

TEST(path, paths_can_be_appended) {
    path p1("home");
    path p2("user");
    path p3(p1 / p2);
    REQUIRE_EQ((const char *)p3, "home/user");
    p3 /= "dir";
    REQUIRE(p3 == "home/user/dir");
    p3 /= "next_dir";
    REQUIRE(p3 == "home/user/dir/next_dir");
    path p4 = p3 / "test";
    REQUIRE(p3 == "home/user/dir/next_dir");
    REQUIRE(p4 == "home/user/dir/next_dir/test");
}

TEST(path, paths_are_normalized) {
    path p;
    p = p / "root" / "////test//" / "/dir////";
    REQUIRE_EQ((const char *)p, "/root/test/dir");
    auto p2 = p / path("dir2");
    REQUIRE_EQ((const char *)p2, "/root/test/dir/dir2");
    p2 /= "//dir3////dir4/";
    REQUIRE_EQ((const char *)p2, "/root/test/dir/dir2/dir3/dir4");
    path p3("/////dir/////////");
    REQUIRE_EQ((const char *)p3, "/dir");
}

TEST(path, can_get_basename) {
    path p("/root/dir1/dir2//dir3/");
    REQUIRE_EQ((const char *)p.basename(), "dir3");
    path p2("some_dir");
    REQUIRE_EQ((const char *)p2.basename(), "some_dir");
    path p3("/");
    REQUIRE_EQ((const char *)p3.basename(), "");
    path p5("/path");
    REQUIRE_EQ((const char *)p5.basename(), "path");
}

TEST(path, can_get_dirname) {
    path p("/");
    REQUIRE_EQ((const char *)p.dirname(), "/");
    path p2("/root/dir1/dir2//dir3/");
    REQUIRE_EQ((const char *)p2.dirname(), "/root/dir1/dir2");
    path p3("root/dir1/dir2//dir3/");
    REQUIRE_EQ((const char *)p3.dirname(), "root/dir1/dir2");
    path p4("path");
    REQUIRE_EQ((const char *)p4.dirname(), "");
    path p5("/path");
    REQUIRE_EQ((const char *)p5.dirname(), "/");
}

TEST(path, can_be_iterated) {
    {
        path p("/root/dir");
        auto it = p.cbegin();
        REQUIRE_EQ((const char *)*it, "/");
        REQUIRE_EQ((*it).length(), 1u);
        ++it;
        REQUIRE_EQ((const char *)*it, "root");
        ++it;
        REQUIRE_EQ((const char *)*it, "dir");
        ++it;
        REQUIRE(it == p.cend());
    }
    {
        path p("root/dir");
        auto it = p.begin();
        REQUIRE_EQ((const char *)*it, "root");
        it++;
        REQUIRE_EQ((const char *)*it, "dir");
        it++;
        REQUIRE(it == p.end());
    }
    {
        path p("/dir1/dir2/dir3/dir4/other_dir");
        string paths[6] = {
            "/",
            "dir1",
            "dir2",
            "dir3",
            "dir4",
            "other_dir"
        };
        auto i = 0u;
        for (const auto &it : p) {
            REQUIRE_EQ((const char *)it, (const char *)paths[i]);
            ++i;
        }
    }
    {
        path p("/dir1/dir2/dir3/dir4/other_dir");
        auto it = p.begin();
        REQUIRE_EQ((const char *)*(it + 1), "dir1");
        REQUIRE_EQ((const char *)*(it + 2), "dir2");
        REQUIRE_EQ((const char *)*(it + 3), "dir3");
        REQUIRE_EQ((const char *)*(it + 4), "dir4");
        REQUIRE_EQ((const char *)*(it + 5), "other_dir");
        REQUIRE((it + 6) == p.end());
        REQUIRE((it + 7) == p.end());
        REQUIRE((it + 1024) == p.end());
    }
}

<commit_msg>Improving path tests<commit_after>#include <path.h>
#include "yatf/include/yatf.h"

using namespace yacppl;

TEST(path, empty_path_is_empty_string) {
    path p;
    REQUIRE(p == "");
}

TEST(path, can_be_constructed_from_char_ptr) {
    path p1(nullptr);
    REQUIRE_FALSE(p1);
    const char *str = "/some_path/dir/file";
    path p2(str);
    REQUIRE_EQ((const char *)p2, "/some_path/dir/file");
    path p4("/");
    REQUIRE_EQ((const char *)p4, "/");
    path p5("/root/aaa/bbb/ccc");
    REQUIRE_EQ((const char *)p5, "/root/aaa/bbb/ccc");
}

TEST(path, can_be_constructed_from_other_path_by_copy) {
    path p1(nullptr);
    path p2("/root/dir/aaa/bbb");
    path p3(p1);
    REQUIRE(p1.get() == nullptr);
    REQUIRE(p3.get() == nullptr);
    path p4(p2);
    REQUIRE(p2.get() != nullptr);
    REQUIRE(p4.get() != nullptr);
    REQUIRE_EQ((const char *)p4, "/root/dir/aaa/bbb");
}

TEST(path, can_be_constructed_from_other_path_by_move) {
    path p1(nullptr);
    path p2("/root/dir/aaa/bbb");
    path p3(move(p1));
    REQUIRE(p1.get() == nullptr);
    REQUIRE(p3.get() == nullptr);
    path p4(move(p2));
    REQUIRE(p2.get() == nullptr);
    REQUIRE(p4.get() != nullptr);
    REQUIRE_EQ((const char *)p4, "/root/dir/aaa/bbb");
}

TEST(path, can_be_assigned_to_other_path) {
    path p1("/some_path");
    path p2(nullptr);
    path p3;
    p3 = p1;
    REQUIRE_EQ((const char *)p3, "/some_path");
    p3 = p2;
    REQUIRE_FALSE(p3);
    p3 = p1;
    REQUIRE_EQ((const char *)p1, "/some_path");
    // FIXME: REQUIRE(p2 == nullptr);
    REQUIRE_EQ((const char *)p3, "/some_path");
}

TEST(path, paths_can_be_appended) {
    path p1("home");
    path p2("user");
    path p3(p1 / p2);
    REQUIRE_EQ((const char *)p3, "home/user");
    p3 /= "dir";
    REQUIRE(p3 == "home/user/dir");
    p3 /= "next_dir";
    REQUIRE(p3 == "home/user/dir/next_dir");
    path p4 = p3 / "test";
    REQUIRE(p3 == "home/user/dir/next_dir");
    REQUIRE(p4 == "home/user/dir/next_dir/test");
}

TEST(path, paths_are_normalized) {
    path p;
    p = p / "root" / "////test//" / "/dir////";
    REQUIRE_EQ((const char *)p, "/root/test/dir");
    auto p2 = p / path("dir2");
    REQUIRE_EQ((const char *)p2, "/root/test/dir/dir2");
    p2 /= "//dir3////dir4/";
    REQUIRE_EQ((const char *)p2, "/root/test/dir/dir2/dir3/dir4");
    path p3("/////dir/////////");
    REQUIRE_EQ((const char *)p3, "/dir");
}

TEST(path, can_get_basename) {
    path p("/root/dir1/dir2//dir3/");
    REQUIRE_EQ((const char *)p.basename(), "dir3");
    path p2("some_dir");
    REQUIRE_EQ((const char *)p2.basename(), "some_dir");
    path p3("/");
    REQUIRE_EQ((const char *)p3.basename(), "");
    path p5("/path");
    REQUIRE_EQ((const char *)p5.basename(), "path");
}

TEST(path, can_get_dirname) {
    path p("/");
    REQUIRE_EQ((const char *)p.dirname(), "/");
    path p2("/root/dir1/dir2//dir3/");
    REQUIRE_EQ((const char *)p2.dirname(), "/root/dir1/dir2");
    path p3("root/dir1/dir2//dir3/");
    REQUIRE_EQ((const char *)p3.dirname(), "root/dir1/dir2");
    path p4("path");
    REQUIRE_EQ((const char *)p4.dirname(), "");
    path p5("/path");
    REQUIRE_EQ((const char *)p5.dirname(), "/");
}

TEST(path, can_be_iterated) {
    {
        path p("/root/dir");
        auto it = p.cbegin();
        REQUIRE_EQ((const char *)*it, "/");
        REQUIRE_EQ((*it).length(), 1u);
        ++it;
        REQUIRE_EQ((const char *)*it, "root");
        ++it;
        REQUIRE_EQ((const char *)*it, "dir");
        ++it;
        REQUIRE(it == p.cend());
    }
    {
        path p("root/dir");
        auto it = p.begin();
        REQUIRE_EQ((const char *)*it, "root");
        it++;
        REQUIRE_EQ((const char *)*it, "dir");
        it++;
        REQUIRE(it == p.end());
    }
    {
        path p("/dir1/dir2/dir3/dir4/other_dir");
        string paths[6] = {
            "/",
            "dir1",
            "dir2",
            "dir3",
            "dir4",
            "other_dir"
        };
        auto i = 0u;
        for (const auto &it : p) {
            REQUIRE_EQ((const char *)it, (const char *)paths[i]);
            ++i;
        }
    }
    {
        path p("/dir1/dir2/dir3/dir4/other_dir");
        auto it = p.begin();
        REQUIRE_EQ((const char *)*(it + 1), "dir1");
        REQUIRE_EQ((const char *)*(it + 2), "dir2");
        REQUIRE_EQ((const char *)*(it + 3), "dir3");
        REQUIRE_EQ((const char *)*(it + 4), "dir4");
        REQUIRE_EQ((const char *)*(it + 5), "other_dir");
        REQUIRE((it + 6) == p.end());
        REQUIRE((it + 7) == p.end());
        REQUIRE((it + 1024) == p.end());
    }
}

<|endoftext|>


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

#include <chillduino.h>
#include <iostream>
#include <assert.h>

template <typename T, T expected>
class Expect {
  private:
    T _actual;

  public:
    Expect(void) :
      _actual() { }

    ~Expect(void) {
      assert(_actual == expected);
    }

    T operator()(void) const {
      return _actual;
    }

    void operator()(const T& value) {
      _actual = value;
    }
};

template <int X>
class WhenFreshFoodThermistorReads {
  public:
    static int getFreshFoodThermistorReading(void) {
      return X;
    }
};

template <int X>
class ShouldHaveFreshFoodTemperature {
  public:
    static Expect<int, X> setFreshFoodTemperature;
};

template <int X>
Expect<int, X> ShouldHaveFreshFoodTemperature<X>::setFreshFoodTemperature;

class ShouldSampleFreshFood :
  public WhenFreshFoodThermistorReads<512>,
  public ShouldHaveFreshFoodTemperature<25> {

  public:
    static const unsigned long FRESH_FOOD_THERMISTOR_B = 3980;
    static const unsigned long FRESH_FOOD_THERMISTOR_ROOM_RESISTANCE = 5000;
    static const unsigned long FRESH_FOOD_THERMISTOR_1_RESISTANCE = 15000;
    static const unsigned long FRESH_FOOD_THERMISTOR_2_RESISTANCE = 10000;
    static const unsigned long FRESH_FOOD_THERMISTOR_VOLTAGE = 5;
    static const unsigned long FRESH_FOOD_THERMISTOR_ROOM_TEMPERATURE = 25;

    static const int FRESH_FOOD_SAMPLE_FREQUENCY = 100;
    static const int FRESH_FOOD_SAMPLES_PER_AVERAGE = 10;
};

class Time {
  public:
    static void elapse(unsigned long ticks) {
      while (ticks--) {
        Application::tick();
        Application::loop();
      }
    }
};

class ShouldReturnNegativeId {
  public:
    static void whenAllTimersAreUsed(void) {
      while (Application::setTimeout<ShouldReturnNegativeId::dummy>(0) >= 0);
      Application::loop();
    }

    static void dummy(void) { }
};

int main(void) {
  ShouldReturnNegativeId::whenAllTimersAreUsed();
  Chillduino<ShouldSampleFreshFood>::setup();
  Time::elapse(1000);

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

#include <chillduino.h>
#include <iostream>
#include <assert.h>

template <typename T, T expected>
class Expect {
  private:
    T _actual;

  public:
    Expect(void) :
      _actual() { }

    virtual ~Expect(void) {
      assert(_actual == expected);
    }

    T operator()(void) const {
      return _actual;
    }

    void operator()(const T& value) {
      _actual = value;
    }
};

template <int X>
class WhenFreshFoodThermistorReads {
  public:
    static int getFreshFoodThermistorReading(void) {
      return X;
    }
};

template <int X>
class ShouldHaveFreshFoodTemperature {
  public:
    static Expect<int, X> setFreshFoodTemperature;
};

template <int X>
Expect<int, X> ShouldHaveFreshFoodTemperature<X>::setFreshFoodTemperature;

class ShouldSampleFreshFood :
  public WhenFreshFoodThermistorReads<512>,
  public ShouldHaveFreshFoodTemperature<25> {

  public:
    static const unsigned long FRESH_FOOD_THERMISTOR_B = 3980;
    static const unsigned long FRESH_FOOD_THERMISTOR_ROOM_RESISTANCE = 5000;
    static const unsigned long FRESH_FOOD_THERMISTOR_1_RESISTANCE = 15000;
    static const unsigned long FRESH_FOOD_THERMISTOR_2_RESISTANCE = 10000;
    static const unsigned long FRESH_FOOD_THERMISTOR_VOLTAGE = 5;
    static const unsigned long FRESH_FOOD_THERMISTOR_ROOM_TEMPERATURE = 25;

    static const int FRESH_FOOD_SAMPLE_FREQUENCY = 100;
    static const int FRESH_FOOD_SAMPLES_PER_AVERAGE = 10;
};

class Time {
  public:
    static void elapse(unsigned long ticks) {
      while (ticks--) {
        Application::tick();
        Application::loop();
      }
    }
};

class ShouldReturnNegativeId {
  public:
    static void whenAllTimersAreUsed(void) {
      while (Application::setTimeout<ShouldReturnNegativeId::dummy>(0) >= 0);
      Application::loop();
    }

    static void dummy(void) { }
};

int main(void) {
  ShouldReturnNegativeId::whenAllTimersAreUsed();
  Chillduino<ShouldSampleFreshFood>::setup();
  Time::elapse(1000);

  return 0;
}
<|endoftext|>


<commit_before>#include "EButton.h"

EButton::EButton(byte pin, bool pressedLow) {
	this->pin = pin;
	pinMode(pin, pressedLow ? INPUT_PULLUP : INPUT);
	pressedState = !pressedLow;
	reset();
}

void EButton::setDebounceTime(byte time) {
	debounceTime = time;
}

#if defined(EBUTTON_SUPPORT_DONE_CLICKING) || defined(EBUTTON_SUPPORT_SINGLE_AND_DOUBLE_CLICKS)
void EButton::setClickTime(unsigned int time) {
	clickTime = time;
}
#endif

#ifdef EBUTTON_SUPPORT_LONG_PRESS
void EButton::setLongPressTime(unsigned int time) {
	longPressTime = time;
}
#endif

#ifdef EBUTTON_SUPPORT_TRANSITION
void EButton::attachTransition(EButtonEventHandler method) {
	transitionMethod = method;
}
#endif

#ifdef EBUTTON_SUPPORT_EACH_CLICK
void EButton::attachEachClick(EButtonEventHandler method) {
	eachClickMethod = method;
}
#endif

#ifdef EBUTTON_SUPPORT_DONE_CLICKING
void EButton::attachDoneClicking(EButtonEventHandler method) {
	doneClickingMethod = method;
}
#endif

#ifdef EBUTTON_SUPPORT_SINGLE_AND_DOUBLE_CLICKS
void EButton::attachSingleClick(EButtonEventHandler method) {
	singleClickMethod = method;
}

void EButton::attachDoubleClick(EButtonEventHandler method) {
	doubleClickMethod = method;
}
#endif

#ifdef EBUTTON_SUPPORT_LONG_PRESS
void EButton::attachLongPressStart(EButtonEventHandler method) {
	longPressStartMethod = method;
}

void EButton::attachDuringLongPress(EButtonEventHandler method) {
	duringLongPresstMethod = method;
}

void EButton::attachLongPressEnd(EButtonEventHandler method) {
	longPressEndMethod = method;
}
#endif

void EButton::reset() {
	state = EBUTTON_STATE_IDLE;
	startTime = 0;
	prevTransitionTime = 0;
	clicks = 0;
}

byte EButton::getPin() {
	return pin;
}

byte EButton::getClicks() {
	return clicks;
}

bool EButton::isButtonPressed() {
	return buttonPressed;
}

#ifdef EBUTTON_SUPPORT_LONG_PRESS
bool EButton::isLongPressed() {
	return state == EBUTTON_STATE_LONG_PRESSED;
}
#endif

unsigned long EButton::getStartTime() {
	return startTime;
}

unsigned long EButton::getPrevTransitionTime() {
	return prevTransitionTime;
}

bool EButton::operator==(EButton &other) {
	return (this == &other);
}

void EButton::tick() {
	unsigned long now = millis();

#ifdef EBUTTON_SUPPORT_LONG_PRESS
	if (state == EBUTTON_STATE_LONG_PRESSED) {
		// Call during press method if in PRESSED state - ON EACH TICK!
		if (duringLongPresstMethod != NULL)
			duringLongPresstMethod(*this);
	}
#endif

	unsigned long sinceLastTransition = now - prevTransitionTime;
	if (sinceLastTransition < debounceTime) {
		// Skip the rest if there is a sample delay applied
		return;
	}

	// Sample button state
	buttonPressed = digitalRead(pin) == pressedState;

	if (state == EBUTTON_STATE_IDLE) {
		// If the state was idle
		if (buttonPressed) {
			//... and the button is pressed now
			startTime = prevTransitionTime = now;		// remember when the first click was detected
			transition(now);		// call transition method
		}
	} else if (state == EBUTTON_STATE_COUNTING_CLICKS_DOWN) {
		if (buttonPressed) {
#ifdef EBUTTON_SUPPORT_LONG_PRESS
			// if the button is still pressed
			if (sinceLastTransition >= longPressTime) {
				// and it's been pressed for long enough since last transition...
				state = EBUTTON_STATE_LONG_PRESSED;			// change to LONG_PRESSED state

				// Call the press start method
				if (longPressStartMethod != NULL)
					longPressStartMethod(*this);
			}
#endif
		} else {
			// if the button is released
			transition(now);		// call transition method
		}
	} else if (state == EBUTTON_STATE_COUNTING_CLICKS_UP) {
		if (buttonPressed) {
			// If the button is pressed
			transition(now);
		} else {
#if defined(EBUTTON_SUPPORT_DONE_CLICKING) || defined(EBUTTON_SUPPORT_SINGLE_AND_DOUBLE_CLICKS)
			if (sinceLastTransition >= clickTime) {
#ifdef EBUTTON_SUPPORT_DONE_CLICKING
				// Handling any-click
				if (doneClickingMethod != NULL)
					doneClickingMethod(*this);
#endif
#ifdef EBUTTON_SUPPORT_SINGLE_AND_DOUBLE_CLICKS
				// Handling single-click
				if (clicks == 1 && singleClickMethod != NULL)
					singleClickMethod(*this);

				// Handling double-click
				if (clicks == 2 && doubleClickMethod != NULL)
					doubleClickMethod(*this);
#endif
				// if the button is not pressed for long enough, then reset the FSM
				reset();
			}
#endif
		}
	}
#ifdef EBUTTON_SUPPORT_LONG_PRESS
	else if (state == EBUTTON_STATE_LONG_PRESSED) {
		if (!buttonPressed) {
			// Button was released from pressed state
			transition(now);
			if (longPressEndMethod != NULL)
				longPressEndMethod(*this);

			// Reset the FSM
			reset();
		}
	}
#endif
}

void EButton::transition(unsigned long now) {
	// Performed when a click transition is detected
	if (buttonPressed) {
		state = EBUTTON_STATE_COUNTING_CLICKS_DOWN;	// change to COUNTING_CLICKS_DOWN state
	} else {
#ifdef EBUTTON_SUPPORT_LONG_PRESS
		if (state != EBUTTON_STATE_LONG_PRESSED) {
			// Count a click only if we were not in PRESSED state
#endif
			state = EBUTTON_STATE_COUNTING_CLICKS_UP;	// change to COUNTING_CLICKS_DOWN state
			clicks++;									// increase clicks on transition to UP
#ifdef EBUTTON_SUPPORT_LONG_PRESS
		}
#endif
	}

#ifdef EBUTTON_SUPPORT_TRANSITION
	// Call the transition method
	if (transitionMethod != NULL)
		transitionMethod(*this);
#endif

#ifdef EBUTTON_SUPPORT_EACH_CLICK
	if (!buttonPressed) {
#ifdef EBUTTON_SUPPORT_LONG_PRESS
		if (state != EBUTTON_STATE_LONG_PRESSED) {
#endif
			// if released and it was not in PRESSED mode, then we have a CLICK event
			if (eachClickMethod != NULL)
				eachClickMethod(*this);
#ifdef EBUTTON_SUPPORT_LONG_PRESS
		}
#endif
	}
#endif
	prevTransitionTime = now;						// remember last transition time
}
<commit_msg>Discrete control over START, DURING and END features in long-press<commit_after>#include "EButton.h"

EButton::EButton(byte pin, bool pressedLow) {
	this->pin = pin;
	pinMode(pin, pressedLow ? INPUT_PULLUP : INPUT);
	pressedState = !pressedLow;
	reset();
}

void EButton::setDebounceTime(byte time) {
	debounceTime = time;
}

#if defined(EBUTTON_SUPPORT_DONE_CLICKING) || defined(EBUTTON_SUPPORT_SINGLE_AND_DOUBLE_CLICKS)
void EButton::setClickTime(unsigned int time) {
	clickTime = time;
}
#endif

#if defined(EBUTTON_SUPPORT_LONG_PRESS_START) || defined(EBUTTON_SUPPORT_LONG_PRESS_DURING) || defined(EBUTTON_SUPPORT_LONG_PRESS_END)
void EButton::setLongPressTime(unsigned int time) {
	longPressTime = time;
}
#endif

#ifdef EBUTTON_SUPPORT_TRANSITION
void EButton::attachTransition(EButtonEventHandler method) {
	transitionMethod = method;
}
#endif

#ifdef EBUTTON_SUPPORT_EACH_CLICK
void EButton::attachEachClick(EButtonEventHandler method) {
	eachClickMethod = method;
}
#endif

#ifdef EBUTTON_SUPPORT_DONE_CLICKING
void EButton::attachDoneClicking(EButtonEventHandler method) {
	doneClickingMethod = method;
}
#endif

#ifdef EBUTTON_SUPPORT_SINGLE_AND_DOUBLE_CLICKS
void EButton::attachSingleClick(EButtonEventHandler method) {
	singleClickMethod = method;
}

void EButton::attachDoubleClick(EButtonEventHandler method) {
	doubleClickMethod = method;
}
#endif

#ifdef EBUTTON_SUPPORT_LONG_PRESS_START
void EButton::attachLongPressStart(EButtonEventHandler method) {
	longPressStartMethod = method;
}
#endif
#ifdef EBUTTON_SUPPORT_LONG_PRESS_DURING
void EButton::attachDuringLongPress(EButtonEventHandler method) {
	duringLongPresstMethod = method;
}
#endif
#ifdef EBUTTON_SUPPORT_LONG_PRESS_END
void EButton::attachLongPressEnd(EButtonEventHandler method) {
	longPressEndMethod = method;
}
#endif

void EButton::reset() {
	state = EBUTTON_STATE_IDLE;
	startTime = 0;
	clicks = 0;
}

byte EButton::getPin() {
	return pin;
}

byte EButton::getClicks() {
	return clicks;
}

bool EButton::isButtonPressed() {
	return buttonPressed;
}

#if defined(EBUTTON_SUPPORT_LONG_PRESS_START) || defined(EBUTTON_SUPPORT_LONG_PRESS_DURING) || defined(EBUTTON_SUPPORT_LONG_PRESS_END)
bool EButton::isLongPressed() {
	return state == EBUTTON_STATE_LONG_PRESSED;
}
#endif

unsigned long EButton::getStartTime() {
	return startTime;
}

unsigned long EButton::getPrevTransitionTime() {
	return prevTransitionTime;
}

bool EButton::operator==(EButton &other) {
	return (this == &other);
}

void EButton::tick() {
	unsigned long now = millis();

#ifdef EBUTTON_SUPPORT_LONG_PRESS_DURING
	if (state == EBUTTON_STATE_LONG_PRESSED) {
		// Call during press method if in PRESSED state - ON EACH TICK!
		if (duringLongPresstMethod != NULL)
			duringLongPresstMethod(*this);
	}
#endif

	unsigned long sinceLastTransition = now - prevTransitionTime;
	if (sinceLastTransition < debounceTime) {
		// Skip the rest if there is a sample delay applied
		return;
	}

	// Sample button state
	buttonPressed = digitalRead(pin) == pressedState;

	if (state == EBUTTON_STATE_IDLE) {
		// If the state was idle
		if (buttonPressed) {
			//... and the button is pressed now
			startTime = now;		// remember when the first click was detected
			transition(now);		// call transition method
		}
	} else if (state == EBUTTON_STATE_COUNTING_CLICKS_DOWN) {
		if (buttonPressed) {
#if defined(EBUTTON_SUPPORT_LONG_PRESS_START) || defined(EBUTTON_SUPPORT_LONG_PRESS_DURING) || defined(EBUTTON_SUPPORT_LONG_PRESS_END)
			// if the button is still pressed
			if (sinceLastTransition >= longPressTime) {
				// and it's been pressed for long enough since last transition...
				state = EBUTTON_STATE_LONG_PRESSED;			// change to LONG_PRESSED state

#ifdef EBUTTON_SUPPORT_LONG_PRESS_START
				// Call the press start method
				if (longPressStartMethod != NULL)
					longPressStartMethod(*this);
#endif
			}
#endif
		} else {
			// if the button is released
			transition(now);		// call transition method
		}
	} else if (state == EBUTTON_STATE_COUNTING_CLICKS_UP) {
		if (buttonPressed) {
			// If the button is pressed
			transition(now);
		} else {
#if defined(EBUTTON_SUPPORT_DONE_CLICKING) || defined(EBUTTON_SUPPORT_SINGLE_AND_DOUBLE_CLICKS)
			if (sinceLastTransition >= clickTime) {
#ifdef EBUTTON_SUPPORT_DONE_CLICKING
				// Handling any-click
				if (doneClickingMethod != NULL)
					doneClickingMethod(*this);
#endif
#ifdef EBUTTON_SUPPORT_SINGLE_AND_DOUBLE_CLICKS
				// Handling single-click
				if (clicks == 1 && singleClickMethod != NULL)
					singleClickMethod(*this);

				// Handling double-click
				if (clicks == 2 && doubleClickMethod != NULL)
					doubleClickMethod(*this);
#endif
				// if the button is not pressed for long enough, then reset the FSM
				reset();
			}
#endif
		}
	}
#if defined(EBUTTON_SUPPORT_LONG_PRESS_START) || defined(EBUTTON_SUPPORT_LONG_PRESS_DURING) || defined(EBUTTON_SUPPORT_LONG_PRESS_END)
	else if (state == EBUTTON_STATE_LONG_PRESSED) {
		if (!buttonPressed) {
			// Button was released from pressed state
			transition(now);
#ifdef EBUTTON_SUPPORT_LONG_PRESS_END
			if (longPressEndMethod != NULL)
				longPressEndMethod(*this);
#endif
			// Reset the FSM
			reset();
		}
	}
#endif
}

void EButton::transition(unsigned long now) {
	// Performed when a click transition is detected
	if (buttonPressed) {
		state = EBUTTON_STATE_COUNTING_CLICKS_DOWN;	// change to COUNTING_CLICKS_DOWN state
	} else {
#if defined(EBUTTON_SUPPORT_LONG_PRESS_START) || defined(EBUTTON_SUPPORT_LONG_PRESS_DURING) || defined(EBUTTON_SUPPORT_LONG_PRESS_END)
		if (state != EBUTTON_STATE_LONG_PRESSED) {
			// Count a click only if we were not in PRESSED state
#endif
			state = EBUTTON_STATE_COUNTING_CLICKS_UP;	// change to COUNTING_CLICKS_DOWN state
			clicks++;									// increase clicks on transition to UP
#if defined(EBUTTON_SUPPORT_LONG_PRESS_START) || defined(EBUTTON_SUPPORT_LONG_PRESS_DURING) || defined(EBUTTON_SUPPORT_LONG_PRESS_END)
		}
#endif
	}

#ifdef EBUTTON_SUPPORT_TRANSITION
	// Call the transition method
	if (transitionMethod != NULL)
		transitionMethod(*this);
#endif

#ifdef EBUTTON_SUPPORT_EACH_CLICK
	if (!buttonPressed) {
#if defined(EBUTTON_SUPPORT_LONG_PRESS_START) || defined(EBUTTON_SUPPORT_LONG_PRESS_DURING) || defined(EBUTTON_SUPPORT_LONG_PRESS_END)
		if (state != EBUTTON_STATE_LONG_PRESSED) {
#endif
			// if released and it was not in PRESSED mode, then we have a CLICK event
			if (eachClickMethod != NULL)
				eachClickMethod(*this);
#if defined(EBUTTON_SUPPORT_LONG_PRESS_START) || defined(EBUTTON_SUPPORT_LONG_PRESS_DURING) || defined(EBUTTON_SUPPORT_LONG_PRESS_END)
		}
#endif
	}
#endif
	prevTransitionTime = now;						// remember last transition time
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
// c++11 sleep
#include <thread>
#include <chrono>

#include "Net.h"

#define SHOW_ACKS

using namespace std;
using namespace net;

const unsigned short ServerPort = 30000;
const unsigned short ClientPort = 30001;
const int ProtocolId = 0x11112222;
const float DeltaTime = 0.001f;
const float SendRate = 0.001f;
const float TimeOut = 0.1f;
const int PacketSize = 256;

	// const int ServerPort = 30000;
	// const int ClientPort = 30001;
	// const int ProtocolId = 0x11112222;
	// const float DeltaTime = 0.001f;
	// const float TimeOut = 0.1f;
	// const unsigned int PacketCount = 100;

class FlowControl
{
public:

	FlowControl()
	{
		printf( "flow control initialized\n" );
		Reset();
	}

	void Reset()
	{
		mode = Bad;
		penalty_time = 4.0f;
		good_conditions_time = 0.0f;
		penalty_reduction_accumulator = 0.0f;
	}

	void Update( float deltaTime, float rtt )
	{
		const float RTT_Threshold = 250.0f;

		if ( mode == Good )
		{
			if ( rtt > RTT_Threshold )
			{
				printf( "*** dropping to bad mode ***\n" );
				mode = Bad;
				if ( good_conditions_time < 10.0f && penalty_time < 60.0f )
				{
					penalty_time *= 2.0f;
					if ( penalty_time > 60.0f )
						penalty_time = 60.0f;
					printf( "penalty time increased to %.1f\n", penalty_time );
				}
				good_conditions_time = 0.0f;
				penalty_reduction_accumulator = 0.0f;
				return;
			}

			good_conditions_time += deltaTime;
			penalty_reduction_accumulator += deltaTime;

			if ( penalty_reduction_accumulator > 10.0f && penalty_time > 1.0f )
			{
				penalty_time /= 2.0f;
				if ( penalty_time < 1.0f )
					penalty_time = 1.0f;
				printf( "penalty time reduced to %.1f\n", penalty_time );
				penalty_reduction_accumulator = 0.0f;
			}
		}

		if ( mode == Bad )
		{
			if ( rtt <= RTT_Threshold )
				good_conditions_time += deltaTime;
			else
				good_conditions_time = 0.0f;

			if ( good_conditions_time > penalty_time )
			{
				printf( "*** upgrading to good mode ***\n" );
				good_conditions_time = 0.0f;
				penalty_reduction_accumulator = 0.0f;
				mode = Good;
				return;
			}
		}
	}

	float GetSendRate()
	{
		return mode == Good ? 30.0f : 10.0f;
	}

private:

	enum Mode
	{
		Good,
		Bad
	};

	Mode mode;
	float penalty_time;
	float good_conditions_time;
	float penalty_reduction_accumulator;
};

// ----------------------------------------------

int main( int argc, char * argv[] )
{
	// parse command line

	enum Mode
	{
		Client,
		Server
	};

	Mode mode = Server;
	Address address;

	if ( argc >= 2 )
	{
		unsigned char a,b,c,d;
		if ( sscanf( argv[1], "%s.%s.%s.%s", &a, &b, &c, &d ) )
		{
			mode = Client;
			address = Address(a,b,c,d,ServerPort);
		}
	}

	// initialize

	if ( !InitializeSockets() )
	{
		printf( "failed to initialize sockets\n" );
		return 1;
	}

	ReliableConnection connection( ProtocolId, TimeOut );

	const unsigned short port = mode == Server ? ServerPort : ClientPort;

	if ( !connection.Start( port ) )
	{
		printf( "could not start connection on port %d\n", port );
		return 1;
	}

	if ( mode == Client )
		connection.Connect( address );
	else
		connection.Listen();

	bool connected = false;
	float sendAccumulator = 0.0f;
	float statsAccumulator = 0.0f;

	FlowControl flowControl;

	while ( true )
	{
		// update flow control

		if ( connection.IsConnected() )
			flowControl.Update( DeltaTime, connection.GetReliabilitySystem().GetRoundTripTime() * 1000.0f );

		const float sendRate = flowControl.GetSendRate();

		// detect changes in connection state

		if ( mode == Server && connected && !connection.IsConnected() )
		{
			flowControl.Reset();
			printf( "reset flow control\n" );
			connected = false;
		}

		if ( !connected && connection.IsConnected() )
		{
			printf( "client connected to server\n" );
			connected = true;
		}

		if ( !connected && connection.ConnectFailed() )
		{
			printf( "connection failed\n" );
			break;
		}

		// send and receive packets

		sendAccumulator += DeltaTime;

		while ( sendAccumulator > 1.0f / sendRate )
		{
			unsigned char packet[PacketSize];
			memset( packet, 0, sizeof( packet ) );
			connection.SendPacket( packet, sizeof( packet ) );
			sendAccumulator -= 1.0f / sendRate;
		}

		while ( true )
		{
			unsigned char packet[256];
			int bytes_read = connection.ReceivePacket( packet, sizeof(packet) );
			if ( bytes_read == 0 )
				break;
		}

		// show packets that were acked this frame

		#ifdef SHOW_ACKS
		unsigned int * acks = NULL;
		int ack_count = 0;
		connection.GetReliabilitySystem().GetAcks( &acks, ack_count );
		if ( ack_count > 0 )
		{
			printf( "acks: %d", acks[0] );
			for ( int i = 1; i < ack_count; ++i )
				printf( ",%d", acks[i] );
			printf( "\n" );
		}
		#endif

		// update connection

		connection.Update( DeltaTime );

		// show connection stats

		statsAccumulator += DeltaTime;

		while ( statsAccumulator >= 0.25f && connection.IsConnected() )
		{
			float rtt = connection.GetReliabilitySystem().GetRoundTripTime();

			unsigned int sent_packets = connection.GetReliabilitySystem().GetSentPackets();
			unsigned int acked_packets = connection.GetReliabilitySystem().GetAckedPackets();
			unsigned int lost_packets = connection.GetReliabilitySystem().GetLostPackets();

			float sent_bandwidth = connection.GetReliabilitySystem().GetSentBandwidth();
			float acked_bandwidth = connection.GetReliabilitySystem().GetAckedBandwidth();

			printf( "rtt %.1fms, sent %d, acked %d, lost %d (%.1f%%), sent bandwidth = %.1fkbps, acked bandwidth = %.1fkbps\n",
				rtt * 1000.0f, sent_packets, acked_packets, lost_packets,
				sent_packets > 0.0f ? (float) lost_packets / (float) sent_packets * 100.0f : 0.0f,
				sent_bandwidth, acked_bandwidth );

			statsAccumulator -= 0.25f;
		}
		//
		std::this_thread::sleep_for(std::chrono::seconds(DeltaTime));
		// net::wait( DeltaTime );
	}

	ShutdownSockets();

	return 0;
}
<commit_msg>fix: wait error; type cast error<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
// c++11 sleep
#include <thread>
#include <chrono>

#include "Net.h"

#define SHOW_ACKS

using namespace std;
using namespace net;

const unsigned short ServerPort = 30000;
const unsigned short ClientPort = 30001;
const int ProtocolId = 0x11112222;
const float DeltaTime = 0.001f;
const chrono::seconds DeltaTimeInSeconds(DeltaTime);
const float SendRate = 0.001f;
const float TimeOut = 0.1f;
const int PacketSize = 256;

	// const int ServerPort = 30000;
	// const int ClientPort = 30001;
	// const int ProtocolId = 0x11112222;
	// const float DeltaTime = 0.001f;
	// const float TimeOut = 0.1f;
	// const uint32_t PacketCount = 100;

class FlowControl
{
public:

	FlowControl()
	{
		printf( "flow control initialized\n" );
		Reset();
	}

	void Reset()
	{
		mode = Bad;
		penalty_time = 4.0f;
		good_conditions_time = 0.0f;
		penalty_reduction_accumulator = 0.0f;
	}

	void Update( float deltaTime, float rtt )
	{
		const float RTT_Threshold = 250.0f;

		if ( mode == Good )
		{
			if ( rtt > RTT_Threshold )
			{
				printf( "*** dropping to bad mode ***\n" );
				mode = Bad;
				if ( good_conditions_time < 10.0f && penalty_time < 60.0f )
				{
					penalty_time *= 2.0f;
					if ( penalty_time > 60.0f )
						penalty_time = 60.0f;
					printf( "penalty time increased to %.1f\n", penalty_time );
				}
				good_conditions_time = 0.0f;
				penalty_reduction_accumulator = 0.0f;
				return;
			}

			good_conditions_time += deltaTime;
			penalty_reduction_accumulator += deltaTime;

			if ( penalty_reduction_accumulator > 10.0f && penalty_time > 1.0f )
			{
				penalty_time /= 2.0f;
				if ( penalty_time < 1.0f )
					penalty_time = 1.0f;
				printf( "penalty time reduced to %.1f\n", penalty_time );
				penalty_reduction_accumulator = 0.0f;
			}
		}

		if ( mode == Bad )
		{
			if ( rtt <= RTT_Threshold )
				good_conditions_time += deltaTime;
			else
				good_conditions_time = 0.0f;

			if ( good_conditions_time > penalty_time )
			{
				printf( "*** upgrading to good mode ***\n" );
				good_conditions_time = 0.0f;
				penalty_reduction_accumulator = 0.0f;
				mode = Good;
				return;
			}
		}
	}

	float GetSendRate()
	{
		return mode == Good ? 30.0f : 10.0f;
	}

private:

	enum Mode
	{
		Good,
		Bad
	};

	Mode mode;
	float penalty_time;
	float good_conditions_time;
	float penalty_reduction_accumulator;
};

// ----------------------------------------------

int main( int argc, char * argv[] )
{
	// parse command line

	enum Mode
	{
		Client,
		Server
	};

	Mode mode = Server;
	Address address;

	if ( argc >= 2 )
	{
		unsigned char a,b,c,d;
		if ( sscanf( argv[1], "%s.%s.%s.%s", &a, &b, &c, &d ) )
		{
			mode = Client;
			address = Address(a,b,c,d,ServerPort);
		}
	}

	// initialize

	if ( !InitializeSockets() )
	{
		printf( "failed to initialize sockets\n" );
		return 1;
	}

	ReliableConnection connection( ProtocolId, TimeOut );

	const unsigned short port = mode == Server ? ServerPort : ClientPort;

	if ( !connection.Start( port ) )
	{
		printf( "could not start connection on port %d\n", port );
		return 1;
	}

	if ( mode == Client )
		connection.Connect( address );
	else
		connection.Listen();

	bool connected = false;
	float sendAccumulator = 0.0f;
	float statsAccumulator = 0.0f;

	FlowControl flowControl;

	while ( true )
	{
		// update flow control

		if ( connection.IsConnected() )
			flowControl.Update( DeltaTime, connection.GetReliabilitySystem().GetRoundTripTime() * 1000.0f );

		const float sendRate = flowControl.GetSendRate();

		// detect changes in connection state

		if ( mode == Server && connected && !connection.IsConnected() )
		{
			flowControl.Reset();
			printf( "reset flow control\n" );
			connected = false;
		}

		if ( !connected && connection.IsConnected() )
		{
			printf( "client connected to server\n" );
			connected = true;
		}

		if ( !connected && connection.ConnectFailed() )
		{
			printf( "connection failed\n" );
			break;
		}

		// send and receive packets

		sendAccumulator += DeltaTime;

		while ( sendAccumulator > 1.0f / sendRate )
		{
			unsigned char packet[PacketSize];
			memset( packet, 0, sizeof( packet ) );
			connection.SendPacket( packet, sizeof( packet ) );
			sendAccumulator -= 1.0f / sendRate;
		}

		while ( true )
		{
			unsigned char packet[256];
			int bytes_read = connection.ReceivePacket( packet, sizeof(packet) );
			if ( bytes_read == 0 )
				break;
		}

		// show packets that were acked this frame

		#ifdef SHOW_ACKS
		uint32_t * acks = NULL;
		int ack_count = 0;
		connection.GetReliabilitySystem().GetAcks( &acks, ack_count );
		if ( ack_count > 0 )
		{
			printf( "acks: %d", acks[0] );
			for ( int i = 1; i < ack_count; ++i )
				printf( ",%d", acks[i] );
			printf( "\n" );
		}
		#endif

		// update connection

		connection.Update( DeltaTime );

		// show connection stats

		statsAccumulator += DeltaTime;

		while ( statsAccumulator >= 0.25f && connection.IsConnected() )
		{
			float rtt = connection.GetReliabilitySystem().GetRoundTripTime();

			uint32_t sent_packets = connection.GetReliabilitySystem().GetSentPackets();
			uint32_t acked_packets = connection.GetReliabilitySystem().GetAckedPackets();
			uint32_t lost_packets = connection.GetReliabilitySystem().GetLostPackets();

			float sent_bandwidth = connection.GetReliabilitySystem().GetSentBandwidth();
			float acked_bandwidth = connection.GetReliabilitySystem().GetAckedBandwidth();

			printf( "rtt %.1fms, sent %d, acked %d, lost %d (%.1f%%), sent bandwidth = %.1fkbps, acked bandwidth = %.1fkbps\n",
				rtt * 1000.0f, sent_packets, acked_packets, lost_packets,
				sent_packets > 0.0f ? (float) lost_packets / (float) sent_packets * 100.0f : 0.0f,
				sent_bandwidth, acked_bandwidth );

			statsAccumulator -= 0.25f;
		}
		//
		std::this_thread::sleep_for(DeltaTimeInSeconds);
		// net::wait( DeltaTime );
	}

	ShutdownSockets();

	return 0;
}
<|endoftext|>


<commit_before>/*
 * Manager.cpp
 *
 *  Created on: Mar 25, 2014
 *      Author: user
 */

#include "Manager.h"

Manager::Manager(Robot* robot, Plan* plan)
{
	_robot = robot;
	_plan = plan;
	_currentBehavior = plan->startBehavior();
	_running = false;
}

void Manager::run()
{
	_running = true;
	_robot->refresh();

	if (_currentBehavior->startCondition() == false)
	{
		_currentBehavior = _currentBehavior->getNextBehavior();

		// If there are no more behaviors
		if (!_currentBehavior)
		{
			std::cout << "The robot fail to start! there isn't any legal step! Please take the robot to other position" << std::endl;
			return;
		}
	}

	double previewsX = 0;
	double previewsY = 0;
	double previewsYaw = 0;

	int runNum=0;
	while (_running)
	{
		_robot->refresh();

		// ------------
		// Calculate deltas

		double deltaX = _robot->getX() - previewsX;
		double deltaY = _robot->getY() - previewsY;
		double deltaYaw = _robot->getYaw() - previewsYaw;

		if (_currentBehavior->stopCondition())
		{
			_currentBehavior = _currentBehavior->getNextBehavior();

			// If there are no more behaviors
			if (!_currentBehavior)
			{
				std::cout << "Can't move! there isn't any legal step!" << std::endl;
				return;
			}
		}

		// ------------
		// Save this iteration x, y ,yaw
		previewsX = _robot->getX();
		previewsY = _robot->getY();
		previewsYaw = _robot->getYaw();

		_currentBehavior->action();

		Laser& laser = _robot->getLaser();
		Map& map = _slamManager.update(deltaX, deltaY, deltaYaw, laser);

		// -----------
		// Print the map
		if (runNum % 3 == 0)
		{
			cout << map << endl;

		}

		runNum++;
	}

}

Manager::~Manager()
{
}
<commit_msg>Change the amounts of prints<commit_after>/*
 * Manager.cpp
 *
 *  Created on: Mar 25, 2014
 *      Author: user
 */

#include "Manager.h"

Manager::Manager(Robot* robot, Plan* plan)
{
	_robot = robot;
	_plan = plan;
	_currentBehavior = plan->startBehavior();
	_running = false;
}

void Manager::run()
{
	_running = true;
	_robot->refresh();

	if (_currentBehavior->startCondition() == false)
	{
		_currentBehavior = _currentBehavior->getNextBehavior();

		// If there are no more behaviors
		if (!_currentBehavior)
		{
			std::cout << "The robot fail to start! there isn't any legal step! Please take the robot to other position" << std::endl;
			return;
		}
	}

	double previewsX = 0;
	double previewsY = 0;
	double previewsYaw = 0;

	int runNum=0;
	while (_running)
	{
		_robot->refresh();

		// ------------
		// Calculate deltas

		double deltaX = _robot->getX() - previewsX;
		double deltaY = _robot->getY() - previewsY;
		double deltaYaw = _robot->getYaw() - previewsYaw;

		if (_currentBehavior->stopCondition())
		{
			_currentBehavior = _currentBehavior->getNextBehavior();

			// If there are no more behaviors
			if (!_currentBehavior)
			{
				std::cout << "Can't move! there isn't any legal step!" << std::endl;
				return;
			}
		}

		// ------------
		// Save this iteration x, y ,yaw
		previewsX = _robot->getX();
		previewsY = _robot->getY();
		previewsYaw = _robot->getYaw();

		_currentBehavior->action();

		Laser& laser = _robot->getLaser();
		Map& map = _slamManager.update(deltaX, deltaY, deltaYaw, laser);

		// -----------
		// Print the map
		if (runNum % 10 == 0)
		{
			cout << map << endl;

		}

		runNum++;
	}

}

Manager::~Manager()
{
}
<|endoftext|>