language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #define M 1000 int a[M][M]; int main(void){ int n,i,j,max,x, y; scanf("%d",&n); for(i = 0; i <n; i++){ for(j = 0; j< n; j++) scanf("%d",&a[i][j]); } max = a[0][0]; x = 1; y = 1; for(i = 0; i < n; i++){ for(j = 0; j < n; j++){ if(max < a[i][j]){ max = a[i][j]; x = i+1; y = j+1; } } } printf("%d %d %d\n",max, x, y); return 0; }
C
#include "pop_ext.h" int32_t StripCR(line) char *line; { char *ptr; if(ptr = strchr(line,'\n')){ *ptr = '\0'; return(1); } else { return(0); } } /* ** read spikes into individual spike arrays rather than ** binning them */ int32_t LoadSpikes(fp,result,clusterid) FILE *fp; Result *result; int32_t clusterid; { uint32_t *sarray; uint32_t timestamp; int32_t count; char **header; char **ReadHeader(); int32_t size; int32_t nspikes; int32_t *binarray; int32_t bin; double sum; double sumsqr; double var; double var1; int32_t i; char *tstring; int32_t convert; /* ** count the number of spikes */ nspikes = 0; fseek(fp,0L,0L); /* rewind spike file */ header = ReadHeader(fp,&size); /* ** compare architectures */ if((GetLocalArchitecture() == GetFileArchitecture(header)) || (GetFileArchitecture(header) == ARCH_UNKNOWN)) { convert = 0; } else { convert = 1; fprintf(stderr,"Converting data from %s to %s architectures.\n", GetFileArchitectureStr(header), GetLocalArchitectureStr()); } /* ** use the input spike file field to match probes */ if((tstring = GetHeaderParameter(header,"Input Spike file:")) != NULL){ result->clustername[clusterid] = (char *)calloc(strlen(tstring) + 1,sizeof(char));; strcpy(result->clustername[clusterid],tstring); /* if(verbose){ fprintf(stderr,"Loading spikes for %s cluster %d\n", result->clustername[clusterid],clusterid); } */ } /* ** compute the total number of spikes in the file from the file length */ fseek(fp,0L,2); nspikes = (ftell(fp) - size)/sizeof(uint32_t); sarray = result->spikearray[clusterid] = (uint32_t *)calloc(nspikes,sizeof(uint32_t)); /* ** allocate the time bin array to be used to compute ** bin variance */ binarray = (int32_t *)calloc(result->ntimebins,sizeof(int32_t)); /* ** make the second pass to fill the spike array */ count = 0; fseek(fp,size,0L); /* rewind spike file */ while(!feof(fp)){ /* scan the entire file */ if(fread(&timestamp,sizeof(uint32_t),1,fp) != 1){ break; } if(convert){ ConvertData(&timestamp,sizeof(uint32_t)); } if(!InRange(result,timestamp)) continue; if(timestamp < result->tstart){ continue; } if(timestamp > result->tend){ break; } if(count >= nspikes){ fprintf(stderr,"ERROR: incongruity in timestamp count\n"); break; } sarray[count] = timestamp; bin = (timestamp - result->tstart)/result->binsize; binarray[bin]++; count++; } /* if(verbose){ fprintf(stderr,"Loaded spikes from %s (%ld)", TimestampToString(sarray[0]),sarray[0]); fprintf(stderr," to %s (%ld)\n", TimestampToString(sarray[count-1]),sarray[count-1]); } */ /* ** compute mean and sd of the binned spike array */ sum = 0; sumsqr = 0; for(i=0;i<result->ntimebins;i++){ if(binarray[i] > 0){ sum += binarray[i]; sumsqr += binarray[i]*binarray[i]; } } result->binmean[clusterid] = sum/result->ntimebins; var1 = (sumsqr*(double)result->ntimebins - sum*sum); var = var1/ ((double)result->ntimebins*(result->ntimebins-1)); result->binsd[clusterid] = sqrt(var); free(binarray); return(count); } LoadAndBinSpikes(fp,result,clusterid) FILE *fp; Result *result; int32_t clusterid; { uint32_t timestamp; float *vector; int32_t bin; int32_t count; int32_t headersize; int32_t convert; char **header; fseek(fp,0L,0L); /* rewind spike file */ header = ReadHeader(fp,&headersize); /* ** compare architectures */ if((GetLocalArchitecture() == GetFileArchitecture(header)) || (GetFileArchitecture(header) == ARCH_UNKNOWN)) { convert = 0; } else { convert = 1; fprintf(stderr,"Converting data from %s to %s architectures.\n", GetFileArchitectureStr(header), GetLocalArchitectureStr()); } count = 0; while(!feof(fp)){ /* ** read a timestamp */ if(fread(&timestamp,sizeof(uint32_t),1,fp) != 1){ break; } if(convert){ ConvertData(&timestamp,sizeof(uint32_t)); } if(!InRange(result,timestamp)) continue; if(timestamp < result->tstart){ continue; } if(timestamp > result->tend){ break; } /* ** assign it to a bin */ bin = (timestamp - result->tstart)/result->binsize; if(bin < 0){ continue; } if(bin >= result->ntimebins){ continue; } /* ** increment the time bin contents for the cluster */ result->datavector[bin][clusterid]++; result->timebinstatus[bin].valid = 1; count++; } return(count); } ReconLoadAndBinSpikes(fp,result,clusterid) FILE *fp; Result *result; int32_t clusterid; { uint32_t timestamp; float *vector; int32_t bin; int32_t count; int32_t headersize; int32_t convert; char **header; fseek(fp,0L,0L); /* rewind spike file */ header = ReadHeader(fp,&headersize); /* ** compare architectures */ if((GetLocalArchitecture() == GetFileArchitecture(header)) || (GetFileArchitecture(header) == ARCH_UNKNOWN)) { convert = 0; } else { convert = 1; fprintf(stderr,"Converting data from %s to %s architectures.\n", GetFileArchitectureStr(header), GetLocalArchitectureStr()); } count = 0; while(!feof(fp)){ /* ** read a timestamp */ if(fread(&timestamp,sizeof(uint32_t),1,fp) != 1){ break; } if(convert){ ConvertData(&timestamp,sizeof(uint32_t)); } if(!InRange(result,timestamp)) continue; if(timestamp < result->recontstart){ continue; } if(timestamp > result->recontend){ break; } /* ** assign it to a bin */ bin = (timestamp - result->recontstart)/result->binsize; if(bin < 0){ continue; } if(bin >= result->nrecontimebins){ continue; } /* ** increment the time bin contents for the cluster */ result->reconvector[bin][clusterid]++; count++; } return(count); } SmoothSpikes(fp,result,clusterid) FILE *fp; Result *result; int32_t clusterid; { uint32_t timestamp; float *vector,sum; int32_t count,i,j; vector = (float *)malloc(sizeof(float)*result->ntimebins); for(i=0;i<result->ntimebins;i++){ count = 0; sum = 0; for(j=i-result->smoothspikes;j<i+result->smoothspikes;j++){ if((j< 0) || (j>= result->ntimebins)) continue; /* ** increment the time bin contents for the cluster */ sum += result->datavector[j][clusterid]; count++; } vector[i] = sum/count; } /* ** load the smoothed result into the data vector */ for(i=0;i<result->ntimebins;i++){ result->datavector[i][clusterid] = vector[i]; } free(vector); } WriteGerstein(fp,result,clusterid) FILE *fp; Result *result; int32_t clusterid; { uint32_t timestamp; float *vector; int32_t bin; int32_t count; count = 0; while(!feof(fp)){ /* ** read a timestamp */ if(fread(&timestamp,sizeof(uint32_t),1,fp) != 1){ break; } /* ** write it out to the output file with the cluster id */ fprintf(result->fpout,"%d\t%u\n",clusterid,timestamp); count++; } return(count); } WriteCorrelationMatrix(result) Result *result; { int32_t i,j; int32_t index; for(i=0;i<result->nclusters;i++){ if(result->sortcorr){ index = result->corrlist[i].index; } else { index = i; } fwrite(result->corrmatrix[index],sizeof(float),result->nclusters, result->fpcorrmatrixout); } } WriteVectors(result) Result *result; { int32_t ival; float fval; int32_t i,j; double sum; FILE *fp; if(verbose){ fprintf(stderr,"writing %d clusters, %d timebins\n", result->nclusters,result->ntimebins); } fp = result->fpout; if(result->lump){ for(i=0;i<result->ntimebins;i++){ sum = 0; for(j=0;j<result->nclusters;j++){ sum += result->datavector[i][j]; } fprintf(fp,"%g\n",sum/result->nclusters); } } else { if(result->asciiout){ /* ** go through each time bin and output the data vector */ for(i=0;i<result->ntimebins;i++){ fprintf(fp,"%"PRIu32"",(uint32_t)(i*result->binsize +result->tstart)); for(j=0;j<result->nclusters;j++){ fprintf(fp,"\t%6.2g",result->datavector[i][j]); } fprintf(fp,"\n"); } } else { /* ** write the binary xview header */ ival = result->nclusters-1; fwrite(&ival,sizeof(int32_t),1,fp); /* ival = result->ntimebins-1; */ ival = 0; fwrite(&ival,sizeof(int32_t),1,fp); fval = 1; fwrite(&fval,sizeof(float),1,fp); ival = FLOAT; fwrite(&ival,sizeof(int32_t),1,fp); /* ** go through each time bin and output the data vector */ for(i=0;i<result->ntimebins;i++){ fwrite(result->datavector[i],sizeof(float),result->nclusters,fp); } } } } float **FillGrid(fp,result,clusterid) FILE *fp; Result *result; int32_t clusterid; { int32_t xmax,ymax; int32_t datatype; float dt; float **newgrid; float **smoothgrid; int32_t i,j; int32_t x,y,x2,y2,count; double sum; char **header; int32_t headersize; int32_t convert; fseek(fp,0L,0L); /* rewind spike file */ header = ReadHeader(fp,&headersize); /* ** compare architectures */ if((GetLocalArchitecture() == GetFileArchitecture(header)) || (GetFileArchitecture(header) == ARCH_UNKNOWN)) { convert = 0; } else { convert = 1; fprintf(stderr,"Converting data from %s to %s architectures.\n", GetFileArchitectureStr(header), GetLocalArchitectureStr()); } /* ** read in the xview format information */ if(fread(&xmax,sizeof(int32_t),1,fp) != 1){ fprintf(stderr, "ERROR: unable to read position file for cluster %d\n", clusterid); return(NULL); } if(convert){ ConvertData(&xmax,sizeof(int32_t)); } if(fread(&ymax,sizeof(int32_t),1,fp) != 1){ fprintf(stderr, "ERROR: unable to read position file for cluster %d\n", clusterid); return(NULL); } if(convert){ ConvertData(&ymax,sizeof(int32_t)); } if(fread(&dt,sizeof(float),1,fp) != 1){ fprintf(stderr, "ERROR: unable to read position file for cluster %d\n", clusterid); return(NULL); } if(convert){ ConvertData(&dt,sizeof(float)); } if(fread(&datatype,sizeof(int32_t),1,fp) != 1){ fprintf(stderr, "ERROR: unable to read position file for cluster %d\n", clusterid); return(NULL); } if(convert){ ConvertData(&datatype,sizeof(int32_t)); } if(datatype != FLOAT){ fprintf(stderr, "ERROR: unable to handle position file of datatype %d\n", datatype); return(NULL); } /* ** allocate the grid */ result->xmax = xmax; result->ymax = ymax; /* ** if bounds were not explicitly specified then use the ** full range */ if(result->xlo == -1){ result->xlo = 0; result->ylo = 0; result->xhi = xmax; result->yhi = ymax; } if(result->gxlo == -1){ result->gxlo = 0; result->gylo = 0; result->gxhi = xmax; result->gyhi = ymax; } /* ** check the specified bounds against the actual bounds */ if(result->xhi > xmax || result->yhi > ymax || result->xlo < 0 || result->ylo < 0){ fprintf(stderr,"ERROR: grid dimension mismatch: specified x=(%d %d) y=(%d %d), actual x=(%d %d) y=(%d %d)\n", result->xlo,result->xhi, result->ylo,result->yhi, 0,xmax,0,ymax); exit(-1); } result->datatype = datatype; newgrid = (float **)malloc((ymax+1)*sizeof(float *)); for(i=0;i<=ymax;i++){ newgrid[i] = (float *)malloc((xmax+1)*sizeof(float)); } /* ** read the data into the grid */ for(i=0;i<=ymax;i++){ if(fread(newgrid[i],sizeof(float),xmax+1,fp) != xmax+1){ fprintf(stderr, "ERROR: reading data from position file for cluster %d\n", clusterid); return(NULL); } if(convert){ for(j=0;j<=xmax;j++){ ConvertData(&newgrid[i][j],sizeof(float)); } } } if(result->smoothgrid){ smoothgrid = (float **)malloc((ymax+1)*sizeof(float *)); for(i=0;i<=ymax;i++){ smoothgrid[i] = (float *)malloc((xmax+1)*sizeof(float)); } /* ** smooth the rate grid */ for(y=result->ylo;y<=result->yhi;y++){ for(x=result->xlo;x<=result->xhi;x++){ /* ** smooth the grid by summing adjacent bins */ sum = 0; count = 0; for(y2=y-result->smoothgrid;y2<=y+result->smoothgrid;y2++){ /* ** dont include points outside the bounds ** in the smoothing */ if((y2 < result->ylo) || (y2 > result->yhi)){ continue; } for(x2=x-result->smoothgrid;x2<=x+result->smoothgrid;x2++){ /* ** dont include points outside the bounds ** in the smoothing */ if((x2 >= result->xlo) && (x2 <= result->xhi)){ sum += newgrid[y2][x2]; count++; } } } /* ** fill the smoothed matrix */ if(count > 0){ smoothgrid[y][x] = sum/count; } else { smoothgrid[y][x] = 0; } } } return(smoothgrid); } return(newgrid); } WriteSparsity(result) Result *result; { int32_t y; if(verbose){ fprintf(stderr,"writing sparsity grid\n"); } for(y=0;y<=result->ymax;y++){ fwrite(result->sparsegrid[y],sizeof(float),result->xmax+1, result->fpsparsegridout); } fclose(result->fpsparsegridout); } WritePositionErrorGrid(result) Result *result; { double sum; int32_t count; int32_t x,y; int32_t x2,y2; /* ** if grid position error output is selected then dump it */ if(result->fpperrgrid){ if(verbose){ fprintf(stderr,"writing position error grid\n"); } for(y=result->ylo;y<=result->yhi;y++){ for(x=result->xlo;x<=result->xhi;x++){ /* ** normalize position error by occupancy */ if(result->occgrid[y][x] > 0){ result->perrgrid[y][x] /= result->occgrid[y][x]; } } } /* ** if smoothing is selected then smooth it */ if(result->smoothcorr){ /* ** initialize the error grid so that unprocessed ** regions are can be distinguised (used by xview display program) */ for(y=0;y<=result->ymax;y++){ for(x=0;x<=result->xmax;x++){ result->smoothperrgrid[y][x] = -999; } } /* ** smooth the position error grid */ for(y=result->ylo;y<=result->yhi;y++){ for(x=result->xlo;x<=result->xhi;x++){ /* ** smooth the grid by summing adjacent bins */ sum = 0; count = 0; for(y2=y-result->smoothcorr;y2<=y+result->smoothcorr;y2++){ /* ** dont include points outside the bounds ** in the smoothing */ if((y2 < result->ylo) || (y2 > result->yhi)){ continue; } for(x2=x-result->smoothcorr;x2<=x+result->smoothcorr;x2++){ /* ** dont include points outside the bounds ** in the smoothing */ if((x2 >= result->xlo) && (x2 <= result->xhi)){ sum += result->perrgrid[y2][x2]; count++; } } } /* ** fill the smoothed matrix */ if(count > 0){ result->smoothperrgrid[y][x] = sum/count; } else { result->smoothperrgrid[y][x] = 0; } } } for(y=0;y<=result->ymax;y++){ fwrite(result->smoothperrgrid[y],sizeof(float),result->xmax+1, result->fpperrgrid); } } else { for(y=0;y<=result->ymax;y++){ fwrite(result->perrgrid[y],sizeof(float),result->xmax+1, result->fpperrgrid); } } } } WriteGridMagnitude(result) Result *result; { int32_t x,y; float fval; if(verbose){ fprintf(stderr,"writing magnitude grid\n"); } for(y=0;y<=result->ymax;y++){ for(x=0;x<=result->xmax;x++){ /* ** if an occupancy cutoff has been specified then test for it */ if(result->trueoccgrid[y][x] > result->occcutoff){ fval = result->truemaggrid[y][x]; } else { fval = -999; } fwrite(&fval,sizeof(float),1, result->fpmagout); } } fclose(result->fpmagout); } CommonHeader(fp,result) FILE *fp; Result *result; { int32_t i; fprintf(fp,"%% Version:\t%s\n",VERSION); fprintf(fp,"%% Start time:\t%s\n", TimestampToString(result->tstart)); fprintf(fp,"%% End time:\t%s\n", TimestampToString(result->tend)); fprintf(fp,"%% Binsize:\t%u\n",result->binsize); fprintf(fp,"%% Ntimebins:\t%u\n",result->ntimebins); fprintf(fp,"%% Nx:\t%d\n",result->xmax+1); fprintf(fp,"%% Ny:\t%d\n",result->ymax+1); fprintf(fp,"%% Nclusters:\t%d\n",result->nactivec); for(i=0;i<result->nclusters;i++){ if(clusterdir[i].ignore) continue; if(result->useprefix){ fprintf(fp,"%% %d:\t%s/t%d\t%d spikes\n", i,clusterdir[i].dirname, clusterdir[i].clusterid, result->spikecount[i]); } else { fprintf(fp,"%% %d:\t%s/%s\t%d spikes\n", i,clusterdir[i].dirname, clusterdir[i].filename, result->spikecount[i]); } } if(result->hasspatialfiring){ for(i=0;i<result->nclusters;i++){ if(result->pdir[i].ignore) continue; fprintf(fp,"%% %d:\t%s\n",i, result->pdir[i].path); } } } WriteOutputHeaders(result,argc,argv) Result *result; int32_t argc; char **argv; { int32_t i; float fval; FILE *fp; int32_t datatype; /* ** write out the standard header to the cluster stats file ** file */ if(result->fpout){ /* ** write out the standard header */ fp = result->fpout; BeginStandardHeader(fp,argc,argv,VERSION); fprintf(fp,"%% File type:\t%s\n","Xview"); CommonHeader(fp,result); fprintf(fp,"%% Analysis type:\tPopulation vectors\n"); EndStandardHeader(fp); } /* ** write out the standard header to the spike train ** file */ if(result->fpspiketrainout){ /* ** write out the standard header */ fp = result->fpspiketrainout; BeginStandardHeader(fp,argc,argv,VERSION); fprintf(fp,"%% File type:\t%s\n","Ascii"); CommonHeader(fp,result); fprintf(fp,"%% Analysis type:\tSpike train\n"); fprintf(fp,"%% Fields:\t%s\t%s\t%s\t%s\n", "time","clusterid","peakx","peaky"); EndStandardHeader(fp); } /* ** write out the standard header to the population spike train ** file */ if(result->fppoptrainout){ /* ** write out the standard header */ fp = result->fppoptrainout; BeginStandardHeader(fp,argc,argv,VERSION); fprintf(fp,"%% File type:\t%s\n","Ascii"); CommonHeader(fp,result); fprintf(fp,"%% Analysis type:\tPopulation spike train\n"); fprintf(fp,"%% Fields:\t%s\n", "spikes"); EndStandardHeader(fp); } /* ** write out the standard header to the population spike train ** file */ if(result->fppopvecout){ /* ** write out the standard header */ fp = result->fppopvecout; BeginStandardHeader(fp,argc,argv,VERSION); fprintf(fp,"%% File type:\t%s\n","Ascii"); CommonHeader(fp,result); fprintf(fp,"%% Analysis type:\tPopulation vector\n"); if(result->hasposition){ fprintf(fp,"%% Fields:\t%s\t%s\t%s\n", "posx","posy","spike_rates"); } else { fprintf(fp,"%% Fields:\t%s\n", "spike_rates"); } EndStandardHeader(fp); } /* ** write out the standard header to the correlation plot ** file */ if(result->fpcorrplotout){ /* ** write out the standard header */ fp = result->fpcorrplotout; BeginStandardHeader(fp,argc,argv,VERSION); fprintf(fp,"%% File type:\t%s\n","Ascii"); CommonHeader(fp,result); fprintf(fp,"%% Analysis type:\tCorrelation matrix plot\n"); fprintf(fp,"%% Fields:\t%s\t%s\t%s\t%s\n", "x","y","corr","cluster"); EndStandardHeader(fp); } /* ** write out the standard header to the population vector ** file */ if(result->fpstatout){ /* ** write out the standard header */ fp = result->fpstatout; BeginStandardHeader(fp,argc,argv,VERSION); fprintf(fp,"%% File type:\t%s\n","Ascii"); CommonHeader(fp,result); fprintf(fp,"%% Analysis type:\tCluster stats\n"); fprintf(fp,"%% Fields:\t%s\t%s\t%s\t%s\n", "cluster","rate","peakx","peaky"); EndStandardHeader(fp); } /* ** write out the standard header to the correlation matrix ** file */ if(result->fpcorrmatrixout){ /* ** write out the standard header */ fp = result->fpcorrmatrixout; BeginStandardHeader(fp,argc,argv,VERSION); fprintf(fp,"%% File type:\t%s\n","Xview"); fprintf(fp,"%% Xsize:\t%d\n",result->nclusters); fprintf(fp,"%% Ysize:\t%d\n",result->nclusters); fprintf(fp,"%% Fields:\t%s,%d,%d,%d\n", "correlations", FLOAT,sizeof(float),1); CommonHeader(fp,result); fprintf(fp,"%% Analysis type:\tCorrelation matrix\n"); EndStandardHeader(fp); } /* ** write out the standard header to the correlation histogram ** file */ if(result->fpcorrhistout){ fp = result->fpcorrhistout; BeginStandardHeader(fp,argc,argv,VERSION); fprintf(fp,"%% File type:\t%s\n","Ascii"); CommonHeader(fp,result); fprintf(fp,"%% Analysis type:\tCorrelation histogram\n"); fprintf(fp,"%% Fields: vecid1\tvecid2\tdist\toverlap\tmeanrate\tbias\tskew\tshift"); if(result->hasparameters){ fprintf(fp,"\tparm1\tparm2"); } fprintf(fp,"\tcorrdata\n"); EndStandardHeader(fp); } /* ** write out the standard header to the ** distance file */ if(result->fpdout){ fp = result->fpdout; BeginStandardHeader(fp,argc,argv,VERSION); fprintf(fp,"%% File type:\t%s\n","Ascii"); CommonHeader(fp,result); fprintf(fp,"%% Analysis type:\tPosition reconstruction\n"); fprintf(fp,"%% Fields: timestamp\txest\tyest\tdist\tinterval\n"); EndStandardHeader(fp); } /* ** write out the standard header to the position reconstruction ** file */ if(result->fppout){ fp = result->fppout; BeginStandardHeader(fp,argc,argv,VERSION); fprintf(fp,"%% File type:\t%s\n","Ascii"); CommonHeader(fp,result); fprintf(fp,"%% Analysis type:\tPosition reconstruction\n"); fprintf(fp,"%% Fields: timestamp\tmeanrate\tspeed\tsparsity\txest\tyest\t1-corr\tnties\txact\tyact\terror\t\n"); EndStandardHeader(fp); } /* ** write out the standard header to the field replay output file ** file */ if(result->fpspikecorr){ fp = result->fpspikecorr; BeginStandardHeader(fp,argc,argv,VERSION); fprintf(fp,"%% File type:\t%s\n","Ascii"); CommonHeader(fp,result); fprintf(fp,"%% Analysis type:\tSpike correlation analysis\n"); fprintf(fp,"%% Fields:\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", "vecid1","vecid2","dist","zerocorr","peakcorr","peakphs","meanphs","overlap", "expectcorr","meanrate","minrate","maxrate","expected","sd","zero"); EndStandardHeader(fp); } /* ** write out the standard header to the field replay output file ** file */ if(result->fpreplayout){ fp = result->fpreplayout; BeginStandardHeader(fp,argc,argv,VERSION); fprintf(fp,"%% File type:\t%s\n","Ascii"); CommonHeader(fp,result); fprintf(fp,"%% Analysis type:\tSpike spatial field replay\n"); fprintf(fp,"%% Fields:\t%s\t%s\t%s\t%s\t\n", "x","y","rate","cluster"); EndStandardHeader(fp); } /* ** write out the standard header to the replay correlation output file ** file */ if(result->fpreplaydot){ fp = result->fpreplaydot; BeginStandardHeader(fp,argc,argv,VERSION); fprintf(fp,"%% File type:\t%s\n","Ascii"); CommonHeader(fp,result); if(result->position_bin_avg != 0){ fprintf(fp,"%% Analysis type:\tReplay dot product output - avg position\n"); fprintf(fp,"%% Fields:\t%s\t%s\t%s\t%s\t\n", "bin","dotprod","netdist","fracdist"); } else if(result->position_bin_search > 0){ fprintf(fp,"%% Analysis type:\tReplay dot product output - optimal search\n"); fprintf(fp,"%% Fields:\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t\n", "bin","bestlag","dotprod","dist","netdist","fracdist","speed"); } EndStandardHeader(fp); } /* ** write out the standard header to the trajectory tree ** file */ if(result->fptreeout){ fp = result->fptreeout; BeginStandardHeader(fp,argc,argv,VERSION); fprintf(fp,"%% File type:\t%s\n","Ascii"); CommonHeader(fp,result); fprintf(fp,"%% Analysis type:\tSpike trajectory tree\n"); switch(result->treeoutputformat){ case XPLOT: if(result->hasposition && result->hasspatialfiring){ fprintf(fp,"%% Fields:\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t\n", "node id","ntraverse","nodex","nodey","distance", "cumdistance","actualx","actualy","adistance","depth"); } else if(result->hasspatialfiring){ fprintf(fp,"%% Fields:\t%s\t%s\t%s\t%s\t%s\t%s\t\n", "node id","ntraverse","nodex","nodey","distance", "cumdistance","depth"); } else { fprintf(fp,"%% Fields:\t%s\t%s\t%s\t\n", "node id","ntraverse","depth"); } } EndStandardHeader(fp); } /* ** write out the standard header to the correlation grid output ** file */ if(result->fpcorrout){ fp = result->fpcorrout; BeginStandardHeader(fp,argc,argv,VERSION); fprintf(fp,"%% File type:\t%s\n","Xview"); CommonHeader(fp,result); fprintf(fp, "%% Analysis type:\tPosition reconstruction correlation grid\n"); EndStandardHeader(fp); /* ** write out the old xview header */ fwrite(&(result->xmax),sizeof(int32_t),1,fp); fwrite(&(result->ymax),sizeof(int32_t),1,fp); fval = 1.0; fwrite(&fval,sizeof(float),1,fp); datatype = FLOAT; fwrite(&datatype,sizeof(int32_t),1,fp); } /* ** write out the standard header to the correlation grid output ** file */ if(result->fpperrgrid){ fp = result->fpperrgrid; BeginStandardHeader(fp,argc,argv,VERSION); fprintf(fp,"%% File type:\t%s\n","Xview"); CommonHeader(fp,result); fprintf(fp, "%% Analysis type:\tPosition reconstruction error grid\n"); EndStandardHeader(fp); /* ** write out the old xview header */ fwrite(&(result->xmax),sizeof(int32_t),1,fp); fwrite(&(result->ymax),sizeof(int32_t),1,fp); fval = 1.0; fwrite(&fval,sizeof(float),1,fp); datatype = FLOAT; fwrite(&datatype,sizeof(int32_t),1,fp); } /* ** write out the standard header to the grid magnitude output ** file */ if(result->fpmagout){ fp = result->fpmagout; BeginStandardHeader(fp,argc,argv,VERSION); fprintf(fp,"%% File type:\t%s\n","Xview"); CommonHeader(fp,result); fprintf(fp, "%% Analysis type:\tPopulation vector magnitude grid\n"); EndStandardHeader(fp); /* ** write out the old xview header */ fwrite(&(result->xmax),sizeof(int32_t),1,fp); fwrite(&(result->ymax),sizeof(int32_t),1,fp); fval = 1.0; fwrite(&fval,sizeof(float),1,fp); fwrite(&(result->datatype),sizeof(int32_t),1,fp); } /* ** write out the standard header to the grid sparsity output ** file */ if(result->fpsparsegridout){ fp = result->fpsparsegridout; BeginStandardHeader(fp,argc,argv,VERSION); fprintf(fp,"%% File type:\t%s\n","Xview"); CommonHeader(fp,result); fprintf(fp,"%% Sparsity cutoff:\t%g\n", result->sparsity_cutoff); fprintf(fp, "%% Analysis type:\tPopulation vector sparsity grid\n"); EndStandardHeader(fp); /* ** write out the old xview header */ fwrite(&(result->xmax),sizeof(int32_t),1,fp); fwrite(&(result->ymax),sizeof(int32_t),1,fp); fval = 1.0; fwrite(&fval,sizeof(float),1,fp); fwrite(&(result->datatype),sizeof(int32_t),1,fp); } /* ** write out the standard header to the vector sparsity output ** file */ if(result->fpsparsevecout){ fp = result->fpsparsevecout; BeginStandardHeader(fp,argc,argv,VERSION); fprintf(fp,"%% File type:\t%s\n","Ascii"); CommonHeader(fp,result); fprintf(fp,"%% Sparsity cutoff:\t%g\n", result->sparsity_cutoff); fprintf(fp, "%% Analysis type:\tPopulation vector sparsity vs time\n"); EndStandardHeader(fp); } } int32_t ReadPositions(result) Result *result; { int32_t i; uint32_t tstart; uint32_t tend; int32_t bin; FILE *fp; uint32_t timestamp; uint32_t ptimestamp; int16_t x1; int16_t y1; int16_t x2; int16_t y2; unsigned char cval; int32_t gx,gy; int32_t px1; int32_t py1; int32_t mx; int32_t my; int32_t mx2; int32_t my2; float mspeed; float speed; int32_t nxy; int32_t nxy2; int32_t nsp; int32_t pbin; int32_t count; int32_t ninterpol; int32_t ibin; int32_t headersize; char **header; int32_t convert; char *typestr; int32_t p2format; int32_t dformat; int32_t direction; fp = result->fppfile; p2format = 0; dformat = 0; fseek(fp,0L,0L); header = ReadHeader(fp,&headersize); /* ** compare architectures */ if((GetLocalArchitecture() == GetFileArchitecture(header)) || (GetFileArchitecture(header) == ARCH_UNKNOWN)) { convert = 0; } else { convert = 1; fprintf(stderr,"Converting data from %s to %s architectures.\n", GetFileArchitectureStr(header), GetLocalArchitectureStr()); } if((typestr = GetHeaderParameter(header,"Record type:")) != NULL){ /* ** look for the D type */ if(strncmp(typestr,"D",strlen("D")) == 0){ dformat = 1; } else { dformat = 0; } /* ** look for the T type */ if(strncmp(typestr,"T",strlen("T")) == 0){ p2format = 1; } else { p2format = 0; } } mx = 0; my = 0; mx2 = 0; my2 = 0; mspeed = 0; px1 = -1; py1 = -1; ptimestamp = 0; nxy = 0; nxy2 = 0; nsp = 0; pbin = -1; count = 0; result->trueoccgrid = (float **)malloc((result->ymax+1)*sizeof(float *)); for(i=0;i<=result->ymax;i++){ result->trueoccgrid[i] = (float *)calloc((result->xmax+1),sizeof(float)); } /* ** compute the number of bins per position interval ** note that binsize is in 100 usec intervals ** while the position interval is in sec */ ninterpol = (int32_t)(POSITION_INTERVAL*1e4/result->binsize + 0.5); while(!feof(fp)){ /* ** read in each position and fill the position bins */ fread(&timestamp,sizeof(uint32_t),1,fp); if(convert){ ConvertData(&timestamp,sizeof(uint32_t)); } /* ** check for the end of the interval */ if(timestamp > result->tend){ break; } if(p2format){ /* ** read in the front and back diode positions */ fread(&x1,sizeof(int16_t),1,fp); fread(&y1,sizeof(int16_t),1,fp); fread(&x2,sizeof(int16_t),1,fp); fread(&y2,sizeof(int16_t),1,fp); if(convert){ ConvertData(&x1,sizeof(int16_t)); ConvertData(&y1,sizeof(int16_t)); ConvertData(&x2,sizeof(int16_t)); ConvertData(&y2,sizeof(int16_t)); } } else { /* ** front diode position */ fread(&cval,sizeof(unsigned char),1,fp); if(convert){ ConvertData(&cval,sizeof(unsigned char)); } x1 = cval; fread(&cval,sizeof(unsigned char),1,fp); if(convert){ ConvertData(&cval,sizeof(unsigned char)); } y1 = cval; /* ** back diode position */ fread(&cval,sizeof(unsigned char),1,fp); if(convert){ ConvertData(&cval,sizeof(unsigned char)); } x2 = cval; fread(&cval,sizeof(unsigned char),1,fp); if(convert){ ConvertData(&cval,sizeof(unsigned char)); } y2 = cval; if(dformat){ /* ** read in the direction */ if(fread(&direction, sizeof(int32_t),1,fp) != 1){ break; } if(convert){ ConvertData(&direction,sizeof(int32_t)); } } } /* ** check for valid positions */ if((x1 == 0) && (y1 == 0)){ continue; } /* ** assign it to a bin */ bin = (timestamp - result->tstart)/result->binsize; /* ** ignore points outside of the interval */ if(bin < 0){ continue; } if(bin >= result->ntimebins){ continue; } /* ** transform the actual coordinate into grid ** coordinates */ gy = y1*(result->ymax+1)/result->yresolution; gx = x1*(result->xmax+1)/result->xresolution; /* ** keep track of occupancies */ result->trueoccgrid[gy][gx]++; /* ** keep a running mean of positions and speed within the bin */ if(bin == pbin){ /* ** mean position */ mx += x1; my += y1; nxy++; if(x2 != 0 || y2 != 0){ mx2 += x2; my2 += y2; nxy2++; } /* ** mean speed */ if(px1 != -1 && (timestamp != ptimestamp)){ speed = sqrt((double)(((int32_t)x1-px1)*((int32_t)x1-px1) + ((int32_t)y1-py1)*((int32_t)y1 - py1)))/ ((timestamp - ptimestamp)*1e-4); mspeed += speed; nsp++; } } else { /* ** save the previous bin contents */ if(pbin != -1){ /* ** if the binsize is below the ** time resolution of the position info ** then fill in the missing bins */ for(ibin = 0;ibin<=ninterpol;ibin++){ if(pbin+ibin >= result->ntimebins){ break; } result->position[pbin+ibin].x = mx/nxy; result->position[pbin+ibin].y = my/nxy; if(nsp>0){ result->speed[pbin+ibin] = mspeed/nsp; } else { result->speed[pbin+ibin] = 0; } if(nxy2 > 0){ result->position[pbin+ibin].x2 = mx2/nxy2; result->position[pbin+ibin].y2 = my2/nxy2; } else { result->position[pbin+ibin].x2 = 0; result->position[pbin+ibin].y2 = 0; } } count++; } /* ** reset the bin count and content */ mx = x1; my = y1; mspeed = 0; nsp = 0; nxy = 1; if(x2 != 0 || y2 != 0){ mx2 = x2; my2 = y2; nxy2 = 1; } else { mx2 = 0; my2 = 0; nxy2 = 0; } pbin = bin; } /* ** update the previous state variables */ ptimestamp = timestamp; px1 = x1; py1 = y1; } return(count); } int32_t ComputeBayesianDistributions(result) Result *result; { int32_t i; int32_t j; uint32_t tstart; uint32_t tend; int32_t bin; FILE *fp; uint32_t timestamp; uint32_t ptimestamp; int16_t x1; int16_t y1; int16_t x2; int16_t y2; unsigned char cval; int32_t gx,gy; int32_t px1; int32_t py1; int32_t mx; int32_t my; int32_t mx2; int32_t my2; float mspeed; float speed; int32_t nxy; int32_t nxy2; int32_t nsp; int32_t pbin; int32_t count; int32_t ninterpol; int32_t ibin; int32_t headersize; char **header; int32_t convert; char *typestr; int32_t p2format; int32_t dformat; int32_t direction; fp = result->fppfile; p2format = 0; dformat = 0; fseek(fp,0L,0L); header = ReadHeader(fp,&headersize); /* ** compare architectures */ if((GetLocalArchitecture() == GetFileArchitecture(header)) || (GetFileArchitecture(header) == ARCH_UNKNOWN)) { convert = 0; } else { convert = 1; fprintf(stderr,"Converting data from %s to %s architectures.\n", GetFileArchitectureStr(header), GetLocalArchitectureStr()); } if((typestr = GetHeaderParameter(header,"Record type:")) != NULL){ /* ** look for the D type */ if(strncmp(typestr,"D",strlen("D")) == 0){ dformat = 1; } else { dformat = 0; } /* ** look for the T type */ if(strncmp(typestr,"T",strlen("T")) == 0){ p2format = 1; } else { p2format = 0; } } mx = 0; my = 0; mx2 = 0; my2 = 0; mspeed = 0; px1 = -1; py1 = -1; ptimestamp = 0; nxy = 0; nxy2 = 0; nsp = 0; pbin = -1; count = 0; result->ntotalocc=0; /* ** allocate grids */ result->zerop = (float *)calloc(result->nclusters,sizeof(float)); result->nonzerop = (float *)calloc(result->nclusters,sizeof(float)); result->trueoccgrid = (float **)malloc((result->ymax+1)*sizeof(float *)); result->occgrid = (float **)malloc((result->ymax+1)*sizeof(float *)); for(j=0;j<=result->ymax;j++){ result->trueoccgrid[j] = (float *)calloc((result->xmax+1),sizeof(float)); result->occgrid[j] = (float *)calloc((result->xmax+1),sizeof(float)); } result->positiongrid = (float ***)malloc(result->nclusters*sizeof(float **)); result->positiongridzero = (float ***)malloc(result->nclusters*sizeof(float **)); for(i=0;i<result->nclusters;i++){ result->positiongrid[i]= (float **)malloc((result->ymax+1)*sizeof(float *)); result->positiongridzero[i]= (float **)malloc((result->ymax+1)*sizeof(float *)); for(j=0;j<=result->ymax;j++){ result->positiongrid[i][j] = (float *)calloc((result->xmax+1),sizeof(float)); result->positiongridzero[i][j] = (float *)calloc((result->xmax+1),sizeof(float)); } } /* ** compute the number of bins per position interval ** note that binsize is in 100 usec intervals ** while the position interval is in sec */ while(!feof(fp)){ /* ** read in each position and fill the position bins */ fread(&timestamp,sizeof(uint32_t),1,fp); if(convert){ ConvertData(&timestamp,sizeof(uint32_t)); } /* ** check for the end of the interval */ if(timestamp > result->tend){ break; } if(p2format){ /* ** read in the front and back diode positions */ fread(&x1,sizeof(int16_t),1,fp); fread(&y1,sizeof(int16_t),1,fp); fread(&x2,sizeof(int16_t),1,fp); fread(&y2,sizeof(int16_t),1,fp); if(convert){ ConvertData(&x1,sizeof(int16_t)); ConvertData(&y1,sizeof(int16_t)); ConvertData(&x2,sizeof(int16_t)); ConvertData(&y2,sizeof(int16_t)); } } else { /* ** front diode position */ fread(&cval,sizeof(unsigned char),1,fp); if(convert){ ConvertData(&cval,sizeof(unsigned char)); } x1 = cval; fread(&cval,sizeof(unsigned char),1,fp); if(convert){ ConvertData(&cval,sizeof(unsigned char)); } y1 = cval; /* ** back diode position */ fread(&cval,sizeof(unsigned char),1,fp); if(convert){ ConvertData(&cval,sizeof(unsigned char)); } x2 = cval; fread(&cval,sizeof(unsigned char),1,fp); if(convert){ ConvertData(&cval,sizeof(unsigned char)); } y2 = cval; if(dformat){ /* ** read in the direction */ if(fread(&direction, sizeof(int32_t),1,fp) != 1){ break; } if(convert){ ConvertData(&direction,sizeof(int32_t)); } } } /* ** check for valid positions */ if((x1 == 0) && (y1 == 0)){ continue; } /* ** assign it to a bin */ bin = (timestamp - result->tstart)/result->binsize; /* ** ignore points outside of the interval */ if(bin < 0){ continue; } if(bin >= result->ntimebins){ continue; } /* ** transform the actual coordinate into grid ** coordinates */ gy = y1*(result->ymax+1)/result->yresolution; gx = x1*(result->xmax+1)/result->xresolution; /* ** keep track of occupancies */ result->trueoccgrid[gy][gx]++; /* ** keep track of total position samples */ result->ntotalocc++; /* ** scan the binned spike trains to determine which cells were active ** during this positional bin ** note that the spike binsize must be greater than the position binsize */ for(i=0;i<result->nclusters;i++){ if(result->datavector[bin][i] > result->zerolevel){ result->positiongrid[i][gy][gx]++; result->nonzerop[i]++; } else { result->positiongridzero[i][gy][gx]++; result->zerop[i]++; } } /* ** update the previous state variables */ ptimestamp = timestamp; px1 = x1; py1 = y1; } return(count); } ReadPositionDirectoryHeader(result) Result *result; { char **header; int32_t headersize; char *tstring; fseek(result->fppdir,0L,0L); header = ReadHeader(result->fppdir,&headersize); /* ** look for the bounding region */ if((result->xlo == -1) && (tstring = GetHeaderParameter(header,"Bounds:")) != NULL){ /* ** get the bounds */ sscanf(tstring,"%d%d%d%d", &result->xlo, &result->ylo, &result->xhi, &result->yhi); } if(verbose){ if(result->xlo != -1){ fprintf(stderr,"using bounding region %d %d to %d %d\n", result->xlo, result->ylo, result->xhi, result->yhi); } else { fprintf(stderr,"using complete region. No bounds specified\n"); } } if((result->gxlo == -1) && (tstring = GetHeaderParameter(header,"PosBounds:")) != NULL){ /* ** get the bounds */ sscanf(tstring,"%d%d%d%d", &result->gxlo, &result->gylo, &result->gxhi, &result->gyhi); } else { result->gxlo = result->xlo; result->gxhi = result->xhi; result->gylo = result->ylo; result->gyhi = result->yhi; } if(verbose){ if(result->gxlo != -1){ fprintf(stderr,"using position bounding region %d %d to %d %d\n", result->gxlo, result->gylo, result->gxhi, result->gyhi); } else { fprintf(stderr,"using complete region. No bounds specified\n"); } } } int32_t ParseId(path) char *path; { int32_t val; char *fptr; char *lptr; char tmpstr[100]; strcpy(tmpstr,path); /* ** first find the first and last numeric character in the string */ fptr = tmpstr; while(fptr && *fptr != '\0' && (*fptr < '0' || *fptr > '9')){ fptr++; } lptr = fptr; while(lptr && *lptr != '\0' && (*lptr >= '0' && *lptr <= '9')){ lptr++; } *lptr = '\0'; if(lptr != fptr){ val = atoi(fptr); } else { val = -1; } return(val); } float ParseParameter(path) char *path; { float val; char *fptr; char *lptr; char tmpstr[100]; strcpy(tmpstr,path); /* ** first find the first whitespace in the string */ fptr = tmpstr; while(fptr && *fptr != '\0' && *fptr != ' ' && *fptr != '\t'){ fptr++; } val = atof(fptr); return(val); } ReadParameterDirectory(result) Result *result; { int32_t i; char line[1001]; char *ptr; char *start; char dirname[100]; int32_t clusterid; FILE *fp; if(verbose){ fprintf(stderr,"\nProcessing parameter list\n"); } i = 0; fp = result->fpparms; /* ** read the entries of the directory file */ while(!feof(fp)){ /* ** read the line and extract the directory and clusterid information */ if(fgets(line,1000,fp) == NULL){ break; } if(line[0] == '%') continue; if(clusterdir[i].ignore){ i++; continue; } /* ** skip over the ignore character */ if(line[0] == '#'){ start = line+1; } else { start = line; } /* ** assume the cluster directory specification is of the ** form dir/???n where dir is a string not containing ** any additional path specifications */ ptr = start; while(strchr(ptr+1,'/') != NULL){ ptr = strchr(ptr+1,'/'); } if(*ptr != '/'){ fprintf(stderr, "ERROR: unable to parse directory from '%s' in dirfile\n", line); continue; } *ptr = '\0'; /* ** copy the directory portion of the string */ strcpy(dirname,start); /* ** compare with the existing cluster dir name */ if(strcmp(clusterdir[i].dirname,dirname) != 0){ fprintf(stderr, "ERROR: cluster/parameter directory mismatch '%s' '%s'\n", clusterdir[i].dirname,dirname); exit(-1); } /* ** then read the cluster number portion of the string ** assume the cluster index file specification is of the form ** ???n where n is the clusterid ** e.g. cl-1, cl-2, ... */ clusterid = ParseId(ptr+1); clusterdir[i].parameter = ParseParameter(ptr+1); /* ** compare with existing id */ if(clusterid != clusterdir[i].clusterid){ fprintf(stderr, "ERROR: cluster/parameter id mismatch '%s' '%s'\n", clusterdir[i].clusterid,clusterid); exit(-1); } if(verbose){ fprintf(stderr,"%d: Parameters for cluster %d in %s :\t%g\n", i,clusterdir[i].clusterid,clusterdir[i].dirname, clusterdir[i].parameter); } i++; } fclose(fp); } ReadClusterDirectory(result) Result *result; { int32_t i; char line[1001]; char *ptr; char *start; if(verbose){ fprintf(stderr,"\nProcessing cluster list\n"); } i = 0; /* ** read the entries of the directory file */ while(!feof(result->fpdir)){ /* ** read the line and extract the directory and clusterid information */ if(fgets(line,1000,result->fpdir) == NULL){ break; } if(line[0] == '%') continue; /* ** check for the ignore cluster character at the ** beginning of the line */ if((line[0] == '#') && (result->useallclusters != 1)){ clusterdir[i].ignore = 1; } else { /* ** implement fractional inclusion */ if((result->fraction > 0) && (frandom(0,1) >= result->fraction)){ clusterdir[i].ignore = 1; } else { clusterdir[i].ignore = 0; } } if(clusterdir[i].ignore){ i++; continue; } /* ** skip over the ignore character */ if(line[0] == '#'){ start = line+1; } else { start = line; } /* ** assume the cluster directory specification is of the ** form dir/???n where dir is a string not containing ** any additional path specifications */ ptr = start; while(strchr(ptr+1,'/') != NULL){ ptr = strchr(ptr+1,'/'); } if(*ptr != '/'){ fprintf(stderr, "ERROR: unable to parse directory from '%s' in dirfile\n", line); continue; } *ptr = '\0'; /* ** copy the directory portion of the string */ strcpy(clusterdir[i].dirname,start); /* ** then read the cluster number portion of the string ** assume the cluster index file specification is of the form ** ???n where n is the clusterid ** e.g. cl-1, cl-2, ... */ clusterdir[i].clusterid = ParseId(ptr+1); /* ** get the filename for use with the noprefix option */ strcpy(clusterdir[i].filename,ptr+1); if((ptr=strchr(clusterdir[i].filename,'\n')) != NULL){ *ptr = '\0'; } /* if(verbose){ fprintf(stderr,"%d: Cluster %d in %s\n", i,clusterdir[i].clusterid,clusterdir[i].dirname); } */ i++; } fclose(result->fpdir); result->nclusters = i; } ReadReconClusterDirectoryHeader(result,has_tstart,has_tend) Result *result; int32_t has_tstart; int32_t has_tend; { char **header; int32_t headersize; char *tstring; fseek(result->fpdirrecon,0L,0L); header = ReadHeader(result->fpdirrecon,&headersize); /* ** look for the start and end time parameters in the header */ if(!has_tstart && ((tstring = GetHeaderParameter(header,"Start time:")) != NULL) || ((tstring = GetHeaderParameter(header,"Start Time:")) != NULL) ){ if(verbose){ fprintf(stderr,"from recon cluster dir file, tstart=%s\n",tstring); } /* ** set the start time */ result->recontstart = ParseTimestamp(tstring); } if(!has_tend && ((tstring = GetHeaderParameter(header,"End time:")) != NULL) || ((tstring = GetHeaderParameter(header,"End Time:")) != NULL)){ if(verbose){ fprintf(stderr,"from recon cluster dir file, tend=%s\n",tstring); } /* ** set the end time */ result->recontend = ParseTimestamp(tstring); } if(verbose){ fprintf(stderr,"processing recon data from "); fprintf(stderr,"%s to ", TimestampToString(result->recontstart)); fprintf(stderr,"%s\n",TimestampToString(result->recontend)); } } ReadReconClusterDirectory(result) Result *result; { int32_t i; char line[1001]; char *ptr; char *start; if(verbose){ fprintf(stderr,"\nProcessing recon cluster list\n"); } i = 0; /* ** read the entries of the directory file */ while(!feof(result->fpdirrecon)){ /* ** read the line and extract the directory and clusterid information */ if(fgets(line,1000,result->fpdirrecon) == NULL){ break; } if(line[0] == '%') continue; /* ** check for the ignore cluster character at the ** beginning of the line */ if((line[0] == '#') && (result->useallclusters != 1)){ reconclusterdir[i].ignore = 1; } else { /* ** implement fractional inclusion */ if((result->fraction > 0) && (frandom(0,1) >= result->fraction)){ reconclusterdir[i].ignore = 1; } else { reconclusterdir[i].ignore = 0; } } if(reconclusterdir[i].ignore){ i++; continue; } /* ** skip over the ignore character */ if(line[0] == '#'){ start = line+1; } else { start = line; } /* ** assume the cluster directory specification is of the ** form dir/???n where dir is a string not containing ** any additional path specifications */ ptr = start; while(strchr(ptr+1,'/') != NULL){ ptr = strchr(ptr+1,'/'); } if(*ptr != '/'){ fprintf(stderr, "ERROR: unable to parse directory from '%s' in dirfile\n", line); continue; } *ptr = '\0'; /* ** copy the directory portion of the string */ strcpy(reconclusterdir[i].dirname,start); /* ** then read the cluster number portion of the string ** assume the cluster index file specification is of the form ** ???n where n is the clusterid ** e.g. cl-1, cl-2, ... */ reconclusterdir[i].clusterid = ParseId(ptr+1); /* ** get the filename for use with the noprefix option */ strcpy(reconclusterdir[i].filename,ptr+1); if((ptr=strchr(reconclusterdir[i].filename,'\n')) != NULL){ *ptr = '\0'; } /* if(verbose){ fprintf(stderr,"%d: Cluster %d in %s\n", i,reconclusterdir[i].clusterid,reconclusterdir[i].dirname); } */ i++; } fclose(result->fpdirrecon); result->nreconclusters = i; } ReadPositionDirectory(result) Result *result; { int32_t i; char line[1001]; char *ptr; char *start; /* ** read the entries of the position directory file */ if(verbose){ fprintf(stderr,"\nProcessing position list\n"); } i = 0; while(!feof(result->fppdir)){ /* ** read the line and extract the directory and clusterid information */ if(fgets(line,1000,result->fppdir) == NULL){ break; } if(line[0] == '%') continue; /* ** blow the CR at the end */ StripCR(line); /* ** check for the ignore cluster character at the ** beginning of the line */ if((line[0] == '#') && (result->useallclusters != 1)){ result->pdir[i].ignore = 1; } else { /* ** implement fractional inclusion ** by using the fraction established in the ** cluster list */ if(result->fraction > 0){ result->pdir[i].ignore = clusterdir[i].ignore; } } if(result->pdir[i].ignore){ i++; continue; } /* ** skip over the ignore character */ if(line[0] == '#'){ start = line+1; } else { start = line; } /* ** copy the path portion of the string */ strcpy(result->pdir[i].path,start); /* ** assume the cluster directory specification is of the ** form dir/?n where dir is a string not containing ** any additional path specifications */ ptr = start; while(strchr(ptr+1,'/') != NULL){ ptr = strchr(ptr+1,'/'); } if(*ptr != '/'){ fprintf(stderr, "ERROR: unable to parse directory from '%s' in dirfile\n", line); continue; } *ptr = '\0'; /* ** copy the directory portion of the string strcpy(result->pdir[i].dirname,start); */ /* ** then read the cluster number portion of the string ** assume the cluster index file specification is of the form ** ?n where n is the clusterid ** e.g. p1, p2, ... */ result->pdir[i].clusterid = ParseId(ptr+1); if(verbose){ fprintf(stderr,"%d: Spatial file %s : %d\n", i, result->pdir[i].path, result->pdir[i].clusterid); } i++; } fclose(result->fppdir); /* ** confirm that this is the same as the number of timestamp ** clusters */ if(result->nclusters != i){ fprintf(stderr, "ERROR: mismatch in cluster count for timestamps and positions\n"); exit(-1); } } ReadClusterDirectoryHeader(result,has_tstart,has_tend) Result *result; int32_t has_tstart; int32_t has_tend; { char **header; int32_t headersize; char *tstring; fseek(result->fpdir,0L,0L); header = ReadHeader(result->fpdir,&headersize); /* ** look for the start and end time parameters in the header */ if(!has_tstart && ((tstring = GetHeaderParameter(header,"Start time:")) != NULL) || ((tstring = GetHeaderParameter(header,"Start Time:")) != NULL) ){ if(verbose){ fprintf(stderr,"from cluster dir file, tstart=%s\n",tstring); } /* ** set the start time */ result->tstart = ParseTimestamp(tstring); } if(!has_tend && ((tstring = GetHeaderParameter(header,"End time:")) != NULL) || ((tstring = GetHeaderParameter(header,"End Time:")) != NULL)){ if(verbose){ fprintf(stderr,"from cluster dir file, tend=%s\n",tstring); } /* ** set the end time */ result->tend = ParseTimestamp(tstring); } if(verbose){ fprintf(stderr,"processing data from "); fprintf(stderr,"%s to ", TimestampToString(result->tstart)); fprintf(stderr,"%s\n",TimestampToString(result->tend)); } } WriteClusterStats(result) Result *result; { int32_t i; FILE *fp; if(result->fpstatout == NULL) return; for(i=0;i<result->nclusters;i++){ /* ** write out the firing rate of the cluster */ fprintf(result->fpstatout,"%d\t%g\t%d\t%d\n", i, (float)result->spikecount[i]/result->ntimebins, result->peakloc[i].x, result->peakloc[i].y); } } ProcessSpikeTrain(result) Result *result; { int32_t i,j; FILE *fp; if(result->fpspiketrainout == NULL) return; for(i=0;i<result->nclusters;i++){ for(j=0;j<result->spikecount[i];j++){ /* ** write out the firing rate of the cluster */ fprintf(result->fpspiketrainout,"%u\t%d\t%d\t%d\n", result->spikearray[i][j], i, result->peakloc[i].x, result->peakloc[i].y); } } }
C
#ifndef _STRMCH_ #define _STRMCH_ #include <string.h> int strmch_rk(char first[], char last[]) { int first_len = strlen(first), last_len = strlen(last), t = 1, l1 = 0, l2 = 0; for(int i = 0; i < last_len - 1; i++) t = (t * 0xff) % 123; for(int i = 0; i < last_len; i++) l1 = (l1 * 0xff + first[i]) % 123, l2 = (l2 * 0xff + last[i]) % 123; for(int i = 0, j = 0; i <= first_len - last_len; i++){ if(l1 == l2 && !strncmp(first + i, last, last_len)) return i; j = (l1 - first[i] * t) % 123; if(j < 0) j += 123; l1 = (j * 0xff + first[i + last_len]) % 123;} return (-1); } int strmch_mp(char first[], char last[]) { int t[0xff]; int first_len = strlen(first), last_len = strlen(last); *t = -1; for(int i = 1, j = -1; i < last_len; i++){ while(j >= 0 && last[j + 1] != last[i]) j = t[j]; if(last[j + 1] == last[i]) j++; t[i] = j;} for(int i = 0, j = -1; i < first_len; i++){ while(j >= 0 && last[j + 1] != first[i]) j = t[j]; if(last[j + 1] == first[i]) j++; if(j == last_len - 1) return i - last_len + 1;} return (-1); } #endif
C
/* Chris Zehr COP 3223C- 15Fal 0R04 Program 6 12/12/2015 */ /* Headers, Definitions, and Structs */ #include <stdio.h> #include <time.h> #include <stdlib.h> #include <string.h> //Number of items in game #define NUM_ITEMS 6 //Item enumeration enum Item { BLANKET, SADDLE, JACKET, HARNESS, GOGGLES, HELMET }; enum bool{ FALSE, TRUE }; //Item Strings ONLY FOR PRINTING const char * itemStrings[] = { "Blanket", "Saddle", "Jacket", "Harness", "Goggles", "Helmet" }; //Struct that stores game state struct dragonGame { int isRunning; int dragonRiders[6][6]; int numRiders; int winner; }; /* Function Declaration */ void init(struct dragonGame * myDragonGame); void update(struct dragonGame * myDragonGame); void close(struct dragonGame * myDragonGame); void takeTurn(int dragonRiderNumber, int dragonRider[NUM_ITEMS]); int processTurn(int dragonRiderNumber, int dragonRider[NUM_ITEMS]); /* Main */ int main(){ struct dragonGame DRAGON_SHED_RAID; /* Initialize game */ init(&DRAGON_SHED_RAID); /* Run Game */ update(&DRAGON_SHED_RAID); /* Shut Down */ close(&DRAGON_SHED_RAID); return 0; } /* Function Implementation */ // Pre-condition: myDragonGame is a pointer to a dragonGame struct that stores // the game state. // Post-condition: Random number generator is seeded, myDragonGame.isRunning // is set to 1, number of players is asked for and stored in numRiders, and // dragonRiders array is initialized to zero. void init(struct dragonGame * myDragonGame) { //Seed random number generator srand((unsigned) time(NULL)); //Game is now running myDragonGame->isRunning = TRUE; //Get number of players from user while(TRUE) { //Prompt user for number of players printf("How many dragonriders are raiding the equipment shed? (1-6)\n"); //Save number of players in numRiders scanf("%d", &myDragonGame->numRiders); if(myDragonGame->numRiders > 6 || myDragonGame->numRiders < 1) { printf("Please enter an integer between 1 and 6!\n"); } else break; } //Initialize dragonRiders array to all zero int i; int j; for(i = 0; i < myDragonGame->numRiders; i++) { for(j = 0; j < NUM_ITEMS; j++) { myDragonGame->dragonRiders[i][j] = 0; } } } // Pre-condition: init() has been run on the struct being passed in // Post-condition: Game is no longer running, and the winner has been stored // in myDragonGame->winner. void update(struct dragonGame * myDragonGame) { //Main game loop int i, itemCount, response; while(myDragonGame->isRunning) { //Cycle through each player for(i = 0; i < myDragonGame->numRiders; i++) { while(TRUE) { //Prompt user to take their turn printf("Rider %d, it is your turn. Enter '0' to look for an item.\n", i+1); scanf("%d", &response); if (response == 0) break; } //Get item, or get caught takeTurn(i, myDragonGame->dragonRiders[i]); //If this rider has 6 items if(processTurn(i, myDragonGame->dragonRiders[i]) == NUM_ITEMS) { //We have a winner! myDragonGame->winner = i; myDragonGame->isRunning = FALSE; break; } } } } // Pre-condition: update() has been run on the struct being passed in. // Post-condition: Winner data has been printed, program free to close. void close(struct dragonGame * myDragonGame) { //Print winner message printf("Congratulations Rider %d, you are the first dragon rider!\n\n", myDragonGame->winner + 1); //Print end game state int i; int j; printf("Dragonrider Array: \n\n"); for(i = 0; i < myDragonGame->numRiders; i++) { for(j = 0; j < NUM_ITEMS; j++) { printf(" %d ", myDragonGame->dragonRiders[i][j]); } printf("\n"); } printf("\n\n"); } // Pre-condition: Takes an array that represents the player's inventory and // an integer that tracks the current player. // Post-condition: Inventory is updated and ready to be processed. void takeTurn(int dragonRiderNumber, int dragonRider[NUM_ITEMS]) { int sumPlayerItems; int response; int i; //Get an integer between 0 and NUM_ITEMS int itemNum = rand() % (NUM_ITEMS + 1); //If the player was caught if(itemNum == NUM_ITEMS) { printf("You've been caught!\n"); sumPlayerItems = 0; //Loop through player inventory for(i = 0; i < NUM_ITEMS; i++) { //Count how many items they have sumPlayerItems += dragonRider[i]; } //If they have nothing if(sumPlayerItems == 0) printf("There is no equipment for you to lose. Lucky you, sort of"); //They have something else { //Prompt user for input printf("Which piece would you like to lose?\n\n"); //Loop through player inventory for(i = 0; i < NUM_ITEMS; i++) { //If they have the item, print if(dragonRider[i]) { //If they have a saddle, don't print blanket if(i == BLANKET && dragonRider[SADDLE]) { //Do nothing } //If they have a harness, don't print jacket else if(i == JACKET && dragonRider[HARNESS]) { //Do nothing } else { printf("%d. %s\n", i+1, itemStrings[i]); } } } scanf("%d", &response); //Pressing 0 here makes everything break. //Remove item from inventory dragonRider[response - 1] = 0; } } //The player was not caught else { printf("Rider %d, you found a %s\n", dragonRiderNumber+1, itemStrings[itemNum]); //If they already have this item if(dragonRider[itemNum]) printf("You already have that item\n"); //If new item is a saddle, and they don't have a blanket else if(itemNum == SADDLE && !dragonRider[BLANKET]) printf("Sorry, you can't obtain %s (You need a Blanket!)\n", itemStrings[itemNum]); //If the new item is a flight harness, and they don't have a jacket. else if(itemNum == HARNESS && !dragonRider[JACKET]) printf("Sorry, you can't obtain %s (You need a Jacket!)\n", itemStrings[itemNum]); //They're able to add this item to their inventory else { printf("Congrats, you now have a %s\n", itemStrings[itemNum]); dragonRider[itemNum] = 1; } } } // Pre-condition: dragonRider is the inventory of a player, should be // called immediately after a player takes their turn. // Post-condition: Rider inventory is printed, returns number of items // in the player's inventory. int processTurn(int dragonRiderNumber, int dragonRider[NUM_ITEMS]) { int i, itemCount; itemCount = 0; printf("Rider %d, here is what you currently have:\n\n", dragonRiderNumber+1); for(i = 0; i < NUM_ITEMS; i++) { //Count how many items this rider has itemCount += dragonRider[i]; //Print Inventory if(dragonRider[i] == 1) { printf("%d. %s\n", i+1, itemStrings[i]); } } printf("\n"); return itemCount; }
C
#include <sys/syscall.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> struct ancestry { pid_t ancestors[10]; pid_t siblings[100]; pid_t children[100]; }; #define __NR_cs3013_syscall2 378 int main(int argc, char *argv[]) { int a = 0; int s = 0; int c = 0; if (argc != 2) { printf("ERROR: Did not specify a PID\n"); return -1; } pid_t pid = atoi(argv[1]); struct ancestry *tree = malloc(sizeof(struct ancestry)); int ref = syscall(__NR_cs3013_syscall2, &pid, tree); if (ref) { perror("SysCall Failed\n"); return -1; } while(1) { if (tree->children[c] < 1) // no pid { break; } else { printf("Child [%d] PID: %d\n", (c+1), (int) tree->children[c]); c++; } } printf("\n~~~~~Siblings~~~~~\n"); while(1) { if (tree->siblings[s] < 1) //if no pid { break; } else { printf("Sibling [%d] PID: %d\n", (s+1), (int) tree->siblings[s]); s++; } } printf("\n~~~~~Ancestors~~~~~\n"); while(1) { if (tree->ancestors[a] < 1) { // if no pid break; } else { printf("Parent [%d] PID: %d\n", (a+1), (int) tree->ancestors[a]); a++; } } return 0; }
C
#ifndef __INC_CONFERENCE_H__ #define __INC_CONFERENCE_H__ #include <sqlite3.h> #include "data_list.h" #include "bowls.h" #include "team.h" #define CONFERENCE_TEAM_SENTINEL { -1, -1 } #define CONFERENCE_STATS_SENTINEL { -1, -1, bg_None, -1, -1, -1, -1, -1, -1, -1, -1 } #define CONFERENCE_ACCOLADE_SENTINEL { -1, -1, cacc_None } typedef enum { cacc_None = 0, cacc_CottonBowlChampions = 1, cacc_OrangeBowlChampions = 2, cacc_RoseBowlChampions = 3, cacc_SugarBowlChampions = 4, cacc_FiestaBowlChampions = 5, cacc_LibertyBowlChampions = 6, cacc_NCFOChampions = 7 } conference_accolade_e; typedef struct { int conference_id; int season; conference_accolade_e accolade; } conference_accolade_s; typedef struct { int conference_id; int season; bowl_game_e bowl_game; int wins; int losses; int home_wins; int home_losses; int road_wins; int road_losses; int points_scored; int points_allowed; } conference_stats_s; typedef struct { int conference_id; int team_id; team_s *team; } conference_team_s; typedef struct { int conference_id; char name [20 + 1]; conference_team_s *teams; conference_stats_s *stats; conference_accolade_s *accolades; } conference_s; int conferences_t_create( sqlite3 *db, const conference_s *conference ); int conferences_t_read( sqlite3 *db, conference_s *conference ); int conferences_t_update( sqlite3 *db, const conference_s *conference ); int conferences_t_delete( sqlite3 *db, const conference_s *conference ); int conference_teams_t_create( sqlite3 *db, const conference_team_s *conference_team ); int conference_teams_t_read_by_conference( sqlite3 *db, const int conference_id, data_list_s *conference_teams ); int conference_teams_t_delete( sqlite3 *db, const conference_team_s *conference_team ); int conference_stats_t_create( sqlite3 *db, const conference_stats_s *conference_stats ); int conference_stats_t_read( sqlite3 *db, conference_stats_s *conference_stats ); int conference_stats_t_read_by_conference( sqlite3 *db, const int conference_id, data_list_s *conference_stats ); int conference_stats_t_update( sqlite3 *db, const conference_stats_s *conference_stats ); int conference_stats_t_delete( sqlite3 *db, const conference_stats_s *conference_stats ); int conference_accolades_t_create( sqlite3 *db, const conference_accolade_s *conference_accolade ); int conference_accolades_t_read_by_conference( sqlite3 *db, const int conference_id, data_list_s *conference_accolades ); int conference_accolades_t_delete( sqlite3 *db, const conference_accolade_s *conference_accolade ); conference_s *get_conference( sqlite3 *db, const int conference_id ); int save_conference( sqlite3 *db, const conference_s *conference ); void free_conference( conference_s *conference ); #endif
C
#include <stdio.h> #include <fcntl.h> #include <sys/file.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <string.h> int main() { int rdfd, n; char buff[256]; while(1) { while((rdfd = open("NP1", O_RDONLY)) == -1) { printf("Cannot read yet \n"); sleep(1); } if(flock(rdfd, LOCK_EX | LOCK_NB) == 0) break; close(rdfd); } remove("NP1"); while((n = read(rdfd, buff, 256)) > 0) { buff[n] = '\0'; printf("Read buffer %s\n", buff); } close(rdfd); return 0; }
C
#include <stdio.h> #include <stdint.h> #include <inttypes.h> inline uint64_t rdmsr(uint32_t msr_id) { uint64_t msr_value; asm volatile ( "rdmsr" : "=A" (msr_value) : "c" (msr_id) ); return msr_value; } void show_smram() { uint64_t rdmsr1 = rdmsr(0xc0000010); uint64_t rdmsr2 = rdmsr(0xc0010111); printf("0xc0000010 : %" PRIu64 "\n", rdmsr1); printf("0xc0010111 : %" PRIu64 "\n", rdmsr2); return; } int main() { printf("yonggon's smm interface\n"); // TODO // 1. SMI handler implementation // 2. SMI handler register // 3. SMI call interface // 4. SMRAM status monitoring show_smram(); return 0; }
C
#include <stdio.h> int main(void) { int w; int h; printf("ڡڡڡڻ簢 ϱڡڡڡ\n\n"); printf("ʺ Է:"); scanf_s("%d", &w); printf(" Է:"); scanf_s("%d", &h); printf(" = %d\n", w*h); system("pause"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* option.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fcapocci <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/01/27 18:30:17 by fcapocci #+# #+# */ /* Updated: 2016/02/28 19:32:43 by fcapocci ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ls.h" t_opt *creat_elem(t_opt *optl, char o) { t_opt *new; new = NULL; if (check_option(o) == 1) { if ((new = (t_opt*)ft_memalloc(sizeof(t_opt))) == NULL) return (NULL); if (!optl) optl = new; else { while (optl->next) optl = optl->next; optl->next = new; } new->c = o; new->next = NULL; if (o == 'n' || o == 'f') { new->next = (o == 'n' ? creat_elem(new->next, 'l') : creat_elem(new->next, 'a')); return (new); } } return (new); } int take_option(t_opt **optl, int *argc, char ***argv) { t_opt *optlist; int i; (*optl) = NULL; optlist = NULL; while ((*argc) > 1) { (*argv)++; if ((***argv != '-') || (***argv == '-' && !(**argv)[1])) { break ; } else if (***argv == '-') { i = 1; while ((**argv)[i]) { optlist = creat_elem(optlist, (**argv)[i++]); if (!(*optl)) (*optl) = optlist; } } (*argc)--; } return (0); } int check_option(char o) { if (o == 'l') return (1); if (o == 'r') return (1); if (o == 't' || o == 'f') return (1); if (o == 'a') return (1); if (o == 'R') return (1); if (o == 'G') return (1); if (o == 'g') return (1); if (o == 'o') return (1); if (o == 'n') return (1); else { illegal_option(o); exit(-1); } return (0); } int op_ok(t_opt *optl, char o) { while (optl) { if (optl->c == o) return (1); optl = optl->next; } return (0); }
C
#include "libft.h" /** * compares n bytes of memory chunks. returns 0 if the parcels are identical. * returns 1 if differing bytes and * s1 > * s2 are encountered. otherwise -1 **/ int ft_memcmp(const void *s1, const void *s2, size_t n) { size_t i; unsigned char *ss1; unsigned char *ss2; i = 0; ss1 = (unsigned char *)s1; ss2 = (unsigned char *)s2; if (n == 0 || s1 == s2) return (0); while (i < n) { if (ss1[i] != ss2[i]) return (ss1[i] - ss2[i]); i++; } return (0); }
C
#include "lecture.h" /*BUT : -Lire le document de donnée afin d'extraire et reconnaitre ACr, DCr, ACir et DCir -Recadrer les composantes alternatives ACr et ACir autour de 0 -retourne struct type absorp(.acr, .acir, .dcr et .dcir) -ignore les lignes corrompues ->à la fin de la lecture du fichier la variable d'état passe à EOF ->Fichier test d'entrée à utiliser : record1_bin.dat*/ absorp lecture(FILE* file_pf, int* file_state){ //Initialisations des variables absorp myAbsorp; myAbsorp.acr = 0; myAbsorp.acir = 0; myAbsorp.dcr = 0; myAbsorp.dcir = 0; int a=0,b=0,c=0,d=0; char chaine[25]; int corrompu = 1; //Vérification des lignes corrompues et lecture du fichier while (corrompu == 1){ int nb = 0; //Lecture ligne à ligne du fichier fgets(chaine, 25, file_pf); //Mise à EOF de l'état lorsque le fichier à fini d'être lu if (feof(file_pf)){ *file_state=EOF; return myAbsorp; } //Initialisation de l'élément séparant ACr,DCr,ACir et DCir char delim[] = ","; //Initialisation du pointeur permettant de séparer la chaine lu en ACr,DCr,ACir et DCir char* ptr = strtok(chaine, delim); //Séparation de la ligne en ACr,DCr,ACir et DCir (respectivement a, b, c et d) while(ptr != NULL){ if(nb == 0){ a = atoi(ptr) ; }else if (nb == 1) { b = atoi(ptr); }else if (nb == 2) { c = atoi(ptr); }else if (nb == 3) { d = atoi(ptr); } //Mise à jour du pointeur ptr = strtok(NULL, delim); //incrémentation de nb (nombre d'élément lu sur la ligne - a,b,c ou d) nb ++; } //Sortie de la boucle si la ligne n'est pas corrompue if (nb == 4){ printf("ligne pas corrompue\n"); corrompu = 0; //Ignorement de la ligne si la ligne est corrompue }else{ printf("ligne corrompue\n"); } } //Calcul du nombre utilisé pour centré ACr et ACir int centre = 4096/2; //Initialisation de myabsorp avec les valeurs lu et le centrage appliqué myAbsorp = init_myabsorp (a, b, c, d, centre); //Renvoie de myabsorb mis à jour return myAbsorp; //return EOF flag } //Fonctin centrant et initialisant les valeurs de myabsorp absorp init_myabsorp(int a,int b,int c,int d, int centre){ absorp myAbsorp; myAbsorp.acir = c - centre; myAbsorp.acr = a - centre; myAbsorp.dcir =d; myAbsorp.dcr = b; return myAbsorp; }
C
#include<stdio.h> #include<stdlib.h> typedef struct nodo{ int n; struct nodo *next; }nodo; void imprime_lista(nodo *head); nodo* final (nodo *head); void adiciona(nodo *head,int valor); void elimina(nodo *head, int v); int main(int argc, char const *argv[]) { int x; nodo *head = (nodo*) malloc(sizeof(nodo)); head->next = NULL; adiciona(head,3); adiciona(head,4); adiciona(head,2); adiciona(head,4); adiciona(head,2); printf("--LISTA ENCADEADA -- : \n"); imprime_lista(head); printf("Apagar ocorrência de: \n"); scanf("%d",&x); elimina(head,x); printf("--LISTA SEM OCORRÊNCIAS DE %d--\n",x ); imprime_lista(head); free(head); return 0; } void adiciona(nodo *head,int valor){ nodo *novo = (nodo*) malloc(sizeof(nodo)); nodo *fim_lista; novo->n = valor; fim_lista = final(head); fim_lista->next = novo;//final é uma função que acha o final da lista que começa em head novo->next = NULL;//sempre adiciona no final } nodo* final (nodo *head){ nodo *count; for(count = head;count->next!=NULL;count=count->next); return count; } void elimina(nodo *head, int v){ nodo *count,*anterior; count = head->next; for(count = head->next,anterior=head;count!=NULL;){ if(count->n==v){ anterior->next = count->next; //free(count); count = anterior; } count= count->next; anterior=anterior->next; } } void imprime_lista(nodo *head){ nodo *count; printf("[ "); for(count = head->next;count!=NULL;count=count->next){ printf(" %d ",count->n); } printf(" ]\n"); }
C
// // Created by lukas on 10.01.2019. // #ifndef STACK_H #define STACK_H typedef struct StackNodeStruct { void * value; struct StackNodeStruct* node; } StackNode; typedef struct { StackNode* node; unsigned int size; } Stack; // Prototypes StackNode* stack_node_create(void*, StackNode*); void stack_node_destroy(StackNode*); Stack* stack_create(); int stack_destroy(Stack*); void stack_push(Stack*, void *); void* stack_pop(Stack*); void* stack_peek(Stack*); unsigned int stack_size(Stack*); #endif //STACK_H
C
#include "xlq_common.h" #include <stdio.h> #include "redismodule.h" int no = 0; int addNum = 0; int delNum = 0; void* xlq_malloc(size_t _size) { no++; addNum++; return RedisModule_Alloc(_size); } void* xlq_calloc(size_t __nmemb, size_t __size) { no++; addNum++; return RedisModule_Calloc(__nmemb, __size); } void xlq_free(void* p) { no--; delNum++; RedisModule_Free(p); } void xlq_get_meminfo(int* _no, int* _addNum, int* _delNum) { *_no = no; *_addNum = addNum; *_delNum = delNum; } void xlq_print_memNO() { printf("\ncurrNum=%d\n", no); printf("\naddNum=%d\n", addNum); printf("\ndelNum=%d\n", delNum); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: amelihov <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/11/26 17:00:40 by amelihov #+# #+# */ /* Updated: 2018/03/30 16:15:24 by amelihov ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" static int modified_strdel(char **str) { ft_strdel(str); return (0); } static int pop_line(char *buff, char **line) { int i; char *s; int res; i = 0; while (buff[i] && buff[i] != '\n') i++; res = buff[i]; buff[i] = '\0'; if (!(s = ft_strjoin(*line ? *line : "", buff))) return (-1); if (*line) free(*line); *line = s; if (i == BUFF_SIZE) buff[0] = '\0'; else { ft_memmove(buff, buff + i + 1, BUFF_SIZE - (i + 1)); buff[BUFF_SIZE - (i + 1)] = '\0'; } return (res); } int get_next_line(const int fd, char **line) { int ret; int res; static t_gnl_data data[NFDS]; int i; if (fd < 0 || !line || BUFF_SIZE <= 0 || NFDS <= 0 || (*line = NULL)) return (-1); i = 0; while (i < NFDS && data[i].fd != 0 && data[i].fd != fd + 1) i++; if (i == NFDS) return (-1); data[i].fd = fd + 1; while ((res = pop_line(data[i].buff, line)) == '\0') { if ((ret = read(data[i].fd - 1, data[i].buff, BUFF_SIZE)) < 0) return (-1); data[i].buff[ret] = '\0'; if (ret == 0) return (**line != '\0' ? 1 : modified_strdel(line)); } return (res == -1 ? -1 : 1); }
C
#include <sys/types.h> #include <sys/socket.h> #include <iostream> #include <string> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <netdb.h> #include <time.h> #include <stdint.h> using namespace std; int64_t nano_count() { struct timespec t; int ret; ret = clock_gettime(CLOCK_MONOTONIC,&t); if(ret != 0) cout<<"clock_gettime failed"<<endl; return t.tv_sec * 1000000000 + t.tv_nsec; } int main(int argc, char **argv ){ char* host_addr = argv[2]; int host_port = atoi(argv[1]); int num_packets = atoi(argv[4]); int my_port = atoi(argv[3]); int recvlen; char* buf = "1"; int s; int buf_size = 30; struct sockaddr_in remaddr; struct sockaddr_in myaddr; struct sockaddr_in servaddr; socklen_t addrlen = sizeof(remaddr); if( (s = socket(AF_INET, SOCK_DGRAM, 0)) <0){ cout<<"socket failed"<<endl; return 0; } memset((char *)&myaddr, 0, sizeof(myaddr)); myaddr.sin_family = AF_INET; myaddr.sin_addr.s_addr = htonl(INADDR_ANY); myaddr.sin_port = htons(my_port); if (bind(s, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) { cout<<"bind failed"<<endl; return 0; } struct hostent *hp; char *my_message = "1"; memset((char*)&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(host_port); hp = gethostbyname(host_addr); if (!hp) { cout<<"gethostbyname failed"<<endl; return 0; } memcpy((void *)&servaddr.sin_addr, hp->h_addr_list[0], hp->h_length); int64_t time_start; int64_t time_end; for(int i=0;;i++){ time_start = nano_count(); if (sendto(s, buf, recvlen, 0, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0){ cout<<"sendto failed"<<endl; return 0; }else{ recvfrom(s, buf, buf_size, 0, (struct sockaddr *)&remaddr, &addrlen); time_end = nano_count(); // cout<<"this took "<<time_end-time_start<<" nanoseconds"<<endl; cout<<(time_end-time_start)/1000<<endl; // cout<<(time_end-time_start)/1000000<<" milliseconds"<<endl; // cout<<(time_end-time_start)/1000000000<<" seconds"<<endl; } } }
C
#include <stdio.h> #include <unistd.h> #include <signal.h> #include <stdlib.h> void handler(int sig); int main(int argc, char* argv[]) { signal(SIGINT,handler); printf("SLeep begins!!\n"); sleep(1000); printf("Wake up!"); return 0; } void handler(int sig) { if(sig == SIGINT) printf("Handler is called.\n"); exit(1); }
C
/*-------------------------------------------------------------------------* *--- ---* *--- prof.c ---* *--- ---* *--- ---- ---- ---- ---- ---- ---- ---- ---- ---* *--- ---* *--- Version 1a 2020 February 2 Joseph Phillips ---* *--- ---* *-------------------------------------------------------------------------*/ #include "sleepyProfHeaders.h" // PURPOSE: To hold '1' while class still is in session, or '0' after class // is over. int isStillClassTime = 1; // PURPOSE: To hold '2' when the prof is quite awake, '1' when the prof is // about to fall asleep, or '0' when the prof is asleep. int awakeLevel = 2; // PURPOSE: To hold the process id number of the student (child) process. pid_t studentPid; // PURPOSE: To tell how many facts are known for each subject. #define NUM_FACTS_PER_SUBJECT 4 // PURPOSE: To tell the physics facts. const char* PHYSICS_KNOWLEDGE[NUM_FACTS_PER_SUBJECT] = { "F = m*a is a special case of F = dp/dt = m*dv/dt + v*dm/dt" " when dm/dt = 0.", "Fermions have 1/2 spin and cannot occupy the same quantum" " state, Bosons have integer spin and can occupy the same" " quantum state.", "The electron-electron repulsion between atoms and molecules" " supports the structure of most matter at our scale. If " "gravity overcomes this electron repulsion, then electrons " "collapse into the nucleus and matter becomes a neutron " "star.", "There is a large Black hole at the center of our galaxy." }; // PURPOSE: To tell the chemistry facts. const char* CHEMISTRY_KNOWLEDGE[NUM_FACTS_PER_SUBJECT] = {"In SN2 reactions, the nucleophile puts electron density into" " the anti-bonding orbital of leaving group, thus weakening" " the bond between the leaving group and the substrate.", "The transition state of a reaction is the configuration of " "highest energy.", "The activation energy between the reactants and the " "transition state determines the rate of reaction", "The Diels-Alder reaction is a popular way to make cyclic " "compounds with atoms other than carbon." }; // PURPOSE: To tell the biology facts. const char* BIOLOGY_KNOWLEDGE[NUM_FACTS_PER_SUBJECT] = {"Allopatric speciation happens when some geological barrier " "forms in the range of a species. The barrier prevents " "genetic interchange and the previous single species can turn" " into two or more by genetic drift and different selective" " pressures.", "A classic case of Allopatric speciation is with chimpanzees" " north of the Congo river and Bonobos south of it.", "The Hox genes control body plan of an embryo from head to " "tail in creatures as diverse from earthworms to fruit flies " "to humans. That implies we all had a common ancestor " "hundreds of millions of years ago.", "The Krebs cycle is very important because it is how all " "known aerobic organisms turn carbohydrates, fats and protein" " into energy." }; // PURPOSE: To make the professor wake up after receiving the COMPLAIN_SIGNAL. // If the signal comes from the dean then sets 'awakeLevel = 2' and // prints: // "Prof \"(Oops! The Dean caught me sleeping on the job!)\"\n" // "Prof \"Now as I was saying . . .\"\n" // // If the signal *merely* comes from the student then sets 'awakeLevel = 1' // and prints: // "Prof \"Huh? What? Oops! I must have fallen asleep!\"\n" // "Prof \"Now as I was saying . . .\"\n". void wakeUpHandler (int sigNum, siginfo_t* infoPtr, void* vPtr ) { if (infoPtr->si_pid == getppid()) { awakeLevel = 2; printf("Prof \"(Oops! The Dean caught me sleeping on the job!)\"\n"); printf("Prof \"Now as I was saying . . .\"\n"); } else if(infoPtr->si_pid == studentPid) { awakeLevel = 1; printf("Prof \"Huh? What? Oops! I must have fallen asleep!\"\n"); printf("Prof \"Now as I was saying . . .\"\n"); } } // PURPOSE: To make this process stop by setting 'isStillClassTime = 0', // and to tell the student process to stop by sending it // CLASS_DISMISSED_SIGNAL. Also prints: // "Prof \"Class dismissed!\"\n" void classDismissedHandler (int sigNum ) { printf("Prof \"Class dismissed!\"\n"); kill(studentPid, CLASS_DISMISSED_SIGNAL); isStillClassTime = 0; } // PURPOSE: To install 'wakeUpHandler()' for 'COMPLAIN_SIGNAL' and // 'classDismissedHandler()' for 'CLASS_DISMISSED_SIGNAL'. void installHandlers () { struct sigaction act; memset(&act,'\0',sizeof(act)); act.sa_flags= SA_SIGINFO | SA_RESTART; act.sa_sigaction = wakeUpHandler; sigaction(COMPLAIN_SIGNAL,&act,NULL); act.sa_handler = classDismissedHandler; sigaction(CLASS_DISMISSED_SIGNAL,&act,NULL); } // PURPOSE: To print the lesson, and to send 'PROF_TEACH_SIGNAL' to the // student. void teach (pid_t studentPid, subject_ty subject ) { const char** cPtrPtr; switch (subject) { case PHYSICS_SUBJECT : cPtrPtr = PHYSICS_KNOWLEDGE; break; case CHEMISTRY_SUBJECT : cPtrPtr = CHEMISTRY_KNOWLEDGE; break; case BIOLOGY_SUBJECT : cPtrPtr = BIOLOGY_KNOWLEDGE; break; } printf("Prof \"%s\"\n",cPtrPtr[rand() % NUM_FACTS_PER_SUBJECT]); kill(studentPid, PROF_TEACH_SIGNAL); } // PURPOSE: To send the 'PROF_SNORE_SIGNAL' to the student. void snore (pid_t studentPid ) { printf("Prof SNORE \n"); kill(studentPid, PROF_SNORE_SIGNAL); } // PURPOSE: To start the student (child) process. The child runs // 'STUDENT_PROGRAM' with the command line argument 'text' (telling the // process id of the dean). It prints // "Student \"I cannot find my classroom!\"\n" // and does: // exit(EXIT_FAILURE); // The parent process returns the process id of the student child process. pid_t obtainStudent () { char text[MAX_LINE]; pid_t childPid; snprintf(text,MAX_LINE,"%d",getppid()); childPid = fork(); if(childPid == 0) { execl(STUDENT_PROGRAM,STUDENT_PROGRAM,text,NULL); exit(EXIT_FAILURE); } return(childPid); } // PURPOSE: To do the work of the professor. Returns 'EXIT_SUCCESS'. int main (int argc, char* argv[] ) { subject_ty subject; struct sigaction act; srand(getpid()); installHandlers(); if ( (argc < 2) || ( (subject = getSubjectFromName(argv[1])) == NO_SUBJECT) ) { printf("Prof \"I don't know which course I'm teaching, I quit!\"\n"); exit(EXIT_FAILURE); } studentPid = obtainStudent(); while (isStillClassTime) { if (awakeLevel > 0) { teach(studentPid,subject); if ( ((rand() % 1024) / 1024.0) < PROF_FALL_ASLEEP_PROB ) { awakeLevel--; } } else { snore(studentPid); } sleep(1); } return(EXIT_SUCCESS); }
C
#include <stdio.h> int soma(); int main(int argc, char const *argv[]) { int N = 6, somatorio = 0; somatorio = soma(N); printf("%d\n",somatorio ); return 0; } int soma(int n){ int s; if (n==0) return 0; else s = n + soma(n-1); return s; }
C
#include <stdio.h> #include <string.h> int majorityElement(int* nums, int numsSize){ int max = 0; int index = -1; for(int i = 0; i < numsSize-1; i++){ int count = 0; for(int j = i+1; j < numsSize; j++){ if(nums[i] == nums[j]){ count++; } } if(count > max){ max = count; index = i; } } return nums[index]; }
C
#include <stdio.h> int main(){ int n; while(scanf("%d",&n)!=EOF){ int max = 0, len = 0, last = -1; while(n != 0){ if(n & 1 == 1){ if(last == 1) len++; else len = 1; max = max > len ? max : len; } last = n & 1; n >>= 1; } printf("%d\n", max); } return 0; }
C
#include <types.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <vfs/fs.h> #include <kserv.h> #include <syscall.h> static int start_vfsd() { printf("start vfs service ... "); int pid = fork(); if(pid == 0) { exec("/sbin/vfsd"); } kserv_wait("kserv.vfsd"); printf("ok.\n"); return 0; } static int mount_root() { printf("mount root fs from sdcard ...\n"); int pid = fork(); if(pid == 0) { exec("/sbin/dev/sdcard"); } kserv_wait("dev.sdcard"); printf("root mounted.\n"); return 0; } static int read_line(int fd, char* line, int sz) { int i = 0; while(i<sz) { char c; if(read(fd, &c, 1) <= 0) { line[i] = 0; return -1; } if(c == '\n') { line[i] = 0; break; } line[i++] = c; } return i; } static int run_init_procs(const char* fname) { int fd = open(fname, 0); if(fd < 0) return -1; char cmd[CMD_MAX]; int i = 0; while(true) { i = read_line(fd, cmd, CMD_MAX-1); if(i < 0) break; if(i == 0) continue; int pid = fork(); if(pid == 0) { exec(cmd); } } close(fd); return 0; } static void session_loop() { while(1) { int pid = fork(); if(pid == 0) { exec("/sbin/session"); } else { wait(pid); } } } int main() { if(getpid() > 0) { printf("Panic: 'init' process can only run at boot time!\n"); return -1; } start_vfsd(); mount_root(); run_init_procs("/etc/init/init.dev"); run_init_procs("/etc/init/init.rd"); /*set uid to root*/ syscall2(SYSCALL_SET_UID, getpid(), 0); /*run 2 session for uart0 and framebuffer based console0*/ int pid = fork(); if(pid == 0) { setenv("STDIO_DEV", "/dev/console0"); init_stdio(); exec("/sbin/session"); return 0; } else { setenv("STDIO_DEV", "/dev/tty0"); session_loop(); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include "zmalloc.h" #define PREFIX_SIZE sizeof(size_t) // 已锁形式增加统计 #define update_zmalloc_stat_add(_n) do{ \ pthread_mutex_lock(&used_memory_mutex); \ used_memory += _n; \ pthread_mutex_unlock(&used_memory_mutex); \ }while(0) // 已锁形式减少统计 #define update_zmalloc_stat_sub(_n) do{ \ pthread_mutex_lock(&used_memory_mutex); \ used_memory -= _n; \ pthread_mutex_unlock(&used_memory_mutex); \ }while(0) // 字节对齐,增加使用量统计 #define update_zmalloc_stat_alloc(__n) do{ \ size_t _n = (__n); \ if (_n&(sizeof(long)-1)) _n += sizeof(long) - (_n&(sizeof(long)-1)); \ if (zmalloc_thread_safe) { \ update_zmalloc_stat_add(_n); \ } else { \ used_memory += _n; \ } \ }while(0) // 字节对齐,减少使用量统计 #define update_zmalloc_stat_free(__n) do{ \ size_t _n = (__n); \ if (_n&(sizeof(long)-1)) _n += sizeof(long) - (_n&(sizeof(long)-1)); \ if (zmalloc_thread_safe) { \ update_zmalloc_stat_sub(_n); \ } else { \ used_memory -= _n; \ } \ }while(0) static void zmalloc_default_oom(size_t size) { fprintf(stderr,"zmalloc:out of memory trying to allocate %lu bytes\n",size); fflush(stderr); abort(); } static void (*zmalloc_oom_handler)(size_t) = zmalloc_default_oom; static size_t used_memory = 0; static int zmalloc_thread_safe = 0; pthread_mutex_t used_memory_mutex = PTHREAD_MUTEX_INITIALIZER; void *zmalloc(size_t size){ // 申请内存 void *ptr = malloc(size+PREFIX_SIZE); if (!ptr) zmalloc_oom_handler(size); // 记录内存大小 *((size_t*)ptr) = size; // 内存使用量统计增加 update_zmalloc_stat_alloc(size+PREFIX_SIZE); // 返回首地址 return (char*)ptr+PREFIX_SIZE; } void *zcalloc(size_t size){ // 申请内存 void *ptr = calloc(1,size+PREFIX_SIZE); if (!ptr) zmalloc_oom_handler(size); // 记录内存大小 *((size_t*)ptr) = size; // 内存使用量统计增加 update_zmalloc_stat_alloc(size+PREFIX_SIZE); // 返回首地址 return (char*)ptr+PREFIX_SIZE; } void *zrealloc(void *ptr,size_t size){ // 内存的真是地址,原地址内存空间大小 void *newptr,*realptr; size_t oldsize; if (ptr == NULL) return zmalloc(size); realptr = (char*)ptr-PREFIX_SIZE; oldsize = *((size_t*)realptr); // 重新分配内存 newptr = realloc(realptr,size+PREFIX_SIZE); if (!newptr) zmalloc_oom_handler(size); *((size_t*)newptr) = size; // 减少原内存大小,增加新内存大小 update_zmalloc_stat_free(oldsize); update_zmalloc_stat_free(size); return (char*)newptr+PREFIX_SIZE; } void zfree(void *ptr){ void *realptr; size_t size; if (ptr == NULL) return; realptr = (char*)ptr-PREFIX_SIZE; size = *((size_t*)realptr); // 减少内存使用量统计 update_zmalloc_stat_free(size+PREFIX_SIZE); // 释放 free(realptr); }
C
/* LibTomCrypt, modular cryptographic library -- Tom St Denis * * LibTomCrypt is a library that provides various cryptographic * algorithms in a highly modular and flexible manner. * * The library is free for all purposes without any express * guarantee it works. */ #include "tomcrypt_private.h" /** @file hmac_init.c HMAC support, initialize state, Tom St Denis/Dobes Vandermeer */ #ifdef LTC_HMAC #define LTC_HMAC_BLOCKSIZE hash_descriptor[hash].blocksize /** Initialize an HMAC context. @param hmac The HMAC state @param hash The index of the hash you want to use @param key The secret key @param keylen The length of the secret key (octets) @return CRYPT_OK if successful */ int hmac_init(hmac_state *hmac, int hash, const unsigned char *key, unsigned long keylen) { unsigned char *buf; unsigned long hashsize; unsigned long i, z; int err; LTC_ARGCHK(hmac != NULL); LTC_ARGCHK(key != NULL); /* valid hash? */ if ((err = hash_is_valid(hash)) != CRYPT_OK) { return err; } hmac->hash = hash; hashsize = hash_descriptor[hash].hashsize; /* valid key length? */ if (keylen == 0) { return CRYPT_INVALID_KEYSIZE; } /* allocate ram for buf */ buf = XMALLOC(LTC_HMAC_BLOCKSIZE); if (buf == NULL) { return CRYPT_MEM; } /* check hash block fits */ if (sizeof(hmac->key) < LTC_HMAC_BLOCKSIZE) { err = CRYPT_BUFFER_OVERFLOW; goto LBL_ERR; } /* (1) make sure we have a large enough key */ if(keylen > LTC_HMAC_BLOCKSIZE) { z = LTC_HMAC_BLOCKSIZE; if ((err = hash_memory(hash, key, keylen, hmac->key, &z)) != CRYPT_OK) { goto LBL_ERR; } keylen = hashsize; } else { XMEMCPY(hmac->key, key, (size_t)keylen); } if(keylen < LTC_HMAC_BLOCKSIZE) { zeromem((hmac->key) + keylen, (size_t)(LTC_HMAC_BLOCKSIZE - keylen)); } /* Create the initialization vector for step (3) */ for(i=0; i < LTC_HMAC_BLOCKSIZE; i++) { buf[i] = hmac->key[i] ^ 0x36; } /* Pre-pend that to the hash data */ if ((err = hash_descriptor[hash].init(&hmac->md)) != CRYPT_OK) { goto LBL_ERR; } if ((err = hash_descriptor[hash].process(&hmac->md, buf, LTC_HMAC_BLOCKSIZE)) != CRYPT_OK) { goto LBL_ERR; } LBL_ERR: #ifdef LTC_CLEAN_STACK zeromem(buf, LTC_HMAC_BLOCKSIZE); #endif XFREE(buf); return err; } #endif /* ref: HEAD -> develop */ /* git commit: 9c0d7085234bd6baba2ab8fd9eee62254599341c */ /* commit time: 2018-10-15 10:51:17 +0200 */
C
#include <stdio.h> #include <stdlib.h> #include "Stack.c" int main(){ Pila *p = crearPila(); printf("\nSe van a apilar 3 elementos al stack\n"); for(int k=0;k<3;k++){ push(p, crearDatos(2*k)); printf("Valor tope: %i\n", p->tope->datos->d); } printf("\nDesapilamos los elementos\n"); while(p->tope != NULL){ printf("Valor tope: %i\n", p->tope->datos->d); pop(p); } freePila(p); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* stack_making.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lschambe <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/09 18:56:24 by lschambe #+# #+# */ /* Updated: 2019/03/29 20:49:14 by lschambe ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" void stackadd(t_stack **alst, t_stack *ne) { t_stack *temp; temp = *alst; while (temp->next) temp = temp->next; temp->next = ne; } t_stack *stacknew(int num) { t_stack *st; st = (t_stack*)malloc(sizeof(t_stack)); if (!st) return (NULL); st->n = num; st->next = NULL; return (st); } void print_stack(t_stack *a) { while (a) { printf("%d\n", a->n); a = a->next; } printf("\n"); } int check_list(t_stack *a) { t_stack *head; t_stack *temp; int counter; head = a; while (a) { temp = head; counter = 0; while (temp) { if (a->n == temp->n) counter++; temp = temp->next; } if (counter > 1) return (0); a = a->next; } return (1); } void free_list(t_stack **a) { t_stack *temp; while ((*a)) { temp = *a; (*a) = (*a)->next; free(temp); } }
C
#include<stdio.h> #include<math.h> #include<string.h> long long f[1301]; void fibo(){ f[0] = 0; f[1] = 1; int i; for(i = 2; i <= 1300; i++){ f[i] = f[i - 1] + f[i - 2]; } } void bai_lam(){ int n,i; scanf("%d", &n); int kq = 0; for(i = 0; i < n; i++){ printf("%lld ", f[i]); } } int main(){ fibo(); //int a; scanf("%d", &a); //while(a--){ bai_lam(); //} return 0; }
C
#include <ApplicationServices/ApplicationServices.h> #include <stdio.h> #include<stdio.h> //printf #include<string.h> //memset #include<stdlib.h> //exit(0); #include<arpa/inet.h> #include<sys/socket.h> #define SERVER "127.0.0.1" #define BUFLEN 512 //Max length of buffer #define PORT 33334 //The port on which to send data struct sockaddr_in si_other; int s, i, slen=sizeof(si_other); char buf[BUFLEN]; char message[BUFLEN]; void bye(void) { close(s); } void die(char *s) { perror(s); exit(1); } char * convertKeyCode(int keyCode) { printf("keyCode: %d\n", keyCode); // Proper key detection seems to want a switch statement, unfortunately switch (keyCode) { case 0: return("a"); case 1: return("s"); case 2: return("d"); case 3: return("f"); case 4: return("h"); case 5: return("g"); case 6: return("z"); case 7: return("x"); case 8: return("c"); case 9: return("v"); // what is 10? case 11: return("b"); case 12: return("q"); case 13: return("w"); case 14: return("e"); case 15: return("r"); case 16: return("y"); case 17: return("t"); case 18: return("1"); case 19: return("2"); case 20: return("3"); case 21: return("4"); case 22: return("6"); case 23: return("5"); case 24: return("="); case 25: return("9"); case 26: return("7"); case 27: return("-"); case 28: return("8"); case 29: return("0"); case 30: return("]"); case 31: return("o"); case 32: return("u"); case 33: return("["); case 34: return("i"); case 35: return("p"); case 36: return("Enter"); case 37: return("l"); case 38: return("j"); case 39: return("'"); case 40: return("k"); case 41: return(";"); case 42: return("\\"); case 43: return(","); case 44: return("/"); case 45: return("n"); case 46: return("m"); case 47: return("."); case 48: return("Tab"); case 49: return("Space"); case 50: return("`"); case 51: return("Delete"); case 52: return("Enter"); case 53: return("ESC"); case 54: return ("RCommand");//Right case 55: return ("LCommand");//Left case 56: return ("LShift");//Left case 57: return ("CapsLock"); case 58: return ("LOption");//Left case 59: return ("Ctrl"); case 60: return ("RShift");//Right case 61: return ("ROption");//Right case 63: return ("FN"); case 65: return("."); case 67: return("*"); case 69: return("+"); case 75: return("/"); case 76: return("Enter"); // numberpad on full kbd case 78: return("-"); case 81: return("="); case 82: return("0"); case 83: return("1"); case 84: return("2"); case 85: return("3"); case 86: return("4"); case 87: return("5"); case 88: return("6"); case 89: return("7"); case 91: return("8"); case 92: return("9"); case 96: return("F5"); case 97: return("F6"); case 98: return("F7"); case 99: return("F3"); case 100: return("F8"); case 101: return("F9"); case 103: return("F11"); case 105: return("F13"); case 107: return("F14"); case 109: return("F10"); case 111: return("F12"); case 113: return("F15"); case 114: return("HELP"); case 115: return("HOME"); case 116: return("PGUP"); case 117: return("DELETE"); // full keyboard right side numberpad case 118: return("F4"); case 119: return("END"); case 120: return("F2"); case 121: return("PGDN"); case 122: return("F1"); case 123: return("Left"); case 124: return("Right"); case 125: return("Down"); case 126: return("Up"); case 131: return ("F4"); case 160: return ("F3"); default: return ("Unknown"); } } char *convertShiftKeyCode(int keyCode) { switch ((int) keyCode) { case 0: return "A"; case 1: return "S"; case 2: return "D"; case 3: return "F"; case 4: return "H"; case 5: return "G"; case 6: return "Z"; case 7: return "X"; case 8: return "C"; case 9: return "V"; case 11: return "B"; case 12: return "Q"; case 13: return "W"; case 14: return "E"; case 15: return "R"; case 16: return "Y"; case 17: return "T"; case 18: return "!"; case 19: return "@"; case 20: return "#"; case 21: return "$"; case 22: return "^"; case 23: return "%"; case 24: return "+"; case 25: return "("; case 26: return "&"; case 27: return "_"; case 28: return "*"; case 29: return ")"; case 30: return "}"; case 31: return "O"; case 32: return "U"; case 33: return "{"; case 34: return "I"; case 35: return "P"; case 37: return "L"; case 38: return "J"; case 39: return "\""; case 40: return "K"; case 41: return ":"; case 42: return "|"; case 43: return "<"; case 44: return "?"; case 45: return "N"; case 46: return "M"; case 47: return ">"; case 50: return "~"; case 51: return("Delete"); case 52: return("Enter"); case 53: return("ESC"); case 54: return ("RCommand");//Right case 55: return ("LCommand");//Left case 56: return ("LShift");//Left case 57: return ("CapsLock"); case 58: return ("LOption");//Left case 59: return ("Ctrl"); case 60: return ("RShift");//Right case 61: return ("ROption");//Right case 63: return ("FN"); case 65: return("."); case 67: return("*"); case 69: return("+"); case 75: return("/"); case 76: return("Enter"); // numberpad on full kbd case 78: return("-"); case 81: return("="); case 82: return("0"); case 83: return("1"); case 84: return("2"); case 85: return("3"); case 86: return("4"); case 87: return("5"); case 88: return("6"); case 89: return("7"); case 91: return("8"); case 92: return("9"); case 96: return("F5"); case 97: return("F6"); case 98: return("F7"); case 99: return("F3"); case 100: return("F8"); case 101: return("F9"); case 103: return("F11"); case 105: return("F13"); case 107: return("F14"); case 109: return("F10"); case 111: return("F12"); case 113: return("F15"); case 114: return("HELP"); case 115: return("HOME"); case 116: return("PGUP"); case 117: return("DELETE"); // full keyboard right side numberpad case 118: return("F4"); case 119: return("END"); case 120: return("F2"); case 121: return("PGDN"); case 122: return("F1"); case 123: return("Left"); case 124: return("Right"); case 125: return("Down"); case 126: return("Up"); case 131: return ("F4"); case 160: return ("F3"); default: return ("Unknown"); } } bool shiftKeyPressed = false; bool controlKeyPressed = false; bool optionKeyPressed = false; bool commandKeyPressed = false; bool functionKeyPressed = false; CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) { // Paranoid sanity check. if ((type != kCGEventKeyDown) && (type != kCGEventKeyUp) && (type != kCGEventFlagsChanged)) { return event; } // The incoming keycode. CGKeyCode keyCode = (CGKeyCode)CGEventGetIntegerValueField( event, kCGKeyboardEventKeycode ); uint8_t isShiftKey = (keyCode == 56 || keyCode == 60); uint8_t isControlKey = (keyCode == 59 || keyCode == 62); uint8_t isOptionKey = (keyCode == 58 || keyCode == 61); uint8_t isCommandKey = (keyCode == 54 || keyCode == 55); uint8_t isFunctionKey = (keyCode == 63); if (type == kCGEventFlagsChanged) { if (isShiftKey) { shiftKeyPressed = !shiftKeyPressed; } if (isControlKey) { controlKeyPressed = !controlKeyPressed; } if (isOptionKey) { optionKeyPressed = !optionKeyPressed; } if (isCommandKey) { commandKeyPressed = !commandKeyPressed; } if (isFunctionKey) { functionKeyPressed = !functionKeyPressed; } } // Print the human readable key switch(type) { case kCGEventKeyDown: if (shiftKeyPressed) { snprintf(buf, sizeof(buf), "%s%s", "d", convertKeyCode(keyCode)); //snprintf(buf, sizeof(buf), "%s%s", "d", convertShiftKeyCode(keyCode)); } else { snprintf(buf, sizeof(buf), "%s%s", "d", convertKeyCode(keyCode)); } break; case kCGEventKeyUp: if (shiftKeyPressed) { snprintf(buf, sizeof(buf), "%s%s", "u", convertKeyCode(keyCode)); //snprintf(buf, sizeof(buf), "%s%s", "u", convertShiftKeyCode(keyCode)); } else { snprintf(buf, sizeof(buf), "%s%s", "u", convertKeyCode(keyCode)); } break; case kCGEventFlagsChanged: if ((isShiftKey && !shiftKeyPressed) || (isControlKey && !controlKeyPressed) || (isOptionKey && !optionKeyPressed) || (isCommandKey && !commandKeyPressed) || (isFunctionKey && !functionKeyPressed)) { //key = "[released %s]\n", convertKeyCode(keyCode)); snprintf(buf, sizeof(buf), "%s%s", "u", convertKeyCode(keyCode)); } else { snprintf(buf, sizeof(buf), "%s%s", "d", convertKeyCode(keyCode)); } break; default: break; } //if (shiftKeyPressed && type == kCGEventKeyDown) { // //key = convertShiftKeyCode(keyCode); // snprintf(buf, sizeof(buf), "%s%s", "d", convertShiftKeyCode(keyCode)); //} else { // if (type != kCGEventKeyUp) { // if ((isShiftKey && !shiftKeyPressed) || // (isControlKey && !controlKeyPressed) || // (isOptionKey && !optionKeyPressed) || // (isCommandKey && !commandKeyPressed)) { // //key = "[released %s]\n", convertKeyCode(keyCode)); // snprintf(buf, sizeof(buf), "%s%s", "u", convertKeyCode(keyCode)); // } else if (!shiftKeyPressed) { // snprintf(buf, sizeof(buf), "%s%s", "u", convertKeyCode(keyCode)); // //printf("%s\n", convertKeyCode(keyCode)); // } // } //} //Keypress code goes here. //keyStringForKeyCode(keycode); if (sendto(s, buf, strlen(buf) , 0 , (struct sockaddr *) &si_other, slen)==-1) { die("sendto()"); } // We must return the event for it to be useful. return event; } int main(void) { if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1 ) { die("socket"); } memset((char *) &si_other, 0, sizeof(si_other)); si_other.sin_family = AF_INET; si_other.sin_port = htons(PORT); if (inet_aton(SERVER , &si_other.sin_addr) == 0) { fprintf(stderr, "inet_aton() failed\n"); exit(1); } CFMachPortRef eventTap; CGEventMask eventMask; CFRunLoopSourceRef runLoopSource; // Create an event tap. We are interested in key presses. eventMask = ((1 << kCGEventKeyDown) | (1 << kCGEventKeyUp) | (1 << kCGEventFlagsChanged)); eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, eventMask, myCGEventCallback, NULL); if (!eventTap) { fprintf(stderr, "failed to create event tap\n"); exit(1); } // Create a run loop source. runLoopSource = CFMachPortCreateRunLoopSource( kCFAllocatorDefault, eventTap, 0 ); // Add to the current run loop. CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes); // Enable the event tap. CGEventTapEnable(eventTap, true); // Set it all running. CFRunLoopRun(); atexit(bye); exit(0); }
C
#include<stdio.h> int main() { int x,y; printf("enter x and y to calculate the sum and product : "); scanf("%d %d",&x,&y); printf("%d %d",x+y,x*y); return 0; }
C
#include <stdio.h> void prStack2(l,y,z) { printf("%2d [y:%d, z:%d]\n", l, y, z); } void prStack(l,x,y,z) { printf("%2d [x:%d, f{}, y:%d, z:%d]\n", l, x, y, z); } main() { int z; int y; prStack2(2,y,z); y = 5; prStack2(3,y,z); { int f(int *x){ prStack(4,*x,y,z); *x = *x+1; prStack(5,*x,y,z); y = *x-4; prStack(6,*x,y,z); *x = *x+1; prStack(7,*x,y,z); return *x; }; prStack2(9,y,z); z = f(&y)+y; prStack2(10,y,z); }; prStack2(11,y,z); }
C
#include "search_algos.h" /** * linear_search - search the first ocurrency of a value in the array * @array: set of numbers * @size: size of the array * @value: value to search * Return: return the first index located */ int linear_search(int *array, size_t size, int value) { size_t i = 0; if (array == NULL) return (-1); for (i = 0; i < size; i++) { printf("Value checked array[%d] = [%d]\n", (int) i, (int) array[i]); if (array[i] == value) return (i); } return (-1); }
C
#include <stdio.h> #include <cs50.h> int main(void) { // Determine variables int height, line, space, hash; // Set height limit to 23 do { printf("Height: "); height = get_int(); } while (height < 0 || height > 23); // Print lines based on height for (line = 1; line <= height; line++) { // Print spaces for (space = 0; space < (height - line); space++) { printf(" "); } // Print hashes on left for (hash = 0; hash < line; hash++) { printf("#"); } // Print gap printf(" "); // Print hashes on right for (hash = 0; hash < line; hash++) { printf("#"); } printf("\n"); } }
C
#include<stdio.h> #include<locale.h> void main() { char *locale = setlocale(LC_ALL, ""); int a=77; printf(" : %d\n", a); if (a/10==4 || a%10==4) { printf (" 4 \n"); } else { printf (" 4 \n"); } if (a/10==7 || a%10==7) { printf (" 7 \n"); } else { printf (" 7 \n"); } getch(); }
C
#include <cstdlib> #include <cstdio> #include <ctype.h> void *emalloc(size_t size) { void *ptr= malloc(size); if (ptr == NULL) { fprintf(stderr, "Memory allocation failed!\n"); exit(EXIT_FAILURE); } return ptr; } void *erealloc(void *ptr, size_t size) { ptr = realloc(ptr, size); if (ptr == NULL) { fprintf(stderr, "Memory allocation failed!\n"); exit(EXIT_FAILURE); } return ptr; }
C
#include <stdio.h> #include <stdlib.h> int A[25][25]; void Warshall(int n) { int i,j,k; for(k=1;k<=n;k++) for(i=1;i<=n;i++) for(j=1;j<=n;j++) A[i][j]=A[i][j] || (A[i][k]&&A[k][j]); } int main() { int v,e,i,j,v1,v2; printf("Enter the number of Vertices and edges: \n"); scanf("%d%d", &v,&e); printf("\nEnter %d edges:\n", e); for(i=1;i<=e;i++) { printf("Edge--%d:",i); scanf("%d%d",&v1,&v2); A[v1][v2]=1; } printf("\n\nAdjacency Matrix:\n"); for(i=1;i<=v;i++) { for(j=1;j<=v;j++) printf("\t%d",A[i][j]); printf("\n"); } Warshall(v); printf("\n\nTransitive Closure: \n"); for(i=1;i<=v;i++) { for(j=1;j<=v;j++) printf("\t%d",A[i][j]); printf("\n"); } return 0; }
C
/* * NOTWORKIN.c * * Created on: Mar 28, 2016 * Author: Yongsuk */ /* * Yes.c * * Created on: 2016. 3. 24. * Author: Administrator */ #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> void swap() // ٲ㼭 { int x, y, temp; printf(" ԷϽÿ: "); fflush(stdout); scanf("%d %d", &x, &y); printf("x: %d, y: %d\n", x, y); temp = x; x = y; y = temp; printf("x: %d, y: %d\n", x, y); } void printReport() // 3 Է¹ް , { int math1, math2, math3;// int eng1, eng2, eng3; // int kor1, kor2, kor3; // int sum; // float average; // // л Է¹޴´. printf("ù ° л ԷϽÿ: "); fflush(stdout); scanf("%d %d %d", &math1, &eng1, &kor1); printf(" ° л ԷϽÿ: "); fflush(stdout); scanf("%d %d %d", &math2, &eng2, &kor2); printf(" ° л ԷϽÿ: "); fflush(stdout); scanf("%d %d %d", &math3, &eng3, &kor3); printf("\t\t\t\t\n"); //sum average ϰ ٷ Ѵ. ̿Ͽ sum average ٽ ʱȭѴ. sum = math1 + kor1 + eng1; average = sum / 3.0; printf("%d\t%d\t%d\t%d\t%.2f\n", kor1, eng1, math1, sum, average); sum = math2 + kor2 + eng2; average = sum / 3.0; printf("%d\t%d\t%d\t%d\t%.2f\n", kor2, eng2, math2, sum, average); sum = math3 + kor3 + eng3; average = sum / 3.0; printf("%d\t%d\t%d\t%d\t%.2f\n", kor3, eng3, math3, sum, average); } void arithmeticOperations() // Է¹ Ģ { long long x, y, sum, sub, mult, div; printf(" ԷϽÿ: "); fflush(stdout); scanf("%lld %lld" , &x, &y); // sum = x + y; sub = x - y; mult = x * y; div = x / y; printf("%lld + %lld = %lld \n", x, y, sum); printf("%lld - %lld = %lld\n", x, y, sub); printf("%lld * %lld = %lld\n", x, y, mult); printf("%lld / %lld = %lld\n", x, y, div); } void transformSpace() // ͷ, ͸ ȯϿ { float flat; float area; printf(" ԷϽÿ: "); fflush(stdout); scanf("%f" , &flat); area = flat * (3.3); printf("Է %.0f %.2f Դϴ\n", flat, area); printf("͸ ԷϽÿ: "); fflush(stdout); scanf("%f", &area); flat = area / 3.3; printf("Է %.0f %.2f Դϴ.\n", area, flat); } void transformHeight() // Է¹ Ű Ʈ ȯϿ { int cm, ft; float inch; printf("Ű<cm> ԷϽÿ: "); fflush(stdout); scanf("%d", &cm); inch = cm / 2.54; ft = inch / 12; inch = inch-(12*ft); printf("ԷϽ Ű %d %d Ʈ %.3f ġԴϴ \n", cm, ft, inch); } void printDigits() // 1000 ̸ Է¹޾ , , ڸ { int num; printf("1000 ̸ ԷϽÿ: "); fflush(stdout); scanf("%d", &num); int one = num % 10; // ڸ ϱ int ten = num / 10 % 10;// ڸ ϱ int hundred = num / 100;// ڸ ϱ printf("%d ڸ %dԴϴ\n", num, hundred); printf("%d ڸ %dԴϴ\n", num, ten); printf("%d ڸ %dԴϴ\n", num, one); } int main() { //swap(); //printReport(); //printDigits(); //arithmeticOperations(); //transformHeight(); //transformSpace(); return 0; }
C
#include "../utility.h" int r_mdet0() { double a[4][4] = {{2.0,1.0,3.0,5.0}, /* 矩阵A,B,C分别赋初值*/ {2.0,2.0,-3.0,-1.0}, {2.0,1.0,7.0,2.}, {4.0,2.0,10.0,7.0} }; double b[4][4] = {{2.0,2.0,-3.0,-1.0}, {2.0,1.0,3.0,5.0}, {2.0,1.0,7.0,2.}, {1.,4.0,9.0,-2.0} }; double c[4][4]= {{14.0,7.0,6.0,1.0}, {7.0,8.0,4.0,3.0}, {6.0,4.0,9.0,5.0}, {1.0,3.0,5.0,10.0} }; double det,eps = 1e-10; /* 数值精度设为1e-10*/ int n; n = r_mrank(a,4,4,eps); /* 求矩阵A的秩和特征值并打印*/ printf("rank(a) = %d\n", n); det = r_mdet(a, 4,eps); printf("det(a) = %2.5f\n", det); n = r_mrank(b,4,4,eps); /* 求矩阵B的秩和特征值并打印*/ printf("rank(b) = %d\n", n); det = r_mdet(b, 4,eps); printf("det(b) = %2.5f\n", det); n = r_mrank(c,4,4,eps); /* 求正定矩阵C的秩和特征值并打印*/ printf("rank(c) = %d\n", n); det = r_chdet(c,4,eps); printf("det(c) = %2.5f\n", det); return 0; }
C
#include <sys/times.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { struct tms start = { 0 }; struct tms end = { 0 }; clock_t clc_start = 0; clock_t clc_end = 0; clock_t clc_tck = 0; if (argc != 2) { return 0; } if ((clc_start = times(&start)) < 0) { printf("start time error!\n"); } if (system(argv[1]) < 0) { printf("system date error!\n"); } if ((clc_end = times(&end)) < 0) { printf("end time error!\n"); } if ((clc_tck = sysconf(_SC_CLK_TCK)) <= 0) { printf("get tck error!\n"); exit(-1); } printf("real time = %lf\n", (clc_end - clc_start) / (double)clc_tck); printf("user cpu = %lf\n", (end.tms_utime - start.tms_utime) / (double)clc_tck); printf("sys cpu = %lf\n", (end.tms_stime - start.tms_stime) / (double)clc_tck); printf("user child= %lf\n", (end.tms_cutime - start.tms_cutime) / (double)clc_tck); printf("sys child= %lf\n", (end.tms_cstime - start.tms_cstime) / (double)clc_tck); printf("exe uid = %d, euid = %d\n", getuid(), geteuid()); return 0; }
C
#include <stdio.h> void main() { int a=5,b=5,c=10; printf("%d==%d is %d\n",a,c,a==c); printf("%d>%d is %d\n",a,b,a>b); printf("%d>%d is %d\n",a,c,a>c); printf("%d<%d is %d\n",a,b,a<b); printf("%d<%d is %d\n",a,c,a<c); printf("%d!=%d is %d\n",a,b,a!=b); printf("%d!=%d is %d\n",a,c,a!=c); printf("%d>=%d is %d\n",a,b,a>=b); printf("%d>=%d is %d\n",a,c,a>=c); printf("%d<=%d is %d\n",a,b,a<=b); printf("%d<=%d is %d\n",a,c,a<=c); getch(); }
C
#include "grafo.h" p_grafo criar_grafo(int tam){ p_grafo g; int i; g = malloc(sizeof(Grafo)); if(g == NULL) exit(1); g->adjacencia = malloc(tam * sizeof(No)); if(g->adjacencia == NULL) exit(1); g->n = tam; for(i=0; i<tam; i++){ g->adjacencia[i] = NULL;/*Seta todas as posições, da lista ligada, voltadas pra 'NULL'*/ } return g; } void libera_lista(p_no lista){/*Desaloca a lista ligada de cada posição de maneira recursiva*/ if (lista != NULL) { libera_lista(lista ->prox); free(lista); } } void destruir_grafo(p_grafo g){/*Destrói grafo*/ int i; for (i = 0; i < g->n; i++){ libera_lista(g->adjacencia[i]);/*Libera a lista ligada de cada posição*/ } free(g->adjacencia);/*Libera vetor do grafo*/ free(g);/*Libera grafo*/ } p_no insere_na_lista(p_no lista , int v){/*Insere nova relação entre pessoas*/ p_no novo = malloc(sizeof(No)); if(novo == NULL) exit(1); novo->v = v; novo->prox = lista;/*Aponta para elemento inicial da lista*/ novo->flag = 0;/*Seta situação como não entediado*/ return novo; } void insere_aresta(p_grafo g, int u, int v){/*Insere nova relação entre duas pessoas*/ g->adjacencia[v] = insere_na_lista(g->adjacencia[v], u); g->adjacencia[u] = insere_na_lista(g->adjacencia[u], v); } int tem_aresta(p_grafo g, int u, int v){/*Verifica se há alguma ligação entre duas pessoas*/ p_no temp; for(temp = g->adjacencia[u]; temp != NULL; temp = temp->prox){ if(temp->v == v){/*Se tiver*/ return 1;/*Retorna 'True'*/ } } return 0;/*Retorna 'False'*/ } void imprime_arestas(p_grafo g){/*Imprime posição das pessoas entediadas*/ int u; for(u=0; u<g->n; u++){ if(g->adjacencia[u]->flag == 1)/*Verifica se a pessoa está entediada*/ printf("%d\n", u);/*Se tiver, imprime sua posição*/ } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* rendering2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rnaumenk <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/01/30 17:42:29 by rnaumenk #+# #+# */ /* Updated: 2018/01/30 17:42:30 by rnaumenk ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" void vertical_line(t_m *m, double y, int i, int next) { double dy; dy = m->d[i + next].win_y - m->d[i].win_y; if (dy >= 0) { while (++y < m->d[i + next].win_y) mlx_pixel_put(m->mlx, m->win, m->d[i].win_x, (int)y, color_calc(m, i, next, 1)); } else { while (--y > m->d[i + next].win_y) mlx_pixel_put(m->mlx, m->win, m->d[i].win_x, (int)y, color_calc(m, i, next, 1)); } } void horizontal_line(t_m *m, double x, int i, int next) { double dx; dx = m->d[i + next].win_x - m->d[i].win_x; if (dx >= 0) { while (++x < m->d[i + next].win_x) mlx_pixel_put(m->mlx, m->win, (int)x, m->d[i].win_y, color_calc(m, i, next, 1)); } else { while (--x > m->d[i + next].win_x) mlx_pixel_put(m->mlx, m->win, (int)x, m->d[i].win_y, color_calc(m, i, next, 1)); } } void wu_shit_for_x_longer(t_m *m, int i, double y, double x) { int module; module = (int)(y * 10) % 10; if (!module) mlx_pixel_put(m->mlx, m->win, (int)x, (int)y, color_calc(m, i, m->next, 1)); else if (module) { mlx_pixel_put(m->mlx, m->win, (int)x, (int)(y + 1), color_calc(m, i, m->next, module * 0.1)); mlx_pixel_put(m->mlx, m->win, (int)x, (int)y, color_calc(m, i, m->next, (10 - module) * 0.1)); } } void wu_shit_for_y_longer(t_m *m, int i, double x, double y) { int module; module = (int)(x * 10) % 10; if (!module) mlx_pixel_put(m->mlx, m->win, (int)x, (int)y, color_calc(m, i, m->next, 1)); else if (module) { mlx_pixel_put(m->mlx, m->win, (int)(x + 1), (int)y, color_calc(m, i, m->next, module * 0.1)); mlx_pixel_put(m->mlx, m->win, (int)x, (int)y, color_calc(m, i, m->next, (10 - module) * 0.1)); } }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #define MAX_LEN 2000 //attention il faudra mettre une limite du nombre de caracteres utilisables #define TEXTE "France Jean-Michel DUPOND [email protected] ID.png 02/02/2016 je n'aime pas cette photo, oui c'est une virgule! exclamation et les accents é à è ù ê î ô û â ï enfin point. interrogation? caracteres speciaux commentaire\\ retourligne\n \\ \n // lepluscomplique \\n fin_explication http://premiereadereferencer.com http://deuxiemeadereferencer.fr FIN_TEXTE BORNE_SECU" //a voir comment le texte sera donne, il sera code comme dans une chaine de caracteres dans un printf //FIN_TEXTE est une balise pour indiquer la fin du texte, et on rajoute BORNE_SECU car ce qui se passe c'est que du texte est rajoute à la fin de texte lors de l'appel systeme et on n'en veut pas de ce texte en plus #define FILE_NAME "parse.php" void cpy(char * src, char * dst, int taille) { int i; for (i = 0; i < taille; i++) dst[i] = src[i]; } int main(int argc, char ** argv) { char buf[MAX_LEN] = TEXTE; ssize_t len_read=strlen(TEXTE); //debut modifications de la chaine de caracteres //debut modification pour apostrophes dans le texte de base int nb_carac_en_plus = 0; int i, j; for (i = 0; i < len_read; i++) { if (buf[i + nb_carac_en_plus] == '\'') { for (j = MAX_LEN - 1; j > i + nb_carac_en_plus + 4 ; j--) buf[j] = buf[j - 4]; buf[i + nb_carac_en_plus] = '\''; buf[i + nb_carac_en_plus + 1] = '"'; buf[i + nb_carac_en_plus + 2] = '\''; buf[i + nb_carac_en_plus + 3] = '"'; buf[i + nb_carac_en_plus + 4] = '\''; nb_carac_en_plus += 4; } } len_read += (ssize_t)nb_carac_en_plus; //fin modification pour apostrophes dans le texte de base //debut modification pour les apostrophes autour des mots for (j = MAX_LEN - 1; j > 0 ; j--) buf[j] = buf[j - 1]; buf[0] = '\''; len_read++; nb_carac_en_plus = 0; for (i = 0; i < len_read; i++) { if (buf[i + nb_carac_en_plus] == ' ') { for (j = MAX_LEN - 1; j > i + nb_carac_en_plus + 2 ; j--) buf[j] = buf[j - 2]; buf[i + nb_carac_en_plus] = '\''; buf[i + nb_carac_en_plus + 1] = ' '; buf[i + nb_carac_en_plus + 2] = '\''; nb_carac_en_plus += 2; } } len_read += (ssize_t)nb_carac_en_plus; buf[(int)len_read] = '\''; len_read++; //fin modification pour les apostrophes autour des mots //fin modifications de la chaine de caracteres //debut creation de la commande char entree[(int)len_read]; cpy(buf, entree, (int)len_read); char * name = FILE_NAME; char * chaine = "php"; asprintf(&chaine, "%s %s %s", chaine, name, entree); //printf("%s\n", chaine); //ca marche tres bien avec make tout, mais il y a qqs problemes avec make lien, c'est bizarre!!! //fin creation de la commande //debut envoi de la commande const char * chaine_system = (const char *)chaine; if(system(chaine_system) == -1) { perror("system"); return EXIT_FAILURE; } //fin envoi de la commande free(chaine); return EXIT_SUCCESS; }
C
#include "libft.h" char **realloc_tab(char **tab, char *str, int cpt) { char **dest; int i; dest = (char **)malloc(sizeof(char *) * (cpt + 1) + 1); i = 0; while (i < cpt) { dest[i] = ft_strdup(tab[i]); i++; } dest[i] = ft_strdup(str); dest[i + 1] = NULL; return (dest); }
C
#include<stdio.h> void main(){ int num; printf("Enter number: "); scanf("%d",&num); char ch; printf("Enter character: "); scanf(" %c",&ch); float num1; printf("Enter float number: "); scanf("%f",&num1); double d; printf("Enter double number: "); scanf("%lf",&d); int *nptr = &num; char *cptr = &ch; float *fptr = &num1; double *dptr = &d; printf("Address of integer number:%p\n",nptr); printf("Address of Character:%p\n",cptr); printf("Address of float:%p\n",fptr); printf("Address of double:%p\n",dptr); printf("Address of integer number pointer:%p\n",&nptr); printf("Address of Character pointer:%p\n",&cptr); printf("Address of float pointer:%p\n",&fptr); printf("Address of double pointer:%p\n",&dptr); printf("Value of integer number:%d\n",*nptr); printf("Value of Character:%c\n",*cptr); printf("Value of float:%f\n",*fptr); printf("Value of double:%lf\n",*dptr); } /*shital@sarode:~/Desktop/PPA/Assignments/Assignment-22-September 2020$ ./a.out Enter number: 23 Enter character: S Enter float number: 0.5 Enter double number: 235.79 Address of integer number:0x7ffc12c80058 Address of Character:0x7ffc12c80057 Address of float:0x7ffc12c8005c Address of double:0x7ffc12c80060 Address of integer number pointer:0x7ffc12c80068 Address of Character pointer:0x7ffc12c80070 Address of float pointer:0x7ffc12c80078 Address of double pointer:0x7ffc12c80080 Value of integer number:23 Value of Character:S Value of float:0.500000 Value of double:235.790000 */
C
#include<stdio.h> struct node{ int data; struct node* next; }; struct node* head = NULL; void insert(int data,int pos){ struct node * A=head; struct node* temp = (struct node *) malloc(sizeof(struct node)); if(pos==1){ temp->data = data; temp->next = head; head = temp; return; } else{ struct node* temp = head; for(int i=0;i<pos-2;i++){ temp=temp->next; } struct node * temp2 = (struct node *) malloc(sizeof(struct node)); temp2->data = data; temp2->next = temp->next; temp->next = temp2; } } void print(){ struct node * temp2 = head; while(temp2!=NULL){ printf("%d\n",temp2->data ); temp2 = temp2->next; } } int main(){ int n; scanf("\n%d",&n); for(int i=0;i<n;i++){ int data,pos; printf("\nEnter The data you want to enter"); scanf("\n%d",&data); printf("\nEnter The positio you want to insert"); scanf("\n%d",&pos ); insert(data,pos); } print(); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strsplit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: pzhang <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/11/28 19:44:13 by pzhang #+# #+# */ /* Updated: 2017/11/30 22:54:46 by pzhang ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static int word_count(char const *str, char c) { int words; int i; words = 0; i = 0; while (str[i]) { if (str[i] == c) i++; else { words++; while (str[i] != '\0' && str[i] != c) i++; } } return (words); } static int letter_count(char const *str, char c) { int n; n = 0; while (str[n] != '\0' && str[n] != c) n++; return (n); } static char **last_elem(char **temp, int c2) { temp[c2] = (char*)malloc(sizeof(char) * 1); if (!temp[c2]) return (NULL); temp[c2] = NULL; return (temp); } char **ft_strsplit(char const *s, char c) { char **temp; int num[3]; if (!s) return (NULL); num[1] = 0; num[2] = 0; if (!(temp = (char**)malloc(sizeof(char*) * (word_count(s, c) + 1)))) return (NULL); while (s[num[1]]) { if (s[num[1]] == c) num[1]++; else { num[0] = letter_count(s + num[1], c); if (!(temp[num[2]] = (char*)malloc(sizeof(char) * (num[0] + 1)))) return (NULL); ft_strncpy(temp[num[2]], s + num[1], num[0]); temp[num[2]++][num[0]] = '\0'; num[1] += num[0]; } } return (last_elem(temp, num[2])); }
C
#include <stdio.h> #include <string.h> #include <ctype.h> #include <math.h> #define MAX 5 int solve(int op1, char operator, int op2) { switch(operator) { case '+': return op1 + op2; case '-': return op1 - op2; case '*': return op1*op2; case '/': return op1/op2; case '^': return pow(op1, op2); case '%': return op1 % op2; } } int evaluate_postfix(char postfix[20]) { int stack[20], top = -1, operator; int op1, op2; for (int i = 0; i < strlen(postfix); i++) { if (isdigit(postfix[i])) stack[++top] = postfix[i] - '0'; else { op2 = stack[top--]; op1 = stack[top--]; stack[++top] = solve(op1, postfix[i], op2); } } return stack[top]; } void towerofhanoi(int n, char s, char t, char d) { if (n == 0) return; towerofhanoi(n - 1, s, d, t); printf("Move disc %d from %c to %c.\n", n, s, d); towerofhanoi(n - 1, t, s, d); } int main() { char postfix[20]; int n, ch; while(1) { printf("\n1. Postfix expression evaluation.\n2. Tower of Hanoi\nAnything else: exit\nChoice : "); scanf("%d", &ch); switch(ch) { case 1: printf("\nEnter the postfix expr : "); scanf("%s", postfix); printf("The solution of this expression is %d. \n\n", evaluate_postfix(postfix)); break; case 2: printf("\nEnter the number of discs : "); scanf("%d", &n); towerofhanoi(n, 'A', 'B', 'C'); break; default: return 0; } } }
C
/** * The MIT License (MIT) * Copyright (c) 2016-2017 [email protected] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * usage: * tsv_t *tsv = tsv_open("input.tsv"); * while (tsv_read(tsv)) { * for (i=0; i < tsv->n; ++i) printf("\t|%s", tsv->fields[i]); * printf("\n"); * } * tsv_close(tsv); **/ #include <string.h> #include <stdlib.h> #include <zlib.h> #include "wzio.h" typedef struct tsv_t { char **fields; size_t n, m; /* number of fields, and allocated */ gzFile fp; int finished; int line_max; char *line; } tsv_t; static inline tsv_t *tsv_open(char *fn) { tsv_t *tsv = calloc(1, sizeof(tsv_t)); tsv->fp = wzopen(fn); tsv->fields = NULL; tsv->line_max = 10000; tsv->line = calloc(tsv->line_max, sizeof(char)); tsv->finished = 0; return tsv; } /* tsv_close release the memory */ static inline void tsv_close(tsv_t *tsv) { unsigned i; for (i = 0; i < tsv->m; ++i) free(tsv->fields[i]); free(tsv->fields); free(tsv->line); gzclose(tsv->fp); free(tsv); } static inline void __tsv_clear_fields(tsv_t *tsv) { tsv->n = 0; } /* i is 0-based */ static inline void __tsv_set_field(tsv_t *tsv, int i, const char *s) { tsv->fields[i] = realloc(tsv->fields[i], strlen(s)+1); strcpy(tsv->fields[i], s); } static inline void __tsv_append_field(tsv_t *tsv, const char *s) { if (tsv->n == tsv->m) { tsv->fields = realloc(tsv->fields, (++tsv->m)*sizeof(char*)); /* the newly incremented memory is always initialized */ tsv->fields[tsv->m-1] = NULL; } __tsv_set_field(tsv, tsv->n++, s); } static inline char *tsv_field(tsv_t *tsv, unsigned k) { if (k < tsv->n) return tsv->fields[k]; else return NULL; } static inline int tsv_is_blankline(tsv_t *tsv) { if (tsv->line[0] == '\0') return 1; else return 0; } #define tsv_num_fields(tsv) (tsv)->n /* return NULL when done */ static inline int tsv_read(tsv_t *tsv) { if (tsv->finished) return 0; char *tok; char *line_null = tsv->line; // point to the terminating NULL *line_null = '\0'; char *tmp = NULL; while (1) { int c = gzgetc(tsv->fp); if (c == '\n' || c == EOF) { /* process current line */ __tsv_clear_fields(tsv); if (line_null == tsv->line) { // empty line if (c == EOF) tsv->finished = 1; break; } // keep original line tmp = realloc(tmp, strlen(tsv->line) + 1); strcpy(tmp, tsv->line); tok = strtok(tmp, "\t"); while (tok != NULL) { __tsv_append_field(tsv, tok); tok = strtok(NULL, "\t"); } if (c == EOF) tsv->finished = 1; break; } else { /* read line */ if (line_null >= tsv->line + tsv->line_max) { // reaches max tsv->line_max <<= 1; int line_len = line_null - tsv->line; tsv->line = realloc(tsv->line, tsv->line_max); line_null = tsv->line + line_len; } *line_null++ = c; *line_null = '\0'; } } free(tmp); return 1; }
C
/******************************************************************************* * @file Thread_LED.c * @author Auguste Lalande, Felix Dube, Juan Morency Trudel * @version 1.0.0 * @date 8-April-2016 * @brief LED thread ****************************************************************************** */ #include <stdlib.h> #include "Thread_LED.h" #include "LED.h" #include "cmsis_os.h" #include "stm32f4xx_hal.h" #include "Thread_SPI.h" osThreadId tid_Thread_LED; // thread id osThreadDef(Thread_LED, osPriorityLow, 1, 0); /** * @brief Configures the LED GPIO, the TIM, the PWM and starts the Thread_Acc * @param None * @retval 0 upon success */ int start_Thread_LED (void) { LED_GPIO_Config(); LED_TIM_Config(); LED_PWM_Config(); //set the default LED pattern LED_pattern = 2; LED_speed = -8; LED_brightness = 100; tid_Thread_LED = osThreadCreate(osThread(Thread_LED ), NULL); // Start LED_Thread if (!tid_Thread_LED) return(-1); return(0); } /** * @brief Thread that controls the LED * LED_pattern = 0 => ON, 1 => OFF, 2 => Rotate * @param None * @retval None */ void Thread_LED (void const *argument) { //adjusts the brightness of all LED //could control LED individually if we set it up on the Android side Adjust_Brightness_Level(LED_brightness, ALL_LED); while(1) { switch(LED_pattern) { case 0: LED_On(); break; case 1: LED_Off(); break; case 2: Rotate_LED(LED_speed); break; } //note that there is no Delay in this thread directly, but all the pattern functions //have some osDelay to save processor time } }
C
#include "backtrack.h" #include "board.h" #include "bool.h" #include "checked_alloc.h" #include "list.h" #include <stdlib.h> #include <string.h> typedef struct { int idx; int value; } backtrack_state_t; static void backtrack_state_push(list_t* stack, int idx) { backtrack_state_t* state = checked_malloc(sizeof(backtrack_state_t)); state->idx = idx; state->value = 0; /* `value` is incremented on every iteration, so start before the minimal one. */ list_push(stack, state); } static void backtrack_state_pop(list_t* stack) { free(list_pop(stack)); } static backtrack_state_t* backtrack_state_top(list_t* stack) { return stack->tail->value; } /** * Advance `idx` to the nearest empty cell, returning false if the end of the * board has been reached. */ static bool_t advance_to_empty(const board_t* board, int* idx) { int block_size = board_block_size(board); while (!cell_is_empty(&board->cells[*idx])) { (*idx)++; if (*idx == block_size * block_size) { return FALSE; } } return TRUE; } int num_solutions(board_t* board) { list_t stack; int block_size = board_block_size(board); int count = 0; int idx = 0; list_init(&stack); if (advance_to_empty(board, &idx)) { backtrack_state_push(&stack, idx); } else { return board_is_legal(board); } while (!list_is_empty(&stack)) { backtrack_state_t* state = backtrack_state_top(&stack); int value = state->value; do { value++; if (value > block_size) { break; } board->cells[state->idx].value = value; } while (!board_is_legal(board)); state->value = value; if (value > block_size) { /* We've exhausted all possibilities for this cell - reset it * and return to the previous one. */ board->cells[state->idx].value = 0; backtrack_state_pop(&stack); } else { int next_idx = state->idx; if (advance_to_empty(board, &next_idx)) { /* We still have more empty cells to explore. */ backtrack_state_push(&stack, next_idx); } else { /* We've finished the board - record our success! */ count++; } } } return count; }
C
#include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <sys/time.h> #define CMPL_OPT #ifndef CMPL_OPT static volatile int glob = 0; #else static int glob = 0; #endif //#define USE_LOCK #ifdef USE_LOCK pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; #endif void* threadFunc(void* arg) { #ifdef USE_LOCK pthread_mutex_lock(&mutex); #endif int loops = *((int*)arg); for(int i = 0 ; i < loops; i ++ ) { glob ++; } #ifdef USE_LOCK pthread_mutex_unlock(&mutex); #endif return NULL; } int main(int argc, char *argv[]) { struct timeval end, start; gettimeofday(&start,NULL); int loops; if(argc == 1) { loops = 1000; } if(argc > 1 ) { loops = atoi(argv[1]); if(loops <= 0 ) { printf("Err: atoi() loops must be > 0\n"); exit(EXIT_FAILURE); } } pthread_t thr1, thr2; int s; /*s is to track the error status*/ s = pthread_create(&thr1, NULL, threadFunc, &loops); /*create the 1st thread*/ if(s != 0) { printf("Err: pthread_create %s",strerror(s)); exit(EXIT_FAILURE); } s = pthread_create(&thr2, NULL, threadFunc, &loops ); if(s != 0) { printf("Err: pthread_create %s",strerror(s)); exit(EXIT_FAILURE); } s = pthread_join(thr1,NULL); if(s != 0) { printf("Err: pthread join %s",strerror(s)); exit(EXIT_FAILURE); } s = pthread_join(thr2, NULL); if(s != 0) { printf("Err: pthread join %s",strerror(s)); exit(EXIT_FAILURE); } printf("Finally, glob = %d\n", glob); gettimeofday(&end,NULL); printf("Totally Running Time %lu us\n", (end.tv_sec - start.tv_sec) * 1000000 + end.tv_usec - start.tv_usec); exit(EXIT_SUCCESS); }
C
#include <stdio.h> //복습할 필요가 있다고 생각함 int dp[101][100001]={0}; typedef struct{ int w; int v; } bag; int maximum(int a, int b){ if(a>b){ return a; } else{ return b; } } int main(){ int n, k, max=0; scanf("%d %d", &n, &k); bag a[n]; for(int i=0;i<n;i++){ scanf("%d %d", &a[i].w, &a[i].v); } for(int i=1;i<=n;i++){ for(int j=0 ;j<=k ;j++){ dp[i][j] = dp[i-1][j]; if(j-a[i-1].w >= 0){ dp[i][j] = maximum(dp[i][j], dp[i - 1][j - a[i-1].w] + a[i-1].v); } } } printf("%d\n", dp[n][k]); }
C
#include <struct.h> #include<HEADER.h> ///iJCϥ *load OebD}ɮ RorC OܿWɮ AccountNum OӪa void loadgame( FILE *load,int RorC,int accountNum) { time1=0; SCORE=0; int t,q; Sleep(1000); system("CLS"); printf("Rules :\n\n" "\t1 There will be a 5 by 5 map\n\n" "\t2 You can switch your candy by the key on keyboard \n\n" "\t3 Input w , a , s , d as upward leftward downward rightward\n\n" "\t Blankspace as choose to switch.\n\n" "\t4 We can only switch inside the 5x5 map\n\n" "\t We don't have the ability to switch outside the map\n\n" "\t5 You can leave the game + recode your game when you input 'x' any time\n\n"); printf("\n\n\n\n\n\n"); system("pause"); system("color 07"); system("CLS"); //music1(); char S[]="Game start !"; for (t=0,q=9;t<12;q++,t++) {SetColor(q); if(q>14)q=q-6; Sleep(100); printf("%c",S[t]); } SetColor(7); printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t\t\t"); system("pause"); //================================================Read if (RorC==0) { //============================Ū========== struct clientData client ; client.acctNum=0; client.Score=0; memset(client.MAT, 0, sizeof(client.MAT)); memset( client.time, '+', strlen(client.time) ); fseek( load, ( accountNum - 1 ) * sizeof( struct clientData ), SEEK_SET ); fread( &client, sizeof( struct clientData ), 1, load ); int r,t1,t2,t0=0; for(t1=0;t1<MAX;t1++) { for(t2=0;t2<MAX;t2++) { r=client.MAT[5*t1+t2]; fiveBy[t1][t2]=r; if ( r ==0)t0++; } } if (t0>20) { system("cls"); printf("\nDue to the way of exiting the program ,your map hasn't be stored\n" "So we prepare a new map for you.\n"); Sleep(1500); RorC=1; } SCORE=client.Score; } if(RorC==1) { //=================================== üƲ ============================ int count1,count2,t1; srand(time(NULL)); for(count1=0;count1<MAX;count1++) { for(count2=0;count2<MAX;count2++) { t1=rand() %4; fiveBy[count1][count2]=t1; } } } //==================== 'x' Xj ================= int k= setjmp(buf); if(k==0) { print_array(*fiveBy,-1); } else{ char S1[]="\n\nGame End\n\n"; for (t=0;t<10;t++,q++) { SetColor(q); if(q>14)q=q-6; Sleep(250); printf("%c",S1[t]); } SetColor(7); music2(); //s________________________________________________________________________ struct clientData client ; client.acctNum=0; client.Score=0; memset(client.MAT, 0, sizeof(client.MAT)); memset( client.time, '+', strlen(client.time) ); fseek( load, ( accountNum - 1 ) * sizeof( struct clientData ),SEEK_SET ); fread( &client, sizeof( struct clientData ), 1, load ); int e1,e2; for (e1=0;e1<MAX;e1++) { for(e2=0;e2<MAX;e2++) { client.MAT[5*e1+e2]=fiveBy[e1][e2]; } } client.Score=SCORE; time_t T = time(NULL);///xsɶ* * * char *now = ctime(&T); int s=0; while(*now!='\0') { client.time[s]=now[s]; s++; } fseek( load, ( client.acctNum - 1 ) * sizeof( struct clientData ), SEEK_SET ); /* insert record in file */ fwrite( &client, sizeof( struct clientData ), 1, load ); system("cls"); } }
C
/* This program change current directory in process. So, when this program terminated, return to previous location. */ #include <stdlib.h> #include <stdio.h> #include <unistd.h> void main(int argc, char *argv[]) { //check arg count. if (argc != 2) { printf("Usage: %s destination",argv[0]); exit(1); } //change directory. if (chdir(argv[1]) < 0) { perror("chdir"); exit(1); } }
C
/// Gerencia a criação e manipulação da tela. /// Este módulo implementa a tela do jogo, bem /// como gerencia as operações relacioanas à ela. /// /// \file main.c /// \author Anderson, André, Cristóvão, Pedro Vítor. /// \since 11/04/16 /// \version 2.0 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> #include "tela.h" #include "engine.h" int main () { TipoTela tela[15][25]; CriarTela(tela); Loop(tela); return 0; }
C
#include <stdio.h> #include <Windows.h> void swap(int* x, int* y) { int temp; temp = *x; *x = *y; *y = temp; } void Sort(int a[], int n) { int i, j, temp; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if (a[i] > a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } } int main() { int a = 1; int b = 2; int i; int array[3] = {1, 3, 2}; swap(&a, &b); Sort(array, 3); printf("a = %d b = %d", a, b); for (i = 0; i < 3; i++) { printf("%d ", array[i]); } system("pause"); }
C
#include <assert.h> #include <inttypes.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include "../aes.h" #include "../cmac.h" uint8_t zeros[16] = {0}; uint8_t ones[16] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; void test_xor(void) { uint8_t out[16]; printf("Testing block_xor: "); block_xor(out, zeros, zeros); assert(block_eq(out, zeros)); printf("."); block_xor(out, zeros, ones); assert(block_eq(out, ones)); printf("."); block_xor(out, ones, zeros); assert(block_eq(out, ones)); printf("."); block_xor(out, ones, ones); assert(block_eq(out, zeros)); printf(".\n"); } void test_cmac(void) { printf("Testing CMAC-AES128: "); fflush(stdout); uint8_t k[16] = {0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}; cmac_aes128_init(k); uint8_t tag[16]; /* Test Null Message, NIST Example */ uint8_t case1[16] = {0xbb, 0x1d, 0x69, 0x29, 0xe9, 0x59, 0x37, 0x28, 0x7f, 0xa3, 0x7d, 0x12, 0x9b, 0x75, 0x67, 0x46}; cmac_aes128(tag, NULL, 0, 16); printf("%s", block_eq(tag, case1) ? "." : "F"); /* 16b example */ uint8_t msg2[] = {0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a}; uint8_t case2[16] = {0x07, 0x0a, 0x16, 0xb4, 0x6b, 0x4d, 0x41, 0x44, 0xf7, 0x9b, 0xdd, 0x9d, 0xd0, 0x4a, 0x28, 0x7c}; cmac_aes128(tag, msg2, sizeof(msg2), 16); printf("%s", block_eq(tag, case2) ? "." : "F"); /* 40b example */ uint8_t msg3[] = {0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a, 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51, 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11}; uint8_t case3[16] = {0xdf, 0xa6, 0x67, 0x47, 0xde, 0x9a, 0xe6, 0x30, 0x30, 0xca, 0x32, 0x61, 0x14, 0x97, 0xc8, 0x27}; cmac_aes128(tag, msg3, sizeof(msg3), 16); printf("%s", block_eq(tag, case3) ? "." : "F"); /* 64b example */ uint8_t msg4[] = {0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a, 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51, 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef, 0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10}; uint8_t case4[16] = {0x51, 0xf0, 0xbe, 0xbf, 0x7e, 0x3b, 0x9d, 0x92, 0xfc, 0x49, 0x74, 0x17, 0x79, 0x36, 0x3c, 0xfe}; cmac_aes128(tag, msg4, sizeof(msg4), 16); printf("%s", block_eq(tag, case4) ? "." : "F"); printf("\n"); } /* void test_truncate_tag(void) { */ /* printf("Testing truncate_tag: "); */ /* uint8_t test[16] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, */ /* 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; */ /* uint8_t tag[16] = {0}; */ /* for (int i = 0; i < 128; i++) { */ /* /\* Truncation and shift are the same operation on the all ones block_t *\/ */ /* uint8_t tag2[16]; */ /* block_shiftl(tag2, test, 128-i); */ /* cmac_truncate(tag, &test, i); */ /* assert(block_eq(tag, tag2)); */ /* } */ /* printf(".\n"); */ /* } */ void test_shiftr(void) { printf("Testing block_shiftr: "); uint8_t out[16]; //uint32_t check; for (int i = 0; i < 128; i++) { printf("Shift Right by %d", i); block_shiftr(out, ones, i); //check = (0xffffffff >> i); block_print("", out); //printf("Check: %" PRIu32 ", %" PRIu32 "\n", *(uint32_t *)out, check); fflush(stdout); //assert(check == out.ui32[0]); } fflush(stdout); printf(".\n"); return; } void test_shiftl(void) { printf("Testing block_shiftl: "); uint8_t out[16]; //uint32_t check; for (int i = 0; i < 129; i++) { //printf("Shift Left by %d", i); block_shiftl(out, ones, i); block_print("", out); //check = (0xffffffff << i); //printf("Check: %.8x, %.8x\n", out32[3], check); fflush(stdout); //assert(check == out.ui32[3]); } printf(".\n"); return; } void test_expand_keys(void) { printf("Testing expand_keys: "); uint8_t k[16] = {0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}; cmac_aes128_init(k); uint8_t k_test[32]; cmac_get_subkeys(k_test); uint8_t k1_test[16] = {0xfb, 0xee, 0xd6, 0x18, 0x35, 0x71, 0x33, 0x66, 0x7c, 0x85, 0xe0, 0x8f, 0x72, 0x36, 0xa8, 0xde}; printf("%s", block_eq(k_test, k1_test) ? "." : "F"); uint8_t k2_test[16] = {0xf7, 0xdd, 0xac, 0x30, 0x6a, 0xe2, 0x66, 0xcc, 0xf9, 0x0b, 0xc1, 0x1e, 0xe4, 0x6d, 0x51, 0x3b}; printf("%s", block_eq(k_test+16, k2_test) ? "." : "F"); printf("\n"); } int main() { test_xor(); test_expand_keys(); test_cmac(); //test_truncate_tag(); return 0; }
C
/* From wikipedia https://en.wikipedia.org/wiki/Partition_(number_theory) In number theory and combinatorics, a partition of a positive integer n, also called an integer partition, is a way of writing n as a sum of positive integers. Two sums that differ only in the order of their summands are considered the same partition. For example, 4 can be partitioned in five distinct ways: 4, 3 + 1, 2 + 2, 2 + 1 + 1, 1 + 1 + 1 + 1. We can write: enum(4) -> [[4],[3,1],[2,2],[2,1,1],[1,1,1,1]] and enum(5) -> [[5],[4,1],[3,2],[3,1,1],[2,2,1],[2,1,1,1],[1,1,1,1,1]]. The number of parts in a partition grows very fast. For n = 50 number of parts is 204226, for 80 it is 15,796,476 It would be too long to tests answers with arrays of such size. So our task is the following: 1 - n being given (n integer, 1 <= n <= 50) calculate enum(n) ie the partition of n. We will obtain something like that: enum(n) -> [[n],[n-1,1],[n-2,2],...,[1,1,...,1]] (order of array and sub-arrays doesn't matter). This part is not tested. 2 - For each sub-array of enum(n) calculate its product. If n = 5 we'll obtain after removing duplicates and sorting: prod(5) -> [1,2,3,4,5,6] prod(8) -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 16, 18] If n = 40 prod(n) has a length of 2699 hence the tests will not verify such arrays. Instead our task number 3 is: 3 - return the range, the average and the median of prod(n) in the following form (example for n = 5): "Range: 5 Average: 3.50 Median: 3.50" Range is an integer, Average and Median are float numbers rounded to two decimal places (".2f" in some languages). Notes: Range : difference between the highest and lowest values. Mean or Average : To calculate mean, add together all of the numbers in a set and then divide the sum by the total count of numbers. Median : The median is the number separating the higher half of a data sample from the lower half. (https://en.wikipedia.org/wiki/Median) Hints: Try to optimize your program to avoid timing out. Memoization can be helpful but it is not mandatory for being successful. */ #include <stdlib.h> #include <stdio.h> void tryadd(int **arr, int val, int *size) { int i; int tmp; int buf; int *tmp_arr; if (*arr == NULL) { if ((*arr = (int *)malloc(sizeof(int))) == NULL) return ; *arr[0] = val; *size += 1; return ; } i = -1; tmp = val; while (++i < *size) { if ((*(*arr +i)) == val) return ; if ((*(*arr +i)) > tmp) { buf = *(*arr +i); *(*arr +i) = tmp; tmp = buf; } } *size += 1; if ((tmp_arr = (int *)calloc(*size, sizeof(int))) == NULL) return ; i = -1; while (++i < *size) { *(tmp_arr + i) = *(*arr + i); } *(tmp_arr + *size - 1) = tmp; free(*arr); *arr = tmp_arr; } char* part(int n) { // your code int i; int j; int tmp; int size; int rage; int *arr; int *iarr; double med; char *result; iarr = NULL; size = 0; if (n > 1) { arr = (int *)calloc(n, sizeof(int)); arr[0] = n - 1; arr[1] = 1; i = 1; tmp = 0; } while (n > 1) { if (arr[0] == 1) break; if (arr[i] != 1) { arr[i]--; tmp++; } else { arr[i] = 0; i--; tmp++; continue ; } while (tmp > arr[i]) { arr[i+1] = arr[i]; tmp = tmp - arr[i]; i++; } arr[i + 1] = tmp; j = -1; tmp = 1; while (++j < n) { if (arr[j] == 0) break ; tmp *= arr[j]; } if (tmp > n) tryadd(&iarr, tmp, &size); tmp = 0; i++; } size = n + size; arr = (int *)calloc(size, sizeof(int)); i = -1; while (++i < n) arr[i] = i + 1; i--; while (++i < size) arr[i] = *(iarr + i - n); i = -1; if (size == 0) rage = n - 1; else rage = arr[size - 1] - 1; tmp = 0; i = -1; while (++i < size) tmp += arr[i]; if ((size % 2) > 0) med = (n == 1) ? 1.0: arr[size / 2] * 1.0; else med = (arr[size / 2 - 1] + arr[size / 2]) / 2.0; if ((result = (char *)malloc(sizeof(char) * 128)) == NULL) return (NULL); sprintf(result,"Range: %d Average: %.2f Median: %.2f", rage, (double)tmp /(size) ,med); free (iarr); return (result); } int main(void) { char *result; result = part(27); printf("%s\n", result); return (0); }
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int main(void) { int age; char name[20]; printf(" Է : "); scanf("%d", &age); fgetc(stdin); // ذ => Ͱ //getchar(); printf("̸ Է : "); gets(name); printf(" : %d, ̸ : %s\n", age, name); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main() { int bytes_read; size_t nbytes = 100; char *my_string; puts ("Please enter a line of text."); /* These 2 lines are the heart of the program. */ my_string = (char *) malloc (nbytes + 1); bytes_read = getline (&my_string, &nbytes, stdin); if (bytes_read == -1) { puts ("ERROR!"); } else { puts ("You typed:"); puts (my_string); } int i = 0; for (; i < bytes_read; ++i ) { if (my_string[i] == EOF){ puts("it has EOF"); }else { puts("it don't"); } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "../headerfile.h" double vfunc(double x_1,double x_2,double xi,double zeta) { double ans; if (fabs(zeta)< SMALL) { double x_2t2 = x_2*x_2; double x_2t3 = x_2*x_2*x_2; double x_2t4 = x_2*x_2*x_2*x_2; double x_2t5 = x_2*x_2*x_2*x_2*x_2; double x_2t6 = x_2*x_2*x_2*x_2*x_2*x_2; double x_2t7 = x_2*x_2*x_2*x_2*x_2*x_2*x_2; double x_1t2 = x_1*x_1; double x_1t3 = x_1*x_1*x_1; double x_1t4 = x_1*x_1*x_1*x_1; double x_1t5 = x_1*x_1*x_1*x_1*x_1; double x_1t6 = x_1*x_1*x_1*x_1*x_1*x_1; double x_1t7 = x_1*x_1*x_1*x_1*x_1*x_1*x_1; double a0,a1,a2,a3,a4,a5; //a0 = -2*sin(2*xi)*(x_2-x_1); //a1 = 2*(sin(2*xi)*(x_2-x_1)-cos(2*xi)*(x_2*x_2-x_1*x_1)); //a2 = 2.0/3.0*(3*cos(2*xi)*(x_2*x_2-x_1*x_1)+2*sin(2*xi)*(x_2*x_2*x_2-x_1*x_1*x_1)); //a3 = 2.0/3.0*(-2*sin(2*xi)*(x_2*x_2*x_2-x_1*x_1*x_1) // +cos(2*xi)*(x_2*x_2*x_2*x_2-x_1*x_1*x_1*x_1)); a0 = -2*sin(2*xi)*x_2+2*sin(2*xi)*x_1; a1 = +(-2*cos(2*xi)*x_2t2+2*cos(2*xi)*x_1t2+2*sin(2*xi)*x_2-2*sin(2*xi)*x_1); a2 = +(4*sin(2*xi)*x_2t3*(1/3.0)-4*sin(2*xi)*x_1t3*(1/3.0) +2*cos(2*xi)*x_2t2-2*cos(2*xi)*x_1t2); a3 = +(2*cos(2*xi)*x_2t4*(1/3.0)-2*cos(2*xi)*x_1t4*(1/3.0) -4*sin(2*xi)*x_2t3*(1/3.0)+4*sin(2*xi)*x_1t3*(1/3.0)); a4 = +(-4*sin(2*xi)*x_2t5*(1/15.0)+4*sin(2*xi)*x_1t5*(1/15.0) -2*cos(2*xi)*x_2t4*(1/3.0)+2*cos(2*xi)*x_1t4*(1/3.0)); a5 = +(-4*cos(2*xi)*x_2t6*(1/45.0)+4*cos(2*xi)*x_1t6*(1/45.0) +4*sin(2*xi)*x_2t5*(1/15.0)-4*sin(2*xi)*x_1t5*(1/15.0)); ans = (a0 + a1*zeta + a2*zeta*zeta + a3*zeta*zeta*zeta + a4*zeta*zeta*zeta*zeta + a5*zeta*zeta*zeta*zeta*zeta); } else { ans = cos(2*(zeta*x_2+xi))-cos(2*(zeta*x_1+xi)); ans *= (1-zeta)/zeta; } return ans; } double dvdx_1(double x_1,double xi,double zeta) { return 2*(1-zeta)*sin(2*(zeta*x_1+xi)); } double dvdx_2(double x_2,double xi,double zeta) { return -2*(1-zeta)*sin(2*(zeta*x_2+xi)); } double dvdxi(double x_1,double x_2,double xi, double zeta) { double ans; if (fabs(zeta)<SMALL) { double x_2t2 = x_2*x_2; double x_2t3 = x_2*x_2*x_2; double x_2t4 = x_2*x_2*x_2*x_2; double x_2t5 = x_2*x_2*x_2*x_2*x_2; double x_2t6 = x_2*x_2*x_2*x_2*x_2*x_2; double x_2t7 = x_2*x_2*x_2*x_2*x_2*x_2*x_2; double x_1t2 = x_1*x_1; double x_1t3 = x_1*x_1*x_1; double x_1t4 = x_1*x_1*x_1*x_1; double x_1t5 = x_1*x_1*x_1*x_1*x_1; double x_1t6 = x_1*x_1*x_1*x_1*x_1*x_1; double x_1t7 = x_1*x_1*x_1*x_1*x_1*x_1*x_1; double a0,a1,a2,a3,a4,a5; a0 = -4*cos(2*xi)*x_2+4*cos(2*xi)*x_1; a1 = +(4*sin(2*xi)*x_2t2-4*sin(2*xi)*x_1t2+4*cos(2*xi)*x_2-4*cos(2*xi)*x_1); a2 = +(8*cos(2*xi)*x_2t3*(1/3.0)-8*cos(2*xi)*x_1t3*(1/3.0) -4*sin(2*xi)*x_2t2+4*sin(2*xi)*x_1t2); a3 = +(-4*sin(2*xi)*x_2t4*(1/3.0)+4*sin(2*xi)*x_1t4*(1/3.0) -8*cos(2*xi)*x_2t3*(1/3.0)+8*cos(2*xi)*x_1t3*(1/3.0)); a4 = +(-8*cos(2*xi)*x_2t5*(1/15.0)+8*cos(2*xi)*x_1t5*(1/15.0) +4*sin(2*xi)*x_2t4*(1/3.0)-4*sin(2*xi)*x_1t4*(1/3.0)); a5 = +(8*sin(2*xi)*x_2t6*(1/45.0)-8*sin(2*xi)*x_1t6*(1/45.0) +8*cos(2*xi)*x_2t5*(1/15.0)-8*cos(2*xi)*x_1t5*(1/15.0)); ans = (a0 + a1*zeta + a2*zeta*zeta + a3*zeta*zeta*zeta + a4*zeta*zeta*zeta*zeta + a5*zeta*zeta*zeta*zeta*zeta); } else { ans = -2*(1-zeta)/zeta*(sin(2*(zeta*x_2+xi))-sin(2*(zeta*x_1+xi))); } return ans; } double dvdzeta(double x_1,double x_2,double xi,double zeta) { double ans; if (fabs(zeta)<SMALL) { double x_2t2 = x_2*x_2; double x_2t3 = x_2*x_2*x_2; double x_2t4 = x_2*x_2*x_2*x_2; double x_2t5 = x_2*x_2*x_2*x_2*x_2; double x_2t6 = x_2*x_2*x_2*x_2*x_2*x_2; double x_2t7 = x_2*x_2*x_2*x_2*x_2*x_2*x_2; double x_1t2 = x_1*x_1; double x_1t3 = x_1*x_1*x_1; double x_1t4 = x_1*x_1*x_1*x_1; double x_1t5 = x_1*x_1*x_1*x_1*x_1; double x_1t6 = x_1*x_1*x_1*x_1*x_1*x_1; double x_1t7 = x_1*x_1*x_1*x_1*x_1*x_1*x_1; double a0,a1,a2,a3,a4,a5; a0 = -2*cos(2*xi)*x_2t2+2*cos(2*xi)*x_1t2+2*sin(2*xi)*x_2-2*sin(2*xi)*x_1; a1 = +(8*sin(2*xi)*x_2t3*(1/3.0)-8*sin(2*xi)*x_1t3*(1/3.0) +4*cos(2*xi)*x_2t2-4*cos(2*xi)*x_1t2); a2 = +(2*cos(2*xi)*x_2t4-2*cos(2*xi)*x_1t4 -4*sin(2*xi)*x_2t3+4*sin(2*xi)*x_1t3); a3 = +(-16*sin(2*xi)*x_2t5*(1/15.0)+16*sin(2*xi)*x_1t5*(1/15.0) -8*cos(2*xi)*x_2t4*(1/3.0)+8*cos(2*xi)*x_1t4*(1/3.0)); a4 = +(-4*cos(2*xi)*x_2t6*(1/9.0)+4*cos(2*xi)*x_1t6*(1/9.0) +4*sin(2*xi)*x_2t5*(1/3.0)-4*sin(2*xi)*x_1t5*(1/3.0)); a5 = +(16*sin(2*xi)*x_2t7*(1/105.0)-16*sin(2*xi)*x_1t7*(1/105.0) +8*cos(2*xi)*x_2t6*(1/15.0)-8*cos(2*xi)*x_1t6*(1/15.0)); ans = (a0 + a1*zeta + a2*zeta*zeta + a3*zeta*zeta*zeta + a4*zeta*zeta*zeta*zeta + a5*zeta*zeta*zeta*zeta*zeta); } else { ans = (1/zeta-1)*(2*x_1*sin(2*(zeta*x_1+xi))-2*x_2*sin(2*(zeta*x_2+xi))); ans += -1/(zeta*zeta)*(cos(2*(zeta*x_2+xi))-cos(2*(zeta*x_1+xi))); } return ans; }
C
/* ============================================================================= A finite volume code to solve the Saint-Venant system in an open channel. ============================================================================= Copyright (C) 2013 Mathieu Besson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.*/ /* ============================================================================= Bodies of functions and procedures for the topography ============================================================================= */ #include "topography.h" void bumpBed(float Z[nbCell+2],float dx) { int i; float x; for(i=0;i<=nbCell+1;i++) { x = (bInf + dx/2.0) + (i-1)*dx; if((x>=-2.0)&&(x<=2.0)) { Z[i] = 0.2 - 0.05*x*x; } else { Z[i] = 0.0; } } } void bumpBedConstantPiecwise(float Z[nbCell+2],float dx) { int i; float xPlus,xMinus; for(i=0;i<=nbCell;i++) { xMinus = bInf + i*dx; xPlus = bInf + (i+1)*dx; if((xPlus<=2.0)&&(xMinus>=-2.0)) { Z[i] = 0.2 - (0.05/3.0)*(xPlus*xPlus + xPlus*xMinus + xMinus*xMinus); } else { if(((xPlus<=2.0)&&(xPlus>=-2.0))&&(xMinus<-2.0)) { Z[i] = (1.0/dx)*(0.2*xPlus - (0.05/3.0)*xPlus*xPlus*xPlus + 0.8/3.0); } else { if(((xMinus>=-2.0)&&(xMinus<=2.0))&&(xPlus>2.0)) { Z[i] = (1.0/dx)*((0.8/3.0) - 0.2*xMinus + (0.05/3.0)*xMinus*xMinus*xMinus); } else { Z[i] = 0.0; } } } } Z[nbCell+1] = 0.0; } void stepBed(float Z[nbCell+2],float dx) { int i; float xCentre,xMinus,xPlus; float midDomain; midDomain = (bSup+bInf)/2.0; for(i=0;i<=nbCell;i++) { xCentre = (bInf + dx/2.0) + (i-1)*dx; xMinus = bInf + i*dx; xPlus = bInf + (i+1)*dx; if((xMinus<midDomain)&&(xPlus>midDomain)) { Z[i] = (0.3/dx)*(xPlus - midDomain); } else { if(xCentre>=midDomain) { Z[i] = 0.3; } else { Z[i] = 0.0; } } } Z[nbCell+1] = Z[nbCell]; } void noBed(float Z[nbCell+2]) { int i; for(i=0;i<=nbCell+1;i++) { Z[i] = 0.0; } } void constantBed(float Z[nbCell+2]) { int i; for(i=0;i<=nbCell+1;i++) { Z[i] = 0.5; } }
C
#include "PowerSetString.h" void printPsetAndHashTest(Node *stack, HashMap* m) { int found,chain_position, count=0; Node *hash_entry, *item=stack; printf("\tP(S)={\n"); while(item != NULL) { printf("%d)\t\t{%s} ", count++,item->S); //Lists the number of the subset within the power set found=0; chain_position=0; size_t h = djb2Hash(item->S) % m->size; hash_entry=m->map[h]; while(hash_entry) { chain_position++; if(strncmp(hash_entry->S,item->S,item->length)!=0) { hash_entry = hash_entry->next; } else { found=1; break; } } if (found) { printf("-> hash hit at entry %zu with chain position %d\n",h, chain_position); } else if (chain_position) { printf("-> hash hit at entry %zu, not located in chain\n",h); } else { printf("-> hash miss! Hash value %zu is empty! \n", h); } item=item->next; } printf("\t};\n"); } int calculatePowerSet(char *str, int str_length) { int i, collisions=0; Node *temp_stack = NULL; Node *item=NULL; // this stack will be populated and used to replace the need for recursive calls printf("%s\n", "Filling stack with single chars from base string"); for(i=0;i<str_length;i++) { push(&temp_stack, &str[i], 1, i); printf("\t %c\n", str[i]); } printf("%s\n", "Calculating Power Set..."); push(&saved_stack, "", 0, -1); // Adds the empty set while(temp_stack!=NULL) { item=pop(&temp_stack); printf("\t popped %s from the stack \n",item->S); push(&saved_stack, item->S, item->length, str_length); // consider removing saved_map and saved_stack for a more functional design collisions += hashMapInsert(saved_map, item); printf("\t saved %s\n",saved_stack->S); for(i=item->last_index; i<str_length-1; i++){ //iterates last item through the size of the subset push(&temp_stack, item->S, item->length+1, i+1); strncat(temp_stack->S,&str[i+1],1); printf("\t %s pushed to stack \n",temp_stack->S); printf("\t next char: %c\n",str[i+1]); } destroyNode(item); } printf("Power Set calculation complete\n"); return collisions; } int main(int argc, char **argv) { if (argc<2) { printf("A single base string is required as input.\nOptionally you can also enter the buckets for the hash table as a 2nd input.\n"); return 0; } int c, i, proceed=1, buffer_length = 20, str_length = strlen(argv[1]); size_t h, buckets, count, collisions; Node* item; if (argc>2) { buckets = atoi(argv[2]); } else { printf("Default load factor is ~50%%\n"); buckets = (((size_t) 1) << (str_length+1))-1; } saved_map = hashMapCreate(buckets); sortStr(argv[1],str_length); collisions = calculatePowerSet(argv[1],str_length); printPsetAndHashTest(saved_stack,saved_map); printf("Hash table load factor: %d / %d = %f\n", (1<<str_length), buckets, ( (1<<str_length) / (float) buckets)); printf("Number of hash map insertions: %d\n", (1 << str_length)); printf("Number of collisions: %d or %.2f%%\n", collisions, 100 * collisions / (float) (1 << str_length)); char* user_str = malloc(sizeof(char) * buffer_length); assert(user_str); while(1) { printf("%s\n", "Enter str to see it exists in the power set: "); while(1) { c = getchar(); if (c==EOF || c=='\n') { proceed=0; break; } if (!isTokenizer(c)) { ungetc(c, stdin); break; } } if(proceed==0) { break; } i=0; while(1) { c = getchar(); if(isTokenizer(c) || c==EOF) { user_str[i] = 0; //terminating 0 break; } user_str[i]=c; if (i == buffer_length - 1) { // buffer is full buffer_length = buffer_length + buffer_length; user_str = realloc(user_str, sizeof(char)*buffer_length); assert(user_str); } i++; } count=0; sortStr(user_str,i); h = djb2Hash(user_str) % saved_map->size; if (saved_map->map[h]) { printf("%s\n", "Hash hit! Checking entries..."); item = saved_map->map[h]; while(item) { printf("Entry #%d : %s",count, item->S); if(strncmp(item->S, user_str, item->length)!= 0) { printf(" -> %s\n", "not a match..."); } else { printf(" -> %s\n", "match found!"); } count++; item=item->next; } } else { printf("%s\n", "Hash miss, this str could not be found..."); } memset(user_str,0,buffer_length); } free(user_str); return 0; }
C
#include "pthread.h" #include <stdio.h> #include <stdlib.h> #include <string.h> void *thread_function(void *arg); int flag = 1; int main(void) { int res; int count = 1; pthread_t a_thread; void *thread_result; /* ߳ */ res = pthread_create(&a_thread, NULL, thread_function, NULL); if (0 != res) { perror("Thread create failed!"); exit(EXIT_FAILURE); } while (count++ <= 20) { if (flag == 1) { printf ("1\r\n"); flag = 2; } else { sleep(1); } } printf("Waiting for thread to finish...\r\n"); /* ߳ͬǰ̵߳ȴa_thread */ res = pthread_join(a_thread, &thread_result); printf("Thread joined, it returned %s\r\n", (char *)thread_result); exit(EXIT_FAILURE); } /* ̵߳Ļص */ void *thread_function(void *arg) { int count = 1; while (count++ <= 20) { if (flag == 2) { printf("2\r\n"); flag = 1; } else { sleep(1); } } /* ֹ߳ijָ룬Ǿֲ */ pthread_exit("Thank you for your CPU time!"); }
C
#ifndef __RUTILS_H #define __RUTILS_H #include <math.h> #include <windows.h> #include <crtdbg.h> const float pi=3.141592654f; typedef enum {NEGATIVE= -1, ZERO= 0, POSITIVE= 1} SIGN; #define TOLER 0.0000076 #define IS_EQ(a,b) ((fabs((double)(a)-(b)) >= (double) TOLER) ? 0 : 1) #define IS_EQ3(a,b) (IS_EQ((a).x,(b).x)&&IS_EQ((a).y,(b).y)&&IS_EQ((a).z,(b).z)) #define signof(f) (((f) < -TOLER) ? NEGATIVE : ((f) > TOLER ? POSITIVE : ZERO)) #define RANDOMFLOAT ((float)rand()/(float)RAND_MAX) // RELEASE & DELETE ũ ( from dxutil.h ) #ifndef SAFE_DELETE #define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } #endif #ifndef SAFE_DELETE_ARRAY #define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } } #endif #ifndef SAFE_RELEASE #define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } #endif typedef struct { float x1,y1,x2,y2; } FRECT,*LPFRECT; typedef union { struct { float Minx,Maxx,Miny,Maxy,Minz,Maxz; }; float m[3][2]; } rboundingbox; struct rvector { public: float x,y,z; rvector(float _x,float _y,float _z) { x=_x;y=_y;z=_z;} rvector(const rvector &v) { x=v.x;y=v.y;z=v.z; } rvector() {}; inline friend rvector operator - (const rvector &v) { return rvector(-v.x,-v.y,-v.z); } inline friend rvector operator - (const rvector& v1, const rvector& v2) { return rvector(v1.x-v2.x, v1.y-v2.y, v1.z-v2.z); } inline friend rvector operator + (const rvector& v1, const rvector& v2) { return rvector(v1.x+v2.x, v1.y+v2.y, v1.z+v2.z); } inline friend void operator += (rvector& v, const rvector& v2) { v.x+=v2.x;v.y+=v2.y;v.z+=v2.z; } inline friend void operator -= (rvector& v, const rvector& v2) { v.x-=v2.x;v.y-=v2.y;v.z-=v2.z; } inline friend void operator *= (rvector& v, const float c) { v.x*=c;v.y*=c;v.z*=c; } inline friend void operator /= (rvector& v, const float c) { v.x/=c;v.y/=c;v.z/=c; } inline friend rvector operator * (const float c, const rvector& v) { return rvector(c*v.x, c*v.y, c*v.z); } inline friend rvector operator * (const rvector& v,const float c) { return rvector(c*v.x, c*v.y, c*v.z); } inline friend rvector operator / (const rvector& v,const float c) { return rvector(v.x/c, v.y/c, v.z/c); } inline friend bool operator==(const rvector& l, const rvector& r) { return (l.x==r.x && l.y==r.y && l.z==r.z); } inline friend bool operator!=(const rvector& l, const rvector& r) { return !(l.x==r.x && l.y==r.y && l.z==r.z); } inline float GetDistance(const rvector &v) const { return sqrtf((v.x-x)*(v.x-x)+(v.y-y)*(v.y-y)+(v.z-z)*(v.z-z)); } inline bool IsZero(void) const { return (x==0.0f && y==0.0f && z==0.0f); } inline float GetMagnitude() const { return sqrtf(x*x+y*y+z*z); } inline float GetSafeMagnitude() { if(IsZero()) return 0; else return (float)sqrt(x*x+y*y+z*z); } inline void Normalize(){ float t=GetMagnitude(); _ASSERT(t>0); x = x/t; y = y/t; z = z/t; } inline friend rvector Normalize(const rvector & v){ rvector r; float t; t = ((rvector*)&v)->GetMagnitude(); _ASSERT(t>0); r.x = v.x/t; r.y = v.y/t; r.z = v.z/t; return r; } /* inline friend rvector SafeNormalize(const rvector & v){ if(v.IsZero()) return v; return Normalize(v); } */ inline friend float DotProduct (const rvector& v1, const rvector& v2) { return v1.x*v2.x + v1.y * v2.y + v1.z*v2.z; } inline friend rvector CrossProduct (const rvector& v1, const rvector& v2) { rvector result; result.x = v1.y * v2.z - v1.z * v2.y; result.y = v1.z * v2.x - v1.x * v2.z; result.z = v1.x * v2.y - v1.y * v2.x; // _ASSERT((result.x!=0.0f)||(result.y!=0.0f)||(result.z!=0.0f)); return result; }; }; struct rplane { union { struct { float a,b,c,d; }; struct { rvector normal; float d; }; float m[4]; }; }; struct rmatrix43 { union { struct { float _11, _12, _13; float _21, _22, _23; float _31, _32, _33; float _41, _42, _43; }; float m[4][3]; }; rmatrix43() {} rmatrix43( float m11,float m12,float m13, float m21,float m22,float m23, float m31,float m32,float m33, float m41,float m42,float m43) { _11=m11;_12=m12;_13=m13; _21=m21;_22=m22;_23=m23; _31=m31;_32=m32;_33=m33; _41=m41;_42=m42;_43=m43; } }; #pragma pack(16) struct rmatrix44 { union { struct { float _11, _12, _13, _14; float _21, _22, _23, _24; float _31, _32, _33, _34; float _41, _42, _43, _44; }; float m[4][4]; }; rmatrix44() {} rmatrix44( float m11,float m12,float m13,float m14, float m21,float m22,float m23,float m24, float m31,float m32,float m33,float m34, float m41,float m42,float m43,float m44) { _11=m11;_12=m12;_13=m13;_14=m14; _21=m21;_22=m22;_23=m23;_24=m24; _31=m31;_32=m32;_33=m33;_34=m34; _41=m41;_42=m42;_43=m43;_44=m44; } float& operator()(int iRow, int iColumn) { return m[iRow][iColumn]; } const float& operator()(int iRow, int iColumn) const { return m[iRow][iColumn]; } }; #pragma pack() typedef rmatrix43 rmatrix; // Arithmatic Functions of Matrix rmatrix ZeroMatrix(); rmatrix IdentityMatrix(); rmatrix RotateZMatrix(const float rads); rmatrix RotateYMatrix(const float rads); rmatrix RotateXMatrix(const float rads); rmatrix TranslateMatrix(const float dx, const float dy, const float dz); rmatrix TranslateMatrix(const rvector &v); rmatrix ScaleMatrix(const float size); rmatrix ScaleMatrixXYZ(const float x,const float y,const float z); rvector TransformNormal(rvector &v,rmatrix &m); rvector TransformVector(rvector &v,rmatrix &m); rmatrix ViewMatrix(const rvector& from,const rvector& at,const rvector& world_up,const float roll); rmatrix ViewMatrix(const rvector& from,const rvector& dir,const rvector& world_up); rmatrix ViewMatrix(const rvector &from,const rvector &dir); rmatrix MatrixInverse(const rmatrix & m); // followings are 44 matrix functions rmatrix44 ZeroMatrix44(); rmatrix44 IdentityMatrix44(); rmatrix44 RotateZMatrix44(const float rads); rmatrix44 RotateYMatrix44(const float rads); rmatrix44 RotateXMatrix44(const float rads); rmatrix44 TranslateMatrix44(const float dx, const float dy, const float dz); rmatrix44 TranslateMatrix44(const rvector &v); rmatrix44 ScaleMatrix44(const float size); rmatrix44 ScaleMatrixXYZ44(const float x,const float y,const float z); rvector TransformNormal(rvector &v,rmatrix44 &m); rvector TransformVector(rvector &v,rmatrix44 &m); rmatrix44 ViewMatrix44(const rvector& from,const rvector& at,const rvector& world_up,const float roll); rmatrix44 ViewMatrix44(const rvector& from,const rvector& dir,const rvector& world_up); rmatrix44 ViewMatrix44(const rvector &from,const rvector &dir); rmatrix44 ProjectionMatrix(const float near_plane,const float far_plane, const float fov_horiz,const float fov_vert, bool bFlipHoriz=false,bool bFlipVert=false); rmatrix44 MatrixInverse(const rmatrix44 & m); rmatrix MatrixMult(rmatrix &m1,rmatrix &m2); rmatrix44 MatrixMult(rmatrix &m1,rmatrix44 &m2); rmatrix44 MatrixMult(rmatrix44 &m1,rmatrix &m2); typedef rmatrix44(_MatrixMult44)(rmatrix44 &m1,rmatrix44 &m2); extern _MatrixMult44 *MatrixMult44; inline rmatrix operator * (rmatrix& m1,rmatrix& m2) { return MatrixMult(m1,m2); } inline rmatrix44 operator * (rmatrix& m1,rmatrix44& m2) { return MatrixMult(m1,m2); } inline rmatrix44 operator * (rmatrix44& m1,rmatrix& m2) { return MatrixMult(m1,m2); } inline rmatrix44 operator * (rmatrix44& m1,rmatrix44& m2) { return MatrixMult44(m1,m2); } // help functions float GetAngle(rvector &a); float GetAngleOfVectors(rvector &ta,rvector &tb); rvector InterpolatedVector(rvector &a,rvector &b,float t1); rmatrix ReflectionMatrix(rvector &dir,rvector &apoint); rmatrix ShadowProjectionMatrix(rvector &normal,rvector &apoint,rvector &lightdir); // Initialize .. void RUtils_Initilize(); extern bool g_bSSE; #endif
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* libft.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: afaucher <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2013/11/20 14:37:27 by afaucher #+# #+# */ /* Updated: 2014/01/05 14:09:14 by afaucher ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef __LIBFT_H__ # define __LIBFT_H__ # include <string.h> # include "maths/maths.h" typedef struct s_list { void *content; size_t content_size; struct s_list *next; } t_list; int ft_isalnum(int c); int ft_isalpha(int c); int ft_isdigit(int c); int ft_isascii(int c); int ft_isprint(int c); int ft_tolower(int c); int ft_toupper(int c); size_t ft_strlen(const char *s); char *ft_strdup(const char *s1); char *ft_strcpy(char *s1, const char *s2); char *ft_strncpy(char *s1, const char *s2, size_t n); char *ft_strcat(char *s1, const char *s2); char *ft_strncat(char *s1, const char *s2, size_t n); size_t ft_strlcat(char *dst, const char *src, size_t size); char *ft_strchr(const char *s, int c); char *ft_strrchr(const char *s, int c); char *ft_strstr(const char *s1, const char *s2); char *ft_strnstr(const char *s1, const char *s2, size_t n); int ft_strcmp(const char *s1, const char *s2); int ft_strncmp(const char *s1, const char *s2, size_t n); void *ft_memset(void *b, int c, size_t len); void ft_bzero(void *s, size_t n); void *ft_memcpy(void *s1, const void *s2, size_t n); void *ft_memccpy(void *s1, const void *s2, int c, size_t n); void *ft_memmove(void *s1, const void *s2, size_t n); int ft_memcmp(const void *s1, const void *s2, size_t n); void *ft_memchr(const void *s, int c, size_t n); void *ft_memalloc(size_t size); void ft_memdel(void **ap); char *ft_strnew(size_t size); void ft_strdel(char **as); void ft_strclr(char *s); void ft_striter(char *s, void (*f)(char *)); void ft_striteri(char *s, void (*f)(unsigned int, char *)); char *ft_strmap(const char *s, char (*f)(char)); char *ft_strmapi(const char *s, char (*f)(unsigned int, char)); int ft_strequ(const char *s1, const char *s2); int ft_strnequ(char const *s1, const char *s2, size_t n); char *ft_strsub(char const *s, unsigned int start, size_t len); char *ft_strjoin(char const *s1, char const *s2); char *ft_strtrim(char const *s); char **ft_strsplit(char const *s, char c); char *ft_itoa(int n); int ft_atoi(const char *str); void ft_putstr(const char *s); int ft_putstr_fd(const char *s, int fd); void ft_putendl(const char *s); int ft_putendl_fd(const char *s, int fd); void ft_putnbr(int n); void ft_putnbr_fd(int n, int fd); void ft_putchar(char c); void ft_putchar_fd(char c, int fd); t_list *ft_lstnew(void const *content, size_t content_size); void ft_lstdelone(t_list **alst, void (*del)(void *, size_t)); void ft_lstdel(t_list **alst, void (*del)(void *, size_t)); void ft_lstadd(t_list **alst, t_list *lnew); t_list *ft_lstlast(t_list *lst); void ft_lstaddlast(t_list **alst, t_list *lnew); void ft_lstiter(t_list *lst, void (*f)(t_list *elem)); t_list *ft_lstmap(t_list *lst, t_list *(*f)(t_list *elem)); t_list *ft_lstgetprev(t_list **begin_list, t_list *elem); void ft_lstswap(t_list *elem1, t_list *elem2); void ft_lstsort(t_list *lst, int (*cmp)()); void ft_lstinv(t_list **begin_list); int ft_match(char *s1, char *s2); int ft_nmatch(char *s1, char *s2); void *ft_memdup(void *s, size_t n); void ft_puttab(char *s); void ft_puttab_fd(char *s, int fd); int ft_strintab(char *str, char **tab, int size); void ft_swap(char **str1_tr, char **str1_ptr); void ft_memswap(void **ptr1, void **ptr2); void ft_sort_wordtab(char **tab); char *ft_align_right(const char *str, size_t size); char *ft_align_left(const char *str, size_t size); size_t ft_nbdigit(int nb); char *ft_tostr(char c); char *ft_getfilename(char *path); int ft_lstlen(t_list *list); int ft_get_next_line(int fd, char **line); #endif /* !__LIBFT_H__ */
C
// // Created by PCHEN on 2020-03-17. // #include <pr_pool_blocklist.h> #include <pr_mem.h> #include <assert.h> //////////////////////////////////////////////////////////////////////////////// struct pr_pool_blocklink_s{ void* d_block_p; struct pr_pool_blocklink_s * d_next_p; }; typedef struct pr_pool_blocklink_s pr_pool_blocklink_t; struct pr_pool_blocklist_s{ pr_pool_blocklink_t * d_blockList_p; }; //////////////////////////////////////////////////////////////////////////////// // blocklist pr_pool_blocklist_t * pr_pool_blocklist_new(){ pr_pool_blocklist_t* p = MALLOC(sizeof(*p)); assert(p); p->d_blockList_p = NULL; return p; } void pr_pool_blocklist_delete(pr_pool_blocklist_t** pp){ assert(pp); assert(*pp); pr_pool_blocklist_t* p = *pp; while(p->d_blockList_p){ pr_pool_blocklink_t* q = p->d_blockList_p; p->d_blockList_p = q->d_next_p; FREE(q); } FREE(*pp); } void pr_pool_blocklist_release(pr_pool_blocklist_t* p){ assert(p); while(p->d_blockList_p){ pr_pool_blocklink_t* q = p->d_blockList_p; p->d_blockList_p = q->d_next_p; FREE(q); } } void* pr_pool_blocklist_alloc(pr_pool_blocklist_t * t, int nbytes){ assert(t); pr_pool_blocklink_t * link = MALLOC(sizeof(*link)); assert(link); link->d_block_p = MALLOC(nbytes); assert(link->d_block_p); link->d_next_p = t->d_blockList_p; t->d_blockList_p = link; return link->d_block_p; }
C
#include <stdio.h> int ggT(int a, int b); void test(int a, int b); int main(int argc, char* argv[]) { int a = 0, b = 0; // setze den testmodus auf 1, wenn du es nicht einlesen möchtest int testmodus = 0; if(testmodus) { printf("### TEST ###\n"); test(1, 3); test(5, 10); test(6, 9); test(1337, 1338); } else { printf("Berechnung des ggT von zwei Zahlen\n\n"); printf("Gib Zahl 1 ein:\n"); scanf(" %d", &a); printf("Gib Zahl 2 ein:\n"); scanf(" %d", &b); printf("Der größte gemeinsame Teiler von %d und %d ist: %d\n", a, b, ggT(a, b)); } } int ggT(int a, int b) { // 1 ist im Zweifel immer der ggT int ggT = 1; // wir müssen nur über alle Zahlen zwischen 1 und der kleineren Zahl iterieren // Optimierungsmöglichkeit: wir müssen sogar nur zwischen der kleineren Zahl und ihrer Hälfte iterieren int lower = a > b ? b : a; for(int i = lower; i > 0; i--) { if(a % i == 0 && b % i == 0) { ggT = i; break; } } return ggT; } // nur zum testen void test(int a, int b) { printf("Der größte gemeinsame Teiler von %d und %d ist: %d\n", a, b, ggT(a, b)); }
C
/* Aluminum foil has a thickness of 0.025mm. A roll is formed by tightly winding it around a tube with an outside diameter of 4cm. Given the length of the foil in cm, write a function that returns the diameter of the roll in cm measured at its thickest point. Round the result to four places. Examples foil(0) ➞ 4.0 foil(50) ➞ 4.02 foil(4321) ➞ 5.4575 foil(10000) ➞ 6.9175 Notes N/A */ #define _GNU_SOURCE #include <assert.h> #include <stdio.h> #include <math.h> // https://math.la.asu.edu/~rich/puzzles/prob002s.html // L = n*l // d = pi*(R*r - r*r)/[n*l - pi*(R - r)] // solve for R // R = (-d*pi + sqrt(pi*(4*L*d + d**2*pi + 4*d*pi*r + 4*pi*r**2)))/(2*pi) // diameter of the thickest point = 2*R double foil(double L) { static const double pi = M_PI; double d, r; d = 0.0025; r = 2.0; return (-d * pi + sqrt(pi * (4 * L * d + d * d * pi + 4 * d * pi * r + 4 * pi * r * r))) / pi; } void test(double L, double r) { assert(fabs(foil(L) - r) < 1e-2); } int main(void) { test(0, 4.0); test(6, 4.0025); test(7, 4.005); test(12, 4.005); test(13, 4.0075); test(1000, 4.3825); test(4321, 5.4575); test(7777, 6.385); test(10000, 6.9175); test(123456, 20.2275); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> //se digitar 4, vai de 0 a 4, 4 é a 5º linha int fatorial(int n) { int fat; for (fat = 1; n > 1; n--) fat = fat * n; return fat; } int CoefBinomial(int n, int k) { int resposta; int k_fatorial, n_fatorial; n_fatorial = fatorial(n); k_fatorial = fatorial(k); resposta = (n_fatorial) / (k_fatorial * (fatorial(n - k))); return resposta; } int main() { int N; scanf("%d", &N); for (int i = 0; i <= N; i++) { for (int j = 0; j < i + 1; j++) { int ans; ans = CoefBinomial(i, j); printf("%d ", ans); } printf("\n"); } return 0; }
C
#include "sandpiles.h" /** * print_grid - prints a matrix * @grid: 3x3 matrix */ static void print_grid(int grid[3][3]) { int x, y; for (x = 0; x < 3; x++) { for (y = 0; y < 3; y++) { if (y) printf(" "); printf("%d", grid[x][y]); } printf("\n"); } } /** * add_matrix - adds 2 matrixes together * @grid1: 3x3 matrix * @grid2: 3x3 matrix */ void add_matrix(int grid1[3][3], int grid2[3][3]) { int x, y; for (x = 0; x < 3; x++) for (y = 0; y < 3; y++) grid1[x][y] = grid1[x][y] + grid2[x][y]; } /** * sandpile - checks to see if a matrix is stable (all values must * be between 0 and 3) * @grid: 3x3 matrix * Return: true or false */ int sandpile(int grid[3][3]) { int x, y; for (x = 0; x < 3; x++) for (y = 0; y < 3; y++) if (grid[x][y] > 3) return (0); return (1); } /** * downfall - collapses a sandpile at a given index * @grid: input grid * @x: input row * @y: input col */ void downfall(int grid[3][3], int x, int y) { int r, a, b; int directions[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; for (r = 0; r < 4; r++) { a = x + directions[r][0]; b = y + directions[r][1]; if ((a >= 0 && a < 3) && (b >= 0 && b < 3)) grid[a][b] += 1; } grid[x][y] -= 4; } /** * sandpiles_sum - sum two matrixes and balances them out * @grid1: 3x3 matrix * @grid2: 3x3 matrix */ void sandpiles_sum(int grid1[3][3], int grid2[3][3]) { int s[3][3]; int x, y, stable = 0; add_matrix(grid1, grid2); while (1) { stable = sandpile(grid1); if (!stable) { printf("=\n"); print_grid(grid1); memcpy(s, grid1, 3 * 3 * sizeof(int)); for (x = 0; x < 3; x++) for (y = 0; y < 3; y++) if (grid1[x][y] > 3) downfall(s, x, y); memcpy(grid1, s, 3 * 3 * sizeof(int)); } else break; } }
C
#include <stdio.h> #include <stdlib.h> int main(void) { int a = 2; int b; /* * Define a constant integer, so the data can never change. * Define a constant pointer, so the pointer can only point to one memory address. * Trying to change either is a compile time error. */ const int *const intPointer = &a; printf("# Constant Pointer To Constant Data\n## Display Address & Value"); /* * Need to cast to a void pointer as that is what %p expects. * Direclty updating the variable is okay because it isn't defined as constant. */ printf("The value at address %p is %d\n", (void *) intPointer, a); a++; printf("The value at address %p after variable++ is %d\n", (void *) intPointer, a); printf("## Attempting To Update Constant Pointer & Constant Variable - compile time error\n"); /* * Assign a value to a new variable * Attempt to update the constant pointer's constant data to the new variable's address. * This is a compile time error. */ b = 2 * 2; intPointer = &b; /* * Attempt to update the constant pointer's value directly. * This is a compile time error. */ *intPointer = 4; return EXIT_SUCCESS; }
C
/* 23 Una papelera vende libros a $100, cuadernos a $15.50 y plumas a $2.35. E.P. que determine e imprima el monto total de una venta, segn el nmero de artculos vendidos. Elaborado por: Ricardo Nicols Canul Ibarra Senaida Norely Chan Chan Javier Alejandro Chim Cem Fecha: 31/ene/2019 Version: 1.0rev Revisado por: Equipo Picateclas Observaciones: El programa cumple con los requisitos dados, funciona correctamente. */ #include <stdio.h> #include <conio.h> int main() { /*Inicializamos las variables necesarias para el programa*/ int total_libros, total_cuadernos, total_plumas; /*Pedimos que se inserte el total de libros*/ printf("\nInserte el nmero de libros vendidos "); scanf("%i", &total_libros); //Leemos el total de libros /*Pedimos que se inserte el total de cuadernos*/ printf("\nInserte el nmero de cudernos vendidos "); scanf("%i", &total_cuadernos); //Leemos el total de cuadernos /*Pedimos que se inserte el total de plumas*/ printf("\nInserte el nmero de plumas vendidos "); scanf("%i", &total_plumas); //Leemos el total de plumas /*Mostramos la salida y, dentro de la misma, se encuentra el calculo para el resultado*/ printf("\nEl total de la venta es de: $%.2f", (float)total_libros * 100 + total_cuadernos * 15.5 + total_plumas * 2.35); getch(); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ls_maker.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ymarji <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/02/25 18:25:56 by ymarji #+# #+# */ /* Updated: 2021/05/03 16:01:30 by ymarji ### ########.fr */ /* */ /* ************************************************************************** */ #include "../minishell.h" t_env *ft_lstlast_m(t_env *lst) { t_env *tmp; tmp = lst; if (tmp == NULL) return (NULL); while (tmp->next != NULL) tmp = tmp->next; return (tmp); } void ft_lstadd_back_m(t_env **alst, t_env *new) { t_env *p; if (*alst == NULL) { *alst = new; return ; } p = ft_lstlast_m(*alst); p->next = new; new->prev = p; } int ft_lstsize_m(t_env *lst) { int cp; cp = 0; while (lst != NULL) { cp++; lst = lst->next; } return (cp); } t_env *ft_lstnew_m(void *ident, void *value, char equal) { t_env *new; new = (t_env *)malloc(sizeof(t_env)); if (new == NULL) return (0); new->ident = ident; new->value = value; new->equal = equal; new->next = NULL; new->prev = NULL; return (new); } void ft_deletenode(t_env **head_ref, t_env *del) { if (*head_ref == NULL || del == NULL) return ; if (*head_ref == del) *head_ref = del->next; if (del->next != NULL) del->next->prev = del->prev; if (del->prev != NULL) del->prev->next = del->next; free(del->ident); free(del->value); free(del); con.exit_stat = 0; }
C
#include <stdio.h> #include <time.h> #include <stdlib.h> void genArr(int arr[], int n){ int i; for (i = 0;i < n; i++){ arr[i] = rand()%1000+1; } } void printArr(int arr[], int n){ int i; for (i = 0; i < n; i++){ printf("%d ",arr[i]); } printf("\n"); } void shellSort(int arr[], int n){ int k = n / 2; int i; for (;k > 0; k /= 2){ for (i = k; i < n; i++){ int temp = arr[i]; int j; for (j = i; j >= k && arr[j - k] > temp; j -= k){ arr[j] = arr[j - k]; } arr[j] = temp; } } } int main(){ int n; scanf("%d", &n); int arr[n]; genArr(arr,n); shellSort(arr,n); printArr(arr,n); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_ELEMENT_NB 10 struct element{ unsigned int id; unsigned int cnt; }; struct table{ struct element ele[MAX_ELEMENT_NB]; unsigned int nb; }; void table_init(void) { return; } unsigned int find_element(unsigned int id) { unsigned int i; for(i=0; i<MAX_ELEMENT_NB; i++){ if(table.ele[i].id == id){ break; } } if(i == MAX_ELEMENT_NB) i=0; return i; } void table_add(unsigned int id) { unsigned int i; i= find_element(id); if(0 == i){ if(table.nb < MAX_ELEMENT_NB){ table.nb ++; printf("new table\n"); } else printf("table full\n"); } else{ printf("old table\n"); } } void table_loop(unsigned int id) { unsigned int i; for(i=0; i<MAX_ELEMENT_NB; i++){ if(table.ele[i].cnt > 0){ table.ele[i].cnt--; } } } void table_printf(unsigned int id) { unsigned int i; printf("id table:\n"); for(i=0; i<MAX_ELEMENT_NB; i++){ if(table.ele[i].cnt > 0){ printf("id: %03d\n", table.ele[i].id); } } printf("\n"); } int main(int argc ,char** argv) { return 0; }
C
#include<stdio.h> struct data { int val; short int num; float f; char name[10]; }size; int main() { struct data *ptr=NULL; ptr++; printf("%d\n",ptr); }
C
#include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/uio.h> #define BUFFSIZE 8192 int main(){ int fdi,fdo; char buf[BUFFSIZE]; fdi = open("input.txt",O_RDONLY); fdo = open("lseekout.txt",O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH); lseek(fdi, 100, SEEK_SET); //lseek(fdo, 20, SEEK_SET); int n; while((n = read(fdi,buf,BUFFSIZE)) > 0){ int out = write(fdo,buf,n); if(n != out){ printf("Write error!\n"); } } close(fdi); close(fdo); return 0; }
C
/****************************************************************************** Linked List Implementation. *******************************************************************************/ #include <stdio.h> #include <stdlib.h> /***Node structure***/ struct Node { int data; struct Node* next; }; struct Node* head=NULL; /***make the head pointer global to be used in every function***/ void traverse(struct Node* n) { printf("----------------TRAVERSING-----------------\n"); struct Node* presentNode=n; if (presentNode==NULL) { printf("EMPTY LINKED LIST\n"); } while(presentNode) { printf("Data=%d and Reference=%u\n",presentNode->data,presentNode->next); presentNode=presentNode->next; } } void insert_beginning(int new_data) { printf("----------------INSERTING NODE AT THE BEGINNING-----------------\n"); struct Node* new_node=NULL; new_node = (struct Node*)malloc(sizeof(struct Node)); if (new_node==NULL) { printf("INSERTION UNSUCCESSFUL: MEMORY USAGE FULL\n"); } else { new_node->data=new_data; new_node->next=head; head=new_node; printf("INSERTION SUCCESSFUL\n"); } } void insert_end(int new_data) { printf("----------------INSERTING NODE AT THE END-----------------\n"); struct Node* new_node=NULL; new_node = (struct Node*)malloc(sizeof(struct Node)); if (new_node==NULL) { printf("INSERTION UNSUCCESSFUL: UNABLE TO ALLOCATE MEMORY\n"); } else { struct Node* presentNode=head; while (presentNode->next) { presentNode=presentNode->next; } new_node->data=new_data; presentNode->next=new_node; new_node->next=NULL; printf("INSERTION SUCCESSFUL\n"); } } void insert_between(int new_data, struct Node*before) { printf("----------------INSERTING NODE IN BETWEEN-----------------\n"); struct Node* new_node=NULL; new_node = (struct Node*)malloc(sizeof(struct Node)); if (new_node==NULL) { printf("INSERTION UNSUCCESSFUL: UNABLE TO ALLOCATE MEMORY\n"); } else { new_node->data=new_data; new_node->next=NULL; struct Node* presentNode=head; while (presentNode->next!=before) { presentNode=presentNode->next; } new_node->next=presentNode->next; presentNode->next=new_node; printf("INSERTION SUCCESSFUL\n"); } } void delete_first() { printf("----------------DELETING THE FIRST NODE-----------------\n"); struct Node* del_node=head; if(head==NULL) { printf("LINKED LIST IS EMPTY\n"); } else { head=head->next; free(del_node); printf("NODE DELETED\n"); } } void delete_last() { printf("----------------DELETING THE LAST NODE-----------------\n"); struct Node* del_node=NULL; if(head==NULL) { printf("LINKED LIST IS EMPTY\n"); } else { if (head->next==NULL) { free(head); head=NULL; } else { struct Node* presentNode=head; while (presentNode->next->next) { presentNode=presentNode->next; } del_node=presentNode->next; presentNode->next=NULL; free(del_node); printf("NODE DELETED\n"); } } } void search_data(int data_find) { printf("--------------SEARCHING------------\n"); struct Node* presentNode=head; int flag=0; while (presentNode) { if (presentNode->data==data_find) { flag=1; break; } presentNode=presentNode->next; } if (flag==1) { printf("Number Present\n"); } else { printf("Number not found\n"); } } int count_nodes() { printf("--------------COUNTING NODES------------\n"); struct Node* presentNode=head; int count=0; while (presentNode) { count+=1; presentNode=presentNode->next; } printf("count=%d\n",count); return count; } void find_mid() { int count=count_nodes(); int i; struct Node* presentNode=head; struct Node* nextNode=NULL; for(i=0;i<(count-1)/2;i++) { presentNode=presentNode->next; if (i==(((count-1)/2)-1)) if (count%2==0) { nextNode=presentNode->next; printf("Even number of nodes present:%d,%d\n",presentNode->data,nextNode->data); } else printf("Odd number of nodes present:%d\n",presentNode->data); } } void remove_node(int data_del) { struct Node* presentNode=head; struct Node* delNode=NULL; int flag=0; if (presentNode->data==data_del) { free(presentNode); } else { while(presentNode->next) { if(presentNode->next->data==data_del) { flag=1; delNode=presentNode->next; presentNode->next=presentNode->next->next; free(delNode); break; } presentNode=presentNode->next; } if (flag==0) printf("Node Not Found"); } } struct Node* reverse_LL() { struct Node* presentNode=head; struct Node* prevNode=NULL; struct Node* nextNode=head->next; while(nextNode) { presentNode->next=prevNode; prevNode=presentNode; presentNode=nextNode; nextNode=presentNode->next; } presentNode->next=prevNode; head=presentNode; return head; } int main() { /***Create pointer***/ struct Node* n1=NULL; struct Node* n2=NULL; /***Allocate memory***/ head = (struct Node*)malloc(sizeof(struct Node)); n1 = (struct Node*)malloc(sizeof(struct Node)); n2 = (struct Node*)malloc(sizeof(struct Node)); /***Assign Data and Link Nodes***/ head->data=1; head->next=n1; n1->data=2; n1->next=n2; n2->data=3; n2->next=NULL; traverse(head); insert_beginning(10); traverse(head); insert_end(60); traverse(head); insert_between(100,n1); traverse(head); delete_first(); traverse(head); delete_last(); traverse(head); search_data(100); count_nodes(); find_mid(); remove_node(2); traverse(head); reverse_LL(); traverse(head); return 0; }
C
# include <stdio.h> # pragma warning (disable:4996) int getMin(int arr[], int size) { int arrmin = 999; for (int i = 0; i < size; i++) { if (arr[i] < arrmin) arrmin = arr[i]; } return arrmin; } int main(void){ int scores[5]; int size = sizeof(scores) / sizeof(scores[0]); // ߰, scores ͸ Է¹޾ƾ մϴ. int score; for (int i = 0; i < size; i++) { scanf("%d", &score); scores[i] = score; } // 4. ּҰ ϴ Լ // scores ּҰ ãƼ main Ͻÿ. printf("scores ּڰ : %d\n", getMin(scores, size)); // Լ(迭, 迭ũ) return 0; }
C
//ENGR 102 Sherry Abbasi LED on Program #include <stdio.h> #include <wiringPi.h> int main() { wiringPiSetup(); //sets up the GPIO pins based on wiringPi chart pinMode(0, OUTPUT); //defines GPIO 0 (pin11) as an output digitalWrite(0, HIGH); //sets the value of GPIO 0 (pin11) at logic 1 (3.3 V) delay(5000); //creates a delay of 5000 ms digitalWrite(0, LOW); //sets the value of GPIO 0 (pin11) at logic 0 (0 V) }
C
/* ** my_putstr.c for my putstr in /home/ ** ** Made by Pigot Aurélien ** Login <[email protected]> ** ** Started on Tue Oct 21 10:38:15 2014 Pigot Aurélien ** Last update Sat Feb 14 20:12:05 2015 Pigot Aurélien */ #include <unistd.h> void my_putstr(char *str) { while (*str != '\0') { write(1, str, 1); str++; } }
C
// #include <stdio.h> // #include <stdlib.h> // // int main() // // #define SIZE 81 // // { // // char *ui, *p; // int count, amount=80; // // ui = malloc(SIZE * sizeof(char)); // // if (str == NULL) // { // puts("Memory is full."); // exit(1); // } // // p = ui; // // for (count = 80; count <= 0; count -= amount) // { // *p++ = fgets(*ui, amount, stdin) // amount = (size(ui) / char) // } // // // // // ptr = str; // // for (count = 97; count <= 99; count++) // { // *ptr++ = count; // } // // *ptr = '\0'; // // puts(str); // // return 0; // }
C
#include <stdio.h> #include <stdlib.h> char *monthName (int month) { char *result; switch (month) { case 1: result = "Jan\n"; break; case 2: result = "Feb\n"; break; case 3: result = "Mar\n"; break; case 4: result = "Apr\n"; break; case 5: result = "May\n"; break; case 6: result = "Jun\n"; break; case 7: result = "Jul\n"; break; case 8: result = "Aug\n"; break; case 9: result = "Sept\n"; break; case 10: result = "Oct\n"; break; case 11: result = "Nov\n"; break; case 12: result = "Dec\n"; break; default : result = "Invalid\n"; } return result; }
C
/* ppmtopcx.c - read a portable pixmap and produce a PCX file ** ** Copyright (C) 1990 by Michael Davidson. ** ** Permission to use, copy, modify, and distribute this software and its ** documentation for any purpose and without fee is hereby granted, provided ** that the above copyright notice appear in all copies and that both that ** copyright notice and this permission notice appear in supporting ** documentation. This software is provided "as is" without express or ** implied warranty. */ #include <stdio.h> #include "ppm.h" #include "ppmcmap.h" #define MAXCOLORS 256 #define MAXPLANES 4 /* * Pointer to function returning an int */ typedef void (* vfunptr) ARGS(( int, int, unsigned char*, int, int )); static void PCXEncode ARGS(( FILE* fp, int GWidth, int GHeight, int Colors, int Red[], int Green[], int Blue[], vfunptr GetPlanes )); static void PutPlane ARGS(( FILE* fp, unsigned char* buf, int Size )); static void ReadPlanes ARGS(( int y, int width, unsigned char* buf, int planes, int bits )); static void Putword ARGS(( int w, FILE* fp )); static void Putbyte ARGS(( int b, FILE* fp )); static pixel** pixels; static colorhash_table cht; void main( argc, argv ) int argc; char* argv[]; { FILE* ifp; int argn, rows, cols, colors, i; pixval maxval; pixel black_pixel; colorhist_vector chv; int Red[MAXCOLORS], Green[MAXCOLORS], Blue[MAXCOLORS]; char* usage = "[ppmfile]"; ppm_init( &argc, argv ); argn = 1; if ( argn < argc ) { ifp = pm_openr( argv[argn] ); ++argn; } else ifp = stdin; if ( argn != argc ) pm_usage( usage ); pixels = ppm_readppm( ifp, &cols, &rows, &maxval ); pm_close( ifp ); /* Figure out the colormap. */ pm_message( "computing colormap..." ); chv = ppm_computecolorhist( pixels, cols, rows, MAXCOLORS, &colors ); if ( chv == (colorhist_vector) 0 ) pm_error( "too many colors - try doing a 'ppmquant %d'", MAXCOLORS ); pm_message( "%d colors found", colors ); /* Force black to slot 0 if possible. */ PPM_ASSIGN(black_pixel, 0, 0, 0 ); ppm_addtocolorhist(chv, &colors, MAXCOLORS, &black_pixel, 0, 0 ); /* Now turn the ppm colormap into the appropriate PCX colormap. */ if ( maxval > 255 ) pm_message( "maxval is not 255 - automatically rescaling colors" ); for ( i = 0; i < colors; ++i ) { if ( maxval == 255 ) { Red[i] = PPM_GETR( chv[i].color ); Green[i] = PPM_GETG( chv[i].color ); Blue[i] = PPM_GETB( chv[i].color ); } else { Red[i] = (int) PPM_GETR( chv[i].color ) * 255 / maxval; Green[i] = (int) PPM_GETG( chv[i].color ) * 255 / maxval; Blue[i] = (int) PPM_GETB( chv[i].color ) * 255 / maxval; } } /* And make a hash table for fast lookup. */ cht = ppm_colorhisttocolorhash( chv, colors ); ppm_freecolorhist( chv ); /* All set, let's do it. */ PCXEncode( stdout, cols, rows, colors, Red, Green, Blue, ReadPlanes ); pm_close (stdout); exit( 0 ); } /***************************************************************************** * * PCXENCODE.C - PCX Image compression interface * * PCXEncode( FName, GHeight, GWidth, Colors, Red, Green, Blue, GetPlanes ) * *****************************************************************************/ #define TRUE 1 #define FALSE 0 /* public */ static void PCXEncode(fp, GWidth, GHeight, Colors, Red, Green, Blue, GetPlanes ) FILE* fp; int GWidth, GHeight; int Colors; int Red[], Green[], Blue[]; vfunptr GetPlanes; { int BytesPerLine; int Planes; int BitsPerPixel; unsigned char *buf; int i; int n; int y; /* * select number of planes and number of bits * per pixel according to number of colors */ /* * 16 colors or less are handled as 1 bit per pixel * with 1, 2, 3 or 4 color planes. * more than 16 colors are handled as 8 bits per pixel * with 1 plane */ if (Colors > 16) { BitsPerPixel = 8; Planes = 1; } else { BitsPerPixel = 1; if (Colors > 8) Planes = 4; else if (Colors > 4) Planes = 3; else if (Colors > 2) Planes = 2; else Planes = 1; } /* * Write the PCX header */ Putbyte( 0x0a, fp); /* .PCX magic number */ Putbyte( 0x05, fp); /* PC Paintbrush version */ Putbyte( 0x01, fp); /* .PCX run length encoding */ Putbyte( BitsPerPixel, fp); /* bits per pixel */ Putword( 0, fp ); /* x1 - image left */ Putword( 0, fp ); /* y1 - image top */ Putword( GWidth-1, fp ); /* x2 - image right */ Putword( GHeight-1, fp ); /* y2 - image bottom */ Putword( GWidth, fp ); /* horizontal resolution */ Putword( GHeight, fp ); /* vertical resolution */ /* * Write out the Color Map for images with 16 colors or less */ n = (Colors <= 16) ? Colors : 16; for (i = 0; i < n; ++i) { Putbyte( Red[i], fp ); Putbyte( Green[i], fp ); Putbyte( Blue[i], fp ); } for (; i < 16; ++i) { Putbyte( 255, fp ); Putbyte( 255, fp ); Putbyte( 255, fp ); } Putbyte( 0, fp); /* reserved byte */ Putbyte( Planes, fp); /* number of color planes */ BytesPerLine = ((GWidth * BitsPerPixel) + 7) / 8; Putword( BytesPerLine, fp ); /* number of bytes per scanline */ Putword( 1, fp); /* pallette info */ for (i = 0; i < 58; ++i) /* fill to end of header */ Putbyte( 0, fp ); buf = (unsigned char *)malloc( MAXPLANES * BytesPerLine ); for (y = 0; y < GHeight; ++y) { (*GetPlanes)(y, GWidth, buf, Planes, BitsPerPixel); for (i = 0; i < Planes; ++i) PutPlane(fp, buf + (i * BytesPerLine), BytesPerLine); } /* * color map for > 16 colors is at end of file */ if (Colors > 16) { Putbyte( 0x0c, fp); /* magic for 256 colors */ for (i = 0; i < Colors; ++i) { Putbyte( Red[i], fp ); Putbyte( Green[i], fp ); Putbyte( Blue[i], fp ); } for (; i < MAXCOLORS; ++i) { Putbyte( 255, fp ); Putbyte( 255, fp ); Putbyte( 255, fp ); } } fclose( fp ); } static void PutPlane(fp, buf, Size) FILE *fp; unsigned char *buf; int Size; { unsigned char *end; int c; int previous; int count; end = buf + Size; previous = *buf++; count = 1; while (buf < end) { c = *buf++; if (c == previous && count < 63) { ++count; continue; } if (count > 1 || (previous & 0xc0) == 0xc0) { count |= 0xc0; Putbyte ( count , fp ); } Putbyte(previous, fp); previous = c; count = 1; } if (count > 1 || (previous & 0xc0) == 0xc0) { count |= 0xc0; Putbyte ( count , fp ); } Putbyte(previous, fp); } static unsigned long PixMap[8][16] = { 0x00000000L, 0x00000080L, 0x00008000L, 0x00008080L, 0x00800000L, 0x00800080L, 0x00808000L, 0x00808080L, 0x80000000L, 0x80000080L, 0x80008000L, 0x80008080L, 0x80800000L, 0x80800080L, 0x80808000L, 0x80808080L, }; static void ReadPlanes(y, width, buf, planes, bits) int y; int width; unsigned char *buf; int planes; int bits; { static int first_time = 1; unsigned char *plane0, *plane1, *plane2, *plane3; int i, j, x; /* * 256 color, 1 plane, 8 bits per pixel */ if (planes == 1 && bits == 8) { for (x = 0; x < width; ++x) buf[x] = ppm_lookupcolor( cht, &pixels[y][x] ); return; } /* * must be 16 colors or less, 4 planes or less, 1 bit per pixel */ if (first_time) { for (i = 1; i < 8; ++i) for (j = 0; j < 16; ++j) PixMap[i][j] = PixMap[0][j] >> i; first_time = 0; } i = (width + 7) / 8; plane0 = buf; plane1 = plane0 + i; plane2 = plane1 + i; plane3 = plane2 + i; i = 0; x = 0; while ( x < width ) { register unsigned long t; t = PixMap[0][ppm_lookupcolor( cht, &pixels[y][x++] )]; t |= PixMap[1][ppm_lookupcolor( cht, &pixels[y][x++] )]; t |= PixMap[2][ppm_lookupcolor( cht, &pixels[y][x++] )]; t |= PixMap[3][ppm_lookupcolor( cht, &pixels[y][x++] )]; t |= PixMap[4][ppm_lookupcolor( cht, &pixels[y][x++] )]; t |= PixMap[5][ppm_lookupcolor( cht, &pixels[y][x++] )]; t |= PixMap[6][ppm_lookupcolor( cht, &pixels[y][x++] )]; t |= PixMap[7][ppm_lookupcolor( cht, &pixels[y][x++] )]; plane0[i] = t; plane1[i] = t >> 8; plane2[i] = t >> 16; plane3[i++] = t >> 24; } } /* * Write out a word to the PCX file */ static void Putword( w, fp ) int w; FILE *fp; { fputc( w & 0xff, fp ); fputc( (w / 256) & 0xff, fp ); } /* * Write out a byte to the PCX file */ static void Putbyte( b, fp ) int b; FILE *fp; { fputc( b & 0xff, fp ); } /* The End */
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> #include "figure.h" #include "geometry.h" #include "nest_structs.h" #include "cmnfuncs.h" #include "cmnnest.h" #include "nestdefs.h" int (*checkpos)(struct Figure *currfig, struct Position *postis, int npos, double xpos, double ypos, double height, double width, int *placed); static int placefig2(struct Figure *figset, int fignum, struct Position *posits, int npos, double width, double height) { int placed = 0, angstep; double angle; double x, ypos, xpos; struct Figure currfig; angstep = figset[fignum].angstep == 0 ? 360 : figset[fignum].angstep; for (angle = 0; angle < 360; angle += angstep) { currfig = figdup(&figset[fignum]); rotate(&currfig, angle); for (x = 0; x < width - currfig.corner.x; x += 1.0) { xpos = x; ypos = getstart(posits, npos, &currfig, x); ymove(&xpos, &ypos, &currfig, posits, npos); if (checkpos(&currfig, posits, npos, xpos, ypos, height, width, &placed)) posits[npos].angle = angle; if (ypos == 0) break; } destrfig(&currfig); } return placed; } static int placefig1(struct Figure *figset, int fignum, struct Position *posits, int npos, double width, double height) { int placed = 0, count, i, angstep; double angle; double x, ypos, *xpos; struct Figure currfig; xpos = (double*)xcalloc((int)width, sizeof(double)); angstep = figset[fignum].angstep == 0 ? 360 : figset[fignum].angstep; for (angle = 0; angle < 360; angle += angstep) { ypos = height; count = 0; currfig = figdup(&figset[fignum]); rotate(&currfig, angle); for (x = 0; x < width - currfig.corner.x; x += 1.0) { double ytmp; ytmp = getstart(posits, npos, &currfig, x); if (ytmp < ypos) { ypos = ytmp; count = 0; } if (ytmp == ypos) { xpos[count] = x; count++; } } for (i = 0; i < count; i++) { double ytmp; ytmp = ypos; ymove(&xpos[i], &ytmp, &currfig, posits, npos); if (checkpos(&currfig, posits, npos, xpos[i], ytmp, height, width, &placed)) posits[npos].angle = angle; } destrfig(&currfig); } free(xpos); return placed; } static int placefig0(struct Figure *figset, int fignum, struct Position *posits, int npos, double width, double height) { int placed = 0, angstep; double angle; double x, ypos, xpos; struct Figure currfig; angstep = figset[fignum].angstep == 0 ? 360 : figset[fignum].angstep; for (angle = 0; angle < 360; angle += angstep) { ypos = height; xpos = 0.0; currfig = figdup(&figset[fignum]); rotate(&currfig, angle); for (x = 0; x < width - currfig.corner.x; x += 1.0) { double ytmp; ytmp = getstart(posits, npos, &currfig, x); if (ytmp < ypos) { ypos = ytmp; xpos = x; } } ymove(&xpos, &ypos, &currfig, posits, npos); if (checkpos(&currfig, posits, npos, xpos, ypos, height, width, &placed)) { posits[npos].angle = angle; } destrfig(&currfig); } return placed; } void rotnest(struct Figure *figset, int setsize, struct Individ *indiv, struct NestAttrs *attrs) { int i, j, k, npos; int *mask; double tmpheight; double width, height; struct Position *posits; static int (*placefig)(struct Figure *figset, int fignum, struct Position *posits, int npos, double width, double height); FILE *logfile; double mtx[3][3]; logfile = attrs->logfile; width = attrs->width; height = attrs->height; placefig = placefig0; if (attrs->type == ROTNEST_MORE) placefig = placefig1; else if (attrs->type == ROTNEST_FULL) placefig = placefig2; checkpos = checkpos_height; if (attrs->checker == CHECK_RADIUS) checkpos = checkpos_radius; else if (attrs->checker == CHECK_SCALE) checkpos = checkpos_scale; mask = (int*)xcalloc(setsize, sizeof(int)); posits = (struct Position*)xmalloc(sizeof(struct Position) * setsize); npos = 0; tmpheight = 0; for (i = 0; i < indiv->gensize; i++) { int fignum; fignum = indiv->genom[i]; if (!placefig(figset, fignum, posits, npos, width, height)) { fprintf(logfile, "fail to position %d\n", fignum); continue; } for (j = 0; j < 3; j++) { for (k = 0; k < 3; k++) { mtx[j][k] = (j == k)? 1.0 : 0.0; } } mtx[0][2] = posits[npos].x; mtx[1][2] = posits[npos].y; mtxmult(mtx, &posits[npos].fig); mask[fignum] = 1; npos++; tmpheight = (tmpheight > posits[npos - 1].fig.corner.y + posits[npos - 1].y)? tmpheight : posits[npos - 1].fig.corner.y + posits[npos - 1].y; fprintf(logfile, "nested_id=%d positioned=%d angle=%lf height=%lf x=%lf y=%lf \n", fignum, npos, posits[npos - 1].angle, tmpheight, posits[npos - 1].x, posits[npos - 1].y); } if (npos < indiv->gensize) { indiv->height = INFINITY; indiv->posits = NULL; free(posits); return; } for (i = 0; i < setsize; i++) { if (mask[i] == -1 || mask[i] == 1) { continue; } if (!placefig(figset, i, posits, npos, width, height)) { for (j = i; j < setsize; j++) { if (figset[i].id == figset[j].id) { mask[j] = -1; } } continue; } for (j = 0; j < 3; j++) { for (k = 0; k < 3; k++) { mtx[j][k] = (j == k)? 1.0 : 0.0; } } mtx[0][2] = posits[npos].x; mtx[1][2] = posits[npos].y; mtxmult(mtx, &posits[npos].fig); mask[i] = 1; npos++; tmpheight = (tmpheight > posits[npos - 1].fig.corner.y + posits[npos - 1].y)? tmpheight : posits[npos - 1].fig.corner.y + posits[npos - 1].y; fprintf(logfile, "nested_id=%d positioned=%d angle=%lf height=%lf x=%lf y=%lf \n", i, npos, posits[npos - 1].angle, tmpheight, posits[npos - 1].x, posits[npos - 1].y); indiv->genom[npos - 1] = i; } free(mask); indiv->gensize = npos; indiv->height = tmpheight; indiv->posits = posits; indiv->npos = npos; }
C
#include "ext2_helper.c" int main(int argc, char **argv) { if(argc != 3) { fprintf(stderr, "Usage: ext2_rm <image file name> <absolute path>\n"); exit(1); } return 0; }
C
#include <stdio.h> #include <stdlib.h> struct TreeNode{ int value; struct TreeNode *left; struct TreeNode *right; }; int main(int argc, char const *argv[]) { /* code */ return 0; } //Binary Tree Operations struct TreeNode *insert(struct TreeNode *root, int value){ if(!root){ return create_TreeNode(value); } else{ if(height(root-> right) == height(root-> left)){ struct TreeNode *walker = root; while(walker-> left){ walker = walker-> left; } walker-> left = create_TreeNode(value); return root; } else if((height(root-> right) - height(root-> left)) > 0){ } } } struct TreeNode *create_TreeNode(int value){ struct TreeNode *new = (struct TreeNode *)malloc(sizeof(struct TreeNode)); new-> value = value; new-> left = new-> right = NULL; return new; }
C
#include <string.h> #include <stdbool.h> #include <errno.h> #include "roman_error_codes.h" #include "roman_arabic_map.h" #include "roman_validator.h" int get_map_index(struct RomanArabicMap map) { for(int i = 0; i < get_maps_size(); ++i) { if (are_equal(roman_arabic_maps[i], map)) { return i; } } return -1; } bool is_roman_valid(const char *roman) { int length = strlen(roman); int mapsSize = get_maps_size(); int counts[mapsSize]; for(int i = 0; i < mapsSize; ++i) { counts[i] = 0; } for(int i = 0; i < length; ++i) { struct RomanArabicMap map = get_map_from_string(roman, i, length); if(map.roman[1] != NA) { i++; } int mapIndex = get_map_index(map); counts[mapIndex]++; if(counts[mapIndex] > map.limit) { errno = ROMAN_NUMERAL_LIMIT; return false; } } errno = ROMAN_SUCCESS; return true; }
C
/* Programa: Laboratorio 04 Exercicio 4 Aluno: Marcelo Mendonca Borges Data: 12/05/2016 Descricao: Le uma matriz e verifica se ela eh simetrica */ /*Inclusao de Bibliotecas*/ #include <stdio.h> #include <stdlib.h> #include <math.h> int main () { /*Declaracao de Variaveis*/ int i, j, n, a[100][100], transp = 1; /*-----------------------*/ printf("Leio uma matriz e verifico se lea eh ou nao simetrica.\n"); printf("Observacao: Uma matriz eh simetrica quando ela eh igual a sua transposta.\n\n"); do { printf("Defina a ordem da matriz M(n x n) = "); scanf("%d",&n); } while(n <= 0); printf("\n"); for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { printf("Digite o valor do elemento M[%d][%d] = ",i,j); scanf("%d",&a[i][j]); } printf("\n"); } printf("Matriz:\n"); for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { printf("%5d",a[i][j]); } printf("\n"); } for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { if(a[i][j] != a[j][i]) { transp = 0; } } } if(transp) { printf("\nA matriz eh transposta.\n"); } else { printf("\n A matriz nao eh transposta.\n"); } return 0; }
C
// Created on Mon March 17 2014 // Natalie Reed, Gal Bejerano, Kasandra Yee, Christine Hsieh, James D // Movement for getting botguy and exercise bench SEPARATELY (bench first) #define LEFTWHEEL 2 #define RIGHTWHEEL 0 #define LIGHT 1 #define ARM 1 int start=1000; void turn90Left(); void turn90Right(); void moveForward(int distance); void moveBackward(int distance); void grabBotGuy(); void liftArm(int height); void claw(int width); void findBlock(); /** NOTE PORTS: 0 = left, 1 = right, for arm = 2 Distance and Height are measured in centimeters. **/ int main() { //wait_for_light(0); clear_motor_position_counter(LEFTWHEEL); clear_motor_position_counter(RIGHTWHEEL); clear_motor_position_counter(ARM); start=analog10(LIGHT); turn90Left(); moveForward(75);//distance to black line turn90Left(); findBlock(); moveForward(150); turn90Left(); } void turn90Right(){ clear_motor_position_counter(LEFTWHEEL); clear_motor_position_counter(RIGHTWHEEL); mtp(LEFTWHEEL,500,754); //port, speed, distance mtp(RIGHTWHEEL,500,-754); bmd(LEFTWHEEL); //makes motor stop running after finished bmd(RIGHTWHEEL); } void turn90Left(){ clear_motor_position_counter(LEFTWHEEL); clear_motor_position_counter(RIGHTWHEEL); mtp(LEFTWHEEL,500,-750); //original is 759 mtp(RIGHTWHEEL,500,750); bmd(LEFTWHEEL); //makes motor stop running after finished bmd(RIGHTWHEEL); } void moveForward(int distance){ clear_motor_position_counter(LEFTWHEEL); clear_motor_position_counter(RIGHTWHEEL); mtp(LEFTWHEEL,500,1000/15*distance); //port, speed, distance 1000 = 15 cm mtp(RIGHTWHEEL,500,1000/15*distance); bmd(RIGHTWHEEL); //makes motor stop running after finished bmd(LEFTWHEEL); } void moveBackward(int distance) { clear_motor_position_counter(LEFTWHEEL); clear_motor_position_counter(RIGHTWHEEL); mtp(LEFTWHEEL,500,distance); //port, speed, distance 1000 = 15 cm mtp(RIGHTWHEEL,500,distance); bmd(LEFTWHEEL); //makes motor stop running after finished bmd(RIGHTWHEEL); } void liftArm(int height) { clear_motor_position_counter(1); printf("arm going down"); mtp(ARM,500,height); bmd(ARM); printf("done! =)"); } void claw(int width) { enable_servos(); set_servo_position(1,width); msleep(1000); disable_servos(); } void findBlock() { while(analog10(LIGHT)>start-5 ){ clear_motor_position_counter(LEFTWHEEL); clear_motor_position_counter(RIGHTWHEEL); mtp(LEFTWHEEL,500,10); //original is 759 mtp(RIGHTWHEEL,500,-10); bmd(LEFTWHEEL); //makes motor stop running after finished bmd(RIGHTWHEEL); } printf("Found block"); //mtp(LEFTWHEEL,500,-5); //original is 759 //mtp(RIGHTWHEEL,500,5); //bmd(LEFTWHEEL); //makes motor stop running after finished //bmd(RIGHTWHEEL); }
C
#include "base64.h" #include "minunit.h" const char *test_b64decode(void) { const char *monkey_biz = "TW9ua2V5IEJ1c2luZXNz"; size_t outlen; char *output = b64decode(monkey_biz, strlen(monkey_biz), B64_STANDARD, &outlen); mu_assert(!strcmp(output, "Monkey Business"), "Decoded output didn't match expected: '%s'", output); mu_assert(outlen == 15, "Wrong length of decoded output!"); free(output); const char *padded = "cGFkZGluZyBjaGVjaw=="; output = b64decode(padded, strlen(padded), B64_STANDARD, &outlen); mu_assert(!strcmp(output, "padding check"), "Padded output didn't match expected: '%s'", output); mu_assert(outlen == 13, "Wrong length of padded output: %zu", outlen); free(output); output = b64decode(padded, strlen(padded)-2, B64_STANDARD, &outlen); mu_assert(!strcmp(output, "padding check"), "Padded output #2 didn't match expected: '%s'", output); mu_assert(outlen == 13, "Wrong length of padded output #2: %zu", outlen); free(output); const char *pad1 = "MSBwYWQgY2hlY2s="; output = b64decode(pad1, strlen(pad1), B64_STANDARD, &outlen); mu_assert(!strcmp(output, "1 pad check"), "1-pad output didn't match expected: '%s'", output); mu_assert(outlen == 11, "Wrong length for 1-pad output: %zu", outlen); free(output); output = b64decode(pad1, strlen(pad1)-1, B64_STANDARD, &outlen); mu_assert(!strcmp(output, "1 pad check"), "1-pad output #2 didn't match expected: '%s'", output); mu_assert(outlen == 11, "Wrong length for 1-pad output #2: %zu", outlen); free(output); return NULL; } const char *test_b64encode(void) { const char *monkey_biz = "Monkey Business"; size_t outlen; char *output = b64encode(monkey_biz, strlen(monkey_biz), B64_STANDARD, &outlen); mu_assert(!strcmp(output, "TW9ua2V5IEJ1c2luZXNz"), "Encoded output didn't match expected: '%s'", output); mu_assert(outlen == 20, "Wrong length of output!"); free(output); const char *padded = "padding check"; output = b64encode(padded, strlen(padded), B64_STANDARD, &outlen); mu_assert(!strcmp(output, "cGFkZGluZyBjaGVjaw=="), "Encoded padded output didn't match expected: '%s'", output); mu_assert(outlen == 20, "Wrong length of output!"); free(output); return NULL; } const char *all_tests() { mu_suite_start(); mu_run_test(test_b64decode); mu_run_test(test_b64encode); return NULL; } RUN_TESTS(all_tests);
C
#include "auxstruct.h" Pagina inicializaPagina() { Pagina res = NULL; res = (Pagina)malloc(sizeof(NPagina)); res->titulo = NULL; res->data = NULL; res->autor = NULL; res->seccoes = createLinkedList(NULL,NULL); res->linkint = createLinkedList(NULL,NULL); res->linkext = createLinkedList(NULL,NULL); return res; } void insereTitulo(Pagina pag, char *tit) { pag->titulo = strdup(tit); } char *verificaData(char *data) { data[10]=' '; data[19]='\0'; return data; } void insereData(Pagina pag, char *date) { pag->data = verificaData(strdup(date)); } void insereAutor(Pagina pag, char *autor) { pag->autor = strdup(autor); } void insereSeccao(int tipo, Pagina pag, char* sec) { char *res = strdup(sec); int x = strlen(res); if(tipo==0) tailInsertLinkedList(pag->seccoes, res); else { if(tipo==1) { char aux[x+4]; strcpy(aux,"1X1"); strcat(aux,res); aux[x+4] = '\0'; tailInsertLinkedList(pag->seccoes, strdup(aux)); pag->seccoes->nrelems--; } else { if (tipo==2) { char aux[x+4]; strcpy(aux,"2X2"); strcat(aux,res); aux[x+4] = '\0'; tailInsertLinkedList(pag->seccoes, strdup(aux)); pag->seccoes->nrelems--; } else { if (tipo==2) { char aux[x+4]; strcpy(aux,"3X3"); strcat(aux,res); aux[x+4] = '\0'; tailInsertLinkedList(pag->seccoes, strdup(aux)); pag->seccoes->nrelems--; } } } } } void insereLinkInt(Pagina pag, char* url) { tailInsertLinkedList(pag->linkint, strdup(url)); } void insereLinkExt(Pagina pag, char* url) { tailInsertLinkedList(pag->linkext, strdup(url)); } char verificaMaiuscula(char c){ if(islower(c)) return toupper(c); return c; } int comparaTitulos(void* tit1, void* tit2){ char * s1 = strdup(tit1); char * s2 = strdup(tit2); s1[0] = verificaMaiuscula(s1[0]); s2[0] = verificaMaiuscula(s2[0]); if(isdigit(s1[0]) || isdigit(s2[0])) return strcmp(s2,s1); return strcmp(s1,s2); } void* getChar(void* tit){ return strdup(tit); } LinkedList iniciaIndiceTitulo() { return createLinkedList(getChar, comparaTitulos); } void insereTituloIndice(LinkedList lpages, char *tit) { ordInsertLinkedList(lpages, tit); }
C
/* * hal_timebase.c * * Created on: Jul 9, 2016 * Author: jmiller */ #include "stm32.h" TIM_HandleTypeDef htim1; uint32_t uwIncrementState = 0; /** * @brief This function configures the TIM1 as a time base source. * The time source is configured to have 1ms time base with a dedicated * Tick interrupt priority. * @note This function is called automatically at the beginning of program after * reset by HAL_Init() or at any time when clock is configured, by HAL_RCC_ClockConfig(). * @param TickPriority: Tick interrupt priorty. * @retval HAL status */ HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) { RCC_ClkInitTypeDef clkconfig; uint32_t uwTimclock = 0; uint32_t uwPrescalerValue = 0; uint32_t pFLatency; /*Configure the TIM1 IRQ priority */ HAL_NVIC_SetPriority(TIM1_UP_TIM10_IRQn, TickPriority, 0); /* Enable the TIM1 global Interrupt */ HAL_NVIC_EnableIRQ(TIM1_UP_TIM10_IRQn); /* Enable TIM1 clock */ __HAL_RCC_TIM1_CLK_ENABLE(); /* Get clock configuration */ HAL_RCC_GetClockConfig(&clkconfig, &pFLatency); /* Compute TIM1 clock */ uwTimclock = HAL_RCC_GetPCLK2Freq(); /* Compute the prescaler value to have TIM1 counter clock equal to 1MHz */ uwPrescalerValue = (uint32_t) ((uwTimclock / 1000000) - 1); /* Initialize TIM1 */ htim1.Instance = TIM1; /* Initialize TIMx peripheral as follow: + Period = [(TIM1CLK/1000) - 1]. to have a (1/1000) s time base. + Prescaler = (uwTimclock/1000000 - 1) to have a 1MHz counter clock. + ClockDivision = 0 + Counter direction = Up */ htim1.Init.Period = (1000000 / 1000) - 1; htim1.Init.Prescaler = uwPrescalerValue; htim1.Init.ClockDivision = 0; htim1.Init.CounterMode = TIM_COUNTERMODE_UP; if (HAL_TIM_Base_Init(&htim1) == HAL_OK) { /* Start the TIM time Base generation in interrupt mode */ return HAL_TIM_Base_Start_IT(&htim1); } /* Return function status */ return HAL_ERROR; } /** * @brief Suspend Tick increment. * @note Disable the tick increment by disabling TIM1 update interrupt. * @param None * @retval None */ void HAL_SuspendTick(void) { /* Disable TIM1 update Interrupt */ __HAL_TIM_DISABLE_IT(&htim1, TIM_IT_UPDATE); } /** * @brief Resume Tick increment. * @note Enable the tick increment by Enabling TIM1 update interrupt. * @param None * @retval None */ void HAL_ResumeTick(void) { /* Enable TIM1 Update interrupt */ __HAL_TIM_ENABLE_IT(&htim1, TIM_IT_UPDATE); } /** * @brief Period elapsed callback in non blocking mode * @note This function is called when TIM1 interrupt took place, inside * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment * a global variable "uwTick" used as application time base. * @param htim : TIM handle * @retval None */ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { HAL_IncTick(); }
C
#include "search_algos.h" /** * binary_searching - binary searching yayyy * @array: array * @left: left * @right: right * @value: value * * Return: index */ int binary_searching(int *array, size_t left, size_t right, int value) { size_t l; if (array == NULL) return (-1); while (right >= left) { printf("Searching in array: "); for (l = left; l < right; l++) printf("%d, ", array[l]); printf("%d\n", array[l]); l = left + (right - left) / 2; if (array[l] == value) return (l); if (array[l] > value) right = l - 1; else left = l + 1; } return (-1); } /** * exponential_search - Searches using exponential search. * @array: array * @size: size * @value: value * * Return: index */ int exponential_search(int *array, size_t size, int value) { size_t l = 0, p; if (array == NULL) return (-1); if (array[0] != value) { for (l = 1; l < size && array[l] <= value; l = l * 2) printf("Value checked array[%ld] = [%d]\n", l, array[l]); } if (l < size) p = l; else p = size - 1; printf("Value found between indexes [%ld] and [%ld]\n", l / 2, p); return (binary_searching(array, l / 2, p, value)); }
C
/** Put this in the src folder **/ #include "keyboard.h" //--------Select input group-------- //#define MatrixKeyInput GPIOA //#define MatrixKeyInput GPIOB //#define MatrixKeyInput GPIOC #define MatrixKeyInput GPIOD //#define MatrixKeyInput GPIOE //--------Select output group-------- #define MatrixKeyOutput GPIOA //#define MatrixKeyOutput GPIOB //#define MatrixKeyOutput GPIOC //#define MatrixKeyOutput GPIOD //#define MatrixKeyOutput GPIOE int PinOut[4] = {GPIO_PIN_0, GPIO_PIN_1, GPIO_PIN_2, GPIO_PIN_3}; int PinIn[4] = {GPIO_PIN_6, GPIO_PIN_7, GPIO_PIN_8, GPIO_PIN_9}; const char value[4][4] = { {'1', '4', '7', '*'}, {'2', '5', '8', '0' }, {'3', '6', '9', '#'}, {'A', 'B', 'C', 'D'} }; char keyboard_read(void) { for (int i = 1; i <= 4; i++) //col { HAL_GPIO_WritePin(MatrixKeyOutput, PinOut[i - 1], RESET); for (int j = 1; j <= 4; j++) //row { if (HAL_GPIO_ReadPin(MatrixKeyInput, PinIn[j - 1]) == RESET) { return value[i - 1][j - 1]; HAL_Delay(175); } } HAL_GPIO_WritePin(MatrixKeyOutput, PinOut[i - 1], SET); } }
C
/** ****************************************************************************** * @file bsp_beep.c * @author fire * @version V1.0 * @date 2015-xx-xx * @brief ʪȴӦúӿ ****************************************************************************** * @attention * * ʵƽ̨: STM32 F429 * ̳ :http://www.firebbs.cn * Ա :https://fire-stm32.taobao.com * ****************************************************************************** */ #include "./Bsp/bsp.h" #include "./Bsp/humiture/humiture.h" /* * TEMP_HUM_GPIO_Config * TEMP_HUMõI/O * * */ void TEMP_HUM_GPIO_Config(void) { /*һGPIO_InitTypeDef͵Ľṹ*/ GPIO_InitTypeDef GPIO_InitStructure; /*DHT11_PORTʱ*/ RCC_AHB1PeriphClockCmd(TEMP_HUM_CLK, ENABLE); /*ѡҪƵDHT11_PORT*/ GPIO_InitStructure.GPIO_Pin = TEMP_HUM_PIN; /*ģʽΪͨ*/ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; /*ŵΪ*/ GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; /*Ϊģʽ*/ GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; /*Ϊ50MHz */ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; /*ÿ⺯ʼDHT11_PORT*/ GPIO_Init(TEMP_HUM_PORT, &GPIO_InitStructure); } /* * TEMP_HUM_Mode_IPU * ʹTEMP_HUM-DATAűΪģʽ * * */ static void TEMP_HUM_Mode_IPU(void) { GPIO_InitTypeDef GPIO_InitStructure; /*ѡҪƵDHT11_PORT*/ GPIO_InitStructure.GPIO_Pin = TEMP_HUM_PIN; /*ģʽΪģʽ*/ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN ; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; /*Ϊ50MHz */ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; /*ÿ⺯ʼDHT11_PORT*/ GPIO_Init(TEMP_HUM_PORT, &GPIO_InitStructure); } /* * TEMP_HUM_Mode_Out_PP * ʹTEMP_HUM-DATAűΪģʽ * * */ static void TEMP_HUM_Mode_Out_PP(void) { GPIO_InitTypeDef GPIO_InitStructure; /*ѡҪƵDHT11_PORT*/ GPIO_InitStructure.GPIO_Pin = TEMP_HUM_PIN; /*ģʽΪͨ*/ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; /*ŵΪ*/ GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; /*Ϊģʽ*/ GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; /*Ϊ50MHz */ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; /*ÿ⺯ʼDHT11_PORT*/ GPIO_Init(TEMP_HUM_PORT, &GPIO_InitStructure); } /* * DHT11ȡһֽڣMSB */ static uint8_t Read_Byte(void) { uint8_t i, temp=0; for(i=0;i<8;i++) { /*ÿbit50us͵ƽÿʼѯֱӻ 50us ͵ƽ */ while(TEMP_HUM_DATA_IN()==Bit_RESET); /*DHT11 26~28usĸߵƽʾ070usߵƽʾ1 *ͨ x usĵƽ״ x ʱ */ bsp_DelayUS(40); //ʱx us ʱҪ0ʱ伴 if(TEMP_HUM_DATA_IN()==Bit_SET)/* x usΪߵƽʾݡ1 */ { /* ȴ1ĸߵƽ */ while(TEMP_HUM_DATA_IN()==Bit_SET); temp|=(uint8_t)(0x01<<(7-i)); //ѵ7-iλ1MSB } else // x usΪ͵ƽʾݡ0 { temp&=(uint8_t)~(0x01<<(7-i)); //ѵ7-iλ0MSB } } return temp; } /* * һݴΪ40bitλȳ * 8bit ʪ + 8bit ʪС + 8bit ¶ + 8bit ¶С + 8bit У */ uint8_t Read_DHT11(DHT11_Data_TypeDef *DHT11_Data) { uint16_t count; /*ģʽ*/ TEMP_HUM_Mode_Out_PP(); /**/ TEMP_HUM_DATA_OUT(HUMITURE_LOW); /*ʱ18ms*/ bsp_DelayUS(20000); /* ʱ30us*/ TEMP_HUM_DATA_OUT(HUMITURE_HIGH); bsp_DelayUS(30); //ʱ30us /*Ϊ жϴӻӦź*/ TEMP_HUM_Mode_IPU(); /*жϴӻǷе͵ƽӦź 粻ӦӦ*/ if(TEMP_HUM_DATA_IN()==Bit_RESET) { count=0; /*ѯֱӻ 80us ͵ƽ ӦźŽ*/ while(TEMP_HUM_DATA_IN()==Bit_RESET) { count++; if(count>1000) return 0; bsp_DelayUS(10); } count=0; /*ѯֱӻ 80us ߵƽ źŽ*/ while(TEMP_HUM_DATA_IN()==Bit_SET) { count++; if(count>1000) return 0; bsp_DelayUS(10); } /*ʼ*/ DHT11_Data->humi_int= Read_Byte(); DHT11_Data->humi_deci= Read_Byte(); DHT11_Data->temp_int= Read_Byte(); DHT11_Data->temp_deci= Read_Byte(); DHT11_Data->check_sum= Read_Byte(); /*ȡŸΪģʽ*/ TEMP_HUM_Mode_Out_PP(); /**/ TEMP_HUM_DATA_OUT(HUMITURE_HIGH); /*ȡǷȷ*/ if(DHT11_Data->check_sum == DHT11_Data->humi_int + DHT11_Data->humi_deci + DHT11_Data->temp_int+ DHT11_Data->temp_deci) return 1; else return 0; } else { return 0; } } /********************* DS18B20 **************************/ /* *ӻ͸λ */ static void DS18B20_Rst(void) { /* Ϊ */ TEMP_HUM_Mode_Out_PP(); TEMP_HUM_DATA_OUT(HUMITURE_LOW); /* ٲ480usĵ͵ƽλź */ bsp_DelayUS(750); /* ڲλźź轫 */ TEMP_HUM_DATA_OUT(HUMITURE_HIGH); /*ӻյĸλźź󣬻15~60usһ*/ bsp_DelayUS(15); } /* * ӻصĴ * 0ɹ * 1ʧ */ static uint8_t DS18B20_Presence(void) { uint8_t pulse_time = 0; /* Ϊ */ TEMP_HUM_Mode_IPU(); /* ȴĵΪһ60~240usĵ͵ƽź * ûʱӻյĸλźź󣬻15~60usһ */ while( TEMP_HUM_DATA_IN() && pulse_time<100 ) { pulse_time++; bsp_DelayUS(1); } /* 100us󣬴嶼ûе*/ if( pulse_time >=100 ) return 0; else pulse_time = 0; /* 嵽Ҵڵʱ䲻ܳ240us */ while( !TEMP_HUM_DATA_IN() && pulse_time<240 ) { pulse_time++; bsp_DelayUS(1); } if( pulse_time >=240 ) return 0; else return 1; } /* * DS18B20ȡһbit */ static uint8_t DS18B20_Read_Bit(void) { uint8_t dat; /* 0Ͷ1ʱҪ60us */ TEMP_HUM_Mode_Out_PP(); /* ʱʼ >1us <15us ĵ͵ƽź */ TEMP_HUM_DATA_OUT(HUMITURE_LOW); bsp_DelayUS(10); /* ó룬ͷߣⲿ轫 */ TEMP_HUM_Mode_IPU(); //Delay_us(2); if( TEMP_HUM_DATA_IN() == SET ) dat = 1; else dat = 0; /* ʱοʱͼ */ bsp_DelayUS(45); return dat; } /* * DS18B20һֽڣλ */ uint8_t DS18B20_Read_Byte(void) { uint8_t i, j, dat = 0; for(i=0; i<8; i++) { j = DS18B20_Read_Bit(); dat = (dat) | (j<<i); } return dat; } /* * дһֽڵDS18B20λ */ void DS18B20_Write_Byte(uint8_t dat) { uint8_t i, testb; TEMP_HUM_Mode_Out_PP(); for( i=0; i<8; i++ ) { testb = dat&0x01; dat = dat>>1; /* д0д1ʱҪ60us */ if (testb) { TEMP_HUM_DATA_OUT(HUMITURE_LOW); /* 1us < ʱ < 15us */ bsp_DelayUS(8); TEMP_HUM_DATA_OUT(HUMITURE_HIGH); bsp_DelayUS(58); } else { TEMP_HUM_DATA_OUT(HUMITURE_LOW); /* 60us < Tx 0 < 120us */ bsp_DelayUS(70); TEMP_HUM_DATA_OUT(HUMITURE_HIGH); /* 1us < Trec(ָʱ) < */ bsp_DelayUS(2); } } } void DS18B20_Start(void) { DS18B20_Rst(); DS18B20_Presence(); DS18B20_Write_Byte(0XCC); /* ROM */ DS18B20_Write_Byte(0X44); /* ʼת */ } uint8_t DS18B20_Init(void) { TEMP_HUM_GPIO_Config(); DS18B20_Rst(); return DS18B20_Presence(); } /* * 洢¶16 λĴչĶƲʽ * 12λֱʱ5λ7λ4Сλ * * |-------------------|-----С ֱ 1/(2^4)=0.0625----| * ֽ | 2^3 | 2^2 | 2^1 | 2^0 | 2^(-1) | 2^(-2) | 2^(-3) | 2^(-4) | * * * |-----λ0-> 1->-------|----------------------| * ֽ | s | s | s | s | s | 2^6 | 2^5 | 2^4 | * * * ¶ = λ + + С*0.0625 */ float DS18B20_Get_Temp(void) { uint8_t tpmsb, tplsb; short s_tem; float f_tem; DS18B20_Rst(); DS18B20_Presence(); DS18B20_Write_Byte(0XCC); /* ROM */ DS18B20_Write_Byte(0X44); /* ʼת */ DS18B20_Rst(); DS18B20_Presence(); DS18B20_Write_Byte(0XCC); /* ROM */ DS18B20_Write_Byte(0XBE); /* ¶ֵ */ tplsb = DS18B20_Read_Byte(); tpmsb = DS18B20_Read_Byte(); s_tem = tpmsb<<8; s_tem = s_tem | tplsb; if( s_tem < 0 ) /* ¶ */ f_tem = (~s_tem+1) * 0.0625; else f_tem = s_tem * 0.0625; return f_tem; }
C
#include "buttons.h" const GPIO_TypeDef *button_gpio_ports[] = {BTN_0_GPIO_Port, BTN_1_GPIO_Port, BTN_2_GPIO_Port, BTN_3_GPIO_Port, BTN_4_GPIO_Port, BTN_5_GPIO_Port, BTN_6_GPIO_Port, BTN_7_GPIO_Port, BTN_8_GPIO_Port, BTN_9_GPIO_Port, BTN_CANCEL_GPIO_Port, BTN_DP_GPIO_Port, BTN_VOLTS_GPIO_Port, BTN_AMPS_GPIO_Port, BTN_SHIFT_GPIO_Port, BTN_OUT_CONT_GPIO_Port}; const uint16_t button_gpio_pins[] = {BTN_0_Pin, BTN_1_Pin, BTN_2_Pin, BTN_3_Pin, BTN_4_Pin, BTN_5_Pin, BTN_6_Pin, BTN_7_Pin, BTN_8_Pin, BTN_9_Pin, BTN_CANCEL_Pin, BTN_DP_Pin, BTN_VOLTS_Pin, BTN_AMPS_Pin, BTN_SHIFT_Pin, BTN_OUT_CONT_Pin}; volatile uint32_t button_state = 0; void BTN_Poll() { // Extra shifting for shift button press uint8_t shift_state = BTN_ReadButton(BTN_SHIFT); if (shift_state) shift_state = 16; // Remember the previous state uint32_t prev = button_state; button_state = 0; // Get the current button states for (uint8_t i = 0; i < BTN_N_BUTTONS; i++) { if ((button_gpio_ports[i]->IDR & button_gpio_pins[i]) != 0x00U) { button_state |= (1 << i); } } uint32_t flags = 0; // Check for rising edges for (uint8_t i = 0; i < BTN_N_BUTTONS; i++) { if (!(prev & (1 << i)) && (button_state & (1 << i))) { flags |= (1 << (i + shift_state)); } } // Send the flags if there are any if (flags) { BTN_CallBack(flags); } } bool BTN_ReadButton(uint8_t button) { if (button > BTN_ONOFF) return false; if ((button_gpio_ports[button]->IDR & button_gpio_pins[button]) != 0x00U) { return true; } return false; } __weak void BTN_CallBack(uint32_t button_flags) { asm("NOP"); }
C
#include "Sorter.h" #include "MergeSort.c" char* trimSpace(char* str){ int end = strlen(str) - 1; while(str[end] == ' ' || str[end] == '\n' || str[end] == '\r') { str[end] = '\0'; end--; } while(*str == ' ') { str++; } return str; } char getDataType(char* data){ if(strcmp(data, "color") == 0) return 's'; else if(strcmp(data, "director_name") == 0) return 's'; else if(strcmp(data, "actor_2_name") == 0) return 's'; else if(strcmp(data, "genres") == 0) return 's'; else if(strcmp(data, "actor_1_name") == 0) return 's'; else if(strcmp(data, "movie_title") == 0) return 's'; else if(strcmp(data, "actor_3_name") == 0) return 's'; else if(strcmp(data, "plot_keywords") == 0) return 's'; else if(strcmp(data, "movie_imdb_link") == 0) return 's'; else if(strcmp(data, "language") == 0) return 's'; else if(strcmp(data, "country") == 0) return 's'; else if(strcmp(data, "content_rating") == 0) return 's'; if(strcmp(data, "num_critic_for_reviews") == 0) return 'n'; else if(strcmp(data, "duration") == 0) return 'n'; else if(strcmp(data, "director_facebook_likes") == 0) return 'n'; else if(strcmp(data, "actor_3_facebook_likes") == 0) return 'n'; else if(strcmp(data, "actor_1_facebook_likes") == 0) return 'n'; else if(strcmp(data, "gross") == 0) return 'n'; else if(strcmp(data, "num_voted_users") == 0) return 'n'; else if(strcmp(data, "cast_total_facebook_likes") == 0) return 'n'; else if(strcmp(data, "facenumber_in_poster") == 0) return 'n'; else if(strcmp(data, "num_user_for_reviews") == 0) return 'n'; else if(strcmp(data, "budget") == 0) return 'n'; else if(strcmp(data, "title_year") == 0) return 'n'; else if(strcmp(data, "actor_2_facebook_likes") == 0) return 'n'; else if(strcmp(data, "imdb_score") == 0) return 'n'; else if(strcmp(data, "aspect_ratio") == 0) return 'n'; else if(strcmp(data, "movie_facebook_likes") == 0) return 'n'; return 'e'; } int main(int argc, char* argv[]) { //Check if valid input if(argc < 2){ printf("ERROR: no arguments\n"); return -1; } if(strcmp(argv[1], "-c") != 0){ printf("ERROR: not sorting by columns\n"); return -1; } if(argc < 3){ printf("ERROR: column to sort by not given\n"); return -1; } //Get column heading and create copy of it char* header = (char*) calloc(1024, sizeof(char)); if(fgets(header, sizeof(char) * 1024, stdin) == NULL){ printf("ERROR: file empty"); return -1; } char* row1 = strdup(header); //If column to search for is found, get column number char* colToSort = argv[2]; int colNumToSort = 0; const char delim[2] = ","; const char otherDelim[3] = "\""; char* curHead = strsep(&row1, delim); while( curHead != NULL && strcmp(colToSort, trimSpace(curHead)) != 0){ curHead = strsep(&row1, delim); colNumToSort++; } if(curHead == NULL){ printf("ERROR: column to sort not found"); return -1; } //Print column headers to output file printf("%s", header); //Creating list of DataRow DataRow** list = (DataRow**) malloc(sizeof(DataRow*) * 20000); char dataType = getDataType(colToSort); int curRowNum = 0; char* origRow = (char*) calloc(1024, sizeof(char)); //Goes through each row in csv file while(fgets(origRow, sizeof(char) * 1024, stdin) != NULL){ //New dataRow for array DataRow* newDataRow = (DataRow*) malloc(sizeof(DataRow)); newDataRow->dataType = dataType; char* rowDelim = strdup(origRow); //newRow is data for new row with trimmed spaces char* newRow = (char*) calloc(1024, sizeof(char)); //Goes through each word, trimming spaces and finding data to sort by and add data to array char* curWord = strsep(&rowDelim, delim); int firstWord = 1; int i = 0; while(curWord != NULL){ if(firstWord) firstWord = 0; else strcat(newRow, ","); char wordToAdd[300]; strcpy(wordToAdd, curWord); if(wordToAdd[0] == '"' && wordToAdd[strlen(wordToAdd) - 1] != '"') { char* otherHalf = strsep(&rowDelim, otherDelim); strcat(wordToAdd, ","); strcat(wordToAdd, otherHalf); strcat(wordToAdd, "\""); curWord = strsep(&rowDelim, delim); } char* trimWord = trimSpace(wordToAdd); if(i == colNumToSort){ DataCompare* newDataCompare = (DataCompare*) malloc(sizeof(DataCompare)); if(dataType == 'n'){ newDataCompare->numData = atof(trimWord); } else if(dataType == 's'){ newDataCompare->stringData = trimWord; } newDataRow->dataCompare = newDataCompare; } strcat(newRow, trimWord); curWord = strsep(&rowDelim, delim); i++; } newDataRow->data = newRow; list[curRowNum] = newDataRow; curRowNum++; } //Sort list mergeSort(list, 0, (curRowNum -1)); //Prints list then frees it int j; for(j = 0; j < curRowNum; j++) { printf("%s\n", list[j]->data); free(list[j]->dataCompare); free(list[j]->data); free(list[j]); } free(header); free(origRow); free(list); return 0; }