Esempio n. 1
0
int DiffTime(char time1[],char time2[],double* second)
{
	int i=0;
	int iYear=0;
	int iMon=0;
	int iDay=0;
	int iHour=0;
	int iMin=0;
	int iSec=0;
	char tmp[5]="";
	int ch=0;
	time_t t1;
	time_t t2;
	struct tm tm_t;

	memset(&t1,0,sizeof(time_t));
	memset(&t2,0,sizeof(time_t));
	memset(&tm_t,0,sizeof(struct tm));

	for (i=0;i<14;i++)
	{
		ch=time1[i];
		if(!isdigit(ch))
			return E_DATE_FMT;
	}
	for (i=0;i<14;i++)
	{
		ch=time2[i];
		if(!isdigit(ch))
			return E_DATE_FMT;
	}

	memcpy(tmp,time1,4);
	iYear=atoi(tmp);
	memset(tmp,0,sizeof(tmp));
	memcpy(tmp,time1+4,2);
	iMon=atoi(tmp);
	memcpy(tmp,time1+6,2);
	iDay=atoi(tmp);
	memcpy(tmp,time1+8,2);
	iHour=atoi(tmp);
	memcpy(tmp,time1+10,2);
	iMin=atoi(tmp);
	memcpy(tmp,time1+12,2);
	iSec=atoi(tmp);

	memset(&tm_t,0,sizeof(struct tm));
	tm_t.tm_year=iYear-1900;
	tm_t.tm_mon=iMon-1;
	tm_t.tm_mday=iDay;
	tm_t.tm_hour=iHour;
	tm_t.tm_min=iMin;
	tm_t.tm_sec=iSec;
	t1=mktime(&tm_t);
	memcpy(tmp,time2,4);
	iYear=atoi(tmp);
	memset(tmp,0,sizeof(tmp));
	memcpy(tmp,time2+4,2);
	iMon=atoi(tmp);
	memcpy(tmp,time2+6,2);
	iDay=atoi(tmp);
	memcpy(tmp,time2+8,2);
	iHour=atoi(tmp);
	memcpy(tmp,time2+10,2);
	iMin=atoi(tmp);
	memcpy(tmp,time2+12,2);
	iSec=atoi(tmp);

	memset(&tm_t,0,sizeof(struct tm));
	tm_t.tm_year=iYear-1900;
	tm_t.tm_mon=iMon-1;
	tm_t.tm_mday=iDay;
	tm_t.tm_hour=iHour;
	tm_t.tm_min=iMin;
	tm_t.tm_sec=iSec;
	t2=mktime(&tm_t);
	*second=difftime(t1,t2);
	return 0;
}
extern void mexFunction(int iNbOut, mxArray *pmxOut[],
        int iNbIn, const mxArray *pmxIn[])
{
    /* vars in */
    float *alpha, *Ct, *pars;
    int Nx, Ny, Nz, nLab, maxIt;
    float errBound, cc, steps;
    
    /* vars out */
    float *u, *cvg;
    int *itNum;
    double *runTime;
    
    int dim[4];
    int nDim;
    
    /* others */
    time_t  start_time, end_time;
    
    /* compute Max-Flow */
    start_time = clock();
    
    /* Inputs */
    Ct = mxGetData(pmxIn[0]);             /* bound of sink flows */
    alpha = mxGetData(pmxIn[1]);        /* penalty parameters */
    pars = mxGetData(pmxIn[2]);  /* Vector of parameters */
    
    /*
     *pfVecParameters Setting
     * [0] : number of columns
     * [1] : number of rows
     * [2] : number of slices
     * [3] : number of labels
     * [4] : the maximum iteration number
     * [5] : error criterion
     * [6] : cc for the step-size of ALM
     * [7] : steps for the step-size of projected-gradient of p
     */
    
    /* pars */
    Ny = (int) pars[0];
    Nx = (int) pars[1];
    Nz = (int) pars[2];
    nLab = (int) pars[3];
    maxIt = (int) pars[4];
    errBound = (float) pars[5];
    cc = (float) pars[6];
    steps = (float) pars[7];
    
    /* Outputs */
    /* outputs the computed u(x)  */
    dim[0] = Ny;
    dim[1] = Nx;
    dim[2] = Nz;
    dim[3] = nLab;
    nDim = 4;
    
    pmxOut[0] = mxCreateNumericArray(nDim,(const int*)dim,mxSINGLE_CLASS,mxREAL);
    u = mxGetData(pmxOut[0]);
    
    /* outputs the convergence rate  */
    nDim = 2;
    dim[0] = maxIt;
    dim[1] = 1;
    pmxOut[1] = mxCreateNumericArray(nDim,(const int*)dim,mxSINGLE_CLASS,mxREAL);
    cvg = mxGetData(pmxOut[1]);
    
    /* outputs the iteration number  */
    nDim = 2;
    dim[0] = 1;
    dim[1] = 1;
    pmxOut[2] = mxCreateNumericArray(nDim,(const int*)dim,mxUINT16_CLASS,mxREAL);
    itNum = mxGetData(pmxOut[2]);
    
    /* outputs the computation time  */
    nDim = 2;
    dim[0] = 1;
    dim[1] = 1;
    pmxOut[3] = mxCreateNumericArray(nDim,(const int*)dim,mxSINGLE_CLASS,mxREAL);
    runTime = mxGetData(pmxOut[3]);
    
    
    /* compute Max-Flow */
    start_time = clock();
    
    
    runMaxFlow(alpha, Ct,
            Nx, Ny, Nz, nLab, maxIt, errBound, cc, steps,
            u, cvg, itNum);
    
    
    end_time = clock();
    
    runTime[0] = difftime(end_time, start_time)/1000000;
    
    mexPrintf("potts model max flow 3D: number of iterations = %i; time = %.4f sec\n",itNum[0],runTime[0]);
    
}
Esempio n. 3
0
flt timertime(void) {
  flt a;
  a = difftime(stoptime, starttime);
  return a;
}
Esempio n. 4
0
int main (){
	if( ( fd = open( "/dev/mem", ( O_RDWR | O_SYNC ) ) ) == -1 ) {
		printf( "ERROR: could not open \"/dev/mem\"...\n" );
		return( 1 );
	}
	virtual_base=mmap(NULL,REG_SPAN,(PROT_READ|PROT_WRITE),MAP_SHARED,fd,REG_BASE);
	if( virtual_base == MAP_FAILED ) {
			printf( "ERROR: mmap() failed...\n" );
			close( fd );
			return( 1 );
		}

result_addr=virtual_base + ( ( unsigned long  )( RESULT_BASE ) & ( unsigned long)( REG_MASK ) );
hash0_addr=virtual_base + ( ( unsigned long  )( HASH0_BASE ) & ( unsigned long)( REG_MASK ) );
snddincount_addr=virtual_base + ( ( unsigned long  )( SNDDINCOUNT_BASE ) & ( unsigned long)( REG_MASK ) );
snddoutcount_addr=virtual_base + ( ( unsigned long  )( SNDDOUTCOUNT_BASE ) & ( unsigned long)( REG_MASK ) );

while(1){
	if(st == 1){
		*(uint32_t *)snddoutcount_addr = count;
		if(count == *(uint32_t *)snddincount_addr){
			hashRec[count] = *(uint32_t *)result_addr;
			printf("Received hash part %i\r\n", count);
			count = count + 1;
		}
		if(count >= 5){
		st = 0;
		count = 0;
		printf("%x %x %x %x %x\n", hashRec[4], hashRec[3], hashRec[2], hashRec[1], hashRec[0]);
		
			if (hashRec[4] == hash[4] && hashRec[3] == hash[3] && hashRec[2] == hash[2] && hashRec[1] == hash[1] && hashRec[0] == hash[0]){
				printf("Recieved hash is correct. \r\n");
				st = 2;
				count = 0;
				*(uint32_t *)snddoutcount_addr = 15;
			}
			else{
			
			printf("Hash from the FPGA is not the same as the hash from the input, restarting. \r\n");
			*(uint32_t *)snddoutcount_addr = 14;
			st = 0;
			}
		}
	
	}

	else if(st == 2){
		if (count == 0){
			printf("What is the minimum amount of characters in the password? \r\n");
			scanf("%i", &length_min);
			if(length_min > 32 || length_min < 1){
				printf("Character count out of bounds, minimum length set to 1.");
				length_min = 1;}
			printf("What is the maximum amount of characters in the password? \r\n");
			scanf("%i", &length_max);
			if(length_max > 32 || length_max < length_min){
				printf("Character count out of bounds, maximum length set to 32.");
				length_max = 32;}
		}
		if (count < length_max){
			printf("What size will the alphabet for position %i be? \r\n", count);
			scanf("%i", &length_alphabet[count]);
			if(length_alphabet[count] > 128){printf("Alphabet size is too large, 128 characters is the maximum. ");}
			else if(length_alphabet[count] < 1){printf("Alphabet size is too small, 1 character is the minimum. ");}
			else{
				for (i = 0; i*4 < length_alphabet[count]; i = i + 1){
					printf("Write the character code, in hex, for characters %i to %i in the alphabet with position %i. \r\n", i*4, i*4 + 3, count);
					scanf("%x", &alphabet_part);
					*(uint32_t *)hash0_addr = alphabet_part;
					if(i < 12){
					*(uint32_t *)snddoutcount_addr = i;}
					else if(i < 24){
					*(uint32_t *)snddoutcount_addr = i - 12;}
					else if(i < 34){
					*(uint32_t *)snddoutcount_addr = i - 24;}
					else if(i < 44){
					*(uint32_t *)snddoutcount_addr = i - 34;}
					else{*(uint32_t *)snddoutcount_addr = i - 44;}
				}
				*(uint32_t *)snddoutcount_addr = 14;
				count = count + 1;
			}
		}
		else{
			*(uint32_t *)snddoutcount_addr = 15;
			count = 0;
			i = 1;
			st = 3;
		}
	}
	
	else if(st == 3){
		if (count < length_max){
			*(uint32_t *)hash0_addr = length_alphabet[count];
			*(uint32_t *)snddoutcount_addr = i;
			if(i == *(uint32_t *)snddincount_addr){
				printf("Length information for part %i is sent. %i. \r\n", count, length_alphabet[count]);
				count = count + 1;
				if(i < 14){ i = i + 1;}
				else {i = 1;}
			}
		}
		else {
			*(uint32_t *)snddoutcount_addr = 0;
			*(uint32_t *)hash0_addr = length_min;
			if (0 == *(uint32_t *)snddincount_addr){
				*(uint32_t *)snddoutcount_addr = 15;
				st = 4;
				count = 0;
				time (&start);
				printf("Done gathering information, starting. \r\n");
			}
		}
	}
		
	else if(st == 4){
		*(uint32_t *)snddoutcount_addr = count;
		if(count == *(uint32_t *)snddincount_addr){
			output[count] = *(uint32_t *)result_addr;
			printf("Received part %i\r\n", count);
			count = count + 1;
		}
		if(count >= 16){
		st = 5;
		count = 0;
		time (&end);
		dif = difftime (end,start);
		printf("%x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x\n", output[15], output[14], output[13], output[12], output[11], output[10], output[9], output[8], output[7], output[6], output[5], output[4], output[3], output[2], output[1], output[0]);		
		}
	}
	
	else if (st == 5){
		*(uint32_t *)snddoutcount_addr = count;
		if(count == *(uint32_t *)snddincount_addr){
			rounds[count] = *(uint32_t *)result_addr;
			count = count + 1;
		}
		if (count == 2){
			rounds64 = (uint64_t) rounds[1] << 32 | rounds[0];
			printf("Number of 20 ns rounds used to find the correct hash: %g\r\n", (double)rounds64);
			printf("That equals to %g seconds \r\n", (double)rounds64*0.00000002);
			printf("This program measured %g seconds from confirmed hash to received result. \r\n", dif);
			st = 0;
		}
		
	}
	else {
		printf("From the left, enter the first 8 digits of the hash: \r\n");
		scanf("%x", &hash[4]);
		*(uint32_t *)hash0_addr = hash[4];
		*(uint32_t *)snddoutcount_addr = 4;
		printf("Enter next 8 digits of the hash: \r\n");
		scanf("%x", &hash[3]);
		*(uint32_t *)hash0_addr = hash[3];
		*(uint32_t *)snddoutcount_addr = 3;
		printf("Enter next 8 digits of the hash: \r\n");
		scanf("%x", &hash[2]);
		*(uint32_t *)hash0_addr = hash[2];
		*(uint32_t *)snddoutcount_addr = 2;
		printf("Enter next 8 digits of the hash: \r\n");
		scanf("%x", &hash[1]);
		*(uint32_t *)hash0_addr = hash[1];
		*(uint32_t *)snddoutcount_addr = 1;
		printf("Enter last 8 digits of the hash: \r\n");
		scanf("%x", &hash[0]);
		*(uint32_t *)hash0_addr = hash[0];
		*(uint32_t *)snddoutcount_addr = 0;

		printf("%x %x %x %x %x\n", hash[4], hash[3], hash[2], hash[1], hash[0]);
		
			st = 1;
			count = 0;
			*(uint32_t *)snddoutcount_addr = 10;
			corr = 0;
		
	}
}
return 0;




}
Esempio n. 5
0
/**
 * main
 */
int main(int argc, const char **argv)
{
    // Our main data storage vessel..
    RASPIVID_STATE state;

    MMAL_STATUS_T status = -1;
    MMAL_PORT_T *camera_video_port = NULL;
    MMAL_PORT_T *camera_still_port = NULL;
    MMAL_PORT_T *preview_input_port = NULL;
    MMAL_PORT_T *encoder_input_port = NULL;
    MMAL_PORT_T *encoder_output_port = NULL;

    time_t timer_begin,timer_end;
    double secondsElapsed;

    bcm_host_init();
    signal(SIGINT, signal_handler);

    // read default status
    default_status(&state);

    // init windows and OpenCV Stuff
    cvNamedWindow("camcvWin", CV_WINDOW_AUTOSIZE);
    int w=state.width;
    int h=state.height;
    dstImage = cvCreateImage(cvSize(w,h), IPL_DEPTH_8U, 3);
    py = cvCreateImage(cvSize(w,h), IPL_DEPTH_8U, 1);		// Y component of YUV I420 frame
    pu = cvCreateImage(cvSize(w/2,h/2), IPL_DEPTH_8U, 1);	// U component of YUV I420 frame
    pv = cvCreateImage(cvSize(w/2,h/2), IPL_DEPTH_8U, 1);	// V component of YUV I420 frame
    pu_big = cvCreateImage(cvSize(w,h), IPL_DEPTH_8U, 1);
    pv_big = cvCreateImage(cvSize(w,h), IPL_DEPTH_8U, 1);
    image = cvCreateImage(cvSize(w,h), IPL_DEPTH_8U, 3);	// final picture to display


    // create camera
    if (!create_camera_component(&state))
    {
        vcos_log_error("%s: Failed to create camera component", __func__);
    }
// AZG(20160226): Debug
    else if ((status = raspipreview_create(&state.preview_parameters)) != MMAL_SUCCESS)
    {
        vcos_log_error("%s: Failed to create preview component", __func__);
        destroy_camera_component(&state);
    }
    else
    {
        PORT_USERDATA callback_data;

        camera_video_port   = state.camera_component->output[MMAL_CAMERA_VIDEO_PORT];
        camera_still_port   = state.camera_component->output[MMAL_CAMERA_CAPTURE_PORT];

        VCOS_STATUS_T vcos_status;

        callback_data.pstate = &state;

        vcos_status = vcos_semaphore_create(&callback_data.complete_semaphore, "RaspiStill-sem", 0);
        vcos_assert(vcos_status == VCOS_SUCCESS);

        // assign data to use for callback
        camera_video_port->userdata = (struct MMAL_PORT_USERDATA_T *)&callback_data;

        // init timer
        time(&timer_begin);


        // start capture
        if (mmal_port_parameter_set_boolean(camera_video_port, MMAL_PARAMETER_CAPTURE, 1) != MMAL_SUCCESS)
        {
            goto error;
        }

        // Send all the buffers to the video port

        int num = mmal_queue_length(state.video_pool->queue);
        int q;
        for (q=0; q<num; q++)
        {
            MMAL_BUFFER_HEADER_T *buffer = mmal_queue_get(state.video_pool->queue);

            if (!buffer)
                vcos_log_error("Unable to get a required buffer %d from pool queue", q);

            if (mmal_port_send_buffer(camera_video_port, buffer)!= MMAL_SUCCESS)
                vcos_log_error("Unable to send a buffer to encoder output port (%d)", q);
        }


        // Now wait until we need to stop
        vcos_sleep(state.timeout);

error:

        mmal_status_to_int(status);


        // Disable all our ports that are not handled by connections
        check_disable_port(camera_still_port);

        if (state.camera_component)
            mmal_component_disable(state.camera_component);

        //destroy_encoder_component(&state);
        //	raspipreview_destroy(&state.preview_parameters);
        destroy_camera_component(&state);

    }
    if (status != 0)
        raspicamcontrol_check_configuration(128);

    time(&timer_end);  /* get current time; same as: timer = time(NULL)  */
    cvReleaseImage(&dstImage);
    cvReleaseImage(&pu);
    cvReleaseImage(&pv);
    cvReleaseImage(&py);
    cvReleaseImage(&pu_big);
    cvReleaseImage(&pv_big);

    secondsElapsed = difftime(timer_end,timer_begin);

    printf ("%.f seconds for %d frames : FPS = %f\n", secondsElapsed,nCount,(float)((float)(nCount)/secondsElapsed));

    return 0;
}
Esempio n. 6
0
PHPAPI int php_setcookie(char *name, int name_len, char *value, int value_len, time_t expires, char *path, int path_len, char *domain, int domain_len, int secure, int url_encode, int httponly TSRMLS_DC)
{
	char *cookie;
	int len=sizeof("Set-Cookie: ");
	zend_string *dt;
	sapi_header_line ctr = {0};
	int result;
	zend_string *encoded_value = NULL;

	if (name && strpbrk(name, "=,; \t\r\n\013\014") != NULL) {   /* man isspace for \013 and \014 */
		zend_error( E_WARNING, "Cookie names cannot contain any of the following '=,; \\t\\r\\n\\013\\014'" );
		return FAILURE;
	}

	if (!url_encode && value && strpbrk(value, ",; \t\r\n\013\014") != NULL) { /* man isspace for \013 and \014 */
		zend_error( E_WARNING, "Cookie values cannot contain any of the following ',; \\t\\r\\n\\013\\014'" );
		return FAILURE;
	}

	len += name_len;
	if (value && url_encode) {
		encoded_value = php_url_encode(value, value_len);
		len += encoded_value->len;
	} else if (value) {
		encoded_value = zend_string_init(value, value_len, 0);
		len += encoded_value->len;
	}

	if (path) {
		len += path_len;
	}
	if (domain) {
		len += domain_len;
	}

	cookie = emalloc(len + 100);

	if (value && value_len == 0) {
		/*
		 * MSIE doesn't delete a cookie when you set it to a null value
		 * so in order to force cookies to be deleted, even on MSIE, we
		 * pick an expiry date in the past
		 */
		dt = php_format_date("D, d-M-Y H:i:s T", sizeof("D, d-M-Y H:i:s T")-1, 1, 0 TSRMLS_CC);
		snprintf(cookie, len + 100, "Set-Cookie: %s=deleted; expires=%s; Max-Age=0", name, dt->val);
		zend_string_free(dt);
	} else {
		snprintf(cookie, len + 100, "Set-Cookie: %s=%s", name, value ? encoded_value->val : "");
		if (expires > 0) {
			const char *p;
			char tsdelta[13];
			strlcat(cookie, COOKIE_EXPIRES, len + 100);
			dt = php_format_date("D, d-M-Y H:i:s T", sizeof("D, d-M-Y H:i:s T")-1, expires, 0 TSRMLS_CC);
			/* check to make sure that the year does not exceed 4 digits in length */
			p = zend_memrchr(dt->val, '-', dt->len);
			if (!p || *(p + 5) != ' ') {
				zend_string_free(dt);
				efree(cookie);
				zend_string_free(encoded_value);
				zend_error(E_WARNING, "Expiry date cannot have a year greater than 9999");
				return FAILURE;
			}
			strlcat(cookie, dt->val, len + 100);
			zend_string_free(dt);

			snprintf(tsdelta, sizeof(tsdelta), ZEND_LONG_FMT, (zend_long) difftime(expires, time(NULL)));
			strlcat(cookie, COOKIE_MAX_AGE, len + 100);
			strlcat(cookie, tsdelta, len + 100);
		}
	}

	if (encoded_value) {
		zend_string_free(encoded_value);
	}

	if (path && path_len > 0) {
		strlcat(cookie, COOKIE_PATH, len + 100);
		strlcat(cookie, path, len + 100);
	}
	if (domain && domain_len > 0) {
		strlcat(cookie, COOKIE_DOMAIN, len + 100);
		strlcat(cookie, domain, len + 100);
	}
	if (secure) {
		strlcat(cookie, COOKIE_SECURE, len + 100);
	}
	if (httponly) {
		strlcat(cookie, COOKIE_HTTPONLY, len + 100);
	}

	ctr.line = cookie;
	ctr.line_len = strlen(cookie);

	result = sapi_header_op(SAPI_HEADER_ADD, &ctr TSRMLS_CC);
	efree(cookie);
	return result;
}
Esempio n. 7
0
File: tcp_recv.c Progetto: mbryk/OS
int main(int argc, char **argv){
	if(argc==1){ fprintf(stderr, "Error- Usage: %s <Port #>\n",argv[0]); return -1;}
        int s,s2,port;
        struct sockaddr_in sin, from;
        int len = sizeof from;

        sin.sin_family = AF_INET;
	if((port=atoi(argv[1]))<1025){
		fprintf(stderr, "Error- Invalid Port #: %s\n", argv[1]);
		return -1;
	}
        sin.sin_port = htons(port);
        sin.sin_addr.s_addr=INADDR_ANY;

        if((s=socket(AF_INET, SOCK_STREAM,0))==-1){perror("Error creating socket."); return -1;}
        if(bind(s, (struct sockaddr *)&sin, sizeof sin)<0){
                perror("Error binding socket to sockaddr.");
                close(s);
                return -1;
        }
	if(listen(s,128)<0){ perror("Error Listening for TCP Connections."); close(s); return -1; }
        if((s2=accept(s, (struct sockaddr *)&from,&len))<0){
                perror("Error Accepting TCP Connection"); close(s); return -1;
        }

	int r,r_full,n;
        int bsize = 4096;
        int bytes = 0;
        char *buf = malloc(bsize);
        if(buf==NULL){perror("Error Allocating Memory for buffer"); close(s); return -1;}
        char *buf_tmp;
        struct timeval begin,end;
        if(gettimeofday(&begin,NULL)==-1){ perror("Error recording begin-time of read from socket"); close(s); return -1; }
        while((r = read(s2,buf,bsize))!=0){
                if(r==-1){ perror("Error reading from socket"); close(s); return -1; }
                buf_tmp = buf; r_full = r;
                while((n=write(1,buf_tmp,r))!=r && n!=-1){
                        buf_tmp = buf_tmp+n;
                        r-=n;
                }
                if(n==-1){ perror("Error writing to output"); close(s); return -1; }
                bytes+=r_full;
        }
	close(s);close(s2);
        if(gettimeofday(&end,NULL)==-1){ perror("Error recording end-time of read from socket"); close(s); return -1; }

        double secs = difftime(end.tv_sec,begin.tv_sec);
        double usecs = difftime(end.tv_usec,begin.tv_usec)/1000000;
        secs += usecs;
        double rate = bytes/secs/1048576;

	struct hostent *he;
	if(!(he=gethostbyaddr((char *)&from.sin_addr, sizeof from.sin_addr, AF_INET))){
		fprintf(stderr, "Error retrieving information on TCP sender\n");
		herror(" ");
                close(s);
		return -1;
	}
	char *ip = inet_ntoa(from.sin_addr);
	fprintf(stderr, "Remote Endpoint:\n\tIP address: %s\n",ip);
	if(he->h_name) fprintf(stderr, "\tName: %s\n", he->h_name);
	fprintf(stderr, "\tPort: %d\n", ntohs(from.sin_port));
        fprintf(stderr, "Bytes Sent:\t%d\nTransfer Rate:\t%f MB/s\n",bytes,rate);
        close(s); free(buf);
        return 0;
}
Esempio n. 8
0
int np_net_ssl_check_cert(int days_till_exp_warn, int days_till_exp_crit){
#  ifdef USE_OPENSSL
	X509 *certificate=NULL;
	X509_NAME *subj=NULL;
	char timestamp[50] = "";
	char cn[MAX_CN_LENGTH]= "";
	char *tz;
	
	int cnlen =-1;
	int status=STATE_UNKNOWN;

	ASN1_STRING *tm;
	int offset;
	struct tm stamp;
	float time_left;
	int days_left;
	int time_remaining;
	time_t tm_t;

	certificate=SSL_get_peer_certificate(s);
	if (!certificate) {
		printf("%s\n",_("CRITICAL - Cannot retrieve server certificate."));
		return STATE_CRITICAL;
	}

	/* Extract CN from certificate subject */
	subj=X509_get_subject_name(certificate);

	if (!subj) {
		printf("%s\n",_("CRITICAL - Cannot retrieve certificate subject."));
		return STATE_CRITICAL;
	}
	cnlen = X509_NAME_get_text_by_NID(subj, NID_commonName, cn, sizeof(cn));
	if (cnlen == -1)
		strcpy(cn, _("Unknown CN"));

	/* Retrieve timestamp of certificate */
	tm = X509_get_notAfter(certificate);

	/* Generate tm structure to process timestamp */
	if (tm->type == V_ASN1_UTCTIME) {
		if (tm->length < 10) {
			printf("%s\n", _("CRITICAL - Wrong time format in certificate."));
			return STATE_CRITICAL;
		} else {
			stamp.tm_year = (tm->data[0] - '0') * 10 + (tm->data[1] - '0');
			if (stamp.tm_year < 50)
				stamp.tm_year += 100;
			offset = 0;
		}
	} else {
		if (tm->length < 12) {
			printf("%s\n", _("CRITICAL - Wrong time format in certificate."));
			return STATE_CRITICAL;
		} else {
			stamp.tm_year =
				(tm->data[0] - '0') * 1000 + (tm->data[1] - '0') * 100 +
				(tm->data[2] - '0') * 10 + (tm->data[3] - '0');
			stamp.tm_year -= 1900;
			offset = 2;
		}
	}
	stamp.tm_mon =
		(tm->data[2 + offset] - '0') * 10 + (tm->data[3 + offset] - '0') - 1;
	stamp.tm_mday =
		(tm->data[4 + offset] - '0') * 10 + (tm->data[5 + offset] - '0');
	stamp.tm_hour =
		(tm->data[6 + offset] - '0') * 10 + (tm->data[7 + offset] - '0');
	stamp.tm_min =
		(tm->data[8 + offset] - '0') * 10 + (tm->data[9 + offset] - '0');
	stamp.tm_sec =
		(tm->data[10 + offset] - '0') * 10 + (tm->data[11 + offset] - '0');
	stamp.tm_isdst = -1;

	tm_t = timegm(&stamp);
	time_left = difftime(tm_t, time(NULL));
	days_left = time_left / 86400;
	tz = getenv("TZ");
	setenv("TZ", "GMT", 1);
	tzset();
	strftime(timestamp, 50, "%c %z", localtime(&tm_t));
	if (tz)
		setenv("TZ", tz, 1);
	else
		unsetenv("TZ");
	tzset();

	if (days_left > 0 && days_left <= days_till_exp_warn) {
		printf (_("%s - Certificate '%s' expires in %d day(s) (%s).\n"), (days_left>days_till_exp_crit)?"WARNING":"CRITICAL", cn, days_left, timestamp);
		if (days_left > days_till_exp_crit)
			status = STATE_WARNING;
		else
			status = STATE_CRITICAL;
	} else if (days_left == 0 && time_left > 0) {
		if (time_left >= 3600)
			time_remaining = (int) time_left / 3600;
		else
			time_remaining = (int) time_left / 60;

		printf (_("%s - Certificate '%s' expires in %u %s (%s)\n"),
			(days_left>days_till_exp_crit) ? "WARNING" : "CRITICAL", cn, time_remaining,
			time_left >= 3600 ? "hours" : "minutes", timestamp);

		if ( days_left > days_till_exp_crit)
			status = STATE_WARNING;
		else
			status = STATE_CRITICAL;
	} else if (time_left < 0) {
		printf(_("CRITICAL - Certificate '%s' expired on %s.\n"), cn, timestamp);
		status=STATE_CRITICAL;
	} else if (days_left == 0) {
		printf (_("%s - Certificate '%s' just expired (%s).\n"), (days_left>days_till_exp_crit)?"WARNING":"CRITICAL", cn, timestamp);
		if (days_left > days_till_exp_crit)
			status = STATE_WARNING;
		else
			status = STATE_CRITICAL;
	} else {
		printf(_("OK - Certificate '%s' will expire on %s.\n"), cn, timestamp);
		status = STATE_OK;
	}
	X509_free(certificate);
	return status;
#  else /* ifndef USE_OPENSSL */
	printf("%s\n", _("WARNING - Plugin does not support checking certificates."));
	return STATE_WARNING;
#  endif /* USE_OPENSSL */
}
int show_whitelist_ip(void)
{
  cmd_hdr *cmd;
  get_wl_ip_key_obj *req;
  get_wl_ip_key_obj next;
  get_wl_ip_acl_obj *wl_obj;
  src_dest_acl_obj *acl_obj;
  time_t cur_time;
  double delta_time;
  char buf[1024];
  char *pbuf = buf;
  char src_ip[15];
  char dst_ip[15];
  char acl_id[15];
  int secs_left;
  int i;
  int ctr = 1;
  int buf_len;
  int more = TRUE;
  int is_first = TRUE;
  int ret;

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

  while (more)
  {
    cmd = (cmd_hdr *)pbuf;

    memset(cmd, 0, sizeof(cmd_hdr));
    cmd->type = CMD_REQUEST;
    cmd->cmd_id = CMD_GET_WHITELIST_IP;
    cmd++;

    req = (get_wl_ip_key_obj *)cmd;
    *req = next;
    req++;

    buf_len = sizeof(buf);
    ret = send_req((char *)pbuf, ((char *)req - buf), (char *)buf, &buf_len);
    if (ret)
    {
      fprintf(stdout, "Daemon is down.\n");
      break;
    }

    cmd = (cmd_hdr *)buf;
    if ((cmd->type != CMD_RESPONSE) || (cmd->cmd_id != CMD_GET_WHITELIST_IP))
    {
      fprintf(stdout, " Unexpected response. Skipping.\n");
      break;
    }

    cmd++;
    wl_obj = (get_wl_ip_acl_obj *)cmd;

    if (is_first)
    {
      fprintf(stdout, "Whitelisted Source-Destination IP Pair\n");
      fprintf(stdout, "======================================\n");
      fprintf(stdout, "ID  SourceIP   DestinationIP   Seconds Left  Age\n\n");

      if (!wl_obj->n_acl)
      {
        fprintf(stdout, " No whitelisted source-destination IPs.\n");
        break;
      }

      is_first = FALSE;
    }

    if (!wl_obj->n_acl)
    {
      break;
    }

    cur_time = time(NULL);

    acl_obj = (src_dest_acl_obj *)(wl_obj + 1);
    for (i = 0; i < wl_obj->n_acl; i++, acl_obj++, ctr++)
    {
      snprintf(src_ip, sizeof(src_ip), "%d.%d.%d.%d",
               (acl_obj->src >> 24) & 0xFF,
               (acl_obj->src >> 16) & 0xFF,
               (acl_obj->src >> 8) & 0xFF,
               acl_obj->src & 0xFF);

      snprintf(dst_ip, sizeof(dst_ip), "%d.%d.%d.%d",
               (acl_obj->dst >> 24) & 0xFF,
               (acl_obj->dst >> 16) & 0xFF,
               (acl_obj->dst >> 8) & 0xFF,
               acl_obj->dst & 0xFF);

      snprintf(acl_id, sizeof(acl_id), "[%d]", ctr);

      delta_time = difftime(cur_time, (time_t)acl_obj->created_at);
      secs_left = acl_obj->age - (int)delta_time;

      fprintf(stdout, "%-5s %-16s %-16s %-5d %lu\n",
              acl_id, src_ip, dst_ip, secs_left, acl_obj->age);

      next.src = acl_obj->src;
      next.dst = acl_obj->dst;
    }

    // more = FALSE;
  }

  fprintf(stdout, "\n");

  ret = RET_OK;

  return(ret);
}
Esempio n. 10
0
void TrackProgress::ReportState(char *my_state){
      time(&analysis_current_time);
      fprintf(stdout, "\n%s: Elapsed: %.1lf minutes\n\n", my_state, difftime(analysis_current_time, analysis_start_time) / 60);
      fprintf(fpLog, "%s = %.1lf minutes\n", my_state, difftime(analysis_current_time, analysis_start_time) / 60);
      fflush(NULL);
}
Esempio n. 11
0
double seconds_since_last_use(void)
{
  return difftime(time(NULL), iqlast);
}
Esempio n. 12
0
/* Thread: scan */
static void
bulk_scan(int flags)
{
  cfg_t *lib;
  int ndirs;
  char *path;
  char *deref;
  time_t start;
  time_t end;
  int parent_id;
  int i;

  // Set global flag to avoid queued scan requests
  scanning = 1;

  start = time(NULL);

  playlists = NULL;
  dirstack = NULL;

  lib = cfg_getsec(cfg, "library");

  ndirs = cfg_size(lib, "directories");
  for (i = 0; i < ndirs; i++)
    {
      path = cfg_getnstr(lib, "directories", i);

      parent_id = process_parent_directories(path);

      deref = m_realpath(path);
      if (!deref)
	{
	  DPRINTF(E_LOG, L_SCAN, "Skipping library directory %s, could not dereference: %s\n", path, strerror(errno));

	  /* Assume dir is mistakenly not mounted, so just disable everything and update timestamps */
	  db_file_disable_bymatch(path, "", 0);
	  db_pl_disable_bymatch(path, "", 0);
	  db_directory_disable_bymatch(path, "", 0);

	  db_file_ping_bymatch(path, 1);
	  db_pl_ping_bymatch(path, 1);
	  db_directory_ping_bymatch(path);

	  continue;
	}

      counter = 0;
      db_transaction_begin();

      process_directories(deref, parent_id, flags);
      db_transaction_end();

      free(deref);

      if (scan_exit)
	return;
    }

  if (!(flags & F_SCAN_FAST) && playlists)
    process_deferred_playlists();

  if (scan_exit)
    return;

  if (dirstack)
    DPRINTF(E_LOG, L_SCAN, "WARNING: unhandled leftover directories\n");

  end = time(NULL);

  if (flags & F_SCAN_FAST)
    {
      DPRINTF(E_LOG, L_SCAN, "Bulk library scan completed in %.f sec (with file scan disabled)\n", difftime(end, start));
    }
  else
    {
      /* Protect spotify from the imminent purge if rescanning */
      db_transaction_begin();
      db_file_ping_bymatch("spotify:", 0);
      db_pl_ping_bymatch("spotify:", 0);
      db_transaction_end();

      DPRINTF(E_DBG, L_SCAN, "Purging old database content\n");
      db_purge_cruft(start);
      db_groups_cleanup();
      db_queue_cleanup();

      cache_artwork_purge_cruft(start);

      DPRINTF(E_LOG, L_SCAN, "Bulk library scan completed in %.f sec\n", difftime(end, start));

      DPRINTF(E_DBG, L_SCAN, "Running post library scan jobs\n");
      db_hook_post_scan();
    }

  // Set scan in progress flag to FALSE
  scanning = 0;
}
Esempio n. 13
0
//int main (int argc, char * const argv[]) {
int main() {
	time_t startTime = time(0);
	time_t currentTime;
	unsigned long long sec;
	time_t treePairAverage = 0;

#ifndef MACOSX
	locale::global(locale("en_US.UTF-8"));
#endif //#ifdef MACOSX
	
	/*	chudInitialize();
	chudMarkPID(getpid(),1);
	chudAcquireRemoteAccess();
	chudStartRemotePerfMonitor("testthetester");*/
		
	Tree::binariseMode = false;
	wifstream input;
	wcout << "DATA_SET: " << DATA_SET << endl;
	//HomeCenter data
	if (DATA_SET == "HomeCentre") {
		NonTerminal::idBase.reset(500);
		Tree::pairedMode = true;
		input.open("/Users/ventzi/Desktop/курсове - университет/ATTEMPT/data/HomeCentre/new_manual.txt");
//		input.open("/Users/ventzi/Desktop/курсове - университет/ATTEMPT/data/HomeCentre/en-fr HomeCenter data.txt");
		//English-Spanish data
	} else if (DATA_SET == "en-sp") {
		Tree::pairedMode = false;
		input.open("/Users/ventzi/Desktop/курсове - университет/ATTEMPT/data/en-sp/pairs.txt");
		//English-German data
	} else if (DATA_SET == "en-de") {
		Tree::pairedMode = false;
		input.open("/Users/ventzi/Desktop/курсове - университет/ATTEMPT/data/en-de/10k/pairs.txt");
		//German News data
	} else if (DATA_SET == "de-news") {
		Tree::pairedMode = false;
		input.open("/Users/ventzi/Desktop/курсове - университет/ATTEMPT/data/de-news/pairs.txt");
	} else {
		exit(15);
	}
	
	//	exit(66);
	
	if (input.fail()) {
		wcout << "!!!Cannot open the pairs file!!!" << endl;
		exit(1);
	}
	
	TreePair treePair;
	int counter = 1;
	
	TreePair::linked = true;
	
	currentTime = time(0);
	
//	int pairNo = 1; //118
//	vector<TreePair> pairs;
	while (!input.eof()) {
		input >> treePair;
		if (!TreePair::error) {
//			pairs.push_back(treePair);
//			wcout << "size of treePair: " << sizeof(treePair) << endl;
//			exit(0);
			++counter;
			//			if (counter <= pairNo) continue;
//			wcout << "TreePair №" << counter - 1 << ":" << endl;
			//			treePair.printXML();
			//			wcout << treePair;
			//			wcout << ".";
//			wcout << endl;
			treePair.removeExtraNodes();
//			treePair.printTaggedSentences();
			treePair.printSentences();
//			treePair.freezeLinks();
//			treePair.printBracketed();
//			wcout << endl;
			//			if (counter > pairNo) break;
		} else {
			wcout << "TreePair №" << counter << ": !!!ERROR!!!" << endl;
		}
	}
	wcout << endl;
	
//	wcout << "Size of pairs: " <<  << endl;
	
	input.close();
	
	/*	chudStopRemotePerfMonitor();
	chudReleaseRemoteAccess();*/
	
	currentTime = time(0);
	tm* local = localtime(&currentTime);
	sec = difftime(currentTime, startTime);
	wcout << endl << "Elapsed: " << sec << "sec" << endl;
	wcout << "Finished at " << asctime(local);
	
	return 0;
}
/*
 * Hook into main program.
 */
int main( int argc, char **argv ) {

	/*
	 * Variables used for time and clock
	 */
	time_t startTime, endTime;
	clock_t clockTime;

	int numThreads;
	int i, j;
	if( argc == 4 ) {
		epsilon = atof(argv[1]);
		affectRate = atof(argv[2]);
		numThreads = atoi(argv[3]);
	} else {
		printf("Invalid command line arguments. Please supply all parameters in the below format.\n");
		printf("%s [<epsilon> <affect_rate> <num_threads>]\n", argv[0]);
		return -1;
	}

	/*
	 * Declare the pthreads on the heap
	 */
	pthread_t *threads = malloc(sizeof(pthread_t) * numThreads);
	
	/*
	 * Read the data file into the boxes structure 
	 */
	int numGridBoxes, numRows, numCols;
	scanf("%d %d %d", &numGridBoxes, &numRows, &numCols); // header file
	simpleBox *boxes = malloc(sizeof(simpleBox) * numGridBoxes);
	if(getInput(boxes, numGridBoxes) != 0) { // The rest of the data file
		printf("Failed to read checksum on last line.\n");
		return -1;	
	}
 
	/*
	 * Create the grid and transfer the useful information from the boxes into the grid
	 */
	gridBox *grid = malloc(sizeof(gridBox) * numGridBoxes);
	transferToGrid(grid, boxes, numGridBoxes);

    /*
     * Free the memory of all simple boxes
     */
    for( i = 0; i < numGridBoxes; i++ ) {
        for( j = 0; j < 4; j++) {
			if( boxes[i].nei[j].num > 0 ) {
				free(boxes[i].nei[j].ids);
			}
		}
    }
    free(boxes);
    
	/* 
	 * Compute the max/min temps for initial values
	 */
   	double *newTemps = malloc(sizeof(double) * numGridBoxes);
	double maxTemp, minTemp;
	int iter = 0; // number of iterations
	
	/*
	 * Insert the temps in the grid structure with the newTemps array
	 * Grab the max and min temperatures
	 */
	for( i = 0; i < numGridBoxes; i++) {
		newTemps[i] = grid[i].temp;
	}
	getMinMax(newTemps, numGridBoxes, &maxTemp, &minTemp);

	/*
	 * Construct the storage box for all threads
	 * We will be blocking the gridboxes instead of cyclic distribution.
	 * For example: 
	 * 		Thread 1: compute grid boxes [0 to (numGridBoxes / numThreads)]
	 */
	threadStorage *storage = malloc(sizeof(threadStorage) * numThreads);
	{
		int start;
		int spacing = numGridBoxes / numThreads;
		for( i = 0, start = 0; i < numThreads; i++, start += spacing ) {
			storage[i].id = i;
			storage[i].newTemps = &newTemps[start];
			storage[i].grid = &grid[start];
			storage[i].numGridBoxes = numGridBoxes / numThreads;
		}
		// Very last thread must pick up the remainder if numGridBoxes/numThreads is not an even integer
		storage[numThreads - 1].numGridBoxes += numGridBoxes - (spacing * numThreads);
	}

	/*
     * Time to do the math.
     * Compute the AMR Dissipation to convergence
     */
	time(&startTime);
	clockTime = clock();
	while( (maxTemp - minTemp) > (epsilon * maxTemp) ) {
	
		iter++;
	
		/* 
		 * Spawn off all threads
		 */
		for( i = 0; i < numThreads; i++){
			int errno = pthread_create(&threads[i], NULL, threadEntry, &storage[i]);
			if( errno ) {
				fprintf(stdout, "Iteration %5d | Error creating thread %3d| ERROR: %5d\n", iter, i, errno);
			}
		}

		/* 
		 * Join all threads
		 */
		for( i = 0; i < numThreads; i++){
			int errno = pthread_join(threads[i], NULL);
			if( errno ) {
				fprintf(stdout, "Iteration %5d | Error joining thread %3d| ERROR: %5d\n", iter, i, errno);
			}
		}
		
		// Grab the max and min temperatures 
		getMinMax(newTemps, numGridBoxes, &maxTemp, &minTemp);

		// Update the temps in the grid structure with the newTemps array
		for( i = 0; i < numGridBoxes; i++) {
			grid[i].temp = newTemps[i];
		}

	}

	/*
	 * Stop the timers
	 */
	time(&endTime);
	clockTime = clock() - clockTime;

	printf("*********************************************************************\n");
	printf("Num Threads: %3d\n", numThreads);
	printf("dissipation converged in %d iterations,\n", iter);
	printf("\twith max DSV\t= %lf and min DSV\t= %lf\n", maxTemp, minTemp);
	printf("\taffect rate\t= %lf;\tepsilon\t= %lf\n", affectRate, epsilon);
	printf("\n");
	printf("elapsed convergence loop time\t(clock): %lu\n", clockTime);
	printf("elapsed convergence loop time\t (time): %.f\n", difftime(endTime, startTime));
	printf("*********************************************************************\n");

    /*
     * Free the memory of all grid boxes, the temporary 'newTemps' variable, the threads, and the storage box
     */
    for( i = 0; i < numGridBoxes; i++ ) {
		free(grid[i].neiTemps);
		free(grid[i].neiCD);
    }
    free(grid);
	free(newTemps);
	free(threads);
	free(storage);

	return 0;
}
Esempio n. 15
0
static
double
custom_diff(time_t t1, time_t t2)
{
  return difftime(t1, t2);
}
Esempio n. 16
0
static void curses_draw(void)
{
	if (NULL == get_current_node()) {
		first_node();
		first_item();
	}

	row = 0;
	move(0,0);
	
	getmaxyx(stdscr, rows, cols);
	
	if (cols < 80) {
		clear();
		putl("Screen must be at least 80 columns wide");
		refresh();
		return;
	}

	if (c_use_colors)
		attrset(COLOR_PAIR(LAYOUT_STATUSBAR) | layout[LAYOUT_STATUSBAR].attr);
	else
		attrset(A_REVERSE);

	if (get_current_node() && get_current_item()) {
		putl(" %s on %s",
			get_current_item()->i_name, get_current_node()->n_name);
	}

	move(row, COLS - strlen(PACKAGE_STRING) - 1);
	putl("%s", PACKAGE_STRING);
	move(row, 0);
	
	if (c_use_colors)
		attrset(COLOR_PAIR(LAYOUT_DEFAULT) | layout[LAYOUT_DEFAULT].attr);
	else
		attroff(A_REVERSE);
	
	print_content();

	if (quit_mode)
		print_quit();
	else if (print_help) {
		if (help_page == 0)
			draw_help();
		else
			draw_help_2();
	}

	for (; row < rows-2;) {
		move(++row, 0);
		putl("");
	}
	
	row = rows-1;
	move(row, 0);

	if (c_use_colors)
		attrset(COLOR_PAIR(LAYOUT_STATUSBAR) | layout[LAYOUT_STATUSBAR].attr);
	else
		attrset(A_REVERSE);

	if (1) {
		char s[27];
		time_t t = time(0);
		double d;
		int h, m;

		asctime_r(localtime(&t), s);
		s[strlen(s) - 1] = '\0';
		d = difftime(time(0), start_time);

		if (d / 3600) {
			h = (int) d / 3600;
			m = (int) d % 3600;
			m /= 60;
		} else {
			h = 0;
			m = (int) d / 60;
		}
		
		putl(" %s (%dh/%dm)", s, h, m);
		move(row, COLS - strlen("Press ? for help") - 1);
		putl("%s", "Press ? for help");
		move(row, 0);
	}
	
	attrset(0);
	refresh();
}
Esempio n. 17
0
static int		set_clock	(CalcHandle* handle, CalcClock* _clock)
{
	int ret;
	uint8_t buffer[9];
	uint32_t calc_time;

	struct tm ref, cur;
	time_t r, c, now;

	time(&now);	// retrieve current DST setting
	memcpy(&ref, localtime(&now), sizeof(struct tm));

	ref.tm_year = 1997 - 1900;
	ref.tm_mon = 0;
	ref.tm_yday = 0;
	ref.tm_mday = 1;
	ref.tm_wday = 3;
	ref.tm_hour = 0;
	ref.tm_min = 0;
	ref.tm_sec = 0;
	//ref.tm_isdst = 1;
	r = mktime(&ref);
	//printf("%s\n", asctime(&ref));

	cur.tm_year = _clock->year - 1900;
	cur.tm_mon = _clock->month - 1;
	cur.tm_mday = _clock->day;
	cur.tm_hour = _clock->hours;
	cur.tm_min = _clock->minutes;
	cur.tm_sec = _clock->seconds;
	cur.tm_isdst = 1;
	c = mktime(&cur);
	//printf("%s\n", asctime(&cur));

	calc_time = (uint32_t)difftime(c, r);

	buffer[0] = 0;
	buffer[1] = 0;
	buffer[2] = MSB(MSW(calc_time));
	buffer[3] = LSB(MSW(calc_time));
	buffer[4] = MSB(LSW(calc_time));
	buffer[5] = LSB(LSW(calc_time));
	buffer[6] = _clock->date_format;
	buffer[7] = _clock->time_format;
	buffer[8] = 0xff;

	ticalcs_strlcpy(handle->updat->text, _("Setting clock..."), sizeof(handle->updat->text));
	ticalcs_update_label(handle);

	ret = SEND_RTS(handle, 13, TI73_CLK, "\0x08\0\0\0\0\0\0\0", 0x00, 0x00);
	if (!ret)
	{
		ret = RECV_ACK(handle, NULL);
		if (!ret)
		{
			ret = RECV_CTS(handle, 13);
			if (!ret)
			{
				ret = SEND_ACK(handle);
				if (!ret)
				{
					ret = SEND_XDP(handle, 9, buffer);
					if (!ret)
					{
						ret = RECV_ACK(handle, NULL);
						if (!ret)
						{
							ret = SEND_EOT(handle);
						}
					}
				}
			}
		}
	}

	return ret;
}
Esempio n. 18
0
/** Drain and close the socket
 * @param sd        socket to close
 * @param l         logger
 * @return          -1: socket to close is invalid
 *                  -1: some kind of error occured (!WIN32)
 *                  SOCKET_ERROR: some kind of error occured  (WIN32)
 *                  0: success
 * @remark          Does not change errno
 */
int jk_shutdown_socket(jk_sock_t sd, jk_logger_t *l)
{
    char dummy[512];
    char buf[DUMP_SINFO_BUF_SZ];
    char *sb = NULL;
    int rc = 0;
    size_t rd = 0;
    size_t rp = 0;
    int save_errno;
    int timeout = MS_TO_LINGER;
    time_t start = time(NULL);

    JK_TRACE_ENTER(l);

    if (!IS_VALID_SOCKET(sd)) {
        JK_TRACE_EXIT(l);
        return -1;
    }

    save_errno = errno;
    if (JK_IS_DEBUG_LEVEL(l)) {
        sb = jk_dump_sinfo(sd, buf, sizeof(buf));
        jk_log(l, JK_LOG_DEBUG, "About to shutdown socket %d [%s]",
               sd, sb);
    }
    /* Shut down the socket for write, which will send a FIN
     * to the peer.
     */
    if (shutdown(sd, SHUT_WR)) {
        rc = jk_close_socket(sd, l);
        if (JK_IS_DEBUG_LEVEL(l))
            jk_log(l, JK_LOG_DEBUG,
                   "Failed sending SHUT_WR for socket %d [%s]",
                   sd, sb);
        errno = save_errno;
        JK_TRACE_EXIT(l);
        return rc;
    }

    do {
        rp = 0;
        if (jk_is_input_event(sd, timeout, l)) {
            /* Do a restartable read on the socket
             * draining out all the data currently in the socket buffer.
             */
            int num = 0;
            do {
                num++;
#if defined(WIN32) || (defined(NETWARE) && defined(__NOVELL_LIBC__))
                rc = recv(sd, &dummy[0], sizeof(dummy), 0);
                if (JK_IS_SOCKET_ERROR(rc))
                    JK_GET_SOCKET_ERRNO();
#else
                rc = read(sd, &dummy[0], sizeof(dummy));
#endif
                if (rc > 0)
                    rp += rc;
            } while (JK_IS_SOCKET_ERROR(rc) && (errno == EINTR || errno == EAGAIN) && num < MAX_READ_RETRY);

            if (rc < 0) {
                /* Read failed.
                 * Bail out from the loop.
                 */
                break;
            }
        }
        else {
            /* Error or timeout (reason is logged within jk_is_input_event)
             * Exit the drain loop
             */
            break;
        }
        rd += rp;
        if (rp < sizeof(dummy)) {
            if (timeout > MS_TO_LINGER_LAST) {
                /* Try one last time with a short timeout
                */
                timeout = MS_TO_LINGER_LAST;
                continue;
            }
            /* We have read less then size of buffer
             * It's a good chance there will be no more data
             * to read.
             */
            if ((rc = sononblock(sd))) {
                rc = jk_close_socket(sd, l);
                if (JK_IS_DEBUG_LEVEL(l))
                    jk_log(l, JK_LOG_DEBUG,
                           "error setting socket %d [%s] to nonblocking",
                           sd, sb);
                errno = save_errno;
                JK_TRACE_EXIT(l);
                return rc;
            }
            if (JK_IS_DEBUG_LEVEL(l))
                jk_log(l, JK_LOG_DEBUG,
                       "shutting down the read side of socket %d [%s]",
                       sd, sb);
            shutdown(sd, SHUT_RD);
            break;
        }
        timeout = MS_TO_LINGER;
    } while ((rd < MAX_LINGER_BYTES) && (difftime(time(NULL), start) < MAX_SECS_TO_LINGER));

    rc = jk_close_socket(sd, l);
    if (JK_IS_DEBUG_LEVEL(l))
        jk_log(l, JK_LOG_DEBUG,
               "Shutdown socket %d [%s] and read %d lingering bytes in %d sec.",
               sd, sb, rd, (int)difftime(time(NULL), start));
    errno = save_errno;
    JK_TRACE_EXIT(l);
    return rc;
}
Esempio n. 19
0
int main(int argc, char *argv[])
{
    long portno;
    int i, con_count=1;
    time_t t1,t2,t3,t4;
    char wbuffer[256];
    int connlist[1024*65];
    int result[1024*65];
    struct hostent *server;
    struct sockaddr_in serv_addr;

    INIT();

    if (argc != 4) {
        fprintf(stderr,"Usage:\n\t%s hostname port clients\n\n", argv[0]);
        exit(0);
    }

    con_count = atol(argv[3]);
    if (con_count<1) con_count=1;
    if (con_count>1024*65) con_count=1024*65;

    portno = atol(argv[2]);
    if (portno<1l || portno>0xFFFFl) {
        fprintf(stderr, "ERROR, invalid port\n");
        exit(0);
    }

    server = gethostbyname(argv[1]);
    if (server == NULL) {
        fprintf(stderr, "ERROR, no such host\n");
        exit(0);
    }

    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    memcpy(server->h_addr, &serv_addr.sin_addr.s_addr, server->h_length);
    serv_addr.sin_port = htons((short)portno);

    sprintf(wbuffer, "GET / HTTP/1.0\r\n\r\n");

    t1 = time(0);
    for (i=0;i<con_count;i++) {
        result[i] = connlist[i] = connect_to_server(&serv_addr);
    }
    t2 = time(0);
    for (i=0;i<con_count;i++) {
        if (result[i]>=0) {
            result[i] = send_to_server(connlist[i], wbuffer);
        }
    }
    t3 = time(0);
    for (i=0;i<con_count;i++) {
        if (result[i]>=0) {
            result[i] = read_from_server(connlist[i]);
        }
    }
    t4 = time(0);

    printf("\n");
    printf("conn:  %.0lf\n", difftime(t2,t1));
    printf("write: %.0lf\n", difftime(t3,t2));
    printf("read:  %.0lf\n", difftime(t4,t3));

    for (i=-10;i<1000;i++) {
        int j,cnt=0;
        for(j=0;j<con_count;j++) {
            if (result[j]==i) cnt++;
        }
        if (cnt>0) {
            printf("%5i\t%7i\n", i, cnt);
        }
    }

    return 0;
}
Esempio n. 20
0
int
main (int argc, char** argv)
{
  srand ((unsigned int) time (NULL));
  time_t start, end;
  double dift;

  float resolution = 5.0f;

  pcl::SegmentDifferences<PointT> sd;
    
  pcl::PointCloud<PointT>::Ptr cloudA (new pcl::PointCloud<PointT>); 

  time(&start);
  cloudA->width = 128;
  cloudA->height = 1;
  cloudA->points.resize (cloudA->width * cloudA->height);  
  for (size_t i = 0; i < cloudA->points.size (); ++i)
  {
    cloudA->points[i].x = 64.0f * rand () / (RAND_MAX + 1.0f);
    cloudA->points[i].y = 64.0f * rand () / (RAND_MAX + 1.0f);
    cloudA->points[i].z = 64.0f * rand () / (RAND_MAX + 1.0f);
	cloudA->points[i].intensity = rand () / 255 + 1.0f;
  }
  time(&end);

  dift = difftime (end,start);
  std::cout<<"It took "<<dift<<" secs to read in the first point cloud"<<std::endl;
  
  pcl::PointCloud<PointT>::Ptr cloudB (new pcl::PointCloud<PointT>);

  time(&start);
  cloudB->width = 128;
  cloudB->height = 1;
  cloudB->points.resize (cloudB->width * cloudB->height);
  for (size_t i = 0; i < cloudB->points.size (); ++i)
  {
    cloudB->points[i].x = 64.0f * rand () / (RAND_MAX + 1.0f);
    cloudB->points[i].y = 64.0f * rand () / (RAND_MAX + 1.0f);
    cloudB->points[i].z = 64.0f * rand () / (RAND_MAX + 1.0f);
	cloudB->points[i].intensity = rand () / 255 + 1.0f;
  }
  time(&end);

  dift = difftime (end,start);
  std::cout<<"It took "<<dift<<" secs to read in the second point cloud"<<std::endl;
 

  pcl::PointCloud<PointT> cloudC;
  cloudC.width = 0;
  cloudC.height = 0;
  cloudC.points.resize (cloudC.width * cloudC.height);

  pcl::search::KdTree<PointT>::Ptr kdtree(new pcl::search::KdTree<PointT>);
  kdtree->setInputCloud(cloudB);
  sd.setDistanceThreshold (resolution);
  sd.setInputCloud (cloudA);
  sd.setTargetCloud (cloudB);
  sd.setSearchMethod (kdtree);  
  sd.segmentInt (cloudC);

  std::cout<<"The points in cloudC are "<<std::endl;
  for (size_t i = 0; i < cloudC.points.size (); ++i)
  {
	std::cout<<cloudC.points[i].x<<" "<<cloudC.points[i].y<<" "<<cloudC.points[i].z<<" "<<cloudC.points[i].intensity<<std::endl;
  }
  system("pause");
}
Esempio n. 21
0
//**********************************************************************
//**********************************************************************
int rewiring_Cbar_annealing(GRAPH G,double B,double increment,double accmin,int rewires,gsl_rng* randgsl){
	
	
	double Caim = G.Ccoef;
    
 /***********************************************************************
	 we create a random network with the same degree sequence 
 ************************************************************************/
	
	rewiring_Pk(G,rewires,randgsl);
    
    double C  = clustering_coeff(G);
    
    double Cnew = C;
    
	printf("Caim %f Cinitial %f\n",Caim,C);
 /***********************************************************************
	       we do the rewiring preserving the C(k)
 ************************************************************************/	
	
	int s1,s2,r1,r2,pos_r,pos_s;						    /// rewiring variables that will store the proposed rewiring
	
	double p,AH;
	int accepted=0,rewirestemp=0,pirem=0;					/// during the proces we count how many proposals rewirings are with AH>0, AH<o and AH=0
	double averAH = 0,averAHneg = 0,averAHpos = 0,oldacc=0;
	int numAH0 = 0,numAHneg = 0,numAHpos = 0;
		
	double H = fabs(C - Caim);                              /// initial energy
	
		
	/******** we start the rewiring *************/
	
	printf("Annealed rewiring fixing the clustering coefficient...\n");fflush(stdout);
	
	time_t start,end;										/// we will measure the time
	double dif;
	time (&start);
	
	int i;	
	for(i=1; oldacc>accmin || i<rewires*G.E+2 ;++i){
		
					
		while(!choose_2_edges_random(G,&pos_r,&pos_s,randgsl)){} /// we try to find two edges avoiding selfedges and multipledges
		
		r1 = G.edge[pos_r].s;								/// the nodes are
		r2 = G.edge[pos_r].d; 
		
		s1 = G.edge[pos_s].s;
		s2 = G.edge[pos_s].d;
		
		AH = calc_AH_Cbar(G,s1,s2,r1,r2,C,&Cnew,Caim);	    /// we calculate the increment of energy that would cause the rewiring
		
		averAH = averAH + fabs(AH);							///we also counbt the average AH of the proposals
		
		if(AH < 0.) {										/// we count how many proposals have AH > 0
			
			numAHneg++;
			averAHneg = averAHneg + AH;
		}
		else if (AH > 0.) {									/// we count how many proposals have AH < 0
			
			numAHpos++;
			averAHpos = averAHpos + AH;
			
		}
		else numAH0++;										/// we count how many proposals have AH = 0
		
		p =  gsl_rng_uniform(randgsl);						/// we throw a random number (0,1)
		
		/********** IF we acccept **************/
		
		if( p < exp(-B*AH) ){						
			
			
			swap_edges(G,s1,s2,r1,r2);					    /// we make the proposed rewired
			
			G.edge[pos_r].d = s2;							/// we modify the edge vector
			G.edge[pos_s].d = r2;
			
			C = Cnew;
			
			if(fabs(AH)>0.)	accepted++;						/// we coubt how many changes we accept
			
			H = H + AH;
		}
		
		/********** IF we reject **************/
		
		else {								
			
			Cnew = C;
		}
		
		rewirestemp++;
		
		/********** we reduce the temperature and we check the acceptance **************/
		
		if(rewirestemp > rewires*G.E ) {	///we try to find the appropiate temperature in order to have the desire acceptation
			
			printf("acceptance rate = %f "                ,(double)accepted/(numAHneg+numAHpos));				/// the acceptance
			//printf("AH = %f "                 ,averAH/(numAHneg+numAHpos));							/// the average energy of the proposed swaps
			//printf("numAHneg = %f AHneg = %e ",(double)numAHneg/rewirestemp,averAHneg/numAHneg);	/// the proportion of negative energy swaps and the average
			//printf("numAHpos = %f AHpos = %e ",(double)numAHpos/rewirestemp,averAHpos/numAHpos);	/// the proportion of positive energy swaps and the average
			//printf("numAH0=%f "               ,(double)numAH0/rewirestemp);							/// the proportion of proposals that do not change the energy
			printf("Beta=%e Energy=%e\n"              ,B,H);												/// the temperature and the energy
			fflush(stdout);
			
			if( ((double)accepted/(numAHneg+numAHpos)) > oldacc && i > rewires*G.E + 2 ) pirem++;	/// in case we havethe acceptance has increased 10 times the rewiring proces
			if(pirem>30) break;
			
			oldacc		= ((double)accepted/(numAHneg+numAHpos));								/// we save the old acceptance in order to compare with the next one
			accepted    = 0;												/// we put to zero all the acceptance counters
			rewirestemp = 0;
			averAH      = 0; numAHneg = 0;averAHneg = 0;
			numAH0      = 0; numAHpos = 0;averAHpos = 0;
			
			B = B*increment;												/// we reduce the temperature
			
		}
		
					
	}
	
      

	time (&end);											///we count the rewiring time and take conclusions
	dif = difftime (end,start);
	printf ("You rewired the entire network %.2f times with %.2lf seconds.\n",(double)i/G.E, dif );
	printf("Cfinal %f\n",C);
    
 /***********************************************************************
		 we free the memory
 ************************************************************************/
	

	
	return 0;
	
}
Esempio n. 22
0
int main(int argc, char **argv){

	//joystick stick;
	socketpair(AF_UNIX, SOCK_STREAM, 0, sv);


	if(fork()){
		printf("Read Thread Alive\n");
		ros::init(argc, argv, "read_byte_client");

		ros::NodeHandle r;
		ros::ServiceClient rclient = r.serviceClient<rxtxserver::Read>("read_byte");
		rxtxserver::Read data;

		FILE * intercomm = fopen("intercomm", "w");

		while(1){
			printf("Read Client Attempting Read");
			if(rclient.call(data)){
				fputc(data.response.outData, intercomm);
				fflush(intercomm);
			}
			usleep(1000);
		}
		return 1;

	}
	else{
		printf("Write Thread Alive\n");

		ros::init(argc, argv, "send_byte_client");
		ros::NodeHandle n;
		ros::ServiceClient client = n.serviceClient<rxtxserver::Byte>("send_byte");

		FILE * intercomm2 = fopen("intercomm", "r");


		time_t start,now;


		char string[11];
		string[0] = ' ';
		string[1] = '0';
		string[2] = 'a';
		string[9] = 's';
		string[10] = 0;

		//int i;
		char buf;



		while(1){
			/*
			   ros::spinOnce();
			   for(i = 3; i < 8; i ++){
			   string[i] = char(stick.axes[i-3]);
			   }
			   string[8] = 20;
			   for(i = 0; i < 11; i ++){
			   if(stick.button[i]){
			   string[8] = i;
			   }
			   }
			   if(string[8] == 0){
			   string[8] = 20;
			   }
			 */
			/*
			   sendstring(string);

			   for(i = 0;i<10;i ++){
			   usleep(4000);

			   if(rclient.call(data)){
			   printf("%c", data.response.outData);
			   }

			   }
			 */
			printf("Write Thread Sending Packet\n");
			sendstring(string, &client);
			time(&start);
			do{
				usleep(1000);
				printf("checking data\n");
				if(fscanf(intercomm2, "%c", buf) == 1){
					printf("%c\n", buf);
				}
				time(&now);
			}while(difftime(now, start) < 0.04);
		}	
		printf("I'm Stopping for some reason\n");
		return 1;
	}
}
Esempio n. 23
0
/* While we're working:
	 * compute better solutions for T seconds
	 * send my fit back to the master process.
	 * get a number back. if it's my rank, broadcast my s array to everyone!
*/
void driver(int rank, int np, data_t D, int n, int k, double p, double tol, long sec, long maxsec)
{
    srand(time(NULL) + rank);

    int s[n];
    gen_starting_set(n, k, s);

    time_t start = time(0), fullstart = start;
    double fit = 0, oldfit = 0;

    int run = 0, stop = 0;

    double *fits = NULL;
    if (rank == 0)
        fits = (double *) malloc(sizeof(double) * np);

    do {

        start = time(0);

        do {
            int u, v;

            fit = NEXT_STATE(D, n, s, k, p, &u, &v, run);

            if (u >= 0)
                s[u] = 0;
            if (v >= 0)
                s[v] = 1;
        } while(difftime(time(0), start) < sec);

        //printf("Run %d, rank %d, fit %g\n", run, rank, fit);

        MPI_Gather(&fit, 1, MPI_DOUBLE, fits, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
        int new_rank = 0;

        /* Master process: find best fit. */
        if (rank == 0) {
            double max = 0;
            for (int i = 0; i < np; i++) {
                printf("Run %d, rank %d, fit %g\n", run, i, fits[i]);
                if (fits[i] > max) {
                    max = fits[i];
                    new_rank = i;
                }
            }
            if (max - oldfit < tol || (difftime(time(0), fullstart) > maxsec)) {
                stop = 1;
            }
            oldfit = max;
        }

        MPI_Bcast(&new_rank, 1, MPI_INT, 0, MPI_COMM_WORLD);

        /* update s, or send it... */
        MPI_Bcast(s, n, MPI_INT, new_rank, MPI_COMM_WORLD);

        MPI_Barrier(MPI_COMM_WORLD);

        if (rank == new_rank) {
            printf("Best fit: %f (rank %d)\n", fit, new_rank);
            print_s(s, n);
        }

        run++;

        MPI_Bcast(&stop, 1, MPI_INT, 0, MPI_COMM_WORLD);
    } while(!stop);
}
Esempio n. 24
0
void peer_main()
{
	// initialize the tables
	tracker_conn = -1;
	fileTable_Initialize();
	peerpeerTable_Initialize();

	// initialize the mutex
	peer_file_table_mutex	= (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
	peer_peer_table_mutex	= (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
	pthread_mutex_init(peer_file_table_mutex, NULL);
	pthread_mutex_init(peer_peer_table_mutex, NULL);

	//register peer_stop
	signal(SIGINT,peer_stop);

	myIP = my_ip();
	printf("%s Local ip address is %s\n", peer_trace, myIP);

	// try to connect to the tracker
	tracker_conn = connectToTracker();
	if (-1 == tracker_conn) {
		printf("%s Can't connect to tracker", peer_trace);
		return;
	}
	printf("%s Connection to the tracker established.\n", peer_trace);

	ptp_peer_t pkt;
	p2T_pkt_set(&pkt, 0, NULL, REGISTER, NULL, myIP, PEER_PORT, 0, NULL);

	if (sendpkt(tracker_conn, &pkt) < 0) {
		printf("%s REGISTER sending failed!\n", peer_trace);
		peer_stop();
		return;
	}

	// create the alive thread
	pthread_t alive_thread;
	pthread_create(&alive_thread, NULL, Alive, NULL);
	printf("%s Alive thread created.\n", peer_trace);

	// create a P2P Listen thread
	pthread_t p2p_listen_thread;
	pthread_create(&p2p_listen_thread, NULL, P2PListen, NULL);
	printf("%s p2p listen thread created.\n", peer_trace);
	
	// create a file monitor thread
	char dir_name[FILE_NAME_LEN];
	printf("%s Please input the directory which you would like to monitor:", peer_trace);
	scanf("%s", dir_name);

	// create a loval file directory to monitor
	mkdir(dir_name, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
	chdir(dir_name);
	
	DIR *dir = opendir(".");
	if (dir == NULL) {
		printf("%s The directory which you input is invalid.\n", peer_trace);
		peer_stop();
		return;
	}
        struct dirent *entry;
	pthread_mutex_lock(peer_file_table_mutex);
	while ((entry = readdir(dir)) != NULL) {
		if (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0) {
			continue;
		}
		filenode tmp;
		memset(&tmp, 0, sizeof(filenode));
		strcpy(tmp.filename, entry->d_name);
		tmp.filesize = getFileSize(tmp.filename);
		if (tmp.filesize < 0) {
			continue;
		}
		tmp.timestamp = 0;
		strcpy(tmp.peerIP, myIP);
		fileTable_Add(&tmp, myIP);
	}
	pthread_mutex_unlock(peer_file_table_mutex);
	
	pthread_t file_monitor_thread;
	pthread_create(&file_monitor_thread, NULL, FileMonitor, (void *) ".");
	printf("%s file monitor thread created.\n", peer_trace);
	

//	int setup = 0;


	filenode *global_table;
	for (;;) {
		if (fileTable_Receive(tracker_conn, &global_table) < 0) {
			printf("%s Connection to the tracker is lost. Exiting...\n", peer_trace);
			break;
		}
		printf("%s Received a file table from the tracker:\n", peer_trace);
		fileTable_Print(global_table);
		pthread_mutex_lock(peer_file_table_mutex);

		// based on the global file table, update the local file table
		filenode *cur = global_table;
		while (cur != NULL) {
			if (cur != fileTable_Exist(global_table, cur->filename, NULL)) {
				// this file has been processed before
				cur = cur->next;
				continue;
			}

			filenode *tmp = fileTable_Exist(file_table, cur->filename, NULL);

			if (tmp == NULL) {
				// if our local file table doesn't have this file, should we add it?
				if (fileTable_Exist(global_table, cur->filename, myIP) != NULL) {
					// if this ip used to have the file in the global table, that means we just deleted locally, but the tracker hasn't updated it yet
					// thus we should not add this file, cause the delete action is the latest one
					cur = cur->next;
					continue;
				}
				else {
					// if this ip never has this file, we should add it
					fileTable_Add(cur, "");
					Download(cur->filename, cur->filesize, global_table);
				}
			}

			// if out local file table has this file, should we update it?
			else {
				// if this file is newly created but hasn't been marked with a timestamp from the tracker
				if (tmp->timestamp == 0) {
//					filenode *p = fileTable_Exist(global_table, cur->filename, myIP);
//					if (p != NULL && p->timestamp == fileTable_latest(global_table, cur->filename)) {
//						// update the timestamp given from the tracker
						tmp->timestamp = cur->timestamp;
//					}
//					else {
//						// some peer created this new file with the same name first or updated it first
//						// then we shuold change our name
//						strcat(strcat(tmp->name, " from "), myIP);
//					}
				}
				else {
					if (difftime(tmp->timestamp, cur->timestamp) >= 0) {
						// this file is the latest one, do nothing
						cur = cur->next;
						continue;
					}
					else {
						// not the latest one
						// need to update
						//remove(cur->filename);
						//fileTable_Add(cur, myIP);
						tmp->filesize = cur->filesize;
						tmp->timestamp = cur->timestamp;
						memset(tmp->peerIP, 0, IP_LEN);
						Download(cur->filename, cur->filesize, global_table);
					}
				}
			}
			cur = cur->next;
		}

//		if (setup > 0) {
//		//traverse the local file table to see if there's anything need to be deleted
			cur = file_table;
			while (cur != NULL) {
				if (fileTable_Exist(global_table, cur->filename, NULL) == NULL/* && cur->timestamp != 0*/) {
					// the global table doesn't have this file and the timestamp used to be assigned by the tracker
					remove(cur->filename);
					fileTable_Delete(cur->filename, myIP);
					// what if we can't delete this file
				}
				cur = cur->next;
			}
//		}
//		setup++;
		
		printf("%s Updated local file table:\n", peer_trace);
		fileTable_Print(file_table);
		fileTable_Destroy(global_table);
		pthread_mutex_unlock(peer_file_table_mutex);
	}

	peer_stop();
}
Esempio n. 25
0
int main()
{
    int i, j;
    long k;
    char buffer[] = {'0', '1','2','3','4','5','6','7','8','9'};

    time_t t1, t2;

    clrscr();

    time (&t1);

    for (i = 0; i < 10; i++)
	printf("%c", buffer[i]);
    puts("");

    for (j = 0; j < 10; j++)
    {
	RotateBufRight(buffer, &buffer[10], j);
	for (i = 0; i < 10; i++)
	    printf("%c", buffer[i]);
	puts("");
    }

    
    time(&t2);
    printf("\n%f\n", difftime(t2, t1));

    getch();puts("\n\n");
    
    clrscr();

    
    for (j = 0; j < 10; j++)
    {
	RotateBufLeft(buffer, &buffer[10], j);
        for (i = 0; i < 10; i++)
            printf("%c", buffer[i]);
        puts("");
    }
  
    puts("\n\n");
  
    SwapBuffer(&buffer[0], &buffer[5], 5);
    for (i = 0; i < 10; i++)
            printf("%c", buffer[i]);
        puts("");
   puts("\n\n");
   
   SwapBuffer(&buffer[0], &buffer[5], 5);
   for (i = 0; i < 10; i++)
            printf("%c", buffer[i]);
        puts("");
        puts("\n\n");
  
   RotateBufLeft(&buffer[0], &buffer[10], 2);

 
   
   SlowSwapBufferParts(&buffer[1],  &buffer[5], &buffer[7], &buffer[9]);
   for (i = 0; i < 10; i++)
            printf("%c", buffer[i]);
        puts("");
      
   SwapBufferParts(&buffer[1],  &buffer[5], &buffer[7], &buffer[9]);
   for (i = 0; i < 10; i++)
            printf("%c", buffer[i]);
        puts("");

    
}
Esempio n. 26
0
void ProgAngularProjectLibrary::createGroupSamplingFiles(void)
{

    //#define DEBUGTIME
#ifdef  DEBUGTIME
    time_t start,end;
    double time_dif;
    time (&start);
#endif

    //load txt file
    mysampling.readSamplingFile(output_file_root,false);
#ifdef  DEBUGTIME

    time (&end);
    time_dif = difftime (end,start);
    start=end;
    printf ("re-read entire sampling file after %.2lf seconds\n", time_dif );
#endif

    StringVector blockList;
    getBlocksInMetaDataFile(fn_groups,blockList);
    FileName fn_temp, fn_exp;
    FileName my_output_file_root;
    MetaData SFBlock;

    fn_exp = FnexperimentalImages.removeBlockName();
    int igrp=1;
    for (StringVector::iterator it= blockList.begin();
         it!=blockList.end(); it++,igrp++)
    {
        my_output_file_root.compose(output_file_root + "_group",igrp,"");
        std::cerr<<"Writing group sampling file "<< my_output_file_root<<std::endl;

        fn_temp.compose(*it,fn_exp);
        SFBlock.read(fn_temp);
        if (SFBlock.size() > 0)//Do we really need this check?
            //I guess so since user may have supplied a particular
            //defocus classification. ROB
        {
            mysampling.fillExpDataProjectionDirectionByLR(fn_temp);//SFBlock@fn_groups
            if(compute_closer_sampling_point_bool)
            {
                //find sampling point closer to experimental point (only 0) and bool
                //and save docfile with this information
                mysampling.findClosestSamplingPoint(fn_temp,my_output_file_root);
            }

            //save saveSamplingFile
            if (compute_neighbors_bool)
            {
                mysampling.computeNeighbors(only_winner);
                mysampling.saveSamplingFile(my_output_file_root,false);
            }
        }
    }
#ifdef  DEBUGTIME
    time (&end);
    time_dif = difftime (end,start);
    start=end;
    printf ("Written all group sampling files after %.2lf seconds\n", time_dif );
#endif


}
Esempio n. 27
0
int _tmain(int argc, _TCHAR* argv[])
{
	time_t start,end;
	start=clock();
//************************************************************
	string readpathname;
	if(argc==1||argc==0){
		string filepath="F:\\xudayong\\Evaluation\\ApplicationPrograms\\";
		readpathname=filepath+EVALUATION_COMPUTE_INFO_FILE_NAME;;
	}
	else if(argc==2){
		char tempstring[1000];
		int i=0;
		while(argv[1][i]!='\0'){
			tempstring[i]=(char)argv[1][i];
			i++;
		}
		tempstring[i]='\0';
		readpathname=(std::string)tempstring;
	}
//************************************************************	
	Evaluation tempeva;
	if(!tempeva.Readinfo(readpathname)){
		//读取配置信息
		return 0;
	}
//	tempeva.GetCellsInRegion();//获得所需计算天线信息
	//int cellsize=(int)tempeva.CellsInRegion.size();//天线个数
	string resultpath1=tempeva.result_path_name+(string)"\\EVA_RESULT";//结果文件夹
	if(_access(resultpath1.c_str(),0)==0)//为真表示文件夹存在,则不做任何处理,如果不存在则新建一个文件夹
	{
		//cout<<"directory exist\n";
	}
	else{
		string delresultpath=(string)"rmdir "+resultpath1+(string)" /q/s";
		_mkdir(resultpath1.c_str());
		if(_mkdir(resultpath1.c_str())==-1){
			system(delresultpath.c_str());
			_mkdir(resultpath1.c_str());
		}
	}
	string result_file_name=resultpath1+(string)"\\cell_eva_compute_"+tempeva.networksort+(string)"_"+tempeva.time;
	string result_file_name1=result_file_name+(string)".csv";
	string result_gridfile_name=resultpath1+(string)"\\grid_eva_compute_"+tempeva.networksort+(string)"_"+tempeva.time;
	string result_gridfile_name1=result_file_name+(string)".csv";
	int i=0;
	char num[64];
	while(_access(result_file_name1.c_str(),0)==0){//如果结果文档存在,则最后的标号加1,这是为了保存以前的计算结果
		sprintf_s(num,"%d",i);
		string result_file_name_new=result_file_name+(string)"_"+(string)num+".csv";
		string result_gridfile_name_new=result_gridfile_name+(string)"_"+(string)num+".csv";
		if(_access(result_file_name_new.c_str(),0)!=0||_access(result_gridfile_name_new.c_str(),0)!=0){
			result_file_name1=result_file_name_new;
			result_gridfile_name1=result_gridfile_name_new;
			break;
		}
		i++;
	}
/************************************************************
	vector<Evaluation> tempcellcompute;
	tempcellcompute.clear();
	tempcellcompute.resize(cellsize);
#pragma  omp parallel for
	for(int i=0;i<cellsize;i++){
	cout<<"************************************************************** i:"<<i<<endl;
		tempcellcompute[i].Readinfo(tempreadinfo);
		tempcellcompute[i].Getcellinfo(tempreadinfo.CellsInRegion[i]);
		tempcellcompute[i].Getcell_coverinfo();
		tempcellcompute[i].Getgrid_info();
		tempcellcompute[i].Grid_Compute();
		tempcellcompute[i].Get_Crossever();
		tempcellcompute[i].Get_Bias();
	}
*/
	if(tempeva.Eval()){
		
		bool r=tempeva.GetRegionKPI();
		if(r==true){
			cout<<"Writing Region Evluation Result File "<<result_file_name1<<endl;
			tempeva.WriteRegionResult(result_file_name1);
			//tempeva.WriteCellsResult(result_file_name1);
			tempeva.WriteGridsInfo(result_gridfile_name1);
			end=clock();
			cout<<"evaluation complete in total "<<difftime(end,start)/1000<<"s.\n";
			return 0;
		}
		else{
			cout<<"Evalution of Region is not complete due to errors"<<endl;
		}
		
	}
	else{
		cout<<"evaluation process error\n";
		return 0;
	}
}
int main(int argc, char **argv) 
{
    int i;
    // init static stuff
    for (i = 0; i < MAXSMPLS; ++i)
        freq[i] = 0;
    for (i = 0; i < PRECMP; ++i)
    {
        prelog[i] = log(i+1);
        presqrt[i] = sqrt(i);
        prelgamma[i] = lgamma(i+1);
    }

    if (argc < 5)
    {
        longhelp(argv[0]);
        return 1;
    }

    int parsepvalues = 0;
    int normalize = 0;
    int smpls = -1, runs = -1;
    int *runtosmpl = 0;
    double *maxent = 0;
    int nmaxent = 0;
    char filesuffix[ROWLEN];
    char smplsfile[ROWLEN];
    char normfile[ROWLEN];
    filesuffix[0] = 0; // empty
    smplsfile[0] = 0;
    normfile[0] = 0;

    static struct option long_options[] =
        {
            {"samples",      required_argument, 0, 's'},
            {"samplefile",   required_argument, 0, 'S'},
            {"maxent",       required_argument, 0, 'm'},
            {"entstep",      required_argument, 0, 'e'},
            {"file",         required_argument, 0, 'F'},            
            {"normalize",    required_argument, 0, 'N'},
            {"minfreq",      required_argument, 0, 'M'},
            {"verbose",      no_argument,       0, 'v'},
            {"help",         no_argument,       0, 'h'},
            {0, 0, 0, 0}
        };
    int option_index = 0;
    int c;
    while ((c = getopt_long(argc, argv, "s:S:m:e:F:N:M:vh", long_options, &option_index)) != -1) 
    {
        switch(c) 
        {
        case 's':
            smpls = atoi_min(optarg, 2, "-s,--samples", argv[0]); 
            break;
        case 'S':
            strncpy(smplsfile, optarg, ROWLEN);
            break;
        case 'm':
            assert(maxent == 0);
            maxent = parse_doubles(optarg, &nmaxent, 0.0, 1.0, "-m,--maxent", argv[0]);
            break;
        case 'e':
            assert(maxent == 0);
            maxent = parse_entropy_steps(optarg, &nmaxent, 0.0, 1.0, "-e,--entstep", argv[0]);
            break;
        case 'F':
            strncpy(filesuffix, optarg, ROWLEN);
            break;
        case 'N':
            normalize = 1;
            strncpy(normfile, optarg, ROWLEN);
            break;
        case 'M':
            minfreq = atoi_min(optarg, 1, "-M,--minfreq", argv[0]); 
            break;
        case 'v':
            verbose = 1; 
            break;
        case 'h':
            longhelp(argv[0]); 
            return 1;
        default:
            myerror("invalid command line argument given!? Please check `%s --help'\n", argv[0]);
            return 1;
            break;
        }
    }

    if (argc != optind)
        fprintf(stderr, "warning: ignoring the last %d arguments\n", argc-optind);

    // sanity checks
    if (filesuffix[0] == 0)
        myerror("the argument -F,--file is mandatory.", argv[0]);
    if (nmaxent < 1)
        myerror("the argument -m,--maxent is mandatory.", argv[0]);
    if (smpls == -1 && strlen(smplsfile) == 0)
        myerror("give either the argument -s,--samples or -S,--samplefile.", argv[0]);
    if (smpls != -1 && strlen(smplsfile))
        myerror("both the arguments -s,--samples and -S,--samplefile cannot be given at the same time.", argv[0]);
    if (smpls != -1 && smpls < 2)
        myerror("the argument -s,--samples must be at least 2.", argv[0]);
    if (nmaxent == 0)
        myerror("the argument -m,--maxent is mandatory.", argv[0]);

    // Parse samples file if needed
    if (smpls == -1)
    {
        assert(strlen(smplsfile));
        runs = parse_samples_file(smplsfile, &runtosmpl, &smpls);
        if (verbose) fprintf(stderr, "sample file: got mapping from %d runs to %d samples\n", runs, smpls);
        if (smpls < 2 || runs < smpls)
            myerror("unable to parse the samples file in the argument -S,--samplefile.", argv[0]);
    }
    else
        runs = smpls;

    if (runs > MAXSMPLS)
    {
        fprintf(stderr, "error: expecting at most %d samples/runs, please increase MAXSMPLS in the source code and recompile\n", MAXSMPLS);
        abort();
    }

    // Parse normalization factors
    double *dsizes = 0;
    if (normalize || normfile[0])
    {
        assert (normalize);
        dsizes = parse_size_file(normfile, smpls);
        assert(dsizes != 0);

        // Compute norm. factors
        assert (smpls < MAXSMPLS);
        for (i = 0; i < smpls; ++i)
        {
            // Iterates over samples to precompute
            assert(dsizes[i] != 0);
            nfactor[i] = (double)1/dsizes[i];

            // Init precomputed values
            prenormlog[i] =    (double *)malloc(PRECMP * sizeof(double));
            prenormsqrt[i] =   (double *)malloc(PRECMP * sizeof(double));
//            prenormlgamma[i] = (double *)malloc(PRECMP * sizeof(double));
            int j;
            for (j = 0; j < PRECMP; ++j)
            {
                // i == sample, j == frequency
                prenormlog[i][j] = log((double)j*nfactor[i] + 1);
                prenormsqrt[i][j] = sqrt((double)j*nfactor[i]);
//                prenormlgamma[i][j] = lgamma((double)j*nfactor[i] + 1); 
            }
        }
        if (verbose) fprintf(stderr, "normalization file %s loaded\n", normfile);
        free(dsizes);
    }

    // Init the matrices
    i = 0;
    int j, nmatrices = nmaxent;
    struct parameters *param = (struct parameters *)malloc(nmatrices * sizeof(struct parameters));
    for (j = 0; j < nmaxent; ++j)
    {
        param[i].maxent = maxent[j];
        param[i].noutput = 0;
        ++i;
    }
    FILE *fileCount = open_output_file(filesuffix, "count");
    FILE *fileLog = open_output_file(filesuffix, "log");
    FILE *fileSqrt = open_output_file(filesuffix, "sqrt");
    FILE *fileLgamma = open_output_file(filesuffix, "lgamma");

    assert(i == nmatrices);
    qsort(param, nmatrices, sizeof(struct parameters), myparamcmp);

    if (verbose)
    {
        fprintf(stderr, "Computing %d matrices for <max_entropy> values:", nmatrices);
        for (i = 0; i < nmatrices; ++i)
            fprintf(stderr, (i == 0 ? " <%f>" : ", <%f>"), param[i].maxent);
        fprintf(stderr, "\n"); 
    }

    // Init matrices
    mymatrix *matrix = (mymatrix *)malloc(nmatrices * smpls * smpls * sizeof(mymatrix));
    for (i = 0; i < nmatrices * smpls * smpls; ++i)
    {
        matrix[i].count = 0;
        matrix[i].log = 0;
        matrix[i].sqrt = 0;
        matrix[i].lgamma = 0;
    }        

    // Init parsing
    time_t wctime = time(NULL);    
    char row[ROWLEN];
    unsigned long rowno = 0;
    while (!feof(stdin))
    {
        if (fgets(row, ROWLEN, stdin) == NULL)
            break;

        char *tmp = row; 
        while (*tmp && *tmp != ' ') ++tmp; // Finds the first ' ',
        assert(*tmp == ' ');
        // Check if we need to parse p-values
        if (rowno == 0)
        {
            char *t = tmp;
            while (*t && *t != '.') ++t;
            if (*t == '.')
                parsepvalues = 1;
            else
                assert(parsepvalues == 0);
        }
        if (parsepvalues)
        {
            //double entropy = atof(tmp++);  // FIXME We need to recompute the entropy if runtosmpl mapping is set
            ++tmp;
            while (*tmp && *tmp != ' ') ++tmp; // Finds the second ' ',
            assert(*tmp == ' ');
        }

        // Parse row
        unsigned uniqueids = parse(tmp, runs, runtosmpl);
        // Retrieve the difference to max. entropy
        double entr = -1;
        if (normalize)
            entr = normalized_entropy(uniqueids, smpls);
        else
            entr = entropy(uniqueids, smpls);

        // Update correct matrix (note: only one matrix needs to be updated, values are accumulated later)
        for (i = nmatrices; i > 0;)
        {
            --i;
            if (entr <= param[i].maxent)
            {
                param[i].noutput ++;
                if (normalize)
                    add_normalized(matrix, smpls, uniqueids, i);
                else
                               add(matrix, smpls, uniqueids, i);
                
                break;
            }
        }
        // Zero the vector
        for (i = 0; i < uniqueids; ++i)
            freq[samples[i]] = 0;
        
        rowno++;
        if (verbose && rowno % 1000000 == 0)
        {
            fprintf(stderr, "Reading row %lu (%.5s...). Time: %.0f s (%.2f hours)\n", rowno, row, difftime(time(NULL), wctime), difftime(time(NULL), wctime) / 3600);
            fprintf(stderr, "noutput values: ");
            int j;
            for (j = 0; j < nmatrices; ++j)
                fprintf(stderr, " %u", param[j].noutput);
            fprintf(stderr, "\n");
        }
    }

    for (i = 0; i < MAXSMPLS; ++i)
        assert(freq[i] == 0);

    // Print output matrices
    for (i = nmatrices; i > 0;)
    {
        --i;
        fprintf(fileCount,  "Matrix for <max_entropy>=<%f> was computed from %u substrings: \n", param[i].maxent, param[i].noutput);
        fprintf(fileLog,    "Matrix for <max_entropy>=<%f> was computed from %u substrings: \n", param[i].maxent, param[i].noutput);
        fprintf(fileSqrt,   "Matrix for <max_entropy>=<%f> was computed from %u substrings: \n", param[i].maxent, param[i].noutput);
        fprintf(fileLgamma, "Matrix for <max_entropy>=<%f> was computed from %u substrings: \n", param[i].maxent, param[i].noutput);
        
        int k;
        for (j = 0; j < smpls; ++j)
        {
            for (k = 0; k < smpls; ++k)
            {
                fprintf(fileCount,  " %u", matrix[OFFSET(i,j,k)].count);
                fprintf(fileLog,    " %f", matrix[OFFSET(i,j,k)].log);
                fprintf(fileSqrt,   " %f", matrix[OFFSET(i,j,k)].sqrt);
                fprintf(fileLgamma, " %f", matrix[OFFSET(i,j,k)].lgamma);
            }
            fprintf(fileCount, "\n");
            fprintf(fileLog, "\n");
            fprintf(fileSqrt, "\n");
            fprintf(fileLgamma, "\n");
        }

        // Accumulate counts from larger diffs
        if (i)
        {
            param[i-1].noutput += param[i].noutput;
            accumulate(matrix, i, i-1, smpls);        
        }
    }

    if (verbose)
    {
        fprintf(stderr, "Number of lines processed: %lu\n", rowno);
        fprintf(stderr, "Wall-clock time: %.0f s (%.2f hours)\n", difftime(time(NULL), wctime), difftime(time(NULL), wctime) / 3600);
    }

    fclose(fileCount);
    fclose(fileLog);
    fclose(fileSqrt);
    fclose(fileLgamma);
    free(param);
    free(maxent);
    free(matrix);
    if (runtosmpl) 
        free(runtosmpl);
    if (normalize)
        for (i = 0; i < smpls; ++i)
        {
            free (prenormlog[i]);
            free (prenormsqrt[i]);
//            free (prenormlgamma[i]);
        }
    return 0;
}
Esempio n. 29
0
int MyProcessDatFileIII(char* DatFileBuffer, int procid, vector<int> AllColumnIDList, vector<vector<int> > ColKeyToAllAlleleByPopList, vector<vector<vector<int> > >& AllAlleleByPopList, vector<std::string>& FullAccessionNameList, vector<std::string>& IndivPerPop, vector<int>& AllAlleles, std::string Rarify)
{
	//declare variables
	std::string foo;
	vector<std::string> foovector;
	std::string OldLocusName;
	std::string CurrLocusName;
	vector<std::string> LocusNames;
	vector<vector<std::string> > ActiveAlleleList;
	vector<std::string> OldAlleles;
	vector<vector<std::string> > TempList2d;
	vector<std::string> FilteredData;
	vector<std::string> ListToFilter;
	std::string IsNewPop = "no";
	vector<std::string>::iterator it;
	
	//initialize important data structures, unsized
	vector<vector<set<int> > > AllAlleleByPopListSet; //structure of this 3D vector is:
	// { { {pop1,loc1 alleles},{pop1,loc2 alleles},...}, { {pop2,loc1 alleles},{pop2,loc2 alleles},...} } }
	// this is the same structure as the vector<vector<vector<int> > > AllAlleleByPopList
	// if Rarify == "yes", AllAlleleByPopList just becomes ByPop3d.  if Rarify == "no", ByPop3d is reduced
	// to unique alleles at each locus using AllAlleleByPopListSet, then converted back into the vector
	// AllAlleleByPopList, which is updated as a reference


	unsigned int i,j,k,l;
	vector<std::string> bufvec;
	std::string NewPopID;
	std::string OldPopID = "init*@#rt4"; //use an unlikely population name for the initialization value

	if (procid == 0) cout << "  Reading data matrix...\n";
	//start the clock
	time_t startm,endm;
	time (&startm);

	//put giant char array buffer into a stream, then delete the buffer to save memory 
	stringstream s(DatFileBuffer);
	strcpy(DatFileBuffer,""); //clear char* 
	
	
	//read buffer into a vector, one line per item
	while (getline(s, foo))//get line from s, put in foo, consecutively
	{
		bufvec.push_back(foo);  
	}
	
	s.str(""); //clear stringstream
	int row = bufvec.size();
		
	//sort vector so that individuals from the same population form consecutive elements
	std::sort(bufvec.begin(), bufvec.end()); //no need to use fancy sort, lexicographic should be fine
		
	//split lines of bufvec into 2d vector
	vector<vector<std::string> > bufvec2d(bufvec.size()); 
	for (i=0;i<bufvec.size();++i) bufvec2d[i] = split(bufvec[i]);
	vector<std::string>().swap(bufvec); //clear bufvec
	
	//stop the clock
	time (&endm);
	double dif = difftime (endm,startm);
	if (procid == 0) 
	{
		if (dif==1) cout << "    " << dif << " second.\n";	
		else cout << "    " << dif << " seconds.\n";
	}
	
	//convert alleles to integer coding to save memory, vector access order 2
	if (procid == 0) 
	{
		cout << "  Recoding data...\n";
		time (&startm);
	}

	vector<vector<int> > bufvec2dint(bufvec2d.size(), vector<int>(bufvec2d[0].size())); //declare and size vector to hold new integer coded alleles
	unsigned int iz = ColKeyToAllAlleleByPopList.size();
	for (unsigned int i=0;i<iz;++i) //go thru each locus
	{
		//get all alleles at the locus
		vector<std::string> AllelesEncountered; //will contain the unique set of alleles at the locus
		unsigned int kz = bufvec2d.size();
		for (unsigned int k=0;k<kz;++k) //go thru all individuals
		{
			unsigned int jz = ColKeyToAllAlleleByPopList[i].size();
			for (unsigned int j=0;j<jz;++j) //get all alleles for an individual at this locus, then move to next indiv
			{
				int ColIndex = ColKeyToAllAlleleByPopList[i][j];
				std::string a = bufvec2d[k][ColIndex];  
				if (a == "9999") bufvec2dint[k][ColIndex] = -9999; //add the missing data value
				else
				{
					int AlleleInt; //the new, integerized, name of the allele
					std::vector<std::string>::iterator itr = std::find(AllelesEncountered.begin(), AllelesEncountered.end(), a);
					if (itr != AllelesEncountered.end()) //the allele has been found before
					{
						AlleleInt = itr - AllelesEncountered.begin(); //convert itr to index, the index is the integerized allele name
						bufvec2dint[k][ColIndex] = AlleleInt; //add the new name
					}
					else // you have a new allele
					{
						AllelesEncountered.push_back(a); //add new allele to list of those encountered
						AlleleInt = AllelesEncountered.size() - 1;  //calculate integerized allele name, starts at 0
						bufvec2dint[k][ColIndex] = AlleleInt;
					}
				}
			}
		}
	}
	
	//stop the clock
	if (procid == 0) 
	{
		time (&endm);
		dif = difftime (endm,startm);
		if (dif==1) cout << "    " << dif << " second.\n";	
		else cout << "    " << dif << " seconds.\n";	
	}

	
	if (procid == 0) cout << "  Building data structures...\n";
	time (&startm);
	
	//simplify bufvec2d by retaining only the first column, with POPID, then swap clear to save memory
	vector<string> PopIDvec;
	for (i=0;i<bufvec2d.size();++i)
		PopIDvec.push_back(bufvec2d[i][0]);
	vector<vector<std::string> >().swap(bufvec2d); //clear bufvec2d

	//break up vector into a 3d vector by population:  { { {pop1ind1elems},{pop1ind2elems},...}, { {pop2ind1elems},{pop2ind2elems},...} }
	vector<vector<vector<int> > > ByPop3d;
	for (i=0;i<bufvec2dint.size();++i)
	{
		//NewPopID = bufvec2d[i][0];  //access string in bufvec2d
		NewPopID = PopIDvec[i];
		IndivPerPop.push_back(NewPopID); //add the pop ID to a list to calc pop sizes later

		if (NewPopID != OldPopID) //then create a new population in ByPop3D
		{
			ByPop3d.resize(ByPop3d.size() + 1);
			
			//add the new population name to the AccessionNameList
			FullAccessionNameList.push_back(NewPopID);
		}
		
		//push row of integer elements on current line, onto last item of ByPop3d, which might be a new population as added just above
		//remember that the first three columns are 0 in bufvec2dint, so will also be 0 in ByPop3d
		ByPop3d[ByPop3d.size()-1].push_back(bufvec2dint[i]);
		
		OldPopID = NewPopID;
	}
	vector<vector<int> >().swap(bufvec2dint); //clear bufvec2dint, the integerized data is in ByPop3d

	//stop the clock
	time (&endm);
	if (procid == 0) 
	{
		dif = difftime (endm,startm);
		if (dif==1) cout << "    " << dif << " second.\n";	
		else cout << "    " << dif << " seconds.\n";	
	}

/*	//print out ByPop3d
	for (i=0;i<ByPop3d.size();++i)
	{
		cout << "Pop" << i << "\n";
		for (j=0;j<ByPop3d[i].size();++j)
		{
			cout << " Ind" << j << "  ";
			for (k=0;k<ByPop3d[i][j].size();++k)
			{
				cout << ByPop3d[i][j][k] << ",";
			}
			cout << "\n";
		}
	
	}
*/

	if (procid == 0) cout << "  Condensing data...\n";
	time (&startm);

	//When Rarify=yes, information on allele frequencies must be retained so all alleles are
	//placed into the AllAlleleByPopList (excluding -9999 missing data).  When Rarify=no, 
	//all alleles are passaged through a set (AllAlleleByPopListSet) so that only unique 
	//alleles end up in AllAlleleByPopList.
	if (Rarify == "yes")
	{
		//resize AllAlleleByPopList
		AllAlleleByPopList.resize(ByPop3d.size());//resize number of populations
		for (i=0;i<AllAlleleByPopList.size();++i)
		{
			AllAlleleByPopList[i].resize(ColKeyToAllAlleleByPopList.size()); //resize number of loci
		}
		
		//calculate size of AllAlleles
		AllAlleles.reserve(row*AllColumnIDList.size());

		//condense alleles by locus in AllAllelesByPopList, within each population
		int AlleleIndex;
		for (i=0;i<ByPop3d.size();++i) //go thru pops
		{
			for (j=0;j<ByPop3d[i].size();++j) //go thru indivs
			{
				for (k=0;k<ColKeyToAllAlleleByPopList.size();++k) //go through each locus
				{
					for (l=0;l<ColKeyToAllAlleleByPopList[k].size();++l) //assign columns to loci
					{
						AlleleIndex = ColKeyToAllAlleleByPopList[k][l];
						int NewAllele = ByPop3d[i][j][AlleleIndex]; //get the allele in the specified column
						AllAlleles.push_back(NewAllele); //add the allele to the list of all alleles, missing data included
						if (NewAllele != -9999) //exclude missing data
							AllAlleleByPopList[i][k].push_back(NewAllele); //add the allele to the set of unique alleles at locus k, pop i	
					}
				}
			}
		}
		
 		//stop the clock on Condensing data...
		time (&endm);
		if (procid == 0) 
		{
			dif = difftime (endm,startm);
			if (dif==1) cout << "    " << dif << " second.\n";	
			else cout << "    " << dif << " seconds.\n";	
		}
	}
	else if (Rarify == "no")
	{
		//resize AllAlleleByPopListSet
		AllAlleleByPopListSet.resize(ByPop3d.size());//resize number of populations
		for (i=0;i<AllAlleleByPopListSet.size();++i)
		{
			AllAlleleByPopListSet[i].resize(ColKeyToAllAlleleByPopList.size()); //resize number of loci
																		   //the index in ColKey is the locus index in AllAllelesByPopList level 2
																		   //the value of ColKey is the index of the allele in ByPop3d level 3
		}
		
		//calculate size of AllAlleles
		AllAlleles.reserve(row*AllColumnIDList.size());

		//condense alleles by locus in AllAllelesByPopListSet, within each population
		int AlleleIndex;
		for (i=0;i<ByPop3d.size();++i) //go thru pops
		{
			for (j=0;j<ByPop3d[i].size();++j) //go thru indivs
			{
				for (k=0;k<ColKeyToAllAlleleByPopList.size();++k) //go through each locus
				{
					for (l=0;l<ColKeyToAllAlleleByPopList[k].size();++l) //assign columns to loci
					{
						AlleleIndex = ColKeyToAllAlleleByPopList[k][l];
						int NewAllele = ByPop3d[i][j][AlleleIndex]; //get the allele in the specified column
						AllAlleles.push_back(NewAllele); //add the allele to the list of all alleles, missing data included
						if (NewAllele != -9999) //exclude missing data
							AllAlleleByPopListSet[i][k].insert(NewAllele); //add the allele to the set of unique alleles at locus k, pop i	
					}
				}
			}
		}
	
		//stop the clock on Condensing data...
		time (&endm);
		if (procid == 0) 
		{
			dif = difftime (endm,startm);
			if (dif==1) cout << "    " << dif << " second.\n";	
			else cout << "    " << dif << " seconds.\n";	
		}
		
		//start the clock on Converting...
		time_t startd,endd;
		if (procid == 0) 
		{
			cout << "  Converting data structures...\n";
			time (&startd);
		}

		//resize AllAlleleByPopList
		AllAlleleByPopList.resize(ByPop3d.size());//resize number of populations
		for (i=0;i<AllAlleleByPopList.size();++i)
		{
			AllAlleleByPopList[i].resize(ColKeyToAllAlleleByPopList.size()); //resize number of loci
		}
		//convert set to vector for further processing
		for (i=0;i<AllAlleleByPopList.size();++i)
		{
			for (j=0;j<AllAlleleByPopList[i].size();++j)
			{
				vector<int> ttvec(AllAlleleByPopListSet[i][j].begin(), AllAlleleByPopListSet[i][j].end()); //use constructor to convert set to vector	
				AllAlleleByPopList[i][j] = ttvec;
			}
		}
		vector<vector<set<int> > >().swap(AllAlleleByPopListSet); //clear variable, no longer needed
	
		//stop the clock on Converting...
		if (procid == 0) 
		{
			time (&endd);
			dif = difftime (endd,startd);
			if (dif==1) cout << "    " << dif << " second.\n";	
			else cout << "    " << dif << " seconds.\n";	
		}
	}
	
	vector<vector<vector<int> > >().swap(ByPop3d); //clear ByPop3d
			
	return 0;
}
Esempio n. 30
0
/*
 * Flush cookies to disk and free all the memory allocated.
 */
static void Cookies_save_and_free()
{
   int i, fd, saved = 0;
   DomainNode *node;
   CookieData_t *cookie;
   time_t now;

#ifndef HAVE_LOCKF
   struct flock lck;
#endif

   if (disabled)
      return;

   now = time(NULL);

   rewind(file_stream);
   fd = fileno(file_stream);
   if (ftruncate(fd, 0) == -1)
      MSG("Cookies: Truncate file stream failed: %s\n", dStrerror(errno));
   fprintf(file_stream, "%s", cookies_txt_header_str);

   /* Iterate cookies per domain, saving and freeing */
   while ((node = dList_nth_data(domains, 0))) {
      for (i = 0; (cookie = dList_nth_data(node->cookies, i)); ++i) {
         if (!cookie->session_only && difftime(cookie->expires_at, now) > 0) {
            int len;
            char buf[LINE_MAXLEN];

            len = snprintf(buf, LINE_MAXLEN, "%s\t%s\t%s\t%s\t%ld\t%s\t%s\n",
                           cookie->domain,
                           cookie->host_only ? "FALSE" : "TRUE",
                           cookie->path,
                           cookie->secure ? "TRUE" : "FALSE",
                           (long) difftime(cookie->expires_at,
                                           cookies_epoch_time),
                           cookie->name,
                           cookie->value);
            if (len < LINE_MAXLEN) {
               fprintf(file_stream, "%s", buf);
               saved++;
            } else {
               MSG("Not saving overly long cookie for %s.\n", cookie->domain);
            }
         }
         Cookies_free_cookie(cookie);
      }
      Cookies_delete_node(node);
   }
   dList_free(domains);
   dList_free(all_cookies);

#ifdef HAVE_LOCKF
   lockf(fd, F_ULOCK, 0);
#else  /* POSIX file lock */
   lck.l_start = 0; /* start at beginning of file */
   lck.l_len = 0;  /* lock entire file */
   lck.l_type = F_UNLCK;
   lck.l_whence = SEEK_SET;  /* absolute offset */

   fcntl(fileno(file_stream), F_SETLKW, &lck);
#endif
   fclose(file_stream);

   MSG("Cookies saved: %d.\n", saved);
}