language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/** * @file encode.h * @brief Encode raw frames to video. * @author Ryan Jacobs <[email protected]> * @date March 18, 2015 * @bug No known bugs. */ #ifndef ENCODE_H #define ENCODE_H /** * Main encode loop. * Captures RGB frames and writes them to an h264 stream. * * @param filename Output filename. * @param frames Number of frames to record. Use 0 to record forever. * @param delay Delay in seconds between each screenshot. * @param framerate FPS for video output. */ void encode_loop(const char *filename, long long int frames, unsigned int delay, int framerate); #endif /* ENCODE_H */
C
/* Note: compile with the Makefile Note: correct output example ./eB4 /u1/junk/shakespeare.txt Number of words with ... 1 letter: 20 2-5 letters: 5916 20-100 letters: 12 ./eB4 /u1/junk/kinne/shakespeare_1000_lines.txt Number of words with ... 1 letter: 6 2-5 letters: 785 20-100 letters: 0 Recall that the definition of the word_t and bst node are - typedef struct WORD_T { char *w; // space for the word int l; // length of w, so we don't have to recompute int count; // for frequency counts } word_t; typedef struct BST_NODE_T { word_t * data; struct BST_NODE_T *left, *right; } bst_node_t; */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "/u1/h0/jkinne/public_html/cs202-f2017/CLASS/DS/words.h" #include "/u1/h0/jkinne/public_html/cs202-f2017/CLASS/DS/bst.h" // examB, you to do - create a count function here. // The function should have two parameters and return the // number of nodes in the tree that are words with length // between the two parameters int count(int x, int y){ if() return NULL; } int main(int argc, char * argv[]) { // by default read from stdin FILE * f = stdin; // otherwise try to open a file with filename given by argv[1] if (argc > 1) { f = fopen(argv[1], "r"); if (f == NULL) { fprintf(stderr, "Error opening file %s for reading.\n", argv[1]); exit(0); } } // init the BST! bst_node_t *root = NULL; char s[100]; int len; while ((len = get_word(f, s, 100)) != -1) { if (len > 0) { bst_node_t *p = lookup_bst(root, s); if (p != NULL) inc_word(p->data); else insert_bst(&root, s); } } fclose(f); // examB - leave this alone, this calls the count // function you should put above main. printf("Number of words with ... \n"); printf(" 1 letter: %d\n", count(root,1,1)); printf(" 2-5 letters: %d\n", count(root,2,5)); printf(" 20-100 letters: %d\n", count(root, 20, 100)); return 0; }
C
#include<stdio.h> void main(void) { int arr1[3] = {1, 2, 3}; for(int i = 0; i<3; i++) { *(arr1+i) += 100*(i+1); } for(int i = 0; i<3; i++) { printf("%d ", arr1[i]); } }
C
#include<stdio.h> #include<conio.h> float PU,MB,MHT,Taxe,TVA,MTTC,Red; int Q; void main () { printf("Donnez le prix unitaire\n"); scanf("%f",&PU); printf("Donnez la quantite\n"); scanf("%d",&Q); MB=Q*PU; printf("Le montant brut est MB=%.2f\n",MB); if(Q<20) Red=0; else { if(Q<100) Red=0.1; else Red=0.12; } MHT=MB-(MB*Red); printf("Le montant hors taxe est MHT=%.2f\n",MHT); TVA=0.20; Taxe=MHT*TVA; MTTC=MHT+Taxe; printf("Le montant tout taxe compris est MTTC=%.2f\n",MTTC); printf("Pour continuer Tapez sur une touche\n"); getch(); }
C
/* created by li Danny Date:/ 2015/12/20 */ #include "DSP2833x_Device.h" #include "DSP2833x_Examples.h" // DSP2833x Examples Include File #include "math.h" #include "DATA_Process.h" #include "ConstData_Table.h" #include "AD7656.h" #include "std_init.h" // Global variable for this example //3·ͨԾĽ float DAL_OutPut1[BUF_SIZE1+LOWFILT_SIZE]={0}; float DAL_OutPut2[BUF_SIZE2+LOWFILT_SIZE]={0}; float DAL_OutPut3[BUF_SIZE3+LOWFILT_SIZE]={0}; /***************************************************** * ܣԾ * ڣ */ void LinearConvolution(unsigned int xn,unsigned int hn,float *input,float *h,float *output) { unsigned int i,j,m,LL; unsigned int yn = 0; //yij yn = xn + hn -1; for(i=0;i<yn;i++) { output[i]=0; //ʼ } m = yn - 1; for(i = hn-1;i>0;i--) //*hΪ { LL=m; for(j=xn-1;j>0;j--) //x[n]1~(xn-1)h[i]һ { output[LL] += h[i]*input[j]; LL--; } output[LL] += input[0]*h[i]; m--; } LL = m; for(j=xn-1;j>0;j--) { output[LL]+=h[0]*input[j]; LL--; } output[LL]+=input[0]*h[0]; } /******************************************************* * SINCOS_TAB * ܣҲο ******************************************************/ void SINCOS_TAB(float * Sin_tab,float *Cos_tab,unsigned int cycle_point) { unsigned int i = 0; float theta = 0; for(i = 0; i < cycle_point; i++) { theta = i* 6.283185/cycle_point; //2pi = 6.283185, Sin_tab[i] = sin(theta)+1.0; Cos_tab[i] = cos(theta)+1.0; } } /**************************************************** * DAL_Process * : Ŵ㣬ֻһͨ ****************************************************/ void DAL_Process(float *Channel_Date, unsigned int Buf_size, float *Low_filter, float *DAL_OutPut) { register int k = 0,j = 0; float temp1 = 0,temp2 = 0; float Cross_OutPut[2*BUF_SIZE1-1]; //3·οĽ float SampleBuffer1[2*BUF_SIZE1-1]={0}; float SampleBuffer2[2*BUF_SIZE1-1]={0}; float sinwave[BUF_SIZE1/CYCLE_NUM] = {0}; float coswave[BUF_SIZE1/CYCLE_NUM] = {0}; SINCOS_TAB(sinwave,coswave,Buf_size/CYCLE_NUM); /* float testsinwave[BUF_SIZE1] = {0}; float testcoswave[BUF_SIZE1] = {0}; for(k = 0;k < Buf_size;k++) { testsinwave[k] = sinwave[k%42]; testcoswave[k] = coswave[k%42]; } */ for(k = 0; k < Buf_size; k++) { temp1 = 0; temp2 = 0; for(j = 0;j < Buf_size-k; j++) { temp1 += Channel_Date[j]*sinwave[(j+k)%(Buf_size/CYCLE_NUM)]; temp2 += Channel_Date[j]*coswave[(j+k)%(Buf_size/CYCLE_NUM)]; } SampleBuffer1[Buf_size-1-k] = temp1/(Buf_size-k); SampleBuffer2[Buf_size-1-k] = temp2/(Buf_size-k); } for(k = 0; k < Buf_size; k++) { temp1 = 0; temp2 = 0; for(j = 0;j < Buf_size-k; j++) { temp1 += Channel_Date[j+k]*sinwave[j%(Buf_size/CYCLE_NUM)]; temp2 += Channel_Date[j+k]*coswave[j%(Buf_size/CYCLE_NUM)]; } SampleBuffer1[Buf_size-1+k] = temp1/(Buf_size-k); SampleBuffer2[Buf_size-1+k] = temp2/(Buf_size-k); } for(k = 0;k < 2*Buf_size-1; k++) { temp1 = SampleBuffer1[2*Buf_size-2-k]; //עԽ⣬K=0ʱ temp2 = SampleBuffer2[2*Buf_size-2-k]; Cross_OutPut[2*Buf_size-2-k]=2*sqrt(temp1*temp1+temp2*temp2); } //******************************************* LinearConvolution(Buf_size,LOWFILT_SIZE,Cross_OutPut,Low_filter,DAL_OutPut); //Ծ } /************************************************************* * ܣ սˮֺ * ڲ ͨαͨ1αͨ2ź,size, Ϸʽ * ֵ սϵˮְٷֺ */ float Moisture_FITcalcu(float* MeasureDal,Uint16 Buf_size1,float* Refer1Dal,Uint16 Buf_size2,float* Refer2Dal,Uint16 Buf_size3,char FIT_Mode) { float Measure_Amp,Refer1_Amp,Refer2_Amp,Ratio,water_content; water_content = 0; Measure_Amp = Single_Amplitude(MeasureDal,Buf_size1); Refer1_Amp = Single_Amplitude(Refer1Dal,Buf_size2); Refer2_Amp = Single_Amplitude(Refer2Dal,Buf_size3); Ratio = Measure_Amp/(Refer1_Amp+Refer2_Amp); // Print_data[0]=(unsigned char)((Uint16)(Measure_Amp*100)>>8); // Print_data[1]=(unsigned char)((Uint16)(Measure_Amp*100)&0x00ff); // Print_data[2]=(unsigned char)((Uint16)(Refer1_Amp*100)>>8); // Print_data[3]=(unsigned char)((Uint16)(Refer1_Amp*100)&0x00ff); // Print_data[4]=(unsigned char)((Uint16)(Refer2_Amp*100)>>8); // Print_data[5]=(unsigned char)((Uint16)(Refer2_Amp*100)&0x00ff); // Print_data[6]=(unsigned char)((Uint16)(Ratio*100)>>8); // Print_data[7]=(unsigned char)((Uint16)(Ratio*100)&0x00ff); switch(FIT_Mode) { case '1': // break; case '2': // ֶ break; case '3': // ָ break; default : break; } return water_content; } /* * : DATA trans * ڲ: DAL_OutPut, */ void Data_Trans(float * Trans_data,Uint16 Buf_size,char * Trans_result) { register int i,j; for(i=0;i<Buf_size;i++) { j=2*i; Trans_result[j]=(unsigned char)((Uint16)(Trans_data[i]*10)>>8); Trans_result[j+1]=(unsigned char)((Uint16)(Trans_data[i]*10)&0x00ff); } } /* * Function get the voltal of the process resule * Inlet parameter: DAL_OutPut and the size of DAL_OutPut * Outlet parameter: the amplitude of the DAL_OutPut. */ float Single_Amplitude(float * DAL_OutPut,Uint16 Buf_size ) { int i = 0; float tempdata = 0; for(i = 100;i <= Buf_size-20; i++) { tempdata += DAL_OutPut[i]; } return tempdata/(BUF_SIZE1-100-19); } //------------------------------------------------- //no more //-------------------------------------------------
C
%{ #include "tabsimb2.c" #include <stdlib.h> #include <stdio.h> simbolo * t; %} %union { int numero; simbolo * ptr_simbolo; } %token <numero> NUMERO %token <ptr_simbolo> ID %token ASIG %type <numero> expr asig prog %left '+' %left '*' %% prog : prog asig '\n' { printf("Asignaciones efectuadas\n");} | prog expr '\n' { printf("%d\n",$2);} | prog error '\n' { yyerrok;} ; asig : ID ASIG expr { $$ = $3; $1->valor = $3; } | ID ASIG asig { $$ = $3; $1->valor = $3; } ; expr : expr '+' expr {$$ = $1 + $3;} | expr '*' expr {$$ = $1 * $3;} | ID {$$ = $1->valor; } | NUMERO {$$ = $1;} ; %% #include "ejem2l.c" #include "errorlib.c" void main() { t = crear(); yyparse (); imprimir(t); } typedef struct nulo { struct nulo * sig; char nombre [20]; int valor; } simbolo; simbolo * crear() { return NULL; }; void insertar(p_t,s) simbolo **p_t; simbolo * s; { s->sig = (*p_t); (*p_t) = s; }; simbolo * buscar(t,nombre) simbolo * t; char nombre[20]; { while ( (t != NULL) && (strcmp(nombre, t->nombre)) ) t = t->sig; return (t); }; void imprimir(t) simbolo * t; { while (t != NULL) { printf("%s\n", t->nombre); t = t->sig; } };
C
#include <stdio.h> //sort arr in incresing order // n is the number of elements in arr void sort_recur(int *arr, int n) { if (n == 0) return; int min = 10000; int pos = 0; for (int i = 0; i < n; i++) if (arr[i] < min) { pos = i; min = arr[i]; } arr[pos] = arr[0]; arr[0] = min; sort_recur(++arr, n - 1); } void main() { printf("Enter number of elements: "); int n; scanf("%d", &n); int arr[n]; printf("Enter Array: "); for (int i = 0; i < n; i++) scanf("%d", &arr[i]); sort_recur(arr, n); printf("Sorted Array: "); for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); }
C
/******************* * * $Date:$ * $Revision:$ * $Author:$ * $HeadUrl:$ * $Id: mvvonmises.c 13 2015-04-17 08:17:47Z lrodriguez $ **/ #include <stdlib.h> #include <stdint.h> #include <math.h> #include <float.h> #include <stdint.h> #include <string.h> #include "bessel.h" #include "mvvonmises_likelihood.h" #include "matrixOps.h" /************* * Likelihood */ /* Transforms theta to Sin(theta-mu) * * Computes Sin(theta-mu) / Cos(theta-mu) for each variable in the dataset. * * @param [in] n * @param [in] p * @param [in] theta * @param [in] mu * @param [out] S * @param [out] C * */ void mv_theta_cos_sinTransform(int n, int p, double *theta, double* mu, long double *S, long double *C){ int i,j; for(i=0;i<n;i++){ for(j=0;j<p;j++){ S[i*p + j] = sinl(theta[i*p + j] - mu[j]); C[i*p + j] = cosl(theta[i*p + j] - mu[j]); } } } /*** * Multivaraite von mises density. Not normalized * * @param [in] p * @param [in] theta * @param [in] mu * @param [in] kappa * @param [in] Lambda * * @return Density val * */ double mvvm_density_unregularized(int p, double *theta, double *mu, double *kappa, double *lambda){ double aux=0; long double *s = malloc(sizeof(long double) * p); long double *v = malloc(sizeof(long double) * p); int i; for(i=0;i<p;i++) s[i] = sin(theta[i]-mu[i]); // Bilinear form generalMatrixMatrix(1,p,p,p,'n','n',s,lambda,v); generalMatrixMatrix(1,p,p,1,'n','n',v,s,&aux); aux /= 2; // Cos prod for(i=0;i<p;i++) aux += kappa[i] * cos(theta[i]-mu[i]); return (exp(aux)); } /***** * Optimized version. Computes simplified log likelihood and its derivatives * * Removes constant terms. Uses matrix multiplications. Reduce number of trigonometric opers. * Reuses terms. Marginal mu is not longer needed, derivatives are simplified as well. * * Instead of PL we will name it "loss function" * * Lambda is taken as a full row-leading pxp matrix with 0's in the diagonal. But d_lambda is only * computed for the upper triangle. * * If d_kappa or d_lambda are NULL, derivatives are not computed. * * To even speed up the process a little bit more, we make the following assumptions: * * Mu is 0 for every j * (input) Theta_i_j = Sin( (real) Theta_i_j - (real)mu_j ) * * * @param [in] n * @param [in] p * @param [in] kappa * @param [in] lambda * @param [in] theta * @param [out] ro * @param [out] d_kappa * @param [out] d_lambda * * @return loss function value */ long double mv_vonmises_lossFunction(int n,int p, double* kappa, double* lambda, long double *S, long double *C, long double *ro, double *d_kappa, double *d_lambda){ // iterators int i,j,s; // Auxiliar terms long double fx; // Loss function value long double k_i_j; // Marginal concentration por i,j long double bes_kij; // Bessel I0(k_ij) long double bes1_kij; // I1(k_ij) long double a_kij; // A_0(k_j_i)/k_j_i // Compute ro as ro = Theta * Lambda (Lambda is symmetric) generalMatrixMatrix(n,p,p,p,'n','n',S,lambda,ro); // Initialize fx=0; if(d_lambda != NULL && d_kappa != NULL){ // Initialize d_lambda d_kappa memset(d_lambda,0,sizeof(double)*p*p); memset(d_kappa,0,sizeof(double)*p); for(j=0;j<p;j++){ for(i=0;i<n;i++){ // Compute k_i_j and a_kij k_i_j = sqrtl( (kappa[j] * kappa[j]) + (ro[i*p + j] * ro[i*p + j]) ); // Bessel kij (Expon scaled) // We get exp(-k_i_j) * I0(k_i_j) bes_kij = bessi0_expon(k_i_j); // A0/k_i_j a_kij = ((bessi1_expon(k_i_j)) / (bes_kij * k_i_j)); // Actually this is A0(k_j_i)/ k_j_i but getting rid of one div. // Loss function part // // logl(exp(-kij)*I0) = -kij + logl(I0) -> We add k_ij to get logl(I0) fx += (k_i_j + logl(bes_kij) ) - ( C[i*p + j] * kappa[j] ) - ( S[i*p + j] * ro[i*p + j] ); // Sum the part that coresponds to d_kappa d_kappa[j] += a_kij * kappa[j] - C[i*p + j]; // Update lambda partial for(s=0;s<j;s++) d_lambda[s*p + j] += S[i*p +s] * (a_kij * ro[i*p + j] - S[i*p + j] ); for(s=j+1;s<p;s++) d_lambda[j*p + s] += S[i*p +s] * (a_kij * ro[i*p + j] - S[i*p + j] ); } // Copy to full matrix for(s=j+1;s<p;s++){ d_lambda[s*p + j] = d_lambda[j*p + s]; } } } else{ for(j=0;j<p;j++){ for(i=0;i<n;i++){ // Compute k_i_j and a_kij k_i_j = sqrtl( (kappa[j] * kappa[j]) + (ro[i*p + j] * ro[i*p + j]) ); // Bessel kij (Expon scaled) bes_kij = bessi0_expon(k_i_j); // Loss function part fx += (k_i_j + logl(bes_kij)) - (C[i*p + j] * kappa[j]) - (S[i*p + j] * ro[i*p + j]); } } } return(fx); }
C
#include "common.h" void next_step() { int i, j; int best_i=-1, best_j=-1, best=INFINITE; for(i=0;i<KORIFES;i++) { //An i korifi einai sto sinolo V, tote elegxoume ton pinaka geitniasis if(vertices[i]) { for(j=0;j<KORIFES;j++) { //An i akmi (i,j) iparxei idi sto sinolo E, tote sinexizoume if(vertices[j]) continue; //An to varos einai kalitero apo to best, tote kanoume tin ananewsi tou best if(matrix[i][j] && matrix[i][j]<best) { best_i=i; best_j=j; best=matrix[best_i][best_j]; } } } } //An best==INFINITE simainei oti de vrethike kamia akmi ston pinaka geitniasis if(best!=INFINITE) { g_best_i=best_i; g_best_j=best_j; } } int main(int argc, char** argv) { init(argc, argv); struct timeval start, stop; gettimeofday(&start, NULL); while(1) { g_best_i=-1; next_step(); //An de vrethike kapoia akmi tote termatizoume if(g_best_i==-1) break; //Alliws, diagrafoume tin akmi ap ton pinaka kai enimerwnoume to sinolo V matrix[g_best_i][g_best_j]=matrix[g_best_j][g_best_i]=0; vertices[g_best_j]=1; if(!BENCHMARK) print_matrix(); } gettimeofday(&stop, NULL); printf("%f seconds\n", (stop.tv_sec-start.tv_sec)+((double)stop.tv_usec-start.tv_usec)/1000000); return 0; }
C
/* 50 ֪ѧļ¼ѧźѧϰɼɣ nѧѴaṹС дfunúĹǣҳɼߵѧ¼ͨβη(涨ֻһ߷) */ #define N 10 struct student { int id; float score; }; struct student s[N]; struct student fun(struct student s[],int n) { int max = 0; struct student temp; for (int i = 0; i < n; i++) { if (s[i].score > max) max = s[i].score; temp = s[i]; } return temp; }
C
#pragma once #define PI 3.1415926535897932384626433832795 #define PI_DEG 180 #define PI_DEGx2 360 struct Point { float x = 0; float y = 0; Point() {} Point(float x, float y) : x(x), y(y){} bool operator==(const Point& point); }; struct Line { float k = 0; float c = 0; Line() {} float f(float x); }; Line* lineFrom2Points(Point* point1, Point* point2); float distanceBetweenTwoPoints(Point* point1, Point* point2); Line* parallelLineFromLineAndPoint(Line* line, Point* point); Point* intersectionOf2Lines(Line* line1, Line* line2); Point* midpointOf2Points(Point* point1, Point* point2); float angleFrom3PointsInRadians(Point* a, Point* o, Point* b); float angleFrom3Points(Point* a, Point* o, Point* b); Point* pointFrom2Points_90(Point* a, Point* o); float radiansToDegrees(float radians); float comparePointAgainstLine(Point* point, Line* line); bool arePointsOnSameLine(Point** points, unsigned int count);
C
#include <stdlib.h> #include "lists.h" /** * delete_dnodeint_at_index -deletes node at index of a dlistint_t linked list. * @head: the head of list. * @index: the index. * Return: 1 or -1. */ int delete_dnodeint_at_index(dlistint_t **head, unsigned int index) { unsigned int i = 0, c = 0; dlistint_t *curr = *head; dlistint_t *last = *head; if (!*head) return (-1); while (last->next) { last = last->next; c++; } if (index > c) return (-1); if (index == 0) { *head = curr->next; if (curr->next) curr->next->prev = NULL; free(curr); return (1); } while (i != index) { if (curr->next == NULL) return (-1); curr = curr->next; i++; } curr->prev->next = curr->next; if (curr->next) curr->next->prev = curr->prev; free(curr); return (1); }
C
#include "sort.h" /** * * * * */ void selection_sort(int *arr, size_t size) { int saved, swap, state; size_t i, j, index; state = 0; for (i = 0; i < size; i++) { for (j = i + 1; j < size; j++) { if (state == 0 && arr[i] > arr[j]) { saved = arr[j]; index = j; state = 1; } else if (state == 1 && saved > arr[j]) { saved = arr[j]; index = j; } } if (state == 1 && arr[i] > arr[index]) { swap = arr[i]; arr[i] = arr[index]; arr[index] = swap; state = 0; print_array(arr, size); } } }
C
#include "privparent.h" #include "privsock.h" #include "sysutil.h" #include "tunable.h" static void privop_pasv_get_data_sock(session_t *sess); static void privop_pasv_active(session_t *sess); static void privop_pasv_listen(session_t *sess); static void privop_pasv_accept(session_t *sess); //ڼͷļDZʱ򻹱implicit declaration of function 'capset' //capsetԭʼһں˽ӿڣԼcapsetӿ //capsetԭʼں˽ӿ int capset(cap_user_header_t hdrp, const cap_user_data_t datap) { return syscall(__NR_capset, hdrp, datap);//man syscall //syscal(ϵͳú,...ɱ)capsetϵͳõĺԲ鿴sys/syscall.hͷļ //ȥ֮bits/syscall.hͷļԿcapsetϵͳú#define SYS_capset __NR_capset } //nobodyһЩҪȨ void minimize_privilege(void) { struct passwd *pw = getpwnam("nobody"); if (pw == NULL) return; if (setegid(pw->pw_gid) < 0) ERR_EXIT("setegid"); if (seteuid(pw->pw_uid) < 0) ERR_EXIT("seteuid"); /* capabilitiesûȨֳһЩȻͬĵԪЩԪ֮Ϊcapabilities ЩcapabilitiesһЩȨޣЩcapabilitiesܹĿ߹ر man 7 capabilities Ȩ޵ķcapsetman 2 capset nobody̾bindȨ˿ڵȨ */ struct __user_cap_header_struct cap_header;//Ҫһhead struct __user_cap_data_struct cap_data;//Ҫһdata memset(&cap_header, 0, sizeof(cap_header)); memset(&cap_data, 0, sizeof(cap_data)); //32bitϵͳѡ_LINUX_CAPABILITY_VERSION_164bitϵͳѡ_LINUX_CAPABILITY_VERSION_2 cap_header.version = _LINUX_CAPABILITY_VERSION_1; cap_header.pid = 0;//capsetҪ̺ţcapgetҪǻȡӦ̵capabilities __u32 cap_mask = 0;//__u32޷32bit32bitȽ0 //cap_maskһ룬Դźܶcapabilities cap_mask |= (1 << CAP_NET_BIND_SERVICE); //#include <linux/capability.h>,vi /usr/include/linux/capability.hԿCAP_NET_BIND_SERVICEڵ10λ /* ....00000000000000000000000 | ....00000000000100000000000Ƶ10λ1ĺ100 */ //cap_dataָЩcapabilitiesֵָͨͬ //effective壺ӦþʲôcapabilitiesӦþпbindȨ˿ڵcapabilitiesCAP_NET_BIND_SERVICE //permittedĺ壺permittedеcapabilitiesԸeffectiveeffectivecapabilitiesСpermittedϣ //permittedĺ壺permittedcapabilitiesϿԷŵinheritableǷԱ̳ //execϵкʱЩcapabilitiesԱ½̼̳Уexecʾ½滻 cap_data.effective = cap_data.permitted = cap_mask; cap_data.inheritable = 0;//0ʾҪ½̼̳ capset(&cap_header, &cap_data); } void handle_parent(session_t *sess) { minimize_privilege(); char cmd; while (1) { //read(sess->parent_fd, &cmd, 1); cmd = priv_sock_get_cmd(sess->parent_fd); // ڲ // ڲ switch (cmd) { case PRIV_SOCK_GET_DATA_SOCK: privop_pasv_get_data_sock(sess); break; case PRIV_SOCK_PASV_ACTIVE: privop_pasv_active(sess); break; case PRIV_SOCK_PASV_LISTEN: privop_pasv_listen(sess); break; case PRIV_SOCK_PASV_ACCEPT: privop_pasv_accept(sess); break; } } } static void privop_pasv_get_data_sock(session_t *sess) { /* nobody̽PRIV_SOCK_GET_DATA_SOCK һһҲport һַҲip fd = socket bind(20) connect(ip, port); OK send_fd BAD */ unsigned short port = (unsigned short)priv_sock_get_int(sess->parent_fd); char ip[16] = {0}; priv_sock_recv_buf(sess->parent_fd, ip, sizeof(ip)); struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = inet_addr(ip);//inet_addrʮתΪ32bit int fd = tcp_client(20); if (fd == -1) { priv_sock_send_result(sess->parent_fd, PRIV_SOCK_RESULT_BAD); return; } if (connect_timeout(fd, &addr, tunable_connect_timeout) < 0) { close(fd); priv_sock_send_result(sess->parent_fd, PRIV_SOCK_RESULT_BAD); return; } priv_sock_send_result(sess->parent_fd, PRIV_SOCK_RESULT_OK); priv_sock_send_fd(sess->parent_fd, fd); close(fd);//nobodyͻ˲ֱӽͨţֻЭͨĽ } static void privop_pasv_active(session_t *sess) { } static void privop_pasv_listen(session_t *sess) { } static void privop_pasv_accept(session_t *sess) { }
C
#include <stdio.h> #include <math.h> int main() { float r1, r2, x1, x2, y1, y2, s = 0, a, b; int ymax, ymin, xmax, rmax, rmin, xmin; printf("Vvedite koordinats x, y b radius pervoy okruzhosti"); scanf("%f %f %f", &x1, &y1, &r1); printf("Vvedite koordinats x, y b radius vtoroy okruzhosti"); scanf("%f %f %f", &x2, &y2, &r2); rmin = fmin(r1, r2); rmax = fmax(r1, r2); if ((x1 == x2) && (y1 == y2) && (r1 == r2)) { printf("okruzhosti sovpadayut"); return 0; } s = sqrt((x1 -x2)* (x1 - x2) + (y1 - y2)*(y1 - y2)); if (s == (r1 + r2)) { printf("okruzhnosti kasautsya snaruzhi"); return 0; } if (s > (r1 + r2)) { printf("okruzhnosti ne peresekautsya"); return 0; } if (s < (r1 + r2)) { if ((s == rmin) || (rmax - s == rmin)) { printf("okruzhnosti kasautsya vnutri"); return 0; } if (rmax - s > rmin) { printf("okruzhnost soderzhitsya v drugoi"); return 0; } printf("okruzhnosti peresekayutsya v dvuh tochkah"); } return 0; }
C
#include "matrixMul8.h" typedef signed char Filtc; typedef signed char FiltcV __attribute__((vector_size (4))); #define SumDotp(a, b, c) __builtin_pulp_sdotsp4(a, b, c) #define Dotp(a, b) __builtin_pulp_dotsp4(a, b) void __attribute__ ((noinline)) matMul8(signed char * __restrict__ A, signed char * __restrict__ B, signed int * __restrict__ C, int N, int M) { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { C[i*N+j] = 0; for (int k = 0; k < N; k++) { C[i*N+j] += A[i*N+k] * B[k*N+j]; } } } } void __attribute__ ((noinline)) matMul8_t_dot(Filtc * __restrict__ A, Filtc * __restrict__ B, signed int * __restrict__ C, int N, int M) { FiltcV VA; FiltcV VB; FiltcV *VectInA; FiltcV *VectInB; int S; Filtc Btmp[N*M]; // transpose array before using it for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { Btmp[i*N+j] = B[j*N+i]; } } for (int i = 0; i < N; i++) { VectInA = (FiltcV*)(&A[i*N]); for (int j = 0; j < M; j++) { S = 0; VectInB = (FiltcV*)(&Btmp[j*N]); for (int k = 0; k < (N>>2); k++) { VA = VectInA[k]; VB = VectInB[k]; S = SumDotp(VA, VB, S); } C[i*N+j] = S; } } } // helper functions void __attribute__ ((noinline)) matrix_init(signed char * __restrict__ A, signed char * __restrict__ B, signed int * __restrict__ C) { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { A[i*SIZE+j] = m_a[i * SIZE + j]; B[i*SIZE+j] = m_b[i * SIZE + j]; C[i*SIZE+j] = 0; } } } unsigned int __attribute__ ((noinline)) matrix_check(signed int * __restrict__ C) { unsigned int errors = 0; // check for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { if (C[i*SIZE+j] != m_exp[i * SIZE + j]) { //printf("At index %d, %d\n", i, j); errors++; } } } return errors; }
C
#include "priority.h" #include "../tasks.h" void init_scheduler(struct process* list, int size, int ramend) { int i; for(i=0; i < size; i++) { list[i].stack_size = 100; list[i].running = 0; } list[0].task_pointer = task0; list[1].task_pointer = task1; list[2].task_pointer = task2; list[3].task_pointer = task3; list[0].priority = 0; list[1].priority = 10; list[2].priority = 150; list[3].priority = 512; list[0].stack_pointer = (int) ramend-100; for(i=1; i < size; i++) list[i].stack_pointer = list[i-1].stack_pointer - list[i-1].stack_size; char *px; for(i=0; i < size; i++) { px = (char *) list[i].stack_pointer; *px = (char) ((int) list[i].task_pointer); px = (char *) list[i].stack_pointer-1; *px = (char) (((int) list[i].task_pointer) >> 8); } for(i=1; i < size; i++) { list[i].stack_pointer-=35; } } int next_task(struct process* list, int size) { /*Variáveis que armazenarão o valor da maior prioridade encontrada entre os processos e o índice do processo com com maior prioridade */ int greatest_priority = 0; int greatest_priority_index = 0; /*Busca pelo processo que estava sendo executado logo antes da interrupção*/ int i; for(i=0; i < size; i++) if(list[i].running == 1) break; int currently_running = i; if(currently_running < size) list[currently_running].running = 0; /*Busca pelo processo com maior prioridade dentro da lista de processos. Se houver mais de um processo com o mesmo nível de prioridade, eles serão executados de forma circular.*/ for(i=0; i < size; i++) { int j = (i + currently_running + 1) % size; if(list[j].priority > greatest_priority) { greatest_priority = list[j].priority; greatest_priority_index = j; } } /*Implementação da técnica de envelhecimento*/ for(i=1; i < size; i++) if(list[i].priority < greatest_priority) list[i].priority++; /*Declara o próximo processo a ser executado e retorna seu índice*/ list[greatest_priority_index].running = 1; return greatest_priority_index; }
C
#include <stdio.h> #define SIZE 128 /* ascii */ /* print a histogram of different characters in its input */ int main() { int c, i, j; count = 0; /* 单词长度计数器 */ int nlen[SIZE]; /* 统计SIZE个字符长度的单词的直方图,超过SIZE,按ZIE-1算 */ max = 0; /* 追踪长的单词 */ for(i = 0; i < SIZE; ++i) nlen[i] = 0; while((c = getchar()) != EOF) { ++nlen[c]; } // print bar histogram for (i = 0; i < SIZE; ++i) { printf("%c ", i); for (j = 0; j < nlen[i]; ++j) printf("*"); printf("\n"); } return 0; }
C
#include "generic.h" #include <stdlib.h> void Generic_Delete(Generic *G){ free(*G); *G = NULL; } void Generic_Interchange(Generic *G, Generic *G2){ Generic tmp; tmp = *G; *G = *G2; *G2 = tmp; }
C
#include<stdio.h> #include<mpi.h> #include<string.h> #define BUFFER_SIZE 32 // MPI data type: MPI_INT, MPI_CHAR // MPI_Send(value or massage to be send, size of message,data type od message, recever rank id, uniqu tage ,MPI_COMM_WORLD); // MPI_Recv(recevung message, size of reseving message,data type ,sender rank, unique tage same as sender,MPI_COMM_WORLD,&status); int main(int argc, char* argv[]) { int rank,numprocs,tag=0,root=3,temp=1; char msg[BUFFER_SIZE]; MPI_Init(&argc,&argv); MPI_Status status; MPI_Comm_rank(MPI_COMM_WORLD,&rank); MPI_Comm_size(MPI_COMM_WORLD,&numprocs); printf("%d\n",numprocs); if(rank==0) { strcpy(msg,"Hello"); MPI_Send(msg,BUFFER_SIZE,MPI_CHAR,1,tag,MPI_COMM_WORLD); int x=10; MPI_Send(&x,1,MPI_INT,2,1,MPI_COMM_WORLD); } else if (rank == 1) { MPI_Recv(msg,BUFFER_SIZE,MPI_CHAR,0,tag,MPI_COMM_WORLD,&status); printf("\n%s recve by process rank %d and sent from process with rank %d\n",msg,rank,root); } else if(rank == 2){ int y; MPI_Recv(&y,1,MPI_INT,0,1,MPI_COMM_WORLD,&status); printf("\n%d receve by process %d",y,rank); } MPI_Finalize(); }
C
/* * Python interface to libc functions. */ #include <stdarg.h> // va_list, etc. #include <stdio.h> // printf #include <limits.h> #include <stdlib.h> // Enable GNU extensions in fnmatch.h. // TODO: Need a configure option for this. #define _GNU_SOURCE 1 #include <fnmatch.h> #include <glob.h> #ifdef __FreeBSD__ #include <gnu/posix/regex.h> #else #include <regex.h> #endif #include <Python.h> // Log messages to stderr. static void debug(const char* fmt, ...) { #ifdef LIBC_VERBOSE va_list args; va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); fprintf(stderr, "\n"); #endif } static PyObject * func_realpath(PyObject *self, PyObject *args) { const char *symlink; if (!PyArg_ParseTuple(args, "s", &symlink)) { return NULL; } char target[PATH_MAX + 1]; char *status = realpath(symlink, target); if (status == NULL) { debug("error from realpath()"); Py_RETURN_NONE; } return PyString_FromString(target); } static PyObject * func_fnmatch(PyObject *self, PyObject *args) { const char *pattern; const char *str; if (!PyArg_ParseTuple(args, "ss", &pattern, &str)) { return NULL; } // NOTE: Testing for __GLIBC__ is the version detection anti-pattern. We // should really use feature detection in our configure script. But I plan // to get rid of the dependency on FNM_EXTMATCH because it doesn't work on // musl libc (or OS X). Instead we should compile extended globs to extended // regex syntax. #ifdef __GLIBC__ int flags = FNM_EXTMATCH; #else debug("Warning: FNM_EXTMATCH is not defined"); int flags = 0; #endif int ret = fnmatch(pattern, str, flags); switch (ret) { case 0: debug("matched: %s", str); return PyLong_FromLong(1); break; case FNM_NOMATCH: debug("no match: %s", str); return PyLong_FromLong(0); break; default: debug("other error: %s", str); return PyLong_FromLong(-1); break; } } // error callback to glob() // // Disabled because of spurious errors. For example, sed -i s/.*// (without // quotes) is OK, but it would be treated as a glob, and prints an error if the // directory 's' doesn't exist. // // Bash does its own globbing -- it doesn't use libc. Likewise, I think dash // and mksh do their own globbing. int globerr(const char *path, int eerrno) { fprintf(stderr, "globerr: %s: %s\n", path, strerror(eerrno)); return 0; // let glob() keep going } static PyObject * func_glob(PyObject *self, PyObject *args) { const char* pattern; if (!PyArg_ParseTuple(args, "s", &pattern)) { return NULL; } glob_t results; // Hm, it's weird that the first one can't be called with GLOB_APPEND. You // get a segfault. int flags = 0; // int flags = GLOB_APPEND; //flags |= GLOB_NOMAGIC; int ret = glob(pattern, flags, NULL, &results); const char *err_str = NULL; switch (ret) { case 0: // no error break; case GLOB_ABORTED: err_str = "read error"; break; case GLOB_NOMATCH: // No error, because not matching isn't necessarily a problem. // NOTE: This can be turned on to log overaggressive calls to glob(). //err_str = "nothing matched"; break; case GLOB_NOSPACE: err_str = "no dynamic memory"; break; default: err_str = "unknown problem"; break; } if (err_str) { fprintf(stderr, "func_glob: %s: %s\n", pattern, err_str); } // http://stackoverflow.com/questions/3512414/does-this-pylist-appendlist-py-buildvalue-leak size_t n = results.gl_pathc; PyObject* matches = PyList_New(n); // Print array of results size_t i; for (i = 0; i < n; i++) { //printf("%s\n", results.gl_pathv[i]); PyObject* m = Py_BuildValue("s", results.gl_pathv[i]); PyList_SetItem(matches, i, m); } globfree(&results); return matches; } static PyObject * func_regex_parse(PyObject *self, PyObject *args) { const char* pattern; if (!PyArg_ParseTuple(args, "s", &pattern)) { return NULL; } regex_t pat; // This is an extended regular expression rather than a basic one, i.e. we // use 'a*' instaed of 'a\*'. int ret = regcomp(&pat, pattern, REG_EXTENDED); regfree(&pat); // Copied from man page const char *err_str = NULL; switch (ret) { case 0: // success break; case REG_BADBR: err_str = "Invalid use of back reference operator."; break; case REG_BADPAT: err_str = "Invalid use of pattern operators such as group or list."; break; case REG_BADRPT: err_str = "Invalid use of repetition operators such as using '*' as the first character."; break; case REG_EBRACE: err_str = "Un-matched brace interval operators."; break; case REG_EBRACK: err_str = "Un-matched bracket list operators."; break; case REG_ECOLLATE: err_str = "Invalid collating element."; break; case REG_ECTYPE: err_str = "Unknown character class name."; break; case REG_EESCAPE: err_str = "Trailing backslash."; break; case REG_EPAREN: err_str = "Un-matched parenthesis group operators."; break; case REG_ERANGE: err_str = "Invalid use of the range operator, e.g., the ending point of the range occurs prior to the starting point."; break; case REG_ESPACE: err_str = "The regex routines ran out of memory."; break; case REG_ESUBREG: err_str = "Invalid back reference to a subexpression."; break; /* NOTE: These are not defined by musl libc on Alpine. * TODO: If we can construct test cases for these, add them back. * */ #if 0 case REG_EEND: err_str = "Nonspecific error. This is not defined by POSIX.2."; break; case REG_ESIZE: err_str = "Compiled regular expression requires a pattern buffer larger than 64Kb. This is not defined by POSIX.2."; break; #endif default: /* TODO: Add the integer to error message */ err_str = "Unknown error compiling regex"; } if (err_str) { // When the regex contains a variable, it can't be checked at compile-time. PyErr_SetString(PyExc_RuntimeError, err_str); return NULL; } else { Py_RETURN_TRUE; } } static PyObject * func_regex_match(PyObject *self, PyObject *args) { const char* pattern; const char* str; if (!PyArg_ParseTuple(args, "ss", &pattern, &str)) { return NULL; } regex_t pat; if (regcomp(&pat, pattern, REG_EXTENDED) != 0) { // When the regex contains a variable, it can't be checked at compile-time. PyErr_SetString(PyExc_RuntimeError, "Invalid regex syntax (func_regex_match)"); return NULL; } int outlen = pat.re_nsub + 1; PyObject *ret = PyList_New(outlen); if (ret == NULL) { regfree(&pat); return NULL; } int match; regmatch_t *pmatch = (regmatch_t*) malloc(sizeof(regmatch_t) * outlen); if (match = (regexec(&pat, str, outlen, pmatch, 0) == 0)) { int i; for (i = 0; i < outlen; i++) { int len = pmatch[i].rm_eo - pmatch[i].rm_so; PyObject *v = PyString_FromStringAndSize(str + pmatch[i].rm_so, len); PyList_SetItem(ret, i, v); } } free(pmatch); regfree(&pat); if (!match) { Py_RETURN_NONE; } return ret; } // For ${//}, the number of groups is always 1, so we want 2 match position // results -- the whole regex (which we ignore), and then first group. // // For [[ =~ ]], do we need to count how many matches the user gave? #define NMATCH 2 static PyObject * func_regex_first_group_match(PyObject *self, PyObject *args) { const char* pattern; const char* str; int pos; if (!PyArg_ParseTuple(args, "ssi", &pattern, &str, &pos)) { return NULL; } regex_t pat; regmatch_t m[NMATCH]; // Could have been checked by regex_parse for [[ =~ ]], but not for glob // patterns like ${foo/x*/y}. if (regcomp(&pat, pattern, REG_EXTENDED) != 0) { PyErr_SetString(PyExc_RuntimeError, "Invalid regex syntax (func_regex_first_group_match)"); return NULL; } debug("first_group_match pat %s str %s pos %d", pattern, str, pos); // Match at offset 'pos' int result = regexec(&pat, str + pos, NMATCH, m, 0 /*flags*/); regfree(&pat); if (result != 0) { Py_RETURN_NONE; // no match } // Assume there is a match regoff_t start = m[1].rm_so; regoff_t end = m[1].rm_eo; return Py_BuildValue("(i,i)", pos + start, pos + end); } // We do this in C so we can remove '%f' % 0.1 from the CPython build. That // involves dtoa.c and pystrod.c, which are thousands of lines of code. static PyObject * func_print_time(PyObject *self, PyObject *args) { double real, user, sys; if (!PyArg_ParseTuple(args, "ddd", &real, &user, &sys)) { return NULL; } fprintf(stderr, "real\t%.3f\n", real); fprintf(stderr, "user\t%.3f\n", user); fprintf(stderr, "sys\t%.3f\n", sys); Py_RETURN_NONE; } // A copy of socket.gethostname() from socketmodule.c. That module brings in // too many dependencies. static PyObject *socket_error; static PyObject * socket_gethostname(PyObject *self, PyObject *unused) { char buf[1024]; int res; Py_BEGIN_ALLOW_THREADS res = gethostname(buf, (int) sizeof buf - 1); //res = gethostname(buf, 0); // For testing errors Py_END_ALLOW_THREADS if (res < 0) return PyErr_SetFromErrno(socket_error); buf[sizeof buf - 1] = '\0'; return PyString_FromString(buf); } #ifdef OVM_MAIN #include "native/libc.c/methods.def" #else static PyMethodDef methods[] = { // Return the canonical version of a path with symlinks, or None if there is // an error. {"realpath", func_realpath, METH_VARARGS, ""}, // Return whether a string matches a pattern." {"fnmatch", func_fnmatch, METH_VARARGS, ""}, // Return a list of files that match a pattern. // We need this since Python's glob doesn't have char classes. {"glob", func_glob, METH_VARARGS, ""}, // Compile a regex in ERE syntax, returning whether it is valid {"regex_parse", func_regex_parse, METH_VARARGS, ""}, // Match regex against a string. Returns a list of matches, None if no // match. Raises RuntimeError if the regex is invalid. {"regex_match", func_regex_match, METH_VARARGS, ""}, // If the regex matches the string, return the start and end position of the // first group. Returns None if there is no match. Raises RuntimeError if // the regex is invalid. {"regex_first_group_match", func_regex_first_group_match, METH_VARARGS, ""}, // "Print three floating point values for the 'time' builtin. {"print_time", func_print_time, METH_VARARGS, ""}, {"gethostname", socket_gethostname, METH_NOARGS, ""}, {NULL, NULL}, }; #endif void initlibc(void) { Py_InitModule("libc", methods); socket_error = PyErr_NewException("socket.error", PyExc_IOError, NULL); }
C
#include "sparsemat.h" #include <stdio.h> #include <stdlib.h> /* This program implements linked lists to represent sparse matrices given in text files, sorting them in row major order, as well as interfacing with them in other ways such as removing nodes, or adding nodes in the proper locations. There are also functions which add or multiply two sparse matrices together. */ sp_tuples * load_tuples(char* input_file) { int row, col ; //allocate memory for a new matrix double val ; sp_tuples * tuples = (sp_tuples*)malloc(sizeof(struct sp_tuples)) ; sp_tuples_node * node, * head ; tuples->nz = 0 ; head = NULL ; FILE * infile = fopen(input_file, "r") ; //Open the input file for reading fscanf(infile, "%d %d", &tuples->m, &tuples->n) ; //read rowsize and colsize values fscanf(infile, "%d %d %lf", &row, &col, &val) ; //read the first node node = (sp_tuples_node*)malloc(sizeof(struct sp_tuples_node)) ; //allocate memory for the node node->next = head ; //set the node up as the head of a new list head = node ; node->value = val ; node->row = row ; node->col = col ; tuples->nz++ ; tuples->tuples_head = head ; while (fscanf(infile, "%d %d %lf", &row, &col, &val) != EOF) { //Iterate while the file has not yet ended /*if (val != 0) { node = (sp_tuples_node*)malloc(sizeof(struct sp_tuples_node)) ; node->next = head ; head = node ; node->value = val ; node->row = row ; node->col = col ; tuples->nz++ ; } */ set_tuples(tuples, row, col, val) ; //insert new nodes in order } //tuples->tuples_head = head ; fclose(infile) ; return tuples; } void sort_tuples(sp_tuples * tuples) { int i ; sp_tuples_node *current, *max, *last, *maxlast, *nxthead, *head ; nxthead = NULL ; head = tuples->tuples_head ; for (i = 0; i < tuples->nz; i++) { //Iterate through all nodes max = head ; maxlast = NULL; last = NULL ; current = head ; while (current != NULL) { if(max->row * tuples->m + max->col < current->row * tuples->m + current->col) { maxlast = last ; max = current ; //Find the node with the largest index and make it the head of the list } last = current ; current = current->next ; } if (maxlast != NULL) { maxlast->next = max->next ; } if (max == head) { head = head->next ; } max->next = nxthead ; nxthead = max ; } tuples->tuples_head = nxthead ; return ; } double gv_tuples(sp_tuples * mat_t,int row,int col) { sp_tuples_node * current ; current = mat_t->tuples_head ; while (current != NULL) { // Iterate through nodes and return value of node at row col if (current->row == row && current->col == col) { return current->value ; } current = current->next ; } return 0; } sp_tuples_node * gp_tuples(sp_tuples * mat_t,int row,int col) { sp_tuples_node * current ; current = mat_t->tuples_head ; while (current != NULL) { if (current->row == row && current->col == col) { return current ; } current = current->next ; } return 0; } void set_tuples(sp_tuples * mat_t, int row, int col, double value) { sp_tuples_node * current = mat_t->tuples_head ; sp_tuples_node * last = NULL ; sp_tuples_node * node ; int flag = 0; while (current != NULL && flag == 0) { if (current->col >= col && current->row >= row && flag == 0) { node = (sp_tuples_node*)malloc(sizeof(struct sp_tuples_node)) ; node->value = value ; node->row = row ; node->col = col ; if (last == NULL) { node->next = current ; mat_t->tuples_head = node ; } if (last != NULL) { last->next = node ; node->next = current ; } mat_t->nz++ ; flag = 1 ; } if ( row == current->row && col == current->col) { if (value != 0) { node->next = current->next ; free(current); current = node->next ; last = node ; mat_t->nz-- ; continue ; } if (value == 0) { last->next = current->next ; free(node) ; free(current) ; current = last->next ; mat_t->nz-- ; mat_t->nz-- ; continue ; } } last = current ; current = current->next ; } if (flag == 0 && value != 0) { sp_tuples_node * node = (sp_tuples_node*)malloc(sizeof(struct sp_tuples_node)) ; node->value = value ; node->row = row ; node->col = col ; last->next = node ; node->next = NULL ; mat_t->nz++; } return; } void save_tuples(char * file_name, sp_tuples * mat_t) { FILE * outfile = fopen(file_name, "w") ; fprintf(outfile, "%d %d\n", mat_t->m, mat_t->n) ; sp_tuples_node * current = mat_t->tuples_head ; while (current != NULL) { fprintf(outfile, "%d %d %lf\n", current->row, current->col, current->value) ; current = current->next ; } fclose(outfile) ; return; } sp_tuples * add_tuples(sp_tuples * matA, sp_tuples * matB){ if (matA->m != matB->m || matA->n != matB->n || matB == NULL || matA == NULL) { return NULL ; } sp_tuples * C = (sp_tuples*)malloc(sizeof(struct sp_tuples)) ; C->m = matB->m ; C->n = matB->n ; C->nz = 0 ; sp_tuples_node * currentA = matA->tuples_head ; sp_tuples_node * currentB = matB->tuples_head ; sp_tuples_node * head = NULL ; sp_tuples_node * node, * target ; while (currentA != NULL) { node = (sp_tuples_node*)malloc(sizeof(struct sp_tuples_node)) ; node->next = head ; head = node ; node->value = currentA->value ; node->row = currentA->row ; node->col = currentA->col ; C->nz++ ; currentA = currentA->next ; } C->tuples_head = head ; while (currentB != NULL) { target = gp_tuples(C, currentB->row, currentB->col) ; if (target != 0) { target->value += currentB->value ; } if (target == 0) { node = (sp_tuples_node*)malloc(sizeof(struct sp_tuples_node)) ; node->next = head ; head = node ; node->value = currentB->value ; node->row = currentB->row ; node->col = currentB->col ; C->nz++ ; } currentB = currentB->next ; } C->tuples_head = head ; sort_tuples(C) ; return C; } sp_tuples * mult_tuples(sp_tuples * matA, sp_tuples * matB){ return 0; } void destroy_tuples(sp_tuples * mat_t){ if (mat_t != NULL) { sp_tuples_node * current, *last ; current = mat_t->tuples_head ; last = NULL ; while (current != NULL) { last = current ; current = current->next ; free(last) ; } free(mat_t->tuples_head) ; free(mat_t) ; } return; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include "Assembler.h" extern int startIndexForTextPart; extern int endIndexForTextPart; extern char rawCodeLines[100][100]; extern int currentInstLine; extern int currentTextLine; extern struct _Label arrOfLabels[100]; extern int indexOfLabelCount ; extern char binaryTextLines[32][200]; extern int binDataPointer; extern int binTextPointer; /** * Passes each line of text data to first extract all labels * Then passes each line of text data to be converted * */ void convertTextPartToBinary(){ for(int i = startIndexForTextPart; i <= endIndexForTextPart; ++i) { gatherLabelData(rawCodeLines[i]); } currentInstLine = 0; currentTextLine = 0; for(int i = startIndexForTextPart; i <= endIndexForTextPart; ++i) { convertTextLineToBinary( rawCodeLines[i]); } } /** * Passes each given line to gather label data is present * */ void gatherLabelData(const char* const line) { if ((strstr(line, ",") != NULL) || (strstr(line, "syscall") != NULL) || (strstr(line, "nop") != NULL) || (strstr(line, "j ") != NULL) ) { currentInstLine++; currentTextLine++; } if (strstr(line, ":") != NULL ) { collectLabel(line); currentTextLine++; } } /** * Collects the label data from the given line and stores it into the appropriate struct. * */ void collectLabel(char* line) { Label* label = (Label*)calloc(1,sizeof(Label)); char delim[] = ":"; char *temp = (char*)calloc(1,sizeof(char)); strcpy(temp, line); char *ptr = strtok(temp, delim); label->labName = ptr; label->lineNum = currentInstLine; arrOfLabels[indexOfLabelCount] = (*label); indexOfLabelCount++; } /** * converts the given text line into binary and passes it to its appropriate function. * */ void convertTextLineToBinary(const char* const line) { if (strstr(line, "lw ") != NULL && strstr(line, "(") != NULL ) { convertRtOffsetRs(line, "lw"); currentInstLine++; currentTextLine++; } if (strstr(line, "sw ") != NULL ) { convertRtOffsetRs(line, "sw"); currentInstLine++; currentTextLine++; } if (strstr(line, "lui ") != NULL ) { convertRtImm16ORLabel(line,"lui"); currentInstLine++; currentTextLine++; } if (strstr(line, "add ") != NULL ) { convertRdRsRt(line,"add"); currentInstLine++; currentTextLine++; } if (strstr(line, "addi ") != NULL ) { convertRtRsImm16(line, "addi"); currentInstLine++; currentTextLine++; } if (strstr(line, "addu ") != NULL ) { convertRdRsRt(line, "addu"); currentInstLine++; currentTextLine++; } if (strstr(line, "addiu ") != NULL ) { convertRtRsImm16(line, "addiu"); currentInstLine++; currentTextLine++; } if (strstr(line, "mul ") != NULL ) { convertRdRsRt(line, "mul"); currentInstLine++; currentTextLine++; } if (strstr(line, "mult ") != NULL ) { convertRsRt(line,"mult"); currentInstLine++; currentTextLine++; } if (strstr(line, "nop") != NULL ) { strcpy(binaryTextLines[binTextPointer], "00000000000000000000000000000000" ); binTextPointer ++; currentInstLine++; currentTextLine++; } if (strstr(line, "nor ") != NULL ) { convertRdRsRt(line, "nor"); currentInstLine++; currentTextLine++; } if (strstr(line, "sll ") != NULL ) { convertRdRtSa(line, "sll"); currentTextLine++; currentInstLine++; } if (strstr(line, "slt ") != NULL ) { convertRdRsRt(line,"slt"); currentTextLine++; currentInstLine++; } if (strstr(line, "slti ") != NULL ) { convertRtRsImm16(line, "slti"); currentTextLine++; currentInstLine++; } if (strstr(line, "sra ") != NULL ) { convertRdRtSa(line, "sra"); currentTextLine++; currentInstLine++; } if (strstr(line, "srav ") != NULL ) { convertRdRtRs(line, "srav"); currentTextLine++; currentInstLine++; } if (strstr(line, "sub ") != NULL ) { convertRdRsRt(line, "sub"); currentTextLine++; currentInstLine++; } if (strstr(line, "beq ") != NULL ) { convertRsRtOffset(line, "beq"); currentTextLine++; currentInstLine++; } if (strstr(line, "blez ") != NULL ) { convertRsOffset(line, "blez"); currentTextLine++; currentInstLine++; } if (strstr(line, "bgtz ") != NULL ) { convertRsOffset(line, "bgtz"); currentTextLine++; currentInstLine++; } if (strstr(line, "bne ") != NULL ) { convertRsRtOffset(line, "bne"); currentTextLine++; currentInstLine++; } if (strstr(line, "j ") != NULL ) { convertTarget(line, "j"); currentTextLine++; currentInstLine++; } if (strstr(line, "syscall") != NULL ) { strcpy(binaryTextLines[binTextPointer], "00000000000000000000000000001100" ); binTextPointer ++; currentTextLine++; } if (strstr(line, "move ") != NULL ) { convertRdRs(line, "move"); currentTextLine++; currentInstLine++; } if (strstr(line, "blt ") != NULL ) { convertRdRsOffSetForBlt(line,"blt"); currentTextLine++; currentInstLine++; } if (strstr(line, "la ") != NULL ) { convertRtImm16ORLabel(line,"la"); currentTextLine++; currentInstLine++; } if (strstr(line, "li ") != NULL ) { convertRtImm16ORLabel(line, "li"); currentTextLine++; currentInstLine++; } if (strstr(line, "lw ") != NULL && strstr(line, "(") == NULL) { convertRtImm16ORLabel(line, "lw"); currentTextLine++; currentInstLine++; } if (strstr(line, ":") != NULL ) { currentTextLine++; } } /** * ALL the following Functions Convert a Given sytax of assembly code into binary and append that assembly code into an array. * */ void convertRdRsRt(const char* const line, char * name) { char * binLine; InstructionData iData = searchInstructionData(name); RegData rData; char * temp = ""; char RD[6]; char RS[6]; char RT[6]; char str[150]; strcpy(str, line); int index = getIndexOf(line,'$'); if(str[index+1]== 'z') { RD[0] = str[index]; index++; RD[1] = str[index]; index++; RD[2] = str[index]; index++; RD[3] = str[index]; index++; RD[4] = str[index]; index++; RD[5] = '\0'; index += 2; } else { RD[0] = str[index]; index++; RD[1] = str[index]; index++; RD[2] = str[index]; index++; RD[3] = '\0'; index += 2; } if(str[index+1]== 'z') { RS[0] = str[index]; index++; RS[1] = str[index]; index++; RS[2] = str[index]; index++; RS[3] = str[index]; index++; RS[4] = str[index]; index++; RS[5] = '\0'; index += 2; } else { RS[0] = str[index]; index++; RS[1] = str[index]; index++; RS[2] = str[index]; index++; RS[3] = '\0'; index += 2; } if(str[index+1]== 'z') { RT[0] = str[index]; index++; RT[1] = str[index]; index++; RT[2] = str[index]; index++; RT[3] = str[index]; index++; RT[4] = str[index]; index++; RT[5] = '\0'; index += 2; } else { RT[0] = str[index]; index++; RT[1] = str[index]; index++; RT[2] = str[index]; index++; RT[3] = '\0'; index += 2; } rData = SearchRegData(RS); char * binRS = rData.binValue; rData = SearchRegData(RT); char * binRT = rData.binValue; rData = SearchRegData(RD); char * binRD = rData.binValue; binLine = append(temp, iData.op); binLine = append(binLine, binRS); binLine = append(binLine, binRT); binLine = append(binLine, binRD); binLine = append(binLine, iData.shift); binLine = append(binLine, iData.func); strcpy(binaryTextLines[binTextPointer],binLine ); binTextPointer ++; } void convertRtRsImm16(const char* const line, char * name) { char * binLine; InstructionData iData = searchInstructionData(name); RegData rData; char * temp = ""; char RT[6]; char RS[6]; char str[150]; int imm; strcpy(str, line); int index = getIndexOf(line,'$'); if(str[index+1]== 'z') { RT[0] = str[index]; index++; RT[1] = str[index]; index++; RT[2] = str[index]; index++; RT[3] = str[index]; index++; RT[4] = str[index]; index++; RT[5] = '\0'; index += 2; } else { RT[0] = str[index]; index++; RT[1] = str[index]; index++; RT[2] = str[index]; index++; RT[3] = '\0'; index += 2; } if(str[index+1]== 'z') { RS[0] = str[index]; index++; RS[1] = str[index]; index++; RS[2] = str[index]; index++; RS[3] = str[index]; index++; RS[4] = str[index]; index++; RS[5] = '\0'; index += 2; } else { RS[0] = str[index]; index++; RS[1] = str[index]; index++; RS[2] = str[index]; index++; RS[3] = '\0'; index += 2; } rData = SearchRegData(RS); char * binRS = rData.binValue; rData = SearchRegData(RT); char * binRT = rData.binValue; imm = extractImmediate(line,2); char * binImm = convertIntTo16BitBinary(imm); binLine = append(temp, iData.op); binLine = append(binLine, binRS); binLine = append(binLine, binRT); binLine = append(binLine, binImm); strcpy(binaryTextLines[binTextPointer],binLine ); binTextPointer ++; } void convertRsRt(const char* const line, char * name) { char * binLine; InstructionData iData = searchInstructionData(name); RegData rData; char * temp = ""; char RS[6]; char RT[6]; char str[150]; strcpy(str, line); int index = getIndexOf(line,'$'); if(str[index+1]== 'z') { RS[0] = str[index]; index++; RS[1] = str[index]; index++; RS[2] = str[index]; index++; RS[3] = str[index]; index++; RS[4] = str[index]; index++; RS[5] = '\0'; index += 2; } else { RS[0] = str[index]; index++; RS[1] = str[index]; index++; RS[2] = str[index]; index++; RS[3] = '\0'; index += 2; } if(str[index+1]== 'z') { RT[0] = str[index]; index++; RT[1] = str[index]; index++; RT[2] = str[index]; index++; RT[3] = str[index]; index++; RT[4] = str[index]; index++; RT[5] = '\0'; index += 2; } else { RT[0] = str[index]; index++; RT[1] = str[index]; index++; RT[2] = str[index]; index++; RT[3] = '\0'; index += 2; } rData = SearchRegData(RS); char * binRS = rData.binValue; rData = SearchRegData(RT); char * binRT = rData.binValue; binLine = append(temp, iData.op); binLine = append(binLine, binRS); binLine = append(binLine, binRT); binLine = append(binLine, "00000"); binLine = append(binLine, iData.shift); binLine = append(binLine, iData.func); strcpy(binaryTextLines[binTextPointer],binLine ); binTextPointer ++; } void convertRdRs(const char* const line, char * name) { char * binLine; InstructionData iData = searchInstructionData(name); RegData rData; char * temp = ""; char RD[6]; char RS[6]; char str[150]; strcpy(str, line); int index = getIndexOf(line,'$'); if(str[index+1]== 'z') { RD[0] = str[index]; index++; RD[1] = str[index]; index++; RD[2] = str[index]; index++; RD[3] = str[index]; index++; RD[4] = str[index]; index++; RD[5] = '\0'; index += 2; } else { RD[0] = str[index]; index++; RD[1] = str[index]; index++; RD[2] = str[index]; index++; RD[3] = '\0'; index += 2; } if(str[index+1]== 'z') { RS[0] = str[index]; index++; RS[1] = str[index]; index++; RS[2] = str[index]; index++; RS[3] = str[index]; index++; RS[4] = str[index]; index++; RS[5] = '\0'; index += 2; } else { RS[0] = str[index]; index++; RS[1] = str[index]; index++; RS[2] = str[index]; index++; RS[3] = '\0'; index += 2; } rData = SearchRegData(RD); char * binRD = rData.binValue; rData = SearchRegData(RS); char * binRS = rData.binValue; binLine = append(temp, iData.op); binLine = append(binLine, "00000"); binLine = append(binLine, binRS); binLine = append(binLine, binRD); binLine = append(binLine, iData.shift); binLine = append(binLine, iData.func); strcpy(binaryTextLines[binTextPointer],binLine ); binTextPointer ++; } void convertRtImm16ORLabel(const char* const line, char * name) { char * binLine; InstructionData iData = searchInstructionData(name); RegData rData; char * temp = ""; char RT[6]; char str[150]; strcpy(str, line); int index = getIndexOf(line,'$'); if(str[index+1]== 'z') { RT[0] = str[index]; index++; RT[1] = str[index]; index++; RT[2] = str[index]; index++; RT[3] = str[index]; index++; RT[4] = str[index]; index++; RT[5] = '\0'; index += 2; } else { RT[0] = str[index]; index++; RT[1] = str[index]; index++; RT[2] = str[index]; index++; RT[3] = '\0'; index += 2; } rData = SearchRegData(RT); char * binRT = rData.binValue; int imm; char* label; char * binImm; if(name == "la" || name == "lw") { label = extractLabel(line, 1); label = removeSpaces(label); binImm = searchWordData(label); } else { imm = extractImmediate(line,1); binImm = convertIntTo16BitBinary(imm); } binLine = append(temp, iData.op); binLine = append(binLine, "00000"); binLine = append(binLine, binRT); binLine = append(binLine, binImm); strcpy(binaryTextLines[binTextPointer],binLine ); binTextPointer ++; } void convertRtOffsetRs(const char* const line, char * name) { char * binLine; InstructionData iData = searchInstructionData(name); RegData rData; char * temp = ""; char RT[6]; char RS[6]; char str[150]; int imm; strcpy(str, line); int index = getIndexOf(str,'$'); if(str[index+1]== 'z') { RT[0] = str[index]; index++; RT[1] = str[index]; index++; RT[2] = str[index]; index++; RT[3] = str[index]; index++; RT[4] = str[index]; index++; RT[5] = '\0'; index += 2; } else { RT[0] = str[index]; index++; RT[1] = str[index]; index++; RT[2] = str[index]; index++; RT[3] = '\0'; index += 2; } int rSIndex = getIndexOf(str,'('); rSIndex++; if(str[rSIndex+1]== 'z') { RS[0] = str[rSIndex]; rSIndex++; RS[1] = str[rSIndex]; rSIndex++; RS[2] = str[rSIndex]; rSIndex++; RS[3] = str[rSIndex]; rSIndex++; RS[4] = str[rSIndex]; rSIndex++; RS[5] = '\0'; } else { RS[0] = str[rSIndex]; rSIndex++; RS[1] = str[rSIndex]; rSIndex++; RS[2] = str[rSIndex]; rSIndex++; RS[3] = '\0'; } rData = SearchRegData(RS); char * binRS = rData.binValue; rData = SearchRegData(RT); char * binRT = rData.binValue; imm = extractImmediate(str,1); char * binImm = convertIntTo16BitBinary(imm); binLine = append(temp, iData.op); binLine = append(binLine, binRS); binLine = append(binLine, binRT); binLine = append(binLine, binImm); strcpy(binaryTextLines[binTextPointer],binLine ); binTextPointer ++; } void convertRsRtOffset(const char* const line, char * name) { char * binLine; InstructionData iData = searchInstructionData(name); RegData rData; char * temp = ""; char RT[6]; char RS[6]; char str[150]; int imm; strcpy(str, line); int index = getIndexOf(line,'$'); if(str[index+1]== 'z') { RS[0] = str[index]; index++; RS[1] = str[index]; index++; RS[2] = str[index]; index++; RS[3] = str[index]; index++; RS[4] = str[index]; index++; RS[5] = '\0'; index += 2; } else { RS[0] = str[index]; index++; RS[1] = str[index]; index++; RS[2] = str[index]; index++; RS[3] = '\0'; index += 2; } if(str[index+1]== 'z') { RT[0] = str[index]; index++; RT[1] = str[index]; index++; RT[2] = str[index]; index++; RT[3] = str[index]; index++; RT[4] = str[index]; index++; RT[5] = '\0'; index += 2; } else { RT[0] = str[index]; index++; RT[1] = str[index]; index++; RT[2] = str[index]; index++; RT[3] = '\0'; index += 2; } rData = SearchRegData(RS); char * binRS = rData.binValue; rData = SearchRegData(RT); char * binRT = rData.binValue; char* offset = extractLabel(line, 2); offset = removeSpaces(offset); int labelLineNum = SearchLabels(offset); int binNum; if((labelLineNum - currentInstLine)>0) binNum = labelLineNum - currentInstLine - 1 ; else binNum = labelLineNum - currentInstLine -1 ;//////FIX char * binImm = convertIntTo16BitBinary(binNum); binLine = append(temp, iData.op); binLine = append(binLine, binRS); binLine = append(binLine, binRT); binLine = append(binLine, binImm); strcpy(binaryTextLines[binTextPointer],binLine ); binTextPointer ++; } void convertRdRtSa(const char* const line, char * name) { char * binLine; InstructionData iData = searchInstructionData(name); RegData rData; char * temp = ""; char RD[6]; char RT[6]; char str[150]; int imm; strcpy(str, line); int index = getIndexOf(line,'$'); if(str[index+1]== 'z') { RD[0] = str[index]; index++; RD[1] = str[index]; index++; RD[2] = str[index]; index++; RD[3] = str[index]; index++; RD[4] = str[index]; index++; RD[5] = '\0'; index += 2; } else { RD[0] = str[index]; index++; RD[1] = str[index]; index++; RD[2] = str[index]; index++; RD[3] = '\0'; index += 2; } if(str[index+1]== 'z') { RT[0] = str[index]; index++; RT[1] = str[index]; index++; RT[2] = str[index]; index++; RT[3] = str[index]; index++; RT[4] = str[index]; index++; RT[5] = '\0'; index += 2; } else { RT[0] = str[index]; index++; RT[1] = str[index]; index++; RT[2] = str[index]; index++; RT[3] = '\0'; index += 2; } rData = SearchRegData(RD); char * binRD = rData.binValue; rData = SearchRegData(RT); char * binRT = rData.binValue; int sa = extractImmediate(str,2); char * binImm = convertIntTo5BitBinary(sa); binLine = append(temp, iData.op); binLine = append(binLine, "00000"); binLine = append(binLine, binRT); binLine = append(binLine, binRD); binLine = append(binLine, binImm); binLine = append(binLine, iData.func); strcpy(binaryTextLines[binTextPointer],binLine ); binTextPointer ++; } void convertRsOffset(const char* const line, char * name) { char * binLine; InstructionData iData = searchInstructionData(name); RegData rData; char * temp = ""; char RS[6]; char str[150]; int imm; strcpy(str, line); int index = getIndexOf(line,'$'); if(str[index+1]== 'z') { RS[0] = str[index]; index++; RS[1] = str[index]; index++; RS[2] = str[index]; index++; RS[3] = str[index]; index++; RS[4] = str[index]; index++; RS[5] = '\0'; index += 2; } else { RS[0] = str[index]; index++; RS[1] = str[index]; index++; RS[2] = str[index]; index++; RS[3] = '\0'; index += 2; } rData = SearchRegData(RS); char * binRS = rData.binValue; char* offset = extractLabel(line, 1); offset = removeSpaces(offset); int labelLineNum = SearchLabels(offset); int binNum; if((labelLineNum - currentInstLine)>0) binNum = labelLineNum - currentInstLine - 1 ; else binNum = labelLineNum - currentInstLine -1 ;//////FIX char * binImm = convertIntTo16BitBinary(binNum); binLine = append(temp, iData.op); binLine = append(binLine, binRS); binLine = append(binLine, "00000"); binLine = append(binLine, binImm); strcpy(binaryTextLines[binTextPointer],binLine ); binTextPointer ++; } convertTarget(const char* const line, char * name) { char * binLine; InstructionData iData = searchInstructionData(name); char * temp = ""; char str[150]; int imm; strcpy(str, line); char* offset = extractJump(line, 1); offset = removeSpaces(offset); int labelLineNum = SearchLabels(offset); char * binImm = convertIntTo26BitBinary(labelLineNum); binLine = append(temp, iData.op); binLine = append(binLine, binImm); strcpy(binaryTextLines[binTextPointer],binLine ); binTextPointer ++; } void convertRdRtRs(const char* const line, char * name) { char * binLine; InstructionData iData = searchInstructionData(name); RegData rData; char * temp = ""; char RD[6]; char RT[6]; char RS[6]; char str[150]; strcpy(str, line); int index = getIndexOf(line,'$'); if(str[index+1]== 'z') { RD[0] = str[index]; index++; RD[1] = str[index]; index++; RD[2] = str[index]; index++; RD[3] = str[index]; index++; RD[4] = str[index]; index++; RD[5] = '\0'; index += 2; } else { RD[0] = str[index]; index++; RD[1] = str[index]; index++; RD[2] = str[index]; index++; RD[3] = '\0'; index += 2; } if(str[index+1]== 'z') { RT[0] = str[index]; index++; RT[1] = str[index]; index++; RT[2] = str[index]; index++; RT[3] = str[index]; index++; RT[4] = str[index]; index++; RT[5] = '\0'; index += 2; } else { RT[0] = str[index]; index++; RT[1] = str[index]; index++; RT[2] = str[index]; index++; RT[3] = '\0'; index += 2; } if(str[index+1]== 'z') { RS[0] = str[index]; index++; RS[1] = str[index]; index++; RS[2] = str[index]; index++; RS[3] = str[index]; index++; RS[4] = str[index]; index++; RS[5] = '\0'; index += 2; } else { RS[0] = str[index]; index++; RS[1] = str[index]; index++; RS[2] = str[index]; index++; RS[3] = '\0'; index += 2; } rData = SearchRegData(RS); char * binRS = rData.binValue; rData = SearchRegData(RT); char * binRT = rData.binValue; rData = SearchRegData(RD); char * binRD = rData.binValue; binLine = append(temp, iData.op); binLine = append(binLine, binRS); binLine = append(binLine, binRT); binLine = append(binLine, binRD); binLine = append(binLine, iData.shift); binLine = append(binLine, iData.func); strcpy(binaryTextLines[binTextPointer],binLine ); binTextPointer ++; } void convertRdRsOffSetForBlt(const char* const line, char * name) { char * binLine; InstructionData iData = searchInstructionData("slt"); RegData rData; char * temp = ""; char RD[6]; char RS[6]; char RT[6]; char str[150]; strcpy(str, line); int index = getIndexOf(line,'$'); if(str[index+1]== 'z') { RS[0] = str[index]; index++; RS[1] = str[index]; index++; RS[2] = str[index]; index++; RS[3] = str[index]; index++; RS[4] = str[index]; index++; RS[5] = '\0'; index += 2; } else { RS[0] = str[index]; index++; RS[1] = str[index]; index++; RS[2] = str[index]; index++; RS[3] = '\0'; index += 2; } if(str[index+1]== 'z') { RT[0] = str[index]; index++; RT[1] = str[index]; index++; RT[2] = str[index]; index++; RT[3] = str[index]; index++; RT[4] = str[index]; index++; RT[5] = '\0'; index += 2; } else { RT[0] = str[index]; index++; RT[1] = str[index]; index++; RT[2] = str[index]; index++; RT[3] = '\0'; index += 2; } RD[0] = '$'; RD[1] = 'a'; RD[2] = 't'; RD[3] = '\0'; rData = SearchRegData(RS); char * binRS = rData.binValue; rData = SearchRegData(RT); char * binRT = rData.binValue; rData = SearchRegData(RD); char * binRD = rData.binValue; binLine = append(temp, iData.op); binLine = append(binLine, binRS); binLine = append(binLine, binRT); binLine = append(binLine, binRD); binLine = append(binLine, iData.shift); binLine = append(binLine, iData.func); strcpy(binaryTextLines[binTextPointer],binLine ); binTextPointer ++; currentTextLine++; binLine = ""; iData = searchInstructionData("bne"); temp = ""; int imm; strcpy(str, line); RT[0] = '$'; RT[1] = 'a'; RT[2] = 't'; RT[3] = '\0'; RS[0] = '$'; RS[1] = 'z'; RS[2] = 'e'; RS[3] = 'r'; RS[4] = 'o'; RS[5] = '\0'; rData = SearchRegData(RS); binRS = rData.binValue; rData = SearchRegData(RT); binRT = rData.binValue; char* offset = extractLabel(line, 2); offset = removeSpaces(offset); int labelLineNum = SearchLabels(offset); int binNum; if((labelLineNum - currentInstLine)>0) binNum = labelLineNum - currentInstLine - 1 ; else binNum = labelLineNum - currentInstLine -1 ;//////FIX char * binImm = convertIntTo16BitBinary(binNum); binLine = append(temp, iData.op); binLine = append(binLine, binRT); binLine = append(binLine, binRS); binLine = append(binLine, binImm); strcpy(binaryTextLines[binTextPointer],binLine ); binTextPointer ++; }
C
#include <stdio.h> #include <string.h> #include <mpi.h> const int MESSAGE_SIZE = 100; int main(int argc, char ** argv) { char message[MESSAGE_SIZE]; int processes, id; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &processes); MPI_Comm_rank(MPI_COMM_WORLD, &id); if (id != 0) { sprintf(message, "Message from process(%d) to process (0)", id); MPI_Send(message, strlen(message)+1, MPI_CHAR, 0, 0, MPI_COMM_WORLD); } else { for (int p = 1; p < processes; p++) { MPI_Recv(message, MESSAGE_SIZE, MPI_CHAR, p, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); printf("%s \n", message); } } MPI_Finalize(); return 0; }
C
// little virtual machine int acc1; int acc2; acc1 = 0; acc2 = 0; void dispatch (int instr){ switch (instr){ case 0: acc1 = 0; acc2 = 0; break; case 1: acc1++; break; case 2: acc2++; break; case 3: acc2 = acc1; break; case 4: acc1 = acc1 + acc2; break; } } dispatch(1); dispatch(1); dispatch(2); dispatch(4); dispatch(3);
C
#include <stdio.h> #include "include/wd.h" int main() { char *name = "name a"; name = wd_get_accel_name(NULL, 0); printf("a name = %p\n", name); name = "name b"; name = wd_get_accel_name("/dev/hisi_zip-0", -1); printf("b name = %p\n", name); name = "name c"; name = wd_get_accel_name("/dev/hisi_zip-0", 2); printf("c name = %p\n", name); name = "name d"; name = wd_get_accel_name("/dev/hisi_zip", 1); printf("d name = %p\n", name); return 0; }
C
/* ================================================ * IST LEIC-T Analise e Sintese de Algoritmos 18/19 * Project 2 - proj2.c * * Authors: * Manuel Mascarenhas - 90751 * Miguel Levezinho - 90756 * ================================================ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MIN(a, b) (a < b ? a : b) #define MAX(a, b) (a > b ? a : b) #define MIN_NUM_PROVIDERS 1 #define MIN_NUM_SUPPLY_ST 0 #define MIN_NUM_CONNECTIONS 0 #define MIN_PROVIDER_ID 2 #define MIN_DESTINY_ID 1 #define MIN_CAPACITY 1 /************************************************************************************************************ * edge.h ***********************************************************************************************************/ /* Struct that represents an edge of a flow network */ struct edge { int u; int v; int cap; int flow; }; /* Abstraction of the edge struct to a pointer type Edge */ typedef struct edge *Edge; /************************************************************************************************************ * list.h ***********************************************************************************************************/ /* Abstraction of the node struct to a pointer type Link */ typedef struct node *Link; /* Struct that represents a node of an edge list */ /* opEdge points to the opposite edge between to vertices */ struct node { Edge edge; Edge opEdge; Link next; }; Link insertL(Link head, Edge edge); void linkOppositesL(Link t, Link u); void freeL(Link head); /************************************************************************************************************ * queue.h ***********************************************************************************************************/ /* Abstraction of the queueNode struct to a pointer type QueueLink */ typedef struct queueNode *QueueLink; /* Abstraction of the queue struct to a pointer type Queue */ typedef struct queue *Queue; /* Struct that represents a node of an integer queue */ struct queueNode { int id; QueueLink next; }; /* Struct that represents a queue */ struct queue { int N; QueueLink front; QueueLink back; }; Queue initQ(); void putQ(Queue Q, int u); int getQ(Queue Q); int isEmptyQ(Queue Q); void freeQ(Queue Q); /************************************************************************************************************ * graph.h ***********************************************************************************************************/ /* Struct that represents the transportation flow network */ struct graph { int V; /* Number of vertices */ int P; /* Number of providers */ int S; /* Number of stations */ int E; /* Number of transport edges */ Link *adj; }; /* Struct that represents the state of the FIFO push-relabel algorithom, * storing its relevant variables */ struct PR_State { int* h; int* e; char* active; int* gap; }; /* Abstraction of the graph struct to a pointer type Graph */ typedef struct graph *Graph; /* Abstraction of the PR_State struct to a type PR_State_t */ typedef struct PR_State PR_State_t; /* Struct that represents the information to retrive from the network */ struct audit { int maxFlow; char* minCutS; Edge* minCutE; int idx; }; /* Abstraction of the audit struct to a pointer type NetAudit */ typedef struct audit *NetAudit; Graph initG(int V,int P,int S); void insertWeightedEdgeG(Graph G, int u, int v, int c); void pushRelabelFIFO(Graph G, NetAudit output); void freeG(Graph G); /************************************************************************************************************ * proj1.h ***********************************************************************************************************/ NetAudit initNetAudit(Graph G); void printNetAudit(Graph G, NetAudit out); void freeAudit(NetAudit a); /************************************************************************************************************ * proj1.c ***********************************************************************************************************/ int cmpfunc (const void * a, const void * b) { if ((*(Edge*)a)->u - (*(Edge*)b)->u) { return (*(Edge*)a)->u - (*(Edge*)b)->u; } return (*(Edge*)a)->v - (*(Edge*)b)->v; } int main() { int P; /* Number of providers */ int S; /* Number of supply stations */ int T; /* Number of network connections */ int V; /* Number of vertices in the flow network */ Graph Net; /* Graph structure that models the transportation network as a flow network */ int u, v; /* Vertices to connect */ int cap; /* Capacity of the connections */ int i; if (!scanf("%d %d %d", &P, &S, &T) || P < MIN_NUM_PROVIDERS || S < MIN_NUM_SUPPLY_ST || T < MIN_NUM_CONNECTIONS) { printf("Invalid input!\n"); exit(1); } V = P + 2*S + 2; /* Add source (hiper) and sink and double stations (have a inner capacity) */ Net = initG(V, P, S); /* Add T edges plus edges from source to providers and for stations (have a inner capacity) */ for (i = 2; i < P+2; i++) { scanf("%d", &cap); insertWeightedEdgeG(Net, i, 0, cap); /* 0 represents the sink */ } for (i = P+2; i < S+(P+2); i++) { scanf("%d", &cap); insertWeightedEdgeG(Net, i+S, i, cap); } for (i = 0; i < T; i++) { if (!scanf("%d %d %d", &u, &v, &cap) || u < MIN_PROVIDER_ID || v < MIN_DESTINY_ID || cap < MIN_CAPACITY) { printf("Invalid input!\n"); exit(1); } if (u > P+1) { u = u + S; } insertWeightedEdgeG(Net, v, u, cap); } NetAudit out = initNetAudit(Net); pushRelabelFIFO(Net, out); printNetAudit(Net, out); freeG(Net); freeAudit(out); return 0; } /* Function that allocs space to store the network audit info. * The vector that stores the edges of the min-cut has max size V and not E * because the number of edges of the min-cut cannot be bigger than V. * Returns a pointer to the audit structure. * * G - Flow network in which the audit will be preformed */ NetAudit initNetAudit(Graph G) { NetAudit new = (NetAudit) malloc(sizeof(struct audit)); new->maxFlow = 0; new->minCutS = (char*) calloc(G->V, sizeof(char)); new->minCutE = (Edge*) calloc(G->E, sizeof(Edge)); new->idx = 0; return new; } /* Function that prints the audit info. * Uses part of the counting sort algorithom to sort stations to print. * Uses the qsort lib function to sort edges by their vertices IDs. * * G - Flow Network the audit was applied on * output - Points to the struct that stores the audit info */ void printNetAudit(Graph G, NetAudit out) { int i; int flag = 0; printf("%d\n", out->maxFlow); for (i = G->P+2; i < (G->V - G->S); i++) { if (out->minCutS[i] != 1) continue; if (!flag) { printf("%d", i); flag = 1; } else { printf(" %d", i); } } printf("\n"); qsort(out->minCutE, out->idx, sizeof(Edge), cmpfunc); for (i = 0; i < G->E; i++) { if (i == out->idx) break; if (out->minCutE[i] == NULL) continue; if (out->minCutE[i]->u >= (G->V - G->S)) { out->minCutE[i]->u -= G->S; } printf("%d %d\n", out->minCutE[i]->u, out->minCutE[i]->v); } } /* Function that frees the network audit info. * * a - Points to the struct that stores the audit info */ void freeAudit(NetAudit a) { free(a->minCutS); free(a->minCutE); free(a); } /************************************************************************************************************ * graph.c ***********************************************************************************************************/ /* Function that creates and initializes a graph, given the number of vertices. * The implementation uses an enhanced list of adjacencies and the graph stores edges. * Asymptotic complexity is O(V). * Returns a pointer to the graph structure. * * V - Number of vertices in the graph * P - Number of providers * S - Number of supply stations */ Graph initG(int V, int P, int S) { int i; Graph new = (Graph) malloc(sizeof(struct graph)); new->V = V; new->P = P; new->S = S; new->E = 0; new->adj = (Link*) malloc(sizeof(Link) * V); for (i = 0; i < V; i++) { new->adj[i] = NULL; } return new; } /* Function that creates a flow restricted edge. * Asymptotic complexity is O(1). * Returns a pointer to the created edge. * * u - Vertex of the edge * v - Vertex of the edge * c - Capacity of the edge */ static Edge createWeightedEdgeG(int u, int v, int c) { Edge new = (Edge) malloc(sizeof(struct edge)); new->u = u; new->v = v; new->cap = c; new->flow = 0; return new; } /* Function that inserts a weighted edge in a graph that represents a flux network. * Asymptotic complexity is O(1). * * G - Graph in which to insert an edge * u - Vertex of the edge * v - Vertex of the edge * c - Capacity of the edge */ void insertWeightedEdgeG(Graph G, int u, int v, int c) { Edge e1 = createWeightedEdgeG(u, v, c); Edge e2 = createWeightedEdgeG(v, u, 0); G->adj[u] = insertL(G->adj[u], e1); G->adj[v] = insertL(G->adj[v], e2); linkOppositesL(G->adj[u], G->adj[v]); G->E++; } /* Function that initializes the flow network and begins the push-relabel algorithom. * Asymptotic complexity is O(V). * * G - Graph that represents the flow network * FIFO - Queue in which vertices with excess are stored * state - Push-relabel state that stores state variables, like heights * s - Source of the flow network * t - Sink of the flow network */ static void initializePreFLow(Graph G, Queue FIFO, PR_State_t* state, int s, int t) { int u, v; Link l; Edge edge; for (u = 0; u < G->V; u++) { state->h[u] = 0; state->e[u] = 0; state->active[u] = 0; } state->h[s] = G->V; state->gap[G->V] = 1; state->active[s] = 1; state->active[t] = 1; for (l = G->adj[s]; l; l = l->next) { edge = l->edge; v = l->edge->v; edge->flow = edge->cap; l->opEdge->flow = edge->flow * -1; state->e[v] = edge->flow; state->e[s] -= edge->flow; state->active[v] = 1; putQ(FIFO, v); } } /* Function that applies the Gap Relabeling heuristic every time there is a mim-cut in the network. * Asymptotic complexity is O(V). * * G - Graph that represents the flow network * FIFO - Queue in which vertices with excess are stored * state - Push-relabel state that stores state variables * h - Height gap that will represent a cut */ static void gapRelabel(Graph G, Queue FIFO, PR_State_t* state, int h) { int u; for (u = 2; u < G->V; u++) { if (state->h[u] >= h) { state->gap[state->h[u]] -= 1; state->h[u] = MAX(G->V, state->h[u]); state->gap[state->h[u]] += 1; } } } /* Function that relabels a vertex, increasing its height to 1+ the minimum height in the neighboors. * Asymptotic complexity is O(V). * * G - Graph that represents the flow network * state - Push-relabel state that stores state variables * u - Vertex to relabel */ static void relabel(Graph G, PR_State_t* state, int u) { Link t; int min = G->V * 2; /* Height upper bound */ for (t = G->adj[u]; t; t = t->next) { if (t->edge->cap - t->edge->flow > 0) { min = MIN(min, state->h[t->edge->v]); } } state->gap[state->h[u]] -= 1; state->h[u] = 1 + min; state->gap[state->h[u]] += 1; } /* Function that pushes flow to a neighboor vertex, through the edge between them. * A push is saturating if it pushes all the excess flow out of the vertex, * and non-sturating if excess remains in the vertex. * Asymptotic complexity is O(1). * * state - Push-relabel state that stores state variables * t - Vertex to relabel * u - Vertex of the edge, in which excess will be removed * v - Vertex of the edge in which flow will pass */ static void push(PR_State_t* state, Link t, int u, int v) { Edge edge = t->edge; int f = MIN(state->e[u], edge->cap - edge->flow); edge->flow += f; t->opEdge->flow = edge->flow * -1; state->e[u] -= f; state->e[v] += f; } /* Function that determines when to apply pushes or relabels to vertices with excess, * managing between the two depending on neighboor residual capacities, heights, and height gaps. * Discharge continues until the vertex has no more excess flow. * * G - Graph that represents the flow network * FIFO - Queue in which vertices with excess are stored * state - Push-relabel state that stores state variables * u - Vertex to discharge of excess */ static void discharge(Graph G, Queue FIFO, PR_State_t* state, int u) { Link t = G->adj[u]; Edge edge; while (state->e[u] > 0) { if (t != NULL) { edge = t->edge; } if (t == NULL) { if (state->h[u] < G->V && state->gap[state->h[u]] == 1) { gapRelabel(G, FIFO, state, state->h[u]); } else { relabel(G, state, u); t = G->adj[u]; } } else if (edge->cap - edge->flow > 0 && state->h[u] == state->h[edge->v] + 1) { push(state, t, u, edge->v); if (!state->active[edge->v]) { state->active[edge->v] = 1; putQ(FIFO, edge->v); } } else { t = t->next; } } if (state->e[u] == 0) { state->active[u] = 0; } } /* Function that determines the edges that the min-cut passes through. * The considered min-cut is the one nearest to the source. * Asymptotic complexity is O(E). * * G - Graph that represents the flow network * FIFO - Queue in which vertices with excess are stored * output - Points to the struct that stores the audit info * s - Source of the flow network */ static void getMinCut(Graph G, PR_State_t* state, NetAudit output, int s) { int u; int h; Link l; for (h = 2; h < G->V; h++) { if (state->gap[h] == 0) break; } for (u = 0; u < G->V; u++) { if (state->h[u] < h) continue; for (l = G->adj[u]; l; l = l->next) { if (state->h[l->edge->v] > h) continue; if (u >= G->V - G->S) { output->minCutS[l->edge->v] = 1; } else if (u == 1 || u > G->P+1) { output->minCutE[output->idx++] = l->opEdge; } } } } /* Start function of the push-relabel method, implemented with the FIFO rule and Gap Relabeling heuristic. * Determines max flow and the edges that cross the min-cut. * Asymptotic complexity is O(V^3). * * G - Graph that represents the flow network * output - Points to the struct that stores the audit info */ void pushRelabelFIFO(Graph G, NetAudit output) { int u; int* h = (int*) malloc(sizeof(int) * G->V); /* Heights of vertices */ int* e = (int*) malloc(sizeof(int) * G->V); /* Excesses of vertices */ char* active = (char*) malloc(sizeof(char) * G->V); /* Active vertices (that have excess) */ int* gap = (int*) calloc(2 * G->V, sizeof(int)); /* Counter of heights */ PR_State_t state = {h, e, active, gap}; /* Push-Relabel state variables declaration */ Queue FIFO = initQ(); /* Queue that will store active vertices (with excess) */ initializePreFLow(G, FIFO, (PR_State_t*) &state, 1, 0); while (!isEmptyQ(FIFO)) { u = getQ(FIFO); discharge(G, FIFO, (PR_State_t*) &state, u); } output->maxFlow = state.e[0]; getMinCut(G, (PR_State_t*) &state, output, 0); free(h); free(e); free(active); free(gap); freeQ(FIFO); } /* Function that frees a graph from memory, given a pointer to it. * Asymptotic complexity is O(V). * * G - Pointer to the graph to free from memory */ void freeG(Graph G) { int i; for (i = 0; i < G->V; i++) { freeL(G->adj[i]); } free(G->adj); free(G); } /************************************************************************************************************ * queue.c ***********************************************************************************************************/ /* Function that creates a firt-in-first-out queue. * Mantains a pointer to the front and back, for efficient removal and insertion respectively. * Asymptotic complexity is O(1). * Returns a pointer to the created queue. */ Queue initQ() { Queue new; new = (Queue) malloc(sizeof(struct queue)); new->front = NULL; new->back = NULL; new->N = 0; return new; } /* Function that inserts an integer into a queue, given the queue. * Insertion is at the end of the queue. * Asymptotic complexity is O(1). * * Q - Queue in which to insert an integer * u - Integer to insert */ void putQ(Queue Q, int u) { QueueLink new = (QueueLink) malloc(sizeof(struct queueNode)); new->id = u; new->next = NULL; if (!isEmptyQ(Q)) { Q->back->next = new; } else { Q->front = new; } Q->back = new; Q->N++; } /* Function that removes an integer from a queue, given the queue. * Removal is at the beginning of the queue. * Asymptotic complexity is O(1). * Returns the removed integer. * * Q - Queue from which to remove an integer */ int getQ(Queue Q) { QueueLink t; int id; if (!isEmptyQ(Q)) { id = Q->front->id; t = Q->front; Q->front = t->next; free(t); if (isEmptyQ(Q)) { Q->back = NULL; } Q->N--; return id; } return 0; } /* Function that determines if a queue is empty, given the queue. * Asymptotic complexity is O(1). * Returns true if empty and false otherwise. * * Q - Queue to query */ int isEmptyQ(Queue Q) { return Q->N == 0; } /* Function frees a queue, given the queue. * Asymptotic complexity is O(N). * * Q - Queue to free */ void freeQ(Queue Q) { QueueLink t; while (Q->front != NULL) { t = Q->front; Q->front = t->next; free(t); } free(Q); } /************************************************************************************************************ * list.c ***********************************************************************************************************/ /* Function that inserts an edge into a list, given its head. * Insertion is at the beginning of the list. * Asymptotic complexity is O(1). * Returns a pointer to the inserted node so that the head can be updated. * * head - Pointer to the first element on the list * edge - Edge to insert */ Link insertL(Link head, Edge edge) { Link new = (Link) malloc(sizeof(struct node)); new->edge = edge; new->next = head; new->opEdge = NULL; return new; } /* Function that sets two edges in the list as opposites, mantaining a pointer to each of them. * Asymptotic complexity is O(1). * * t - Link of the edge * u - Link of the opposite edge */ void linkOppositesL(Link t, Link u) { t->opEdge = u->edge; u->opEdge = t->edge; } /* Function that frees a list from memory, given its head. * Asymptotic complexity is O(N). * * head - Pointer to the first element on the list */ void freeL(Link head) { Link t; while (head != NULL) { t = head; head = t->next; free(t->edge); free(t); } }
C
/* ** EPITECH PROJECT, 2019 ** CPE_matchstick_2018 ** File description: ** matchstick_main */ #include "my.h" char **remove_matches_ai(char **map, struct a_intelligence *ai, int i) { while (ai->matches > 0) { i--; map[ai->line][i] = ' '; ai->matches--; } return (map); } char **remove_matches(char **map, struct data *dt, int i) { while (dt->matches > 0) { i--; map[dt->line][i] = ' '; dt->matches--; } return (map); } int randomize(int min, int max) { return ((rand() % (max + 1 - min)) + min); } int nbr_pipes(char **map, int line) { int nbr = 0; for (int j = 0; map[line][j] != '\n'; j++) { if (map[line][j] == '|') nbr++; } return (nbr); } int main(int ac, char **av) { struct data *dt = malloc(sizeof(struct data)); char **map; if (check_errors(ac, av) == 84) return (84); dt->length = my_getnbr(av[1]); dt->maxMatches = my_getnbr(av[2]); if (dt->maxMatches < 1 || dt->length <= 1 || dt->length >= 100) return (84); map = create_map(dt); dt->totalMatches = get_nbr_matches(map); return (game(map, dt)); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "utf8.h" #define FILE_NAME "Blocks.txt" #define LINE_SIZE 10000 #define UTF8_SIZE 7 #define NAME_SIZE 50 typedef struct { long count; char begin[UTF8_SIZE]; int begin_d; char end [UTF8_SIZE]; int end_d; char name [NAME_SIZE]; }Language; static Language ls[300]; int i=0; int binary_search(unsigned int state){ int min=0,max=i-1,mid; while(max>=min){ mid=(min+max)/2; if(state>ls[mid].begin_d){ min=mid+1; } else if(state<ls[mid].begin_d){ max=mid-1; } else{ ls[mid].count++; return 0; } } if(state>ls[mid].begin_d){ ls[mid].count++; return 0; } else ls[mid-1].count++; return 0; } int main() { char line[LINE_SIZE]; FILE *fp=fopen(FILE_NAME,"r"); if(!fp){ printf("file \"Blocks.txt\" open failed\n"); exit(1); } char *p=NULL; char *q=NULL; while(!feof(fp)){ fgets(line,LINE_SIZE,fp); if(line[0]=='#'||line[0]==' '||line[0]=='\n') continue; else{ if((p=strchr(line,'.'))!=NULL) { *p++ = '\0'; *p++ = '\0'; strncpy(ls[i].begin, line, UTF8_SIZE); q = p; if((p = strchr(q, ';'))!=NULL) { *p++ = '\0'; while(*p==' ') p++; strncpy(ls[i].end, q, UTF8_SIZE); strncpy(ls[i].name, p, NAME_SIZE); p=ls[i].name; while(*p!='\n') p++; *p='\0'; sscanf((char *)&ls[i].begin,"%X",&ls[i].begin_d); sscanf((char *)&ls[i].end,"%X",&ls[i].end_d); ls[i].count=0; i++; } else continue; } else continue; } } fclose(fp); int state,len; int blocks_bl_index=0; FILE *fp_2 = stdin; if(fp_2){ while(!feof(fp_2)){ fgets(line,LINE_SIZE,fp_2); p=line; while(*p != '\0') { state = utf8_to_codepoint((unsigned char*)p, &len); if(len) { p += len; binary_search((unsigned int) state); } else { p++; break; } } } for (int j = 1; j <i ; ++j) { if(ls[j].count>ls[blocks_bl_index].count){ blocks_bl_index=j; } } printf("%s\n",ls[blocks_bl_index].name); }else{ printf("failed to open sample file!\n"); exit(1); } return 0; }
C
#include "graph_funcs.h" /** Computes the number of neighbors in each part * @param i - vertex for which we compute * @param part - pointer to the first part * @param other_part - pointer to the second part * @param neigh_part - pointer to the number of neighbours in the first part * @param neigh_other_part - pointer to the number of neighbours in the second part */ void nb_of_neighbours(int i,int *adj,int *adjBeg,int *part,int *neigh_part_zero,int *neigh_part_one) { int j; *neigh_part_zero = 0; *neigh_part_one = 0; for (j = adjBeg[i]; j < adjBeg[i + 1]; j++) { *neigh_part_one = *neigh_part_one + part[adj[j]]; *neigh_part_zero = *neigh_part_zero + 1 - part[adj[j]]; } }
C
void f(int n){ if(n==0) printf("zero"); else if(n>0) printf("positive"); else if(n<0) printf("negative"); }
C
/* Write a loop equivalent to this that doens't use && or || */ #include <stdio.h> int main() { int lim = 5; int c; printf("BEFORE:\n"); for (int i = 0; i < lim - 1 && (c = getchar()) != '\n' && c != EOF; ++i) putchar(c); printf("\n\n\nAFTER:\n"); int i = 0; while (1) { if (i == lim - 1) break; c = getchar(); if (c == '\n') break; if (c == EOF) break; putchar(c); ++i; } }
C
#include <stdio.h> #include <cs50.h> #include <math.h> int main(void) { float change = get_float("Cash owed: "); while (change < 0) //only accept positive values { change = get_float("Cash owed: "); } int pennies = round(change * 100); //convert to pennies and from float to int int total_coins = 0; //sum of coins int coins = 0; //temporary counter of each type of coins if (pennies >= 25) //count quarters { coins += pennies / 25; pennies -= coins * 25; total_coins += coins; coins = 0; } if (pennies >= 10) //count dimes { coins += pennies / 10; pennies -= coins * 10; total_coins += coins; coins = 0; } if (pennies >= 5) //count nickels { coins += (pennies / 5); pennies -= (coins * 5); total_coins += coins; coins = 0; } if (pennies >= 0) //convert leftover to pennies { coins += pennies / 1; pennies -= coins * 1; total_coins += coins; coins = 0; } printf("%d\n", total_coins); }
C
/* *a tyne user app: a->b b->c ...z->a *used to show tty mode * */ #include<stdio.h> #include<stdlib.h> #include<ctype.h> int main(){ int c; while( (c = getchar()) != EOF){ if(c == 'z') c = 'a'; else if( islower(c)) c++; putchar(c); } return 0; }
C
#include <stdio.h> #include <string.h> #include <malloc.h> // Sprite Rotation void GUGSpriteRotate90(char *sprite) { int sz,sx,sy,x,y,y1; char *spr_save; // [1028]; sx = GUGSpriteWidth(sprite); sy = GUGSpriteHeight(sprite); sz = GUGSpriteSize(sprite); if ((spr_save = malloc(sz)) == NULL) return; memcpy((char *)spr_save,(char *)sprite,sz); sprite[0] = sy; sprite[2] = sx; for (x=0; x<sx; ++x) { for (y=0,y1=sy-1; y<sy; ++y,--y1) { sprite[(x*sy)+y1+4] = spr_save[(y*sx)+x+4]; } } free(spr_save); }
C
#include <stdio.h> #include <stdlib.h> struct DEqueue { int size; int front; int rear; int *arr; }; int isEmpty(struct DEqueue *q) { if (q->front == q->rear) { return 1; } else { return 0; } } int isFull(struct DEqueue *q) { if (q->front == -1 && q->rear == q->size - 1) { return 1; } else { return 0; } } void enqueue_rear(struct DEqueue *q, int value) { if (q->rear == q->size - 1) { printf("Cannot insert more element at the rear side.\n"); } else { q->rear++; q->arr[q->rear] = value; printf("Successfully inserted at the rear end.\n"); } } void enqueue_front(struct DEqueue *q, int value) { if (q->front == -1) { printf("Cannot insert more element at the front end.\n"); } else { q->arr[q->front] = value; q->front--; printf("Successfully inserted at the front end.\n"); } } void dequeue_front(struct DEqueue *q) { if (q->rear == q->front) { printf("Cannot delete elements as there are no more elements in the DEqueue.\n"); } else { q->front++; int y = q->arr[q->front]; printf("Deleted element at the front end is %d.\n", y); } } void dequeue_rear(struct DEqueue *q) { if (q->rear == q->front) { printf("Cannot delete elements as there are no more elements in the DEqueue.\n"); } else { int y = q->arr[q->rear]; q->rear--; printf("Deleted element at the front end is %d.\n", y); } } void display(struct DEqueue *q) { if (isEmpty(q)) { printf("Queue is Empty.\n"); } else { for (int i = (q->front + 1); i <= q->rear; i++) { printf("%d ", q->arr[i]); } } } void main(){ struct DEqueue *q; q->size = 50; q->front = -1; q->rear = -1; q->arr = (int *)malloc(q->size * sizeof(int)); enqueue_rear(q,45); enqueue_rear(q,85); enqueue_rear(q,22); enqueue_rear(q,14); enqueue_rear(q,44); enqueue_rear(q,21); enqueue_rear(q,78); enqueue_rear(q,96); enqueue_rear(q,85); enqueue_rear(q,21); enqueue_rear(q,54); enqueue_rear(q,91); enqueue_rear(q,21); enqueue_front(q,65); dequeue_front(q); dequeue_front(q); dequeue_front(q); dequeue_front(q); dequeue_front(q); dequeue_rear(q); dequeue_rear(q); dequeue_rear(q); dequeue_rear(q); enqueue_front(q,65); display(q); }
C
//Poligonal: Série de segmentos de retas conectados //Perimetro é a soma de todos os lados da poligonal #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <math.h> typedef struct { double northing; double easting; } coord; typedef struct { coord v1,v2,v3; } Triangulo; coord *coordenadas; int gNumVertPolig; char hemisferio; int zona; bool ler_arquivo (char nomeArquivo[]){ FILE *ponteiro_arquivo; strcat(nomeArquivo, ".txt"); int i; ponteiro_arquivo = fopen(nomeArquivo,"r"); if (ponteiro_arquivo==NULL){ printf("Erro ao abrir o arquivo!\n"); return false; } else { fscanf(ponteiro_arquivo,"%i %c %i ", &zona, &hemisferio, &gNumVertPolig); coordenadas = (coord*) malloc(gNumVertPolig * sizeof(coord)); for (i=0; i < gNumVertPolig;i++){ fscanf(ponteiro_arquivo,"%lf %lf",&coordenadas[i].easting,&coordenadas[i].northing); } fclose(ponteiro_arquivo); return true; } } double CalcularAreaPoligono (coord vertices[], int gNumVertPolig){ double area = 0; int i; for (i=0;i<gNumVertPolig-1;i++) { area +=(vertices[i].easting*vertices[i+1].northing-vertices[i+1].easting*vertices[i].northing)/2; } if (area < 0) { return (area * (-1)); } return area; } //calculo é raiz quadrada da soma dos quadrados dos catetos double CalcularPerimetroPoligono(coord vertices[], int gNumVertPolig){ double perimetro = 0; int i; for (i=0;i<gNumVertPolig-1;i++) { perimetro += sqrt(pow(vertices[i+1].easting-vertices[i].easting,2) + pow(vertices[i+1].northing-vertices[i].northing,2)); } if (perimetro < 0) { return (perimetro * (-1)); } return perimetro; } //retorna a area do triangulo calculado a partir dos 3 pares de coordenadas double CalculaAreaTriangulo(Triangulo t) { double area = (t.v1.northing * t.v2.easting + t.v2.northing * t.v3.easting + t.v3.northing * t.v1.easting -t.v1.easting * t.v2.northing - t.v2.easting * t.v3.northing - t.v3.easting * t.v1.northing)*0.5; if (area < 0) { return (area * (-1)); } return area; } Triangulo CriaTriangulo (coord p1, coord p2, coord pdado){ Triangulo novo; novo.v1 = p1; novo.v2 = p2; novo.v3 = pdado; return novo; } //recebe uma coordenada "aleatoria" passada por quem deseja saber se esta inserida bool isIn(coord pdado){ int i; Triangulo n; double areaTotal = 0; for(i=0; i<gNumVertPolig-1;i++ ){ n = CriaTriangulo(coordenadas[i], coordenadas[i+1], pdado); //retorna os 3 pontos no formato (X,Y) in a struct areaTotal = CalculaAreaTriangulo(n) + areaTotal; } if (areaTotal == CalcularAreaPoligono(coordenadas,gNumVertPolig)) //poderia ser usado uma variavel global return true; return false; } int main() { int opcaoMenu; char opcaoSair; bool sair=false; char nomeArq[70]; bool abriu = false; double area, perimetro; coord coorde; do { system("cls"); printf ("\n\n======= Calculos com Poligonal ===============\n"); printf("\n 1- Ler arquivo com Dados da Poligonal\n"); printf("\n 6- Sair\n"); printf("\n Selecione uma opcao do menu:"); scanf("%i",&opcaoMenu); switch (opcaoMenu) { case 1: system("cls"); printf("\n Digite o nome do arquivo para leitura: "); scanf("%s", nomeArq); abriu = ler_arquivo(nomeArq); case 2: system("cls"); if (abriu) { do { printf("\n 3- Calcular Area da Poligonal \n"); printf("\n 4- Calcular Perimetro da Poligonal\n"); printf("\n 5- Testar se um ponto (em coordenadas geograficas) pertence a poligonal\n"); printf("\n 6- Gerar Arquivo de Saida em KML \n"); printf("\n 7- Sair\n"); printf("\n Selecione uma opcao do menu:"); scanf("%i",&opcaoMenu); switch (opcaoMenu) { system("cls"); case 3: area = CalcularAreaPoligono(coordenadas,gNumVertPolig); printf(" A area do poligono em metros quadrados e %lf : \n\n", area); // system("Pause"); break; case 4: perimetro = CalcularPerimetroPoligono(coordenadas, gNumVertPolig); printf(" O perimetro do poligono em metros e %lf : \n\n", perimetro); break; case 5: printf("\n Digite a primeira coordenada para verificacao: "); scanf("%lf",&coorde.easting); printf("\n Digite a segunda coordenada para verificacao: "); scanf("%lf",&coorde.northing); if (isIn(coorde)) printf("\n A coordenada fornecida está dentro da area de desapropriacao"); else printf("\n A coordenada fornecida nao esta dentro da area de desapropriacao"); break; case 6: // convertUTM2LatLon(coordenadas,zona,hemisferio); // printf(" Arquivo utm e %lf : \n\n", UTM2LatLon); break; case 7: do { system("cls"); printf("Digite S para sair e N para continuar:"); scanf(" %c",&opcaoSair); } while (opcaoSair!='S'&& opcaoSair!='s' && opcaoSair!='N' && opcaoSair!='n'); if (opcaoSair == 'S' || opcaoSair == 's') { sair=true; } break; default: printf("Opcao Invalida\n"); system("PAUSE"); break; } }while(!sair); } else{ printf("Arquivo nao foi lido corretamente.\n"); system("Pause"); } break; case 8: do { system("cls"); printf("Digite S para sair e N para continuar:"); scanf(" %c",&opcaoSair); } while (opcaoSair!='S'&& opcaoSair!='s' && opcaoSair!='N' && opcaoSair!='n'); if (opcaoSair == 'S' || opcaoSair == 's') { sair=true; } break; default: printf("Opcao Invalida\n"); system("PAUSE"); break; } } while(!sair); }
C
#include <stdio.h> void pf(void); int main(void) { for(int i=1; i <=3;i++) { pf(); } return 0; } void pf(void) { static int i = 1; int y =1; printf("%d %d \n", i++, y++); }
C
/***************************************************************************//** @file +Nombre del archivo (ej: template.h)+ @brief +Descripcion del archivo+ @author +Nombre del autor (ej: Salvador Allende)+ ******************************************************************************/ #ifndef _FSM_H_ #define _FSM_H_ /******************************************************************************* * INCLUDE HEADER FILES ******************************************************************************/ #include <stdio.h> //#include <allegro5/allegro.h> //#include <allegro5/events.h> #include <time.h> #include <stdlib.h> #include <stdint.h> /******************************************************************************* * CONSTANT AND MACRO DEFINITIONS USING #DEFINE ******************************************************************************/ #define BOARD_SIZE 16 #define LIVES 3 #define END_TABLE 0 /******************************************************************************* * ENUMERATIONS AND STRUCTURES AND TYPEDEFS ******************************************************************************/ enum events { RIGHT_EVENT = 1024, UP_EVENT, DOWN_EVENT, LEFT_EVENT, GAME_OVER_EVENT, LEVEL_UP_EVENT, FROG_HIT_EVENT, ENTER_EVENT, TIMER_EVENT, PAUSE_EVENT, }; typedef char boolean_t; typedef struct { boolean_t flag; int type; boolean_t timerFlag; }event_t; typedef struct { char player[3]; uint score; } scorer_t; typedef struct STATE { event_t event; struct STATE *nextState; void (*actionRoutine)(void *); int stateID; } state_t; typedef struct { uint8_t x; uint8_t y; }frog_t; typedef struct { int lives; boolean_t levelUp; boolean_t frogHit; boolean_t quitGame; boolean_t (*pBoard)[16][16]; frog_t frog; char player[3]; uint score; scorer_t (*pTop10)[10]; state_t *currentState; event_t event; }gameData_t; /******************************************************************************* * VARIABLE PROTOTYPES WITH GLOBAL SCOPE ******************************************************************************/ // +ej: extern unsigned int anio_actual;+ /******************************************************************************* * FUNCTION PROTOTYPES WITH GLOBAL SCOPE ******************************************************************************/ void non_act_routine(void *pArg); void cars_routine(void *pArg); void shift_right_row(boolean_t row[BOARD_SIZE][BOARD_SIZE], int row_num); void shift_left_row(boolean_t row[BOARD_SIZE][BOARD_SIZE], int row_num); void shift_handler(boolean_t row[BOARD_SIZE][BOARD_SIZE], boolean_t way, int row_num); void frog_up(void *pArg); void frog_down(void *pArg); void frog_left(void *pArg); void frog_right(void *pArg); void frog_hit(void *pArg); void start_game(void *pArg); void letter_up(void *pArg, int letter); void letter_down(void *pArg, int letter); void fst_letter_up(void *pArg); void scd_letter_up(void *pArg); void trd_letter_up(void *pArg); void fst_letter_down(void *pArg); void scd_letter_down(void *pArg); void trd_letter_down(void *pArg); void end_game(void *pArg); void game_over(void *pArg); /** * @brief TODO: completar descripcion * @param param1 Descripcion parametro 1 * @param param2 Descripcion parametro 2 * @return Descripcion valor que devuelve */ // +ej: char lcd_goto (int fil, int col);+ /******************************************************************************* ******************************************************************************/ #endif // _FSM_H_
C
#include <err.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <libgen.h> #include <unistd.h> #include <ctype.h> #include <openssl/sha.h> #include <errno.h> #include <math.h> #include <fcntl.h> #include <sys/param.h> #include <regex.h> #include <archive.h> #include <archive_entry.h> #include <wchar.h> typedef enum { Quiet, Noquiet, Verbose } verbosity; const char * archive_entry_pathname(struct archive_entry *); int64_t archive_entry_size(struct archive_entry *); char * SHA256_End(SHA256_CTX *context, char *buf); void usage(char *selfpath) { printf("Usage:\n\t%s[-r <exclude_expression> [path_to_tar]\n", basename(selfpath)); exit(0); } void pt(unsigned char *md) { int i; for (i=0; i<SHA256_DIGEST_LENGTH; i++) printf("%02x",md[i]); printf("\n"); } char * toUpper(char *str){ char *newstr, *p; p = newstr = strdup(str); while((*p++=toupper(*p))); return newstr; } int main(int argc, char **argv) { char tarpath[PATH_MAX]; char origtarpath[PATH_MAX]; char selfpath[PATH_MAX]; char *entrydata; struct archive *a; struct archive_entry *entry; int r; int64_t asize; //char *exclude_pattern = ".*/\\.svn/.*"; //char buf[block]; SHA256_CTX c; unsigned char md[SHA256_DIGEST_LENGTH]; regex_t preg; int ch, i; verbosity verb; char *modeline; int modelinesize; uint64_t (*modefunctions[11])( struct archive_entry *entry) = { archive_entry_mode, archive_entry_dev, archive_entry_devmajor, archive_entry_devminor, archive_entry_ino, archive_entry_nlink, archive_entry_rdevmajor, archive_entry_rdevminor, archive_entry_uid, archive_entry_gid, archive_entry_size }; /* * 16 characters should be enougth for all possible modefields */ char modes[(int)(sizeof(modefunctions)/sizeof(modefunctions[0]))][16]; (void)realpath(argv[0], selfpath); // "$." -- empty match for any not-multiline input string if (regcomp(&preg, "$.", REG_EXTENDED) != 0) { fprintf(stderr, "Bad pattern\n"); exit(1); } while ((ch = getopt(argc, argv, "r:")) != -1) { switch (ch) { case 'r': if (regcomp(&preg, optarg, REG_EXTENDED) != 0) { fprintf(stderr, "Bad pattern\n"); exit(1); }; break; case '?': default: usage(selfpath); } } argc -= optind; argv += optind; a = archive_read_new(); archive_read_support_compression_all(a); archive_read_support_format_all(a); if (argc == 0) { strncpy(tarpath, "stdin", sizeof("stdin")); r = archive_read_open_filename(a, NULL, ARCHIVE_DEFAULT_BYTES_PER_BLOCK); verb = Quiet; } else { (void)realpath(argv[0], tarpath); strcpy(origtarpath, argv[0]); if ((r = archive_read_open_filename(a, tarpath, ARCHIVE_DEFAULT_BYTES_PER_BLOCK)) == ARCHIVE_OK){ verb = Noquiet; } else { printf("%s\n", archive_error_string(a)); exit(1); } } int counter=0; SHA256_Init(&c); while ((r = archive_read_next_header(a, &entry)) == ARCHIVE_OK) { modelinesize = 0; if ((++counter % 100) == 0) { printf ("%09d ", counter); printf("%s\n",archive_entry_pathname(entry)); } if (regexec(&preg, archive_entry_pathname(entry), 0, NULL, 0) !=0) { SHA256_Update(&c, archive_entry_pathname(entry), sizeof(archive_entry_pathname(entry))); //printf("%s\n",archive_entry_pathname(entry)); for (i=0; i < sizeof(modefunctions)/sizeof(modefunctions[0]); i++){ sprintf(modes[i], "%ld", modefunctions[i](entry)); modelinesize += sizeof(modes[i]); } modeline = malloc(modelinesize); for (i=0; i < sizeof(modefunctions)/sizeof(modefunctions[0]); i++){ if (i == 0){ strlcpy(modeline, modes[i], sizeof(modes[i])); } else { strlcat(modeline, modes[i], sizeof(modes[i])); } //free(modes[i]); } SHA256_Update(&c, modeline, modelinesize); free(modeline); if (archive_entry_filetype(entry) == AE_IFLNK){ SHA256_Update(&c, archive_entry_symlink(entry), sizeof(archive_entry_symlink(entry))); } if (archive_entry_filetype(entry) == AE_IFREG ) { asize = archive_entry_size(entry); entrydata = malloc(asize); archive_read_data(a, entrydata, asize); SHA256_Update(&c, entrydata, asize); //SHA256_Update(&lc, entrydata, asize); //SHA256_Final(&(md[0]),&lc); //pt(md); free(entrydata); } } else { archive_read_data_skip(a); } } if ( r == ARCHIVE_EOF ) { if (verb != Quiet) printf("%s (%s) = ", toUpper(basename(selfpath)), origtarpath); SHA256_Final(&(md[0]),&c); pt(md); } else { //fprintf(stderr, "%s: %s\n", tarpath, "Can't operate with archive"); fprintf(stderr, "%s: %s\n", tarpath, archive_error_string(a)); exit(1); } archive_read_close(a); archive_read_free(a); regfree(&preg); }
C
/*******************************************************************//** * * \file Gfx.c * * \author Xavier Del Campo * * \brief Implementation of Gfx module. * ************************************************************************/ /* ************************************* * Includes * *************************************/ #include "Gfx.h" #include "IO.h" #include <psx.h> #include <psxgpu.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> /* ************************************* * Defines * *************************************/ /* ***************************************************************************** * Types definition * ****************************************************************************/ /* ***************************************************************************** * Global variables definition * ****************************************************************************/ /* ***************************************************************************** * Local variables definition * ****************************************************************************/ /* The drawing environment points to VRAM * coordinates where primitive data is * being drawn onto. */ static GsDrawEnv sDrawEnv; /* The display environment points to VRAM * coordinates where primitive data is * being shown on screen. */ static GsDispEnv sDispEnv; /* This variable is set to true on VSYNC event. */ static volatile bool bSyncFlag; /* ***************************************************************************** * Local prototypes declaration * ****************************************************************************/ static void GfxInitDrawEnv(void); static void GfxInitDispEnv(void); static void GfxSwapBuffers(void); static void GfxSortBigSprite(GsSprite *const psSpr); static void GfxSetPrimList(void); static void ISR_VBlank(void); /* ***************************************************************************** * Functions definition * ****************************************************************************/ /***************************************************************************//** * * \brief Initialization of Gfx module. * * \remarks This is where PSX GPU and its interface get initialized. * *******************************************************************************/ void GfxInit(void) { /* Graphics synthetiser (GPU) initialization. */ GsInit(); /* Clear VRAM. */ GsClearMem(); #if (VIDEO_MODE == VMODE_PAL) || (VIDEO_MODE == VMODE_NSTC) /* Set Video Resolution. VIDEO_MODE can be either VMODE_PAL or VMODE_NTSC */ GsSetVideoMode(X_SCREEN_RESOLUTION, Y_SCREEN_RESOLUTION, VIDEO_MODE); #else /* (VIDEO_MODE == VMODE_PAL) || (VIDEO_MODE == VMODE_NSTC) */ #error "Undefined VIDEO_MODE" #endif /* (VIDEO_MODE == VMODE_PAL) || (VIDEO_MODE == VMODE_NSTC) */ /* Set Drawing Environment. */ GfxInitDrawEnv(); /* Set Display Environment. */ GfxInitDispEnv(); /* Set primitive list. */ GfxSetPrimList(); /* Set Vsync interrupt handler for screen refresh. */ SetVBlankHandler(&ISR_VBlank); } /***************************************************************************//** * * \brief Loads data from file indicated by strFilePath, uploads * it into VRAM and sets up a new GsSprite instance. * * \param strFilePath * Absolute file path e.g.: * "cdrom:\\DATA\\SPRITES\\TILESET1.TIM;1". * * \param pSpr * Pointer to sprite to be filled with image data. * * \return Returns true when tasks could be made successfully, * false otherwise. * * \see IOLoadFile() for file I/O handling implementation. * *******************************************************************************/ bool GfxSpriteFromFile(const char* const strFilePath, GsSprite *const pSpr) { /* File size in bytes. Modified by IOLoadFile(). */ size_t eSize; /* Get buffer address where file data is contained. */ const uint8_t *const buffer = IOLoadFile(strFilePath, &eSize); if (buffer && (eSize != IO_INVALID_FILE_SIZE)) { /* File was loaded successfully into buffer. * Now read buffer data and upload it to VRAM. */ /* Declare a GsImage instance, needed by GsImageFromTim(). */ GsImage sGsi; while (GsIsDrawing()); if (GsImageFromTim(&sGsi, buffer) == 1 /* Success code. */) { enum { UPLOAD_IMAGE_FLAG = 1 }; /* sGsi is now filled with data. Create * a GsSprite instance from it. */ /* Call PSXSDK libs to upload image data to VRAM. "const" flag must be removed. */ if (GsSpriteFromImage(pSpr, &sGsi, UPLOAD_IMAGE_FLAG) == 1 /* Success code. */) { /* Return success code. */ return true; } else { /* Something went wrong when obtaining data * from GsImage instance. Fall through. */ } } else { /* Something went wrong when obtaining *.TIM data. * Fall through. */ } } else { /* Something went wrong when loading the file. Fall through. */ } /* Return failure code if reached here. */ return false; } void GfxClear(void) { GsSortCls(0, 0, 0); } /***************************************************************************//** * * \brief Draws current primitive list into screen and performs double * buffering. * * \remarks Blocking function. This function waits for GPU to be free and GPU * VSYNC IRQ flag to be set. * *******************************************************************************/ void GfxDrawScene(void) { /* Hold program execution until VSYNC flag is set * and GPU is ready to work. */ while (!bSyncFlag || GsIsDrawing()); /* Reset VSYNC event flag. */ bSyncFlag = false; /* Swap drawing and display enviroments Y position. */ GfxSwapBuffers(); /* Draw all primitives into screen. */ GsDrawList(); } bool GfxIsBusy(void) { return GsIsDrawing(); } /***************************************************************************//** * * \brief Indicates whether a rectangle defined by x, y, w and h whether * inside current drawing area. * * \param x * Rectangle initial X offset. * * \param y * Rectangle initial X offset. * * \param w * Rectangle width. * * \param h * Rectangle height. * * \return Returns true if rectangle defined by input parameters * is inside screen area, false otherwise. * *******************************************************************************/ bool GfxIsInsideScreenArea(const short x, const short y, const short w, const short h) { if (((x + w) >= 0) && (x < sDrawEnv.w) && ((y + h) >= 0) && (y < sDrawEnv.h)) { /* Rectangle is inside drawing environment area. */ return true; } else { /* Rectangle is outside drawing environment area. * Fall through. */ } /* Return failure code if reached here. */ return false; } /***************************************************************************//** * * \brief Indicates whether a tSprite instance is inside active * drawing environment area. * * \param psSpr * Pointer to tSprite structure. * *******************************************************************************/ bool GfxIsSpriteInsideScreenArea(const GsSprite *const psSpr) { /* Define X/Y and width/height parameters. */ const short x = psSpr->x; const short y = psSpr->y; const short w = psSpr->w; const short h = psSpr->h; /* Return results. */ return GfxIsInsideScreenArea(x, y, w, h); } /***************************************************************************//** * * \brief Extracting information from tSprite instance, this function adds a * low-level GsSprite structure into internal primitive list if inside * drawing environment area. * * \param psSpr * Index of low-level sprite structure inside the internal array. * * \remarks Sprites bigger than 256x256 px are also supported. Internally, * GfxSortBigSprite() draws two primitive, so up to 512x256 px * primitives are supported. * * \see GfxSortBigSprite() to see how big sprites are handled. * *******************************************************************************/ void GfxSortSprite(GsSprite *const psSpr) { if (GfxIsSpriteInsideScreenArea(psSpr)) { /* Small sprites can be directly drawn using PSXSDK function. * On the other hand, big sprites need some more processing. */ psSpr->w > MAX_SIZE_FOR_GSSPRITE ? GfxSortBigSprite(psSpr) : GsSortSprite(psSpr); } else { /* Sprite is outside drawing environment area. Exit. */ } } int GfxToDegrees(const int rotate) { return rotate >> 12; } int GfxFromDegrees(const int degrees) { return degrees << 12; } void GfxDrawRectangle(GsRectangle* const rect) { GsSortRectangle(rect); } /***************************************************************************//** * * \brief Processes big sprites (e.g.: more than 256 px wide) by drawing two * separate primitives. * * \param psSpr * Pointer to low-level GsSprite structure (given by * GfxSortSprite()). * *******************************************************************************/ static void GfxSortBigSprite(GsSprite *const psSpr) { /* On the other hand, GsSprite instances bigger than * 256x256 px must be split into two primitives, so * GsSortSprite shall be called twice. */ /* Store original TPage, width and X data. */ const unsigned char aux_tpage = psSpr->tpage; const short aux_w = psSpr->w; const short aux_x = psSpr->x; /* First primitive will be 256x256 px. */ psSpr->w = MAX_SIZE_FOR_GSSPRITE; /* Render first primitive (256x256 px). */ GsSortSprite(psSpr); /* Second primitive will be: * Width = Original Width - 256 px. * Height = Original Height - 256 px. */ psSpr->x += MAX_SIZE_FOR_GSSPRITE; psSpr->w = X_SCREEN_RESOLUTION - MAX_SIZE_FOR_GSSPRITE; /* TPage must be increased as we are looking 256 px to * the right inside VRAM. Remember that TPages are 64x64 px. */ psSpr->tpage += MAX_SIZE_FOR_GSSPRITE >> GFX_TPAGE_WIDTH_BITSHIFT; /* Render second primitive. */ GsSortSprite(psSpr); /* Restore original TPage, width and X values. */ psSpr->tpage = aux_tpage; psSpr->w = aux_w; psSpr->x = aux_x; } /*******************************************************************//** * * \brief Initialization of PSX low-level drawing environment. * * The drawing environment is a rectangle where primitives * are drawn on. * * \remarks Not to be confused with display environment, which is a * rectangle showing VRAM active display area. * ************************************************************************/ static void GfxInitDrawEnv(void) { /* Initialize drawing environment default values. */ sDrawEnv.w = X_SCREEN_RESOLUTION; sDrawEnv.h = Y_SCREEN_RESOLUTION; /* Initialize drawing environment. */ GsSetDrawEnv(&sDrawEnv); } /*******************************************************************//** * * \brief Initialization of PSX low-level display environment. * * The display environment is a rectangle describing VRAM * (video RAM) active display area. * * \remarks Not to be confused with drawing environment, which is a * rectangle where primitives are drawn on. * ************************************************************************/ static void GfxInitDispEnv(void) { /* Initialize display environment. */ GsSetDispEnv(&sDispEnv); } /*******************************************************************//** * * \brief This function sets a pointer to a buffer which holds * low-level primitive data, and performs double buffering * so a secondary buffer can be used to calculate the new scene. * ************************************************************************/ static void GfxSetPrimList(void) { enum { /* Maximum amount of each low-level primitive data buffer. */ PRIMITIVE_LIST_SIZE = 0x800 }; /* Buffers that will hold all primitive low-level data. */ static uint32_t primList[PRIMITIVE_LIST_SIZE]; /* Set primitive list. */ GsSetList(primList); } /*******************************************************************//** * * \brief Performs double buffering. * * Double buffering consists of swapping drawing and display * environments Y position, so that the display environment is * showing current frame, whereas the drawing environment * is calculating the next frame. * ************************************************************************/ static void GfxSwapBuffers(void) { enum { DOUBLE_BUFFERING_SWAP_Y = 256 }; if (sDispEnv.y == 0) { sDispEnv.y = DOUBLE_BUFFERING_SWAP_Y; sDrawEnv.y = 0; } else if (sDispEnv.y == DOUBLE_BUFFERING_SWAP_Y) { sDispEnv.y = 0; sDrawEnv.y = DOUBLE_BUFFERING_SWAP_Y; } /* Update drawing and display environments * with new calculated Y position. */ GsSetDispEnv(&sDispEnv); GsSetDrawEnv(&sDrawEnv); } /*******************************************************************//** * * \brief This function is executed on VSYNC event. * * Game runs at a fixed rate of 50 Hz (if PAL) or 60 Hz (NTSC), * so if CPU has finished calculating the new scene, it must * wait for this interrupt to be triggered so the game runs * at desired frame rate. * ************************************************************************/ static void ISR_VBlank(void) { /* Set VSYNC flag. */ bSyncFlag = true; }
C
#include <stdio.h> int main(int argc, char const *argv[]) { int x; for (int x = 10; x>0; x--) { printf("%d\n",x ); } return 0; }
C
#include "PlotHandler.h" /*************************************************************************** * Name :PlotHandler.c * Author :Sai * Date :07/15/99 * Purpose :setupPlotHandler: Sets up the array of the plothandler. The * celltypes that correspond to the subset are stored in cellIndicesToPlot * The number of lines to plot are calculated and the CNsave vector is * initialized * PlotHandler: The handler that calculates the cellcounts for each * line from the subset celltypes and calls the VB PlotData *****************************************************************************/ #include <stdlib.h> #include "build.h" #include "defines.h" #include "classes.h" #include "cellp.h" int EXPORT PASCAL getCellLevelbyClassforPlotting(); void get_macro_levelname(int cn,int lnum,char *name); int EXPORT PASCAL setupPlotHandler() { unsigned int i; unsigned int j; int classIdx,levelIdx; boolean selectCellType; int retVal; boolean selectcellTypebyHetclass[MAXCLASSES]; char tStr[255],tStr1[255], errStr[255]; retVal = 0; //Init CNsave if (CNsave.cellcount != NULL) { free(CNsave.cellcount); CNsave.cellcount = NULL; } // set up the subsetting if (SubsetOption ==SUBSETSOMECELLSSELECTED) { //setup the subset numCellIndicesToPlot = 0; //initially allocate cellIndicesToPlot to MAXLOOKUPS cellIndicesToPlot = (unsigned int *)calloc(MAXLOOKUPS, sizeof(unsigned int)); if (cellIndicesToPlot == NULL) { sprintf(errStr,"setupPlotHandler: Out of memory, unable to allocate cellIndicesToPlot"); MsgBoxError(errStr); } maxCellIndicesToPlot = MAXLOOKUPS; //for all possible celltypes for(i=1;i<=ntypes;i++) { //initialize the boolean for(j=0;j<(unsigned int)Number_of_Classes;j++) { selectcellTypebyHetclass[j] = false; } selectCellType = true; //check conditions for(j=1;j<=numPlotSubset;j++) { levelIdx = getcelllevelbyclass(i,PlotSubset[j].classIdx); //check is this celltype matches the subset class and level if (levelIdx == PlotSubset[j].levelIdx) { selectcellTypebyHetclass[PlotSubset[j].classIdx] = true; } } //if this celltype has matched atleast one subset condition for each class for(j=1;j<=numPlotSubset;j++) { if( selectcellTypebyHetclass[PlotSubset[j].classIdx] == false) { selectCellType = false; } } if (selectCellType == true) { numCellIndicesToPlot++; if (numCellIndicesToPlot >= maxCellIndicesToPlot) { maxCellIndicesToPlot += MAXLOOKUPS; cellIndicesToPlot = (unsigned int *) realloc (cellIndicesToPlot , maxCellIndicesToPlot * sizeof(unsigned int)); if (cellIndicesToPlot == NULL) { sprintf(errStr,"setupPlotHandler: Out of memory, unable to allocate cellIndicesToPlot"); MsgBoxError(errStr); } } cellIndicesToPlot[numCellIndicesToPlot] = i; } } } //Allocate CNsave.cellcount, calculate numPlotLines switch(PlotOption) { case PLOTNOPROPSELECTED: CNsave.cellcount = (double *) calloc (2, sizeof(double)); numPlotLines = 1; strcpy(PlotLineName[1],"Total Cellcount"); break; case PLOTALLPROPSELECTED: CNsave.cellcount = (double *) calloc (ntypes+1, sizeof(double)); numPlotLines = ntypes; // PlotLineName = (char *) calloc for(i=1;i<=ntypes;i++) { strcpy(PlotLineName[i],""); construct_type_name(i,PlotLineName[i]); } break; case PLOTSOMEPROPSELECTED: //calculcate the number of lines numPlotLines=1; for(i=1;i<=numPlotProperty;i++) { numPlotLines = numPlotLines * Class[PlotProperty[i]].no_levels; } CNsave.cellcount = (double *) calloc (numPlotLines+1, sizeof(double)); //Create Plot line names for(i=1;i<=numPlotLines;i++) { // PlotLineName[i] = (char *) calloc(255, sizeof(char)); strcpy(PlotLineName[i],""); for(j=1;j<=numPlotProperty;j++) { classIdx = PlotProperty[j]; levelIdx = getCellLevelbyClassforPlotting(i,j-1); if (Class[classIdx].class_type == MACRO) { get_macro_levelname(classIdx,levelIdx,tStr1); } else { strcpy(tStr1,Class[classIdx].Level[levelIdx].level_name); } if (j>1) { sprintf(tStr,"/%s",tStr1); strcat(PlotLineName[i],tStr); } else { sprintf(PlotLineName[i],"%s",tStr1); } } } break; }//end select return(retVal); } void PlotHandler() { unsigned int i,j,k; int classIdx1,levelIdx1,classIdx2,levelIdx2; boolean found, addCellcountToLine; switch(PlotOption) { case PLOTNOPROPSELECTED: CNsave.cellcount[1] = 0.0; for(i=1;i<=(unsigned int)active_ntypes;i++) { if (SubsetOption == SUBSETALLCELLSSELECTED) //if all cells selected, no need to check in cellindicesToPlot { CNsave.cellcount[1] = CNsave.cellcount[1] + CN[i]; } else { k=1; found = false; while((k<=numCellIndicesToPlot) && (!found)) { if(LookUp[i].LookUpId == cellIndicesToPlot[k]) { found = true; CNsave.cellcount[1] = CNsave.cellcount[1] + CN[i]; } else { k++; } } } } break; case PLOTALLPROPSELECTED: for(i=1;i<=(unsigned int)active_ntypes;i++) { if (SubsetOption == SUBSETALLCELLSSELECTED) //if all cells selected, no need to check in cellindicesToPlot { CNsave.cellcount[LookUp[i].LookUpId] = CN[i]; } else { k=1; found = false; while((k<=numCellIndicesToPlot) && (!found)) { if(LookUp[i].LookUpId == cellIndicesToPlot[k]) { found = true; CNsave.cellcount[LookUp[i].LookUpId] = CN[i]; } else { k++; } } } } break; case PLOTSOMEPROPSELECTED: // for each line for(i=1;i<=numPlotLines;i++) { CNsave.cellcount[i] = 0.0; if (SubsetOption == SUBSETALLCELLSSELECTED) //if all cells selected, no need to check in cellindicesToPlot { // for each celltype in the subset for(j=1;j<=(unsigned int)active_ntypes;j++) { addCellcountToLine = true; for(k=1;k<=numPlotProperty;k++) { classIdx1 = PlotProperty[k]; levelIdx1 = getCellLevelbyClassforPlotting(i,k-1); classIdx2 = classIdx1; levelIdx2 = getcelllevelbyclass(LookUp[j].LookUpId,classIdx2); //if the level of the line does not match the level of the celltype then //do not add this celltype to the line if(levelIdx2 != levelIdx1) { addCellcountToLine = false; } } if (addCellcountToLine == true) { CNsave.cellcount[i]=CNsave.cellcount[i] + getcellcounts(LookUp[j].LookUpId,!VEGF); } } } else { // for each celltype in the subset for(j=1;j<=numCellIndicesToPlot;j++) { addCellcountToLine = true; for(k=1;k<=numPlotProperty;k++) { classIdx1 = PlotProperty[k]; levelIdx1 = getCellLevelbyClassforPlotting(i,k-1); classIdx2 = classIdx1; levelIdx2 = getcelllevelbyclass(cellIndicesToPlot[j],classIdx2); //if the level of the line does not match the level of the celltype then //do not add this celltype to the line if(levelIdx2 != levelIdx1) { addCellcountToLine = false; } } if (addCellcountToLine == true) { CNsave.cellcount[i]=CNsave.cellcount[i] + getcellcounts(cellIndicesToPlot[j],!VEGF); } } } } break; } PlotData(); } int EXPORT PASCAL getCellLevelbyClassforPlotting( int icell, int iclass) { unsigned int i; int preProd,postProd; int sLevel,retVal; preProd = 1; icell--; for(i=iclass;i<numPlotProperty;i++) { preProd = preProd * Class[PlotProperty[i+1]].no_levels; } postProd = 1; for(i=iclass+1;i<numPlotProperty;i++) { postProd = postProd * Class[PlotProperty[i+1]].no_levels; } sLevel = icell % preProd; retVal = (sLevel / postProd); return(retVal); }
C
#include<stdio.h> #include<string.h> struct student { int m[100]; char name[100]; float avg; int rank; }; int input(struct student stu[],int i,int m) { int k,flag=0; printf("Enter the student name :"); scanf("%s",&stu[i].name); for(k=0;k<m;k++) { printf("Enter the Subject %d marks :",k+1); scanf("%d",&stu[i].m[k]); if(stu[i].m[k]<50) { flag=1; } } if(flag==1) { return 1; } else { return 0; } } void average(struct student stu[],int n,int k) { int i,sum=0; for(i=0;i<n;i++) { sum+=stu[k].m[i]; } stu[k].avg=sum/n; } void output(struct student stu[],int n,int m) { int i,j; for(i=0;i<n;i++) { printf("\nName :%-10s|Marks :",stu[i].name); for(j=0;j<m;j++) { printf("%-5d",stu[i].m[j]); } printf("\n"); } for(i=0;i<n;i++) { printf("\nThe Average of %s is %.3f\n",stu[i].name,stu[i].avg); } } void classaverage(struct student stu[],int n) { int i; float total; for(i=0;i<n;i++) { total+=stu[i].avg; } printf("\nThe Class average is %.3f\n",total/n); } void passpercentage(int fail[],int n) { int i; float count=0,pp,fp; for(i=0;i<n;i++) { if(fail[i]!=0) { count++; } } fp=(count/n)*100; pp=100-fp; printf("\nThe passpercentage of the class is %.3f\n\nThe failpercentage of the class is %.3f\n",pp,fp); } void rank(struct student stu[],int n,int fail[]) { int i,j,k,te; float temp; char t[100]; struct student temp1; for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(stu[i].avg<stu[j].avg) { temp1=stu[i]; stu[i]=stu[j]; stu[j]=temp1; } } } for(i=0;i<n;i++) { if(fail[i]==1) { stu[i].rank=0; } else { stu[i].rank=i+1; } } for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(stu[i].avg==stu[j].avg) { stu[j].rank=stu[i].rank; } } } for(i=0;i<n;i++) { if(stu[i].rank!=0) { printf("\nName:%-10s|Avg: %-7.3f|Rank:%d\n",stu[i].name,stu[i].avg,stu[i].rank); } else { printf("\nName:%-10s|Avg: %-7.3f|Rank:FAIL\n",stu[i].name,stu[i].avg); } } } void main() { int n,i,m; printf("Enter the number of students :"); scanf("%d",&n); printf("Enter the number of subjects :"); scanf("%d",&m); int fail[n]; struct student stu[n]; for(i=0;i<n;i++) { fail[i]=input(stu,i,m); average(stu,m,i); } output(stu,n,m); classaverage(stu,n); passpercentage(fail,n); rank(stu,n,fail); } /*Output: PS C:\TDM-GCC-64\myprogram\A6> gcc 161-A64b.c -o a PS C:\TDM-GCC-64\myprogram\A6> ./a Enter the number of students :7 Enter the number of subjects :2 Enter the student name :john Enter the Subject 1 marks :99 Enter the Subject 2 marks :100 Enter the student name :jony Enter the Subject 1 marks :100 Enter the Subject 2 marks :99 Enter the student name :ram Enter the Subject 1 marks :100 Enter the Subject 2 marks :99 Enter the student name :mahi Enter the Subject 1 marks :97 Enter the Subject 2 marks :96 Enter the student name :virot Enter the Subject 1 marks :97 Enter the Subject 2 marks :96 Enter the student name :david Enter the Subject 1 marks :77 Enter the Subject 2 marks :93 Enter the student name :maxwell Enter the Subject 1 marks :33 Enter the Subject 2 marks :22 Name :john |Marks :99 100 Name :jony |Marks :100 99 Name :ram |Marks :100 99 Name :mahi |Marks :97 96 Name :virot |Marks :97 96 Name :david |Marks :77 93 Name :maxwell |Marks :33 22 The Average of john is 99.000 The Average of jony is 99.000 The Average of ram is 99.000 The Average of mahi is 96.000 The Average of virot is 96.000 The Average of david is 85.000 The Average of maxwell is 27.000 The Class average is 85.857 The passpercentage of the class is 85.714 The failpercentage of the class is 14.286 Name:john |Avg: 99.000 |Rank:1 Name:jony |Avg: 99.000 |Rank:1 Name:ram |Avg: 99.000 |Rank:1 Name:mahi |Avg: 96.000 |Rank:4 Name:virot |Avg: 96.000 |Rank:4 Name:david |Avg: 85.000 |Rank:6 Name:maxwell |Avg: 27.000 |Rank:FAIL*/
C
/* #Author : kiran raj r #Language : C #Topic : Array #Date : 02/12/2020 */ #include <stdlib.h> #include <stdio.h> void main() { int array1[] = {22,12,23,44,55}; printf("First element %d \n", array1[0]); printf("Last element %d \n", array1[4]); array1[0] = 100; array1[4] = 1000; printf("First element %d \n", array1[0]); printf("Last element %d \n", array1[4]); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* history_write.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ade-sede <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/11/24 23:13:36 by ade-sede #+# #+# */ /* Updated: 2017/11/24 23:14:21 by ade-sede ### ########.fr */ /* */ /* ************************************************************************** */ #include "failure.h" #include "libft.h" #include "history.h" static int write_to_hist(char *value, int fd) { size_t i; i = 0; while (value[i]) { if (value[i] == '\n') write(fd, "\\", 1); write(fd, value + i, 1); ++i; } return (1); } void history_write_to_file(int fd, t_hist *h) { t_list_d *last; last = (!h->list) ? NULL : h->list->last; while (last) { write_to_hist(last->data, fd); write(fd, "\n", 1); last = last->prev; } } void history_write_to_histfile(void) { t_hist *h; int fd; h = singleton_hist(); if ((fd = open(h->file, O_RDWR | O_TRUNC | O_CREAT, 0644)) == -1) { investigate_error(1, "open", NULL, -1); return ; } history_write_to_file(fd, h); close(fd); } void history_append_command_to_list(char *command) { t_hist *h; t_list_d *list; h = singleton_hist(); if (command[0] == '\0' || ft_str_is_clr(command)) return ; command[ft_strlen(command) - 1] = 0; list = ft_double_lst_create(ft_strdup(command)); if (h->list == NULL) h->list = ft_create_head(list); else ft_double_lst_add(&h->list, list); }
C
#include "llist.h" struct ListNode *ll_create_node(void *data) { struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode)); node->next = NULL; node->data = data; return node; } /* Inserts a new node after the one provided */ void ll_insert(struct ListNode *prev_node, void *data) { struct ListNode *new_node = ll_create_node(data); /* Making the pointers point to the correct nodes */ new_node->next = prev_node->next; prev_node->next = new_node; } /* frees current_node and keeps the list intact */ void ll_delete(struct ListNode *prev_node, struct ListNode *current_node) { /* Making the pointers point to the correct nodes */ prev_node->next = current_node->next; free(current_node); } void ll_push_front(struct ListNode **head, void *data) { struct ListNode *new_node = ll_create_node(data); new_node->next = *head; *head = new_node; } void ll_push_back(struct ListNode **head, void *data) { struct ListNode *new_node = ll_create_node(data); /* Checking the "next" pointer to see if it's the end of the list */ struct ListNode *check_node = *head; // If check_node is NULL then the list is empty and we just add it to the front if (!check_node) { *head = new_node; return; } while(check_node->next != NULL) check_node = check_node->next; check_node->next = new_node; } struct ListNode *ll_pop_front(struct ListNode **head) { /* Pointing to the node about to be removed from the list */ struct ListNode *popped_node = *head; /* Making the head point to the next node down the line */ *head = (*head)->next; return popped_node; } struct ListNode *ll_pop_back(struct ListNode **head) { /* If the list is one node long then just call ll_pop_front */ if ((*head)->next == NULL) return ll_pop_front(head); /* Setup for the loop */ struct ListNode *prev_node = *head; struct ListNode *popped_node = (*head)->next; /* Moving to the end of the list */ while (popped_node->next != NULL) { prev_node = prev_node->next; popped_node = popped_node->next; } /* Making a new end of the list and returning the former end */ prev_node->next = NULL; return popped_node; } /** * Deinitialises a list by popping the front and freein the resource * Should write your own if the node.data also has pointers that need to be freed */ void ll_deinit(struct ListNode **head) { struct ListNode *del_node; while (*head != NULL) { del_node = ll_pop_front(head); free(del_node->data); free(del_node); } }
C
#include <stdio.h> int main(void) { const int ROWS = 6; const int CHARS = 6; int row; char ch; for(row = 0;row<ROWS;row++) { for(ch=('A'+row);ch<('A'+CHARS);ch++) printf("%c",ch); printf("\n"); } return 0; }
C
/* * base.cpp * function???? * Created on: 2012-11-28 * Author: sear */ int main() { int a, b, c; //a,b,c???????????1?2?3 int i, j, k; //i,j,k????abc?? for (a = 1; a < 4; a++) //a,b,c??1?3?? for (b = 1; b < 4; b++) { if (a == b) continue; //a=b?b???1 for (c = 1; c < 4; c++) { if (c == a || c == b) continue; //c=a?c=b?c???1 if (((a + (b > a) + (a == c)) == 3) && ((b + (a > b) + (a > c)) == 3) && ((c + (c > b) + (b > a)) == 3)) break; //?????????????????????3 } } a=i,b=j,c=k; //??abc?? //???????????? if (a > b) { if (b > c) cout << "ABC"; else { if (c < a) cout << "ACB"; else cout << "CAB"; } } else { if (a > c) cout << "BAC"; else { if (c < b) cout << "BCA"; else cout << "CBA"; } } return 0; //???? }
C
/* cbregister.c - cbregister */ #include <xinu.h> /*--------------------------------------------------- * cbregister - callback function *--------------------------------------------------- */ syscall cbregister( void (* fp)(void), /* a function pointer to a user callback */ umsg32 *mbufptr /* a pointer to a 1 word msg buffer */ ) { struct procent *prptr; /* Check to ensure that fp lies within the bounds of text segment, and * mbufptr does not point inside the the text segment */ if (!( (uint32)fp >= (uint32)&text && (uint32)fp <= (uint32)&etext )) { XDEBUG_KPRINTF("cbregister: BAD -- fp not in text segment: %08X\n", (uint32) &fp); /* fp is not within text segment bounds */ return SYSERR; } XDEBUG_KPRINTF("cbregister: fp is in text segment\n"); /* fp is within bounds, so check membufptr */ if (!((uint32)mbufptr > (uint32)&etext)) { XDEBUG_KPRINTF("cbregister: BAD -- mbufptr is in the text segment\n"); /* mbufptr is inside text */ return SYSERR; } XDEBUG_KPRINTF("cbregister: mbufptr is not in text segment\n"); /* Both arguments are now good to go */ prptr = &proctab[currpid]; /* Initialize the callback function fields */ prptr->prcbptr = fp; prptr->prcbvalid = TRUE; XDEBUG_KPRINTF("cbregister: Set prcbvalid to TRUE\n"); /* Initialize the processes bufptr field */ prptr->prmbufptr = mbufptr; return OK; }
C
/* Program: small-db-2.c */ #include <stdio.h> #include <strings.h> #include <stdbool.h> #include <stdlib.h> #include <errno.h> #include <limits.h> // ===================== // = Type declarations = // ===================== // The Column Value union. Stores either an integer, a // double or 8 (7 + 1) characters. typedef union { int int_val; //todo: Add double as an option char txt_val[8]; } column_value; // The Data Kind enumeration indicates the kind of data // stored in a row, matches the options available in the // Column Value union. typedef enum { INT_VAL, //todo: Add double as an option TXT_VAL, UNK_VAL // an unknown value } data_kind; // The Row record/structure. Each row contains an id // a kind, and some data (a Column Value). typedef struct { int id; data_kind kind; column_value data; } row; // The data store is a dynamic array of rows, keeping track // of the number of rows in the array, and the id for the next row typedef struct { int next_row_id; // The id of the row that will be added next int row_count; // The number of rows in the array row *rows; // A pointer to the rows in memory } data_store; // The user can choose to add, delete, or print data or to quit typedef enum { ADD_DATA, DELETE_DATA, PRINT_DATA, QUIT } menu_option; // ==================================== // = General Functions and Procedures = // ==================================== // Trim spaces from the start/end of a string (in place) // This is passed the string to trim, and the number of characters it contains void trim(char* text, int n) { int i, j; int first_non_space = 0; // Get the position of the last character int last_char = strlen(text); if (last_char > n) last_char = n; // Move back one character - past the null terminator if (text[last_char] == '\0') last_char--; // for each character, back from the last char to the first for(i = last_char; i >= 0; i--) { if (text[i] == ' ') text[i] = '\0'; //replace spaces with null else break; // found a non-space so break out of this loop } // remember the new position of the last character last_char = i; // Search forward from the start... for(first_non_space = 0; first_non_space < last_char; first_non_space++) { // Break at the first character that is not a space if (text[first_non_space] != ' ') break; } if (first_non_space > 0) { // Need to copy characters back to start of text... // j will track from the start of the text j = 0; // i will track the index of the non-white space characters // starting at the first_non_white space and looping // until it gets to the last char (include last char so <= not <) for(i = first_non_space; i <= last_char; i++) { text[j] = text[i]; j++; } text[j] = '\0'; // add a null terminator to the end } } // Test if the passed in text refers to an integer bool is_integer(const char* text) { char * p; long val; // If the text is empty there is no integer if (text == NULL || *text == '\0') return false; // Test that it can be converted to an integer val = strtol (text, &p, 10); // base 10 // It is an integer if all characters were used in // the conversion, and there was no range error // and the result is in the return *p == '\0' && errno != ERANGE && val <= INT_MAX && val >= INT_MIN; } // Test if the passed in text refers to a double bool is_double(const char* text) { char * p; // IF the text is empty there is no double if (text == NULL || *text == '\0') return false; // Test that it converts to a double strtod (text, &p); // It is a double if the next character in the text // after the conversion is the end of the string return *p == '\0'; } void clear_input() { scanf("%*[^\n]"); // skip anything is not not a newline scanf("%*1[\n]"); // read the newline } // ===================================== // = Small DB Functions and Procedures = // ===================================== // Read a row in from the user and return it. The next_id // is the id number for the newly created row. row read_row(int next_id) { char line[16] = "", temp[2]; row result = {0, UNK_VAL, {0}}; //store the id result.id = next_id; // Read the value from the user into the line printf("Enter value: "); // Read at most 15 characters up to a new line // check if only one of the two inputs is matched if (scanf("%15[^\n]%1[\n]", line, temp) != 2) { // If the next character was not a newline, read // any remaining text and skip it clear_input(); } // Remove any leading or trailing spaces trim(line, 16); // test int first if (is_integer(line)) { // read the integer from the line, and store in row sscanf(line, "%d", &result.data.int_val); // store the kind in the row result.kind = INT_VAL; } else if (is_double(line)) // test dbl { // todo: Add handling of double... } else { // copy the text into the row (at most 7 + 1 characters) strncpy(result.data.txt_val, line, 7); // 7 + 1 // store the kind in the row result.kind = TXT_VAL; } printf("Stored in row with id %d\n", result.id); return result; } // Print the row to the Terminal void print_row(row to_print) { // Print the row's id printf("Row with id %d: ", to_print.id); // Branch based on the kind, and output the data switch (to_print.kind) { case INT_VAL: printf(" has integer %d\n", to_print.data.int_val); break; // Add double as an option case TXT_VAL: printf(" has text '%s'\n", to_print.data.txt_val); break; default: printf(" has an unknown value\n"); } } menu_option get_menu_option() { int input = 0; printf("=========================\n"); printf("| Small DB |\n"); printf("=========================\n"); printf(" 1: Add Data\n"); printf(" 2: Print Data\n"); printf(" 3: Delete Data\n"); printf(" 4: Quit\n"); printf("=========================\n"); printf("Choose Option: "); while(scanf("%d", &input) != 1 || input < 1 || input > 4 ) { clear_input(); printf("Please enter a value between 1 and 4.\n"); printf("Choose Option: "); } // Ensure that input is clear after menu is read. clear_input(); switch(input) { case 1: return ADD_DATA; case 2: return PRINT_DATA; case 3: return DELETE_DATA; case 4: return QUIT; default: return QUIT; } } void add_a_row(data_store *db_data) { int row_id = 0; if (db_data == NULL) return; // Allocate the id row_id = db_data->next_row_id; db_data->next_row_id++; // Store the data db_data->row_count++; db_data->rows = (row *) realloc(db_data->rows, sizeof(row) * db_data->row_count); db_data->rows[db_data->row_count - 1] = read_row(row_id); // last idx = n - 1 } int idx_of_row_with_id(data_store *db_data, int row_id) { int i; if (db_data == NULL) return -1; // Loop through each element of the array for(i = 0; i < db_data->row_count; i++) { // is this the one we are after? if (db_data->rows[i].id == row_id) { return i; // return the index found. } } // Nothing found... return -1; } void delete_a_row(data_store *db_data) { int row_id; int i; int row_index; printf("Please enter id of row to delete: "); scanf("%d", &row_id); // Get the index of the row (will test if db_data == NULL) row_index = idx_of_row_with_id(db_data, row_id); if (row_index >= 0) // a row was found to delete... { // copy all data past the row, back over the row to delete it for(i = row_index; i < db_data->row_count - 1; i++) { // copy data back one spot in the array (one element at a time) db_data->rows[i] = db_data->rows[i+1]; } // change the row count, and resize the array db_data->row_count--; db_data->rows = realloc(db_data->rows, sizeof(row) * db_data->row_count); } } // Print all of the rows from the data store void print_all_rows(const data_store *db_data) { int i = 0; if (db_data == NULL) return; // For each row in the array for (i = 0; i < db_data->row_count; i++) { // Print the row to the Terminal print_row(db_data->rows[i]); } } // =========================== // = Loading and Saving Data = // =========================== void read_row_from_file(row *to_load, FILE *input) { // Load defaults in case loading fails... to_load->id = 0; to_load->kind = INT_VAL; to_load->data.int_val = 0; // Read in the id and the kind (as an integer) fscanf(input, " %d %d ", &to_load->id, (int*)&to_load->kind); // Branch based on the kind, and output the data switch (to_load->kind) { case INT_VAL: // Read in the integer from the file fscanf(input, "%d\n", &to_load->data.int_val); break; // Add double as an option case TXT_VAL: // Read in the text value from the file (upto 7 characters) fscanf(input, "%7[^\n]\n", to_load->data.txt_val); // no & as char array break; default: // Dont know what the value is... set it to 0 to_load->data.int_val = 0; } } bool load(data_store *db_data, const char *filename) { FILE *input; input = fopen(filename, "r"); if ( input == NULL ) return false; int i = 0; if (db_data != NULL) { db_data->row_count = 0; // Save the row count... fscanf(input, "next id:%d ", &(db_data->next_row_id)); fscanf(input, "rows:%d ", &(db_data->row_count)); // Allocate space for rows... db_data->rows = (row *) realloc(db_data->rows, sizeof(row) * db_data->row_count); if (db_data->rows == NULL) { fclose(input); return false; } // For each row in the array for (i = 0; i < db_data->row_count; i++) { // read the row from the file, into the space allocated for this row read_row_from_file(&(db_data->rows[i]), input); } } fclose(input); return true; } void save_row(row to_save, FILE *out) { fprintf(out, "%d %d ", to_save.id, to_save.kind); // Branch based on the kind, and output the data switch (to_save.kind) { case INT_VAL: fprintf(out, "%d\n", to_save.data.int_val); break; // Add double as an option case TXT_VAL: fprintf(out, "%s\n", to_save.data.txt_val); break; default: fprintf(out, "\n"); //dont save unknown data } } bool save(const data_store *db_data, const char *filename) { FILE *out; int i; out = fopen(filename, "w"); if ( out == NULL ) return false; if (db_data != NULL) { // Save the row count... fprintf(out, "next id:%d\n", db_data->next_row_id); fprintf(out, "rows:%d\n", db_data->row_count); // For each row in the array for (i = 0; i < db_data->row_count; i++) { // Print the row to the Terminal save_row(db_data->rows[i], out); } } fclose(out); return true; } // ======== // = Main = // ======== // Entry point int main() { menu_option opt; data_store db_data = {0, 0, NULL}; load(&db_data, "data.txt"); do { opt = get_menu_option(); switch(opt) { case ADD_DATA: add_a_row(&db_data); break; case DELETE_DATA: delete_a_row(&db_data); break; case PRINT_DATA: print_all_rows(&db_data); break; case QUIT: printf("Bye.\n"); break; } } while(opt != QUIT); save(&db_data, "data.txt"); return 0; }
C
main() { int i,arr[25],prsnt=0,num; printf("Please enter 25 numbers: \n"); for(i=0;i<25;i++) { scanf("%d",&arr[i]); } printf("\n\nPlease enter the number to be searched: "); scanf("%d",&num); for(i=0;i<25;i++) { if(num==arr[i]) prsnt=prsnt+1; } if(prsnt==0) { printf("\n\nNumber does not present in the array.\n"); } else { printf("\n\nNumber presents in the array.\n"); printf("\nNumber of times it appears = %d.\n",prsnt); } }
C
#include "binary_trees.h" /** * binary_tree_size - Function that measures the size of a binary tree * @tree: Pointer to the root node of the tree to measure the size. * * Return: return the sum of the the two branches. */ size_t binary_tree_size(const binary_tree_t *tree) { size_t left = 0; size_t right = 0; if (!tree) return (0); if (tree->left) left = binary_tree_size(tree->left); if (tree->right) right = binary_tree_size(tree->right); return (right + left + 1); }
C
#define SIZE 10 void size(int arr[SIZE]) { printf("size of array is:%d\n",sizeof(arr)); } int main() { int arr[SIZE]; //its doesnt work cause the param in size is a pointer size(arr); printf("%d\n", sizeof(arr) ); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #define livre 1 #define parede 2 #define visitada 3 #define beco 4 #define saida 5 #define max 30 #define ANSI_COLOR_RED "\x1b[31m" #define ANSI_COLOR_YELLOW "\x1b[33m" #define ANSI_COLOR_BLUE "\x1b[34m" #define ANSI_COLOR_RESET "\x1b[0m" //Estrutura typedef struct Nodo_Pilha { int elemento; struct Nodo_Pilha *prox; }*NODOPTR; //Variável Global int labirinto[max][max]; NODOPTR pilha= NULL; //Funções //Função que Aloca Memória para o Nodo NODOPTR Cria_Nodo() { NODOPTR p; p = (NODOPTR) malloc(sizeof(struct Nodo_Pilha)); if(!p) { printf("Problemas na Alocação!!!"); exit(0); } return p; } //Função que carrega a matriz void carrega_matriz(){ int i, j, k; for (j = 0; j < max; j++){ labirinto[0][j]= parede; labirinto[29][j]= parede; labirinto[j][0]= parede; labirinto[j][29]= parede; } for(i=1; i < max-1; i++){ for(j=1; j < max-1; j++) labirinto[i][j] = livre; } for(i=1; i < max-1; i++){ for(j=1; j < max-1; j++){ if(rand()%4 == 1){ labirinto[i][j] = parede; } else labirinto[i][j] = livre; } } labirinto[1][1] = livre; labirinto[1][2] = livre; labirinto[2][1] = livre; labirinto[2][2] = livre; //Sorteio da saida k = (rand()%28) + 1; if(rand()%2 == 1){ labirinto[29][k] = saida; labirinto[28][k] = livre; } else{ labirinto[k][29] = saida; labirinto[k][28] = livre; } } //Função que Imprime a matriz void imprime_matriz(int k, int l) { int i,j; printf("\n ----------------------- LABIRINTO -----------------------\n"); printf(" ------------------ EM BUSCA DA SOLUÇÃO ------------------\n"); for (i = 0; i < max; i++) { for (j = 0; j < max; j++){ if(labirinto[i][j] == parede){ printf(ANSI_COLOR_BLUE "# " ANSI_COLOR_RESET); } else if((i == k) && (j == l)) printf(ANSI_COLOR_YELLOW "@ " ANSI_COLOR_RESET); else if(labirinto[i][j] == livre) printf(" "); else if(labirinto[i][j] == visitada) printf(". "); else if(labirinto[i][j] == beco) printf(ANSI_COLOR_RED ". " ANSI_COLOR_RESET); else if(labirinto[i][j] == saida) printf(" "); else printf("E "); } printf("\n"); } } //Função Push - Empilha void push(int dado) { NODOPTR nodo; nodo= Cria_Nodo( ); nodo->elemento = dado; nodo->prox = pilha; pilha = nodo; } //Função Pop - Desempilha int pop( ) { NODOPTR nodo; int elem; if(!pilha) { printf("A pilha está vazia!!!"); return -1; } nodo = pilha; elem = nodo->elemento; pilha = nodo->prox; free(nodo); return elem; } //Função que gera inteiro a partir das coordenadas int calc_empilha(int i, int j){ int coordenada= i * 100 + j; return coordenada; } //Função que gera coordenadas a partir do inteiro void calc_desempilha(int *i, int *j, int coordenada){ *i = coordenada / 100; *j = coordenada % 100; } //Função que indica posições válidas para caminhar no labirinto int posicao_valida(int i, int j){ if(labirinto[i][j] == parede) return 0; else if(labirinto[i][j] == visitada) return 0; else if(labirinto[i][j] == beco) return 0; else if(labirinto[i][j] == saida) return 2; else return 1; } //Função que caminha no labirinto void cria_caminho(){ int i, j, k, p, v=0, aux[4]; i = j = 1; labirinto[i][j] = visitada; do{ imprime_matriz(i, j); k=0; //testes //Norte if( posicao_valida (i-1, j) == 1 ){ aux[k]= calc_empilha(i-1, j); k++; } else if(posicao_valida (i-1, j) == 2){ i = i-1; v = 1; break; } //Sul if( posicao_valida (i+1, j) == 1){ aux[k]= calc_empilha(i+1, j); k++; } else if(posicao_valida (i+1, j) == 2){ i = i+1; v = 1; break; } //Leste if( posicao_valida (i, j-1) == 1){ aux[k]= calc_empilha(i, j-1); k++; } else if(posicao_valida (i, j-1) == 2){ j = j-1; v = 1; break; } //Oeste if( posicao_valida (i, j+1) == 1){ aux[k]= calc_empilha(i, j+1); k++; } else if(posicao_valida (i, j+1) == 2){ j = j+1; v = 1; break; } if((k == 0) && (pilha != NULL)){ calc_desempilha( &i, &j, pop()); labirinto[i][j] = beco; } else if (k > 0) { p= rand() % k; push(aux[p]); calc_desempilha(&i, &j, aux[p]); labirinto[i][j] = visitada; } usleep(200000); system("clear"); }while((labirinto[i][j] != saida) && (pilha != NULL)); if(v){ imprime_matriz(i, j); printf("\nPARABÉNS, SAIDA ENCONTRADA!!\n"); sleep(2); } else{ imprime_matriz(i, j); printf("\nSAIDA NAO ENCONTRADA!!\n"); sleep(2); } } int menu(){ int a; system("clear"); printf("******************** O RATO E O LABIRINTO ********************\n\n"); printf("Entre com a opção desejada: \n\n"); printf("1 - Executar o labirinto\n"); printf("2 - Sair do programa\n"); scanf(" %d", &a); switch(a) { case 1: system("clear"); carrega_matriz(); cria_caminho(); break; case 2: system("clear"); printf("PROGRAMA FINALIZADO\n\n"); break; default: system("clear"); printf("\nOpcao Invalida!!!"); } return a; } void main(){ int a; srand( (unsigned)time(NULL) ); do{ a = menu(); }while(a != 2); }
C
//Program 37: Print the 8th pattern #include <stdio.h> void main() { int i,j,x; for(i=1;i<=4;i++) { x=i; for(j=1;j<=i;j++) { int p=(x%2==0)?0:1; printf("%d",p); x++; } printf("\n"); } } /* Output: 1 01 101 0101 */
C
#include<stdio.h> void swap(int *a,int *b); int main() { int a,b; scanf("%d %d",&a,&b); swap(&a,&b); printf("%d %d\n",a,b); return 0; } void swap(int *a,int *b) { int temp; temp = *a; *a = *b; *b = temp; }
C
#include <stdio.h> /* The program prints the Floyd's triangle for a given row size. */ int main() { int size; int number = 1; printf("Please enter a row size\n> "); scanf("%d", &size); printf("\n"); for (int row = 1; row <= size; row++) { for (int i = 1; i <= row; i++) { printf("%d ", number); number += 1; } printf("\n"); } printf("\n"); return 0; }
C
#include "Assignment_1_headder.h" struct dll { int info; struct dll *dll_llink; struct dll *dll_rlink; }; struct dll *dll_start = NULL; struct dll *dll_temp = NULL; struct dll *dll_p = NULL; int dll_count = 0; int double_linked(void) { int ch; do { printf("\n*************Double Linked List**************\n"); printf("\n1.insert\n2.delete\n3.display\n0.exit\nenter your option:\n"); scanf("%d", &ch); switch (ch) { case 0: break; case 1: dll_insert(); break; case 2: dll_deletion(); break; case 3: dll_display(); break; default: printf("invalid option.........\n"); } } while (ch != 0); return 0; } void dll_insert() { int ch; int num; int val; int dll_pos; printf("\n**********MENU**********\n"); printf("\n1.Insert at the beginning\n2.Insert at the end\n3. Insert at" "a given position\n4.Insert before a given position\n5.Insert" " after a given position\n6.Insert before a given number\n" "7.Insert after a given number\n8. Insert at the middle\n9." "Insert at penultimate node\n"); scanf("%d", &ch); printf("enter the element need to insert:\n"); scanf("%d", &num); switch (ch) { case 1: dll_i_begin(num); break; case 2: dll_i_end(num); break; case 3: printf("enter the position:\n"); scanf("%d", &dll_pos); dll_i_pos(num, dll_pos); break; case 4: printf("enter the position:\n"); scanf("%d", &dll_pos); if (dll_pos <= dll_count) { dll_i_pos(num, (dll_pos - 1)); } else { printf("it is not possible......!\n"); } break; case 5: printf("enter the position:\n"); scanf("%d", &dll_pos); if (dll_pos <= dll_count) { dll_i_pos(num, (dll_pos + 1)); } else { printf("it is not possible......!\n"); } break; case 6: printf("enter the number where insertion before that number :\n"); scanf("%d", &val); dll_i_bnum(num, val); break; case 7: printf("enter the number where insertion after that number :\n"); scanf("%d", &val); dll_i_anum(num, val); break; case 8: dll_i_mid(num); break; case 9: dll_i_pend(num); break; default: printf("invalid option......!\n"); break; } } void dll_deletion() { int ch; int dll_pos; int val; printf("\n1.Delete at the beginning\n2.delete at the end\n3.Deletion at" "a given position\n4.Deletion before a given position\n5.Deletion" " after a given position\n6.Deletion before a given number\n" "7.Deletion after a given number\n8.Deletion at the middle\n9." "Deletion at penultimate node\n"); scanf("%d", &ch); switch (ch) { case 1: dll_d_begin(); break; case 2: dll_d_end(); break; case 3: printf("enter the position:\n"); scanf("%d", &dll_pos); dll_d_pos(dll_pos); break; case 4: printf("enter the position:\n"); scanf("%d", &dll_pos); dll_d_pos((dll_pos - 1)); break; case 5: printf("enter the position:\n"); scanf("%d", &dll_pos); dll_d_pos((dll_pos + 1)); break; case 6: printf("enter the number where deletion before that number :\n"); scanf("%d", &val); dll_d_bnum(val); break; case 7: printf("enter the number where deletion after that number :\n"); scanf("%d", &val); dll_d_anum(val); break; case 8: dll_d_mid(); break; case 9: dll_d_pend(); break; default: printf("invalid option......!\n"); break; } } void dll_i_begin(int num) { dll_temp = (struct dll*)malloc(sizeof(struct dll)); dll_temp -> info = num; dll_temp -> dll_rlink = dll_start; dll_temp -> dll_llink = NULL; dll_start = dll_temp; dll_count++; } void dll_i_end(int num) { dll_p = dll_start; if (dll_start == NULL) { dll_i_begin(num); } else { dll_i_pos(num, dll_count+1); } } void dll_i_pos(int num, int dll_pos) { int i = 1; if (dll_pos == 1) { dll_i_begin(num); } else { dll_p = dll_start; dll_temp = (struct dll*)malloc(sizeof(struct dll)); dll_temp -> info = num; while (i < (dll_pos - 1)) { dll_p = dll_p -> dll_rlink; i++; } dll_temp -> dll_llink = dll_p; dll_temp -> dll_rlink = dll_p -> dll_rlink; if (dll_pos != (dll_count + 1)) { dll_p -> dll_rlink -> dll_llink = dll_temp; } dll_p -> dll_rlink = dll_temp; dll_count++; } } void dll_i_bnum(int num, int val) { int i = 1; if (dll_count == 0) { printf("list is empty your num is not there..!\n"); } else if (dll_start -> info == val) { dll_i_begin(num); } else { dll_p = dll_start; while(i <= dll_count) { if (dll_p -> info == val) { dll_i_pos(num, (i - 1)); break; } i++; dll_p = dll_p -> dll_rlink; } if (i > dll_count) { printf("the number is not present...!\n"); } } } void dll_i_anum(int num, int val) { int i = 1; if (dll_count == 0) { printf("list is empty your num is not there..!\n"); } else { dll_p = dll_start; while(i <= dll_count) { if (dll_p -> info == val) { dll_i_pos(num, (i + 1)); break; } i++; dll_p = dll_p -> dll_rlink; } if (i > dll_count) { printf("the number is not present...!\n"); } } } void dll_i_mid(int num) { if (dll_count%2 == 0) { dll_i_pos(num, dll_count/2); } else { dll_i_pos(num, (dll_count/2 + 1)); } } void dll_i_pend(int num) { dll_temp = (struct dll*)malloc(sizeof(struct dll)); dll_temp -> info = num; if(dll_count == 0) { printf("list is empty\n"); } else if (dll_count == 1) { dll_i_begin(num); } else { dll_i_pos(num, dll_count); } } // deletion of double linked lists void dll_d_begin() { if (dll_count == 0) { printf("list is empty......!\n"); } else { printf("the deleted element:%d \n", (dll_start -> info)); dll_start = dll_start -> dll_rlink; dll_count--; } } void dll_d_end() { if (dll_count == 0) { printf("list is empty......!\n"); } else if (dll_count == 1) { printf("the deleted element:%d \n", (dll_start -> info)); dll_start = NULL; dll_count--; } else { dll_p = dll_start; while (dll_p -> dll_rlink != '\0') { dll_p = dll_p -> dll_rlink; } printf("the deleted element:%d \n", (dll_p -> info)); dll_p -> dll_llink -> dll_rlink = NULL; dll_count--; } } void dll_d_pos(int dll_pos) { if (dll_count == 0) { printf("list is empty......!\n"); } else if (dll_pos > dll_count) { printf("it is not possble...!"); } else if (dll_pos == 1) { dll_d_begin(); } else if (dll_pos == dll_count){ dll_d_end(); }else { int i = 1; dll_p = dll_start; while (i < dll_pos) { dll_p = dll_p -> dll_rlink; i++; } dll_p -> dll_llink -> dll_rlink = dll_p -> dll_rlink; dll_p -> dll_rlink -> dll_llink = dll_p -> dll_llink; dll_count--; } } //deletion after number and before number void dll_d_bnum(int val) { int i = 1; if (dll_count == 0) { printf("list is empty...!\n"); } else if (dll_start -> info == val) { printf("no number is before that....!\n"); } else { dll_p = dll_start; while(i <= dll_count) { if (dll_p -> info == val) { dll_d_pos(i - 1); break; } i++; dll_p = dll_p -> dll_rlink; } if (i > dll_count) { printf("the number is not resent...!\n"); } } } void dll_d_anum(int val) { if (dll_count == 0) { printf("list is empty your num is not there..!\n"); } else if (dll_start -> info == val) { dll_d_pos(2); } else { int i = 1; dll_p = dll_start; while(i <= dll_count) { if (dll_p -> info == val) { dll_d_pos(i+1); break; } i++; dll_p = dll_p -> dll_rlink; } if (i > dll_count) { printf("invalid number...!\n"); } } } void dll_d_mid() { if (dll_count == 0) { printf("list is emdty......!\n"); } else if (dll_count%2 == 0) { dll_d_pos(dll_count/2); } else { dll_d_pos((dll_count/2) + 1); } } void dll_d_pend(int num) { if (dll_count > 1) { dll_d_pos((dll_count - 1)); } else { printf("there is no any penultimate for the list.....!!\n"); } } void dll_display() { if(dll_count == 0) { printf("no elements in the list\n"); } else { dll_p = dll_start; printf("Double linked list is:\n"); while (dll_p -> dll_rlink != '\0') { printf("%d\t", dll_p -> info); dll_p = dll_p -> dll_rlink; } printf("%d\t\n", dll_p -> info); } }
C
#include <stdio.h> #include <stdlib.h> /** * constant to represent infinity * it is assumed that no edge in the vertex will have weight equal * to this value. */ #define INF 9999 /** * total number of vertices in the graph */ #define V 9 //nodes number /** * this function will return the minimum value */ int findMin(int x, int y) { if (x < y) { return x; } return y; } /** * this function will check if the vertex is marked */ int isMarked(int v, int markedVertices[], int markedVerticesIdx) { int i = 0; for (i = 0; i < markedVerticesIdx; i++) { if (v == markedVertices[i]) { return 1; } } return 0; } /** * this function will find shortest path between source and destination vertex */ void dijkstra(int graph[V][V], int src, int dest) { //variables int i, r, c, tmpC, min, currVertex, edgeWt = 0, destValue = 0, markedValue = 0, wtTableR = 0, markedVerticesIdx = 0; /** * array containing vertices in the shortest path */ int shortestPathVertices[V] = {-1}; int shortestPathVerticesIdx = 0; /** * this table will hold the weight */ int weightTable[V][V]; for (r = 0; r < V; r++) { for (c = 0; c < V; c++) { weightTable[r][c] = INF; } } weightTable[wtTableR++][src] = 0; /** * vertices that are marked */ int markedVertices[V] = {-1}; markedVertices[markedVerticesIdx++] = src; currVertex = src; /** * find shortest path */ while(currVertex != dest) { /** * copy marked values to the next row of weightTable */ for (i = 0; i < markedVerticesIdx; i++) { c = markedVertices[i]; weightTable[wtTableR][c] = weightTable[wtTableR - 1][c]; } /** * find the weight from the current vertex to all the other * vertices that are directly connected and not yet marked */ for (c = 0; c < V; c++) { if (c != currVertex && !isMarked(c, markedVertices, markedVerticesIdx)) { edgeWt = graph[currVertex][c]; destValue = weightTable[wtTableR - 1][c]; markedValue = weightTable[wtTableR][currVertex]; min = findMin(destValue, markedValue + edgeWt); weightTable[wtTableR][c] = min; } } /** * find minimum unmarked vertices in current row */ min = INF; for (c = 0; c < V; c++) { if (!isMarked(c, markedVertices, markedVerticesIdx)) { if (weightTable[wtTableR][c] < min) { min = weightTable[wtTableR][c]; tmpC = c; } } } /** * found a new vertex for marking */ markedVertices[markedVerticesIdx++] = tmpC; currVertex = tmpC; /** * variables update */ wtTableR++; } /** * compute shortest path vertices */ c = dest; shortestPathVertices[shortestPathVerticesIdx++] = c; markedValue = weightTable[wtTableR - 1][dest]; for (r = wtTableR - 2; r >= 0; r--) { if (weightTable[r][c] != markedValue) { c = markedVertices[r]; markedValue = weightTable[r][c]; shortestPathVertices[shortestPathVerticesIdx++] = c; } } /** * display the weight and shortest path */ printf("Shortest Path between %d and %d\n", src, dest); for (i = shortestPathVerticesIdx-1; i >= 0; i--) { printf("%d", shortestPathVertices[i]); if (i > 0) { printf(" --> "); } } printf("\n"); printf("Weight of the path: %d\n", weightTable[wtTableR-1][dest]); } int main(void) { /** * 2d array which holds the weight of the edges */ int graph[V][V] = { {0, 4, INF, INF, INF, INF, INF, 8, INF}, {4, 0, 8, INF, INF, INF, INF, 11, INF}, {INF, 8, 0, 7, INF, 4, INF, INF, 2}, {INF, INF, 7, 0, 9, 14, INF, INF, INF}, {INF, INF, INF, 9, 0, 10, INF, INF, INF}, {INF, INF, 4, 14, 10, 0, 2, INF, INF}, {INF, INF, INF, INF, INF, 2, 0, 1, 6}, {8, 11, INF, INF, INF, INF, 1, 0, 7}, {INF, INF, 2, INF, INF, INF, 6, 7, 0} }; /** * source and destination vertices */ int src = 0; int dest = 6; /** * find shortest path */ dijkstra(graph, src, dest); return 0; }
C
/* getline.c -- Replacement for GNU C library function getline Copyright (C) 1993, 1996, 1997, 1998, 2000 Free Software Foundation, Inc. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* Written by Jan Brittenson, [email protected]. */ #if HAVE_CONFIG_H # include <config.h> #endif /* The `getdelim' function is only declared if the following symbol is defined. */ #ifndef _GNU_SOURCE # define _GNU_SOURCE 1 #endif #include <stdio.h> #include <sys/types.h> #if defined __GNU_LIBRARY__ && HAVE_GETDELIM int getline(char **lineptr, size_t * n, FILE * stream) { return getdelim(lineptr, n, '\n', stream); } #else /* ! have getdelim */ # include "getstr.h" int getline(char **lineptr, size_t * n, FILE * stream) { return getstr(lineptr, n, stream, '\n', 0, 0); } int getdelim(char **lineptr, size_t * n, int delimiter, FILE * stream) { return getstr(lineptr, n, stream, delimiter, 0, 0); } #endif
C
/* This program builds a large database and tests the time required for various * operations */ #include <stdio.h> #include <stdlib.h> #include <gdbm.h> #include <time.h> #define SIZE 1000000 // A function for timing functions int time_function(GDBM_FILE db, void(*fun)(GDBM_FILE)){ clock_t start; clock_t stop; start = clock(); fun(db); stop = clock(); return((stop - start) * 1000 / CLOCKS_PER_SEC); } // Build a big db, it will hold int keys and int values void build_db(GDBM_FILE db){ datum key; // key to stored data datum val; // stored data // insert a value int k,v; for(k = 0; k < SIZE; k++){ key.dptr = (void*)&k; key.dsize = sizeof(int); v = k % 5; val.dptr = (void*)&v; val.dsize = sizeof(int); gdbm_store(db, key, val, GDBM_REPLACE); } } void random_access(GDBM_FILE db){ int keyval; datum key; datum val; key.dsize = sizeof(int); for(int i = 0; i < SIZE; i++){ keyval = rand() % SIZE; key.dptr = (void*)&keyval; val = gdbm_fetch(db, key); free(val.dptr); } } void count_keys(GDBM_FILE db){ datum key = gdbm_firstkey(db); // iterate through all keys while(key.dptr){ datum nextkey; nextkey = gdbm_nextkey(db, key); free(key.dptr); key = nextkey; } } void dump(GDBM_FILE db){ datum key; datum val; int key_int; int val_int; // iterate through all keys key = gdbm_firstkey(db); while(key.dptr){ datum nextkey; val = gdbm_fetch(db, key); key_int = *(int*)key.dptr; val_int = *(int*)val.dptr; printf("%d\t%d\n", key_int, val_int); nextkey = gdbm_nextkey(db, key); free(key.dptr); key = nextkey; } } int main(){ GDBM_FILE db; int ms; // open a new database db = gdbm_open("database.db", 0, GDBM_WRCREAT, 0666, NULL); ms = time_function(db, build_db); printf("Added %d entries in %d ms\n", SIZE, ms); ms = time_function(db, count_keys); printf("Counted %d keys in %d ms\n", SIZE, ms); ms = time_function(db, random_access); printf("Randomly accessed %d keys in %d ms\n", SIZE, ms); gdbm_close(db); exit(EXIT_SUCCESS); }
C
#include <stdio.h> #include <assert.h> #include <stdlib.h> #include "cards.h" void assert_card_valid(card_t c) { assert (c.value>=2 && c.value<=VALUE_ACE); assert (c.suit>=SPADES && c.suit<=CLUBS); } const char * ranking_to_string(hand_ranking_t r) { switch (r) { case STRAIGHT_FLUSH: return "STRAIGHT_FLUSH"; break; case FOUR_OF_A_KIND: return "FOUR_OF_A_KIND"; break; case FULL_HOUSE: return "FULL_HOUSE"; break; case FLUSH: return "FLUSH"; break; case STRAIGHT: return "STRAIGHT"; break; case THREE_OF_A_KIND: return "THREE_OF_A_KIND"; break; case TWO_PAIR: return "TWO_PAIR"; break; case PAIR: return "PAIR"; break; case NOTHING: return "NOTHING"; break; default : return "?"; break;} } char value_letter (card_t c) { switch (c.value) { case 2: return '2'; break; case 3: return '3'; break; case 4: return '4'; break; case 5: return '5'; break; case 6: return '6'; break; case 7: return '7'; break; case 8: return '8'; break; case 9: return '9'; break; case 10:return '0'; break; case VALUE_JACK: return 'J'; break; case VALUE_QUEEN: return 'Q'; break; case VALUE_KING: return 'K'; break; case VALUE_ACE: return 'A'; break; default : return '?'; break; } } char suit_letter(card_t c) { switch (c.suit) { case SPADES: return 's'; break; case HEARTS: return 'h'; break; case DIAMONDS: return 'd'; break; case CLUBS: return 'c'; break; default : return '?'; break; }} void print_card(card_t c) { char value=value_letter(c); char suit=suit_letter(c); printf ("%c%c",value,suit); } card_t card_from_letters(char value_let, char suit_let) { card_t temp; switch (value_let) { case '2': temp.value=2; break; case '3': temp.value=3; break; case '4': temp.value=4; break; case '5': temp.value=5; break; case '6': temp.value=6; break; case '7': temp.value=7; break; case '8': temp.value=8; break; case '9': temp.value=9; break; case '0': temp.value=10; break; case 'J': temp.value=VALUE_JACK; break; case 'Q': temp.value=VALUE_QUEEN; break; case 'K': temp.value=VALUE_KING; break; case 'A': temp.value=VALUE_ACE; break;} switch(suit_let) { case 's' : temp.suit = SPADES; break; case 'h' : temp.suit = HEARTS; break; case 'd' : temp.suit = DIAMONDS; break; case 'c' : temp.suit = CLUBS; break; } assert_card_valid(temp); return temp; } card_t card_from_num(unsigned c) { card_t temp; temp.value = (c / 4) + 2; temp.suit = c % 4; return temp; }
C
/*** *vsprintf.c - print formatted data into a string from var arg list * * Copyright (c) 1985-1997, Microsoft Corporation. All rights reserved. * *Purpose: * defines vsprintf() and _vsnprintf() - print formatted output to * a string, get the data from an argument ptr instead of explicit * arguments. * *******************************************************************************/ #include <cruntime.h> #include <stdio.h> #include <dbgint.h> #include <stdarg.h> #include <internal.h> #include <limits.h> #include <mtdll.h> #define MAXSTR INT_MAX /*** *ifndef _COUNT_ *int vsprintf(string, format, ap) - print formatted data to string from arg ptr *else *int _vsnprintf(string, format, ap) - print formatted data to string from arg ptr *endif * *Purpose: * Prints formatted data, but to a string and gets data from an argument * pointer. * Sets up a FILE so file i/o operations can be used, make string look * like a huge buffer to it, but _flsbuf will refuse to flush it if it * fills up. Appends '\0' to make it a true string. * * Allocate the 'fake' _iob[] entryit statically instead of on * the stack so that other routines can assume that _iob[] entries are in * are in DGROUP and, thus, are near. * *ifdef _COUNT_ * The _vsnprintf() flavor takes a count argument that is * the max number of bytes that should be written to the * user's buffer. *endif * * Multi-thread: (1) Since there is no stream, this routine must never try * to get the stream lock (i.e., there is no stream lock either). (2) * Also, since there is only one staticly allocated 'fake' iob, we must * lock/unlock to prevent collisions. * *Entry: * char *string - place to put destination string *ifdef _COUNT_ * size_t count - max number of bytes to put in buffer *endif * char *format - format string, describes format of data * va_list ap - varargs argument pointer * *Exit: * returns number of characters in string * *Exceptions: * *******************************************************************************/ #ifndef _COUNT_ int __cdecl vsprintf ( char *string, const char *format, va_list ap ) #else /* _COUNT_ */ int __cdecl _vsnprintf ( char *string, size_t count, const char *format, va_list ap ) #endif /* _COUNT_ */ { FILE str; REG1 FILE *outfile = &str; REG2 int retval; _ASSERTE(string != NULL); _ASSERTE(format != NULL); outfile->_flag = _IOWRT|_IOSTRG; outfile->_ptr = outfile->_base = string; #ifndef _COUNT_ outfile->_cnt = MAXSTR; #else /* _COUNT_ */ outfile->_cnt = count; #endif /* _COUNT_ */ retval = _output(outfile,format,ap ); _putc_lk('\0',outfile); return(retval); }
C
#include <stdio.h> void func1(void); void func2(void); void func1(void) { int a = 520; printf("value of a is %d\n", a); printf("addr of a is %p\n", &a); } void func2(void) { int b = 880; printf("value of b is %d\n", b); printf("addr of b is %p\n", &b); } int main(void) { func1(); func2(); return 0; }
C
#include <stdio.h> #include <stdlib.h> #define inf 999 int main() { int m,n,min,i,j,book[10]={0},d[10],e[10][10],t1,t2,t3,s=0,sum=0; //ȷͱ printf("붥Լ:Ҫ9\n"); scanf("%d%d",&m,&n); //ʼ for(i=1;i<=m;i++) for(j=1;j<=m;j++) if(i==j) e[i][j]=0; else e[i][j]=inf; //¼Ȩ printf("ȨʽΪ Ȩ:\n"); for(i=1;i<=n;i++) { scanf("%d%d%d",&t1,&t2,&t3); e[t1][t2]=t3; e[t2][t1]=t3; } //ʼd for(i=1;i<=m;i++) d[i]=e[1][i]; //Prim㷨ʼ book[1]=1; s++; while(s!=m) { min=inf; for(i=1;i<=m;i++) { if(book[i]==0 && d[i]<min) { j=i; min=d[i]; } } book[j]=1; s++; sum+=min; for(i=1;i<=m;i++) { if(book[i]==0 && d[i]>e[j][i]) d[i]=e[j][i]; } } printf("СȨ֮Ϊ%d",sum); return 0; }
C
// (c) 2020 shdown // This code is licensed under MIT license (see LICENSE.MIT for details) #include "lexer.h" #include "ht.h" #include "hash.h" enum { BLOCKY_BIT = 1 << 10, }; enum { LEVEL_EXPR, LEVEL_STMT, }; typedef struct { char *data; size_t size; size_t capacity; size_t blocky_level; char is_expr_context; } LevelStack; static LevelStack level_stack_new(void) { return (LevelStack) {NULL, 0, 0, (size_t) -1, 0}; } static void level_stack_push(LevelStack *s, char level) { if (s->size == s->capacity) { s->data = uu_x2realloc(s->data, &s->capacity, 1); } s->data[s->size++] = level; s->is_expr_context = (level == LEVEL_EXPR); } static void level_stack_set_blocky(LevelStack *s) { s->blocky_level = s->size; } static void level_stack_push_blocky(LevelStack *s) { char level = LEVEL_EXPR; if (s->blocky_level == s->size) { s->blocky_level = -1; level = LEVEL_STMT; } level_stack_push(s, level); } static void level_stack_pop(LevelStack *s) { if (!s->size) return; --s->size; s->is_expr_context = (s->size && s->data[s->size - 1] == LEVEL_EXPR); } static void level_stack_free(LevelStack *s) { free(s->data); } static Ht make_keywords_ht(void) { typedef struct { const char *spelling; LexemeKind kind; char is_blocky; } Keyword; static const Keyword keywords[] = { {"fun", LK_FUN, 1}, {"if", LK_IF, 1}, {"else", LK_ELSE, 1}, {"elif", LK_ELIF, 1}, {"for", LK_FOR, 1}, {"while", LK_WHILE, 1}, {"break", LK_BREAK, 0}, {"continue", LK_CONTINUE, 0}, {"return", LK_RETURN, 0}, {"true", LK_TRUE, 0}, {"false", LK_FALSE, 0}, {"nil", LK_NIL, 0}, {0}, }; Ht ht = ht_new(1); for (const Keyword *p = keywords; p->spelling; ++p) { const char *spelling = p->spelling; size_t nspelling = strlen(spelling); uint32_t hash = hash_str(spelling, nspelling); uint32_t value = p->kind | (p->is_blocky ? BLOCKY_BIT : 0); ht_insert_new_unchecked(&ht, spelling, nspelling, hash, value); } return ht; } struct Lexer { const char *cur; const char *end; size_t line_num; const char *line_start; LevelStack level_stack; char inserted_semicolon_flag; Ht keywords; const char *err_msg; }; Lexer *lexer_new(const char *source, size_t nsource) { Lexer *x = uu_xmalloc(1, sizeof(Lexer)); *x = (Lexer) { .cur = source, .end = source + nsource, .line_num = 1, .line_start = source, .level_stack = level_stack_new(), .inserted_semicolon_flag = 0, .keywords = make_keywords_ht(), .err_msg = NULL, }; return x; } static inline Lexeme make_lexeme(Lexer *x, LexemeKind kind, const char *start) { return (Lexeme) { .kind = kind, .start = start, .size = x->cur - start, .pos = { .line = x->line_num, .column = start - x->line_start + 1, }, }; } static inline Lexeme make_lexeme_advance(Lexer *x, LexemeKind kind, size_t size) { const char *start = x->cur; x->cur += size; return make_lexeme(x, kind, start); } static inline Lexeme make_error_advance(Lexer *x, const char *msg, size_t size) { x->err_msg = msg; return make_lexeme_advance(x, LK_ERROR, size); } static inline Lexeme choice1223( Lexer *x, LexemeKind if_a, char b, LexemeKind if_ab, char c, LexemeKind if_ac, char d, LexemeKind if_acd) { if (x->cur + 1 != x->end) { if (x->cur[1] == b) { return make_lexeme_advance(x, if_ab, 2); } if (c != '\0' && x->cur[1] == c) { if (d != '\0' && x->cur + 2 != x->end && x->cur[2] == d) { return make_lexeme_advance(x, if_acd, 3); } return make_lexeme_advance(x, if_ac, 2); } } return make_lexeme_advance(x, if_a, 1); } static Lexeme number(Lexer *x) { const char *start = x->cur; bool seen_dot = false; for (;;) { ++x->cur; if (UU_UNLIKELY(x->cur == x->end)) goto out; switch (*x->cur) { case '0' ... '9': case '\'': break; case '.': if (seen_dot) goto out; seen_dot = true; break; default: goto out; } } out: return make_lexeme(x, LK_NUMBER, start); } static Lexeme string(Lexer *x) { const char *start = x->cur; for (;;) { ++x->cur; if (UU_UNLIKELY(x->cur == x->end)) return make_error_advance(x, "unterminated string (EOF reached)", 0); switch (*x->cur) { case '"': ++x->cur; return make_lexeme(x, LK_STRING, start); case '\\': ++x->cur; if (UU_UNLIKELY(x->cur == x->end)) return make_error_advance(x, "unterminated string (EOF reached)", 0); break; case '\n': return make_error_advance(x, "unterminated string (EOL reached)", 0); } } } static Lexeme identifier(Lexer *x) { const char *start = x->cur; for (;;) { ++x->cur; if (UU_UNLIKELY(x->cur == x->end)) goto out; switch (*x->cur) { case '0' ... '9': case 'a' ... 'z': case 'A' ... 'Z': case '_': break; default: goto out; } } out: (void) 0; size_t size = x->cur - start; uint32_t value = ht_get(&x->keywords, start, size, hash_str(start, size), LK_IDENT); if (value & BLOCKY_BIT) { level_stack_set_blocky(&x->level_stack); value &= ~BLOCKY_BIT; } return make_lexeme(x, value, start); } static inline Lexeme fake_semicolon(Lexer *x) { return make_lexeme_advance(x, LK_SEMICOLON, 0); } static inline bool insert_semicolon(Lexer *x) { if (x->level_stack.is_expr_context) { return false; } if (x->inserted_semicolon_flag) { x->inserted_semicolon_flag = 0; return false; } x->inserted_semicolon_flag = 1; return true; } static Lexeme token(Lexer *x) { switch (*x->cur) { case '0' ... '9': return number(x); case 'a' ... 'z': case 'A' ... 'Z': case '_': return identifier(x); case '"': return string(x); case '!': return choice1223(x, LK_BANG, '=', LK_BANG_EQ, 0, 0, 0, 0); case '%': return choice1223(x, LK_PERCENT, '=', LK_PERCENT_EQ, 0, 0, 0, 0); case '&': return choice1223(x, LK_AND, '=', LK_AND_EQ, '&', LK_AND_AND, '=', LK_AND_AND_EQ); case '|': return choice1223(x, LK_OR, '=', LK_OR_EQ, '|', LK_OR_OR, '=', LK_OR_OR_EQ); case '(': level_stack_push(&x->level_stack, LEVEL_EXPR); return make_lexeme_advance(x, LK_LPAREN, 1); case ')': level_stack_pop(&x->level_stack); return make_lexeme_advance(x, LK_RPAREN, 1); case '*': return choice1223(x, LK_STAR, '=', LK_STAR_EQ, '*', LK_STAR_STAR, '=', LK_STAR_STAR_EQ); case '+': return choice1223(x, LK_PLUS, '=', LK_PLUS_EQ, 0, 0, 0, 0); case '-': return choice1223(x, LK_MINUS, '=', LK_MINUS_EQ, '>', LK_MINUS_GREATER, 0, 0); case ',': return make_lexeme_advance(x, LK_COMMA, 1); case '.': return make_lexeme_advance(x, LK_DOT, 1); case '@': return make_lexeme_advance(x, LK_AT, 1); case '/': return choice1223(x, LK_SLASH, '=', LK_SLASH_EQ, '/', LK_SLASH_SLASH, '=', LK_SLASH_SLASH_EQ); case ':': return choice1223(x, LK_COLON, '=', LK_COLON_EQ, 0, 0, 0, 0); case ';': return make_lexeme_advance(x, LK_SEMICOLON, 1); case '<': return choice1223(x, LK_LESS, '=', LK_LESS_EQ, '<', LK_LESS_LESS, '=', LK_LESS_LESS_EQ); case '=': return choice1223(x, LK_EQ, '=', LK_EQ_EQ, 0, 0, 0, 0); case '>': return choice1223(x, LK_GREATER, '=', LK_GREATER_EQ, '>', LK_GREATER_GREATER, '=', LK_GREATER_GREATER_EQ); case '[': level_stack_push(&x->level_stack, LEVEL_EXPR); return make_lexeme_advance(x, LK_LBRACKET, 1); case ']': level_stack_pop(&x->level_stack); return make_lexeme_advance(x, LK_RBRACKET, 1); case '^': return choice1223(x, LK_HAT, '=', LK_HAT_EQ, 0, 0, 0, 0); case '{': level_stack_push_blocky(&x->level_stack); return make_lexeme_advance(x, LK_LBRACE, 1); case '~': return choice1223(x, LK_TILDE, '=', LK_TILDE_EQ, 0, 0, 0, 0); case '}': if (insert_semicolon(x)) return fake_semicolon(x); level_stack_pop(&x->level_stack); return make_lexeme_advance(x, LK_RBRACE, 1); default: return make_error_advance(x, "unexpected symbol", 1); } } Lexeme lexer_next(Lexer *x) { for (;;) { if (UU_UNLIKELY(x->cur == x->end)) { if (insert_semicolon(x)) return fake_semicolon(x); return make_lexeme_advance(x, LK_EOF, 0); } switch (*x->cur) { case ' ': case '\t': ++x->cur; break; case '\n': if (insert_semicolon(x)) return fake_semicolon(x); ++x->cur; ++x->line_num; x->line_start = x->cur; break; case '#': do { ++x->cur; } while (x->cur != x->end && *x->cur != '\n'); break; default: return token(x); } } } const char *lexer_error_msg(Lexer *x) { return x->err_msg; } void lexer_destroy(Lexer *x) { level_stack_free(&x->level_stack); ht_destroy(&x->keywords); free(x); }
C
#include "native.h" #include "vm.h" #include "comet.h" #include <string.h> #include <stdio.h> void defineNativeFunction(VM *vm, const char *name, NativeFn function) { push(vm, OBJ_VAL(newNativeFunction(vm, function))); push(vm, copyString(vm, name, (int)strlen(name))); addGlobal(peek(vm, 0), peek(vm, 1)); pop(vm); pop(vm); } VALUE bootstrapNativeClass(VM *vm, const char *name, NativeConstructor constructor, NativeDestructor destructor, ClassType classType) { return OBJ_VAL(newNativeClass(vm, name, constructor, destructor, classType)); } VALUE completeNativeClassDefinition(VM *vm, VALUE klass_, const char *super_name) { ObjClass *klass = AS_CLASS(klass_); Value name_string = copyString(vm, klass->name, (int)strlen(klass->name)); push(vm, name_string); if (string_compare_to_cstr(name_string, "Object") != 0) { Value parent; if (super_name == NULL) { super_name = "Object"; } if (!findGlobal(copyString(vm, super_name, (int)strlen(super_name)), &parent)) { runtimeError(vm, "Could not inherit from unknown class '%s'", super_name); return NIL_VAL; } ObjClass *parent_class = AS_CLASS(parent); tableAddAll(&parent_class->methods, &klass->methods); tableAddAll(&parent_class->staticMethods, &klass->staticMethods); for (int i = 0; i < NUM_OPERATORS; i++) { klass->operators[i] = parent_class->operators[i]; } klass->super_ = AS_CLASS(parent); } if (addGlobal(name_string, OBJ_VAL(klass))) { pop(vm); pop(vm); return OBJ_VAL(klass); } else { runtimeError(vm, "Redefining class %s", klass->name); return NIL_VAL; } } VALUE defineNativeClass(VM *vm, const char *name, NativeConstructor constructor, NativeDestructor destructor, const char *super_name, ClassType classType) { VALUE klass = OBJ_VAL(newNativeClass(vm, name, constructor, destructor, classType)); return completeNativeClassDefinition(vm, klass, super_name); } void defineNativeMethod(VM *vm, VALUE klass, NativeMethod function, const char *name, uint8_t arity, bool isStatic) { Value name_string = copyString(vm, name, strlen(name)); push(vm, name_string); push(vm, klass); push(vm, OBJ_VAL(newNativeMethod(vm, function, arity, isStatic, name_string))); defineMethod(vm, name_string, isStatic); pop(vm); pop(vm); } void defineNativeOperator(VM *vm, VALUE klass, NativeMethod function, uint8_t arity, OPERATOR operator) { const char *op_method_chars = getOperatorString(operator); Value op_method_name = copyString(vm, op_method_chars, strlen(op_method_chars)); push(vm, op_method_name); push(vm, klass); push(vm, OBJ_VAL(newNativeMethod(vm, function, arity, false, op_method_name))); defineOperator(vm, operator); pop(vm); pop(vm); } void setNativeProperty(VM *vm, VALUE self, const char *property_name, VALUE value) { push(vm, self); push(vm, value); Value name_string = copyString(vm, property_name, strlen(property_name)); push(vm, name_string); tableSet(&AS_INSTANCE(self)->fields, name_string, value); pop(vm); pop(vm); pop(vm); } VALUE getNativeProperty(VM *vm, VALUE self, const char *property_name) { Value value; Value name_string = copyString(vm, property_name, strlen(property_name)); if (tableGet(&AS_INSTANCE(self)->fields, name_string, &value)) { return value; } return NIL_VAL; }
C
#include <stdio.h> #include <string.h> #include "../util.h" char * get_engine(void) { FILE *pf; char command[20]; char data[512]; char *engine; sprintf(command, "ibus engine"); pf = popen(command, "r"); fgets(data, 512, pf); data[strlen(data) - 1] = '\0'; if (pclose(pf) != 0) { engine = (char *)bprintf("%s", "error"); } else { engine = (char *)bprintf("%s", data); } return engine; } const char * ibus_engine(void) { char *engine; engine = get_engine(); if(strcmp(engine, "xkb:us::eng") == 0) { return (char *)bprintf("%s", "en"); } else if(strcmp(engine, "OpenBangla") == 0) { return (char *)bprintf("%s", "bn"); } return engine; }
C
#include "LPC17xx.h" #include "stdio.h" #define NUM 198 // EE2024 Assignment 1 skeleton code // (C) CK Tham, ECE, NUS, 2018 // Do not modify the following function prototype extern int asm_stats(int* px, int* pvar, int* pmin, int* pmax); typedef struct data { int x[NUM]; int mean; int variance; int min; int max; } dataset; // Do not modify the following function prototype void compute_stats(dataset* dptr) { // Write the code to call asm_stats() function // in an appropriate manner to compute the statistical parameters asm_stats(dptr->x, dptr->variance, dptr->min, dptr->max); } int main(void) { int i; // Instantiate a dataset object X dataset X; // Initialize the dataset object X for (i=0;i<NUM;i++) X.x[i] = i-100; X.mean = X.variance = X.min = X.max = 0; // Call compute_stats() function in an appropriate manner to process the dataset object X compute_stats(&X); // Print out the contents of the dataset object X for (i=0;i<NUM;i++) printf("x[%d]: %d\n", i, X.x[i]); printf("mean: %d\n", X.mean); printf("variance: %d\n", X.variance); printf("min: %d\n", X.min); printf("max: %d\n", X.max); // Enter an infinite loop, just incrementing a counter. // Do not modify the code below. It enables values or variables and registers to be inspected before the program ends. volatile static int loop = 0; while (1) { loop++; } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> //void inti(struct stack *);//initialize stack members //void push(struct stack *, int);//grow contents to store int //int pop(struct stack *); //shrink contents and return top int struct node{ int val; //integer node value struct node *next; //pointer to next node }; struct stack { struct node *head; //pointer to first node in stack struct node *tail; //pointer to top of stack }; void init(struct stack *s){ s->head = NULL; s->tail = NULL; } void push(struct stack *s, int val){ struct node *new_node = malloc(sizeof(struct node)); new_node->val = val; new_node->next = NULL; if(s->head == NULL){ s->head = new_node; s->tail = new_node; } else{ s->tail->next = new_node; s->tail = new_node; } } int pop(struct stack *s){ struct node *t = s->head; int val = s->tail->val; if (s->head == s->tail){ free(s->head); s->head = s->tail = NULL; return val; } while(t->next != s->tail){ t = t->next; } free(s->tail); s->tail = t; s->tail->next = NULL; return val; } void print(struct stack *s){ struct node *t = s->head; while(t != NULL){ printf("%d\n", t->val ); t = t->next; } printf("\n"); } int main(){ struct stack s; init(&s); /* push(&s, 7); push(&s, 1); push(&s, 10); print(&s); printf("popped :%d\n", pop(&s) ); //push(&s, 9); //push(&s, 23); print(&s); printf("popped: %d\n", pop(&s)); print(&s); pop(&s); //print(&s); */ printf("popped :%d\n", pop(&s) ); }
C
/** * @file adc.h * @brief ADC - Analog-to-Digital Converter * @details This API is used to read values from the ADC-channels. * @pre Initiate board and enable peripheral clock for ADC. * * Important: Not all functionality of the ADC is implemented in this API yet. * * @author Hisham Ramish * @author Mattias Nilsson * @author Prince Balabis * @author Andreas Drotth * @date 16 October 2014 */ #ifndef ADC_H_ #define ADC_H_ #include <inttypes.h> ///@cond // pointer to registers of ADC, base address: 0x400C0000 #define ADC ((adc_reg_t *) 0x400C0000U) ///@endcond // Valid DACC channels #define ADC_CHANNEL_0 0 ///< ADC Channel 0 #define ADC_CHANNEL_1 1 ///< ADC Channel 1 #define ADC_CHANNEL_2 2 ///< ADC Channel 2 #define ADC_CHANNEL_3 3 ///< ADC Channel 3 #define ADC_CHANNEL_4 4 ///< ADC Channel 4 #define ADC_CHANNEL_5 5 ///< ADC Channel 5 #define ADC_CHANNEL_6 6 ///< ADC Channel 6 #define ADC_CHANNEL_7 7 ///< ADC Channel 7 #define ADC_CHANNEL_8 8 ///< ADC Channel 8 #define ADC_CHANNEL_9 9 ///< ADC Channel 9 #define ADC_CHANNEL_10 10 ///< ADC Channel 10 #define ADC_CHANNEL_11 11 ///< ADC Channel 11 #define ADC_CHANNEL_12 12 ///< ADC Channel 12 #define ADC_CHANNEL_13 13 ///< ADC Channel 13 #define ADC_CHANNEL_14 14 ///< ADC Channel 14 #define ADC_CHANNEL_15 15 ///< ADC Channel 15 // Resolution values #define ADC_RESOLUTION_10_BIT 1 ///< ADC 10 bit resolution #define ADC_RESOLUTION_12_BIT 0 ///< ADC 12 bit resolution ///@cond /* * Set specified bit levels in a register at specified position. * The bit mask should consist of a number of high bits. * This macro function could be of common use..... */ #define _SET_BIT_LEVELS(reg, levels, bit_mask, pos) \ ((reg & ~((bit_mask) << (pos))) | ((levels) << (pos))) #define ADC_MR_SET_RESOLUTION(reg, bits) \ _SET_BIT_LEVELS(reg, bits, 0x1u, 4) // Highest channel ID #define ADC_CHANNEL_MAX (15) // ADC_CR: (ADC Offset: 0x0000) Control Register #define ADC_CR_START (0x1u << 1) #define ADC_CR_RESET (0x1u << 0) // ADC_MR: (ADC Offset: 0x0004) Mode Register #define ADC_MR_RESET (0) #define ADC_MR_PRES_POS (8) #define ADC_MR_SUT0 (0x0u << 16) #define ADC_MR_SUT8 (0x1u << 16) #define ADC_MR_SUT16 (0x2u << 16) #define ADC_MR_SUT24 (0x3u << 16) #define ADC_MR_SUT64 (0x4u << 16) #define ADC_MR_SUT80 (0x5u << 16) #define ADC_MR_SUT96 (0x6u << 16) #define ADC_MR_SUT112 (0x7u << 16) #define ADC_MR_SUT512 (0x8u << 16) #define ADC_MR_SUT576 (0x9u << 16) #define ADC_MR_SUT640 (0xAu << 16) #define ADC_MR_SUT704 (0xBu << 16) #define ADC_MR_SUT768 (0xCu << 16) #define ADC_MR_SUT832 (0xDu << 16) #define ADC_MR_SUT896 (0xEu << 16) #define ADC_MR_SUT960 (0xFu << 16) #define ADC_MR_RES(resolution) \ ((resolution) << 4) // ADC_ISR: (ADC Offset: 0x0030) Interrupt Status Register #define ADC_ISR_DRDY (0x01 << 24) /* * Mapping of ADC registers * Base address: 0x400E0800 */ typedef struct { // Control Register, offset 0x0000 uint32_t ADC_CR; // Mode Register, offset 0x0004 uint32_t ADC_MR; // Channel Sequence Register 1, offset 0x0008 uint32_t ADC_SEQR1; // Channel Sequence Register 2, offset 0x00C uint32_t ADC_SEQR2; // Channel Enable Register, offset 0x0010 uint32_t ADC_CHER; // Channel Disable Register, offset 0x0014 uint32_t ADC_CHDR; // Channel Status Register, offset 0x0018 uint32_t ADC_CHSR; // Reserved, offset 0x001C uint32_t reserved1[1]; // Last Converted Data Register, offset 0x0020 uint32_t ADC_LCDR; // Interrupt Enable Register, offset 0x0024 uint32_t ADC_IER; // Interrupt Disable Register, offset 0x0028 uint32_t ADC_IDR; // Interrupt Mask Register, offset 0x002C uint32_t ADC_IMR; // Interrupt Status Register, offset 0x0030 uint32_t ADC_ISR; // Reserved, offset 0x0034 and 0x0038 uint32_t reserved2[2]; // Overrun Status Register, offset 0x003C uint32_t ADC_OVER; // Extended Mode Register, offset 0x0040 uint32_t ADC_EMR; // Compare Window Register, offset 0x0044 uint32_t ADC_CWR; // Channel Gain Register, offset 0x0048 uint32_t ADC_CGR; // Channel Offset Register, offset 0x004C uint32_t ADC_COR; // Channel Data Register, offset 0x0050 to 0x008C uint32_t ADC_CDR[16]; // Reserved, offset 0x90 uint32_t reserved3; // Analog Control Register, offset 0x0094 uint32_t ADC_ACR; // Reserved, offset 0x0098 to 0x00E0 uint32_t reserved4[19]; // Write Protect Mode Register, offset 0x00E4 uint32_t ADC_WPMR; // Write Protect Status Register, offset 0x00E8 uint32_t ADC_WPSR; // Reserved, offset 0x00EC to 0x00FC uint32_t reserved5[5]; } adc_reg_t; ///@endcond /** * Input parameters when initializing the ADC. */ typedef struct { /** * Set the startup time of the ADC. */ uint32_t startup_time; /** * Set the preferred prescaler. * Valid values are between 0-255. * ADCClock = MCK / ((PRESCAL+1) * 2) */ uint32_t prescaler; } adc_settings_t; /** * Initializes the ADC. * @param adc_settings Pointer to settings for the initlization (startuptime, precaler). */ void adc_init(adc_settings_t * adc_settings); /** * Starts the ADC. */ void adc_start(void); /** * Resets the ADC. */ void adc_reset(void); /** * Sets ADC resolution to 10 bits or 12 bits. 12 bits is default after initiation. * @param resolution The resolution of the ADC. */ void adc_set_resolution(uint32_t resolution); /** * Enables a specific channel. * Channel 15 is used for temperature-reader. * @param channel The channel (0-15) that is to be enabled. * Nothing will happen if the specified channel is out of bounds. */ void adc_enable_channel(uint32_t channel); /** * Disables a specific channel. * @param channel The channel (0-15) that is to be disabled. * Nothing will happen if the specified channel is out of bounds. */ void adc_disable_channel(uint32_t channel); /** * Reads the status for a specific channel. Channel 0-15 is available for readout. * @param channel The channel (0-15) that the status is asked for. * @return If the channel is enabled, returns 1. Otherwise returns 0. * @return 0 is also returned if the specified channel is out of bounds. */ uint32_t adc_channel_enabled(uint32_t channel); /** * Read the values from a specific channel. Channel 0-15 is available. * @param channel The channel (0-15) that is to be read from. * @return ADC value of the specific channel. */ uint32_t adc_read_channel(uint32_t channel); #endif
C
#include "types.h" #include "stat.h" #include "user.h" int x = 0; int thread_func(void *arg) { int id = (int) arg; printf("Hello from thread %d\n", arg); x = 99; thread_exit(0); } int main(int argc, char **argv) { void *m; void *stack; struct thread t; int rv; stack = malloc(4096); printf("x = %d\n", x); thread_create(&t, thread_func, stack, (void *) 0); rv = thread_join(&t); printf("x = %d\n", x); }
C
/* ַ */ #include<stdlib.h> main() { int i,j; char a[][5]={{'B','a','s','i','c'},{'D','b','a','s','e'}}; for(i=0;i<=1;i++) { for(j=0;j<=4;j++) printf("%c",a[i][j]); printf("\n"); } getch(); }
C
/* The module game contain the board that we are playing on and the solution of this borad. The module is used to manipulate the game status, validate, set, restart, exit game, printing sudoku board ect. The game takes place in this module. */ #ifndef GAME_H_ #define GAME_H_ #include<stdbool.h> /*mode: 1 - solve command and 2 - edit and 0 - init*//*######delete??#######*/ int idCommand; /*1 - solve command and 2 - edit and 0 - else 3-save*/ int blockHeight, blockWidth, N; /*blockHeight=m; blockWidth=n; N=n*m*/ int numOfEmptyCells; /*the number of empty cells in the sudoku*/ /* The struct node will respresent every 'cell' in the doubly linked list below it's field: row- the row of the node's cell col- the coulmn of the node's cell value- the value of the node's cell oldVal- the previous value of the node's cell next- the next node in the linked list prev- the previous node in the linked list */ typedef struct node { int row, col, value, oldValue, autoCells, generateCells; struct node* next; struct node* prev; }node; /* The struct linkedeList will represent a doubly linked list for the undo/redo list. We will also use this struct as a field for each cell in the sudoku. it's fields: head- a pointer to the first node in the linked list current- a pointer to the current node (for undo/redo list) tail- a pointer to the last node in the linked list len- the length of the linked list */ typedef struct linkedList { node* head; node* current; node* tail; int len; }linkedList; /* The struct cell will represent every cell in the sudoku. his fields: value - the value of the cell fixed - 0 -> the cell isnt fixed, 1 - otherwise empty - 0 -> the cell isnt empty, 1 - otherwise arr - this field is being used in the random backtrack algorithm: arr[0] - the number of candidate that can be in the cell value arr[1] - arr[(blockHeight*blockWidth) + 1]: 1 - if the index (that represent the value) is a candidate and 0 - otherwise */ typedef struct cell_t { int value; int fixed; /*0 meaning not used*/ int empty; int arr[10]; int erroneous; linkedList erroneousNeib; }Cell; /* This function get value and create the cell with the value and the other fields will be default : cell->value = value; cell->fixed = 0; cell->empty = 0; cell->arr[0] = 0; */ Cell* createCell(int value); /* This function checks if the num parameter is valid in the row of the sudoku. (checks if num is already exist in the row of the sudoku) @return True - the num parameter doesnt exist False - otherwise */ bool isRowValidGame(Cell** sudoku, int row, int col, int num); /* This function checks if the num parameter is valid in the column of the sudoku. (checks if num is already exist in the column of the sudoku) @return True - the num parameter doesnt exist False - otherwise */ bool isColValidGame(Cell** sudoku, int row, int col, int num); /* This function checks if the num parameter is valid in the block of the sudoku. (checks if num is already exist in the block of the sudoku) @return True - the num parameter doesnt exist False - otherwise */ bool isBlockValidGame(Cell** sudoku, int startRow, int startCol, int row, int col, int num); /* The goal of the function is to receive commands and continue to play according to this commands from the user. This function is actually the place that the game occure. */ void playGame(); #endif /*GAME_H_*/
C
/* * Programming Assignment #1_2 * ۼ : 20160074 ȭаа * ۼ : 160929 */ #include <stdio.h> #include <math.h> int main() { // int x1, x2, x3, y1, y2, y3; double S, s, l12, l13, l23; //ǥ Է printf("Enter P1 (x1, y1) : "); scanf("%d%d", &x1, &y1); printf("Enter P2 (x2, y2) : "); scanf("%d%d", &x2, &y2); printf("Enter P3 (x3, y3) : "); scanf("%d%d", &x3, &y3); //ﰢ ̿ s, S l12 = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); l13 = sqrt((x3 - x1) * (x3 - x1) + (y3 - y1) * (y3 - y1)); l23 = sqrt((x3 - x2) * (x3 - x2) + (y3 - y2) * (y3 - y2)); s = (l12 + l13 + l23) / 2; S = sqrt(s*(s - l12)*(s - l13)*(s - l23)); // printf("The perimeter of triangle is : %.3lf\n", 2 * s); printf("The area of triangle is : %.3lf\n",S); return 0; }
C
#include <stdio.h> #include <stdlib.h> int foo(int tab[][100], int unsigned n) { int wynik = 0; for(int i=0; i<n; i++) { for(int j=0; j<100; j++) { tab[i][j] = rand() % 100+1; wynik += tab[i][j]; } } return wynik; } int main() { int tablica[50][100]; printf("%d",foo(tablica,50)); return 0; }
C
#include <git2.h> #include <stdio.h> #include <string.h> #include "common.h" int parse_pkt_line(git_repository *repo, int argc, char **argv) { char *line = argv[1]; char oid[GIT_OID_HEXSZ+1] = {0}; const char *after = line; int error; unsigned int len; git_pkt *pkt; /* * Assume that the user has piped a file in */ fseek(stdin, 0, SEEK_END); len = ftell(stdin); fseek(stdin, 0, SEEK_SET); line = malloc(len+1); if(line == NULL) return GIT_ENOMEM; memset(line, 0, len+1); fread(line, len, sizeof(char), stdin); after = line; while(*after != '\0'){ error = git_pkt_parse_line(&pkt, line, &after, len); if (error < GIT_SUCCESS) return error; line = (char *) after; switch(pkt->type){ case GIT_PKT_REF: { git_remote_head *h = &(((git_pkt_ref *)pkt)->head); const char *caps = ((git_pkt_ref *)pkt)->capabilities; //puts("Found a ref pkt"); git_oid_fmt(oid, &h->oid); printf("%s\t%s\n", oid, h->name); if(caps != NULL) printf(" Capabilities: %s\n", caps); break; } case GIT_PKT_FLUSH: puts("flush! do something!"); default: printf("default: %d\n", *after); } } return error; }
C
#include "main.h" #include "malloc_safe.h" #include "iface_usart.h" #include "utils/timebase.h" #include "utils/circbuf.h" #include "com/com_fileio.h" #include "com/debug.h" #include "bus/event_queue.h" #define DEF_WAIT_TO_MS 5 typedef struct { uint16_t wait_timeout; USART_TypeDef *dev; CircBuf *rxbuf; // allocated receive buffer CircBuf *txbuf; // allocated transmit buffer, can be NULL -> no buffer } usart_opts; #define opts(iface) ((usart_opts *)(iface)->opts) // ---- Instances ---- // (needed for async rx/tx with interrupts) static ComIface *usart1_iface = NULL; static ComIface *usart2_iface = NULL; static ComIface *usart3_iface = NULL; // ------------------- /** Check if data is ready for reading */ static bool if_rx_rdy(ComIface *iface) { CircBuf *buf = opts(iface)->rxbuf; return !cbuf_empty(buf); } /** Check if sending is done */ static bool if_tx_rdy(ComIface *iface) { CircBuf *buf = opts(iface)->txbuf; if (buf == NULL) { // non-buffered mode USART_TypeDef* USARTx = opts(iface)->dev; return (USARTx->SR & USART_SR_TXE); } return !cbuf_full(buf); } /** Check if sending is done */ static bool if_tx_done(ComIface *iface) { CircBuf *buf = opts(iface)->txbuf; USART_TypeDef* USARTx = opts(iface)->dev; // NULL buffer is considered empty return cbuf_empty(buf) && (USARTx->SR & USART_SR_TC); } /** Read one byte (wait for it). False on error. */ static bool if_rx(ComIface *iface, uint8_t *b) { // wait for data in the buffer if (!com_rx_wait(iface, opts(iface)->wait_timeout) || b == NULL) { return false; } // read from buffer cbuf_pop(opts(iface)->rxbuf, b); return true; } /** Try to unreceive a byte. False on error. */ static bool if_unrx(ComIface *iface, uint8_t b) { // push back return cbuf_push(opts(iface)->rxbuf, &b); } /** Send one byte (waits for tx) */ static bool if_tx(ComIface *iface, uint8_t b) { usart_opts *uopts = opts(iface); USART_TypeDef* USARTx = uopts->dev; if (uopts->txbuf == NULL) { // Blocking tx mode until_timeout(uopts->wait_timeout) { if (USARTx->SR & USART_SR_TXE) { USARTx->DR = b; return true; // success } } return false; } else { // Buffered mode // wait for free space in the buffer bool ready = com_tx_rdy_wait(iface, uopts->wait_timeout); if (ready) { // append to the buffer cbuf_append(uopts->txbuf, &b); } // regardless ready state, start Tx if there are bytes // (should fix a bug where full buffer was never emptied) // If TXE (send buffer empty), start sending the buffer // Otherwise, IRQ chain is in progress. if (USARTx->SR & USART_SR_TXE) { USART_ITConfig(USARTx, USART_IT_TXE, ENABLE); // start tx chain } return ready; } } /** Read a blob. Returns real read size */ static size_t if_rxb(ComIface *iface, void *buf, size_t buflen) { if (buf == NULL) return false; //if (!com_rx_wait(iface, opts(iface)->wait_timeout)) return 0; uint8_t* byteptr = (uint8_t*)buf; for (size_t i = 0; i < buflen; i++) { if (!if_rx(iface, byteptr++)) return i; } return buflen; } /** Send a binary blob. False on error. */ static size_t if_txb(ComIface *iface, const void *blob, size_t size) { if (blob == NULL) return false; //if (!com_tx_rdy_wait(iface, opts(iface)->wait_timeout)) return false; const uint8_t* byteptr = (const uint8_t*)blob; for (size_t i = 0; i < size; i++) { if (!if_tx(iface, *byteptr++)) return i; } return size; } /** Check for incoming data */ static void if_poll(ComIface *iface) { if (if_rx_rdy(iface)) { // call user cb if (iface->rx_callback) { iface->rx_callback(iface); } } } // ---- Init interface ---- //void usart_iface_set_baudrate(ComIface *iface, uint32_t baud) //{ // USART_TypeDef* USARTx = opts(iface)->dev; // // USART_SetBaudrate(USARTx, baud); //} /* public */ ComIface *usart_iface_init(USART_TypeDef* USARTx, uint32_t baud, size_t rxbuf_len, size_t txbuf_len) { assert_param(IS_USART_BAUDRATE(baud)); assert_param(rxbuf_len > 0); ComIface *iface = malloc_s(sizeof(ComIface)); // --- setup device specific iface data --- // Allocate the opts config object iface->opts = malloc_s(sizeof(usart_opts)); // Set device ID opts(iface)->dev = USARTx; opts(iface)->wait_timeout = DEF_WAIT_TO_MS; // Initialize the rx/tx buffers (malloc's the array) opts(iface)->rxbuf = cbuf_create(rxbuf_len, 1); // zero-length TX buffer -> blocking Tx opts(iface)->txbuf = (txbuf_len == 0) ? NULL : cbuf_create(txbuf_len, 1); // --- driver instance --- iface->rx_rdy = if_rx_rdy; iface->tx_rdy = if_tx_rdy; iface->tx_done = if_tx_done; iface->rx = if_rx; iface->unrx = if_unrx; iface->tx = if_tx; iface->txb = if_txb; iface->rxb = if_rxb; iface->poll = if_poll; iface->rx_callback = NULL; // user can replace /* enable peripehral clock, assign to holder var, enable IRQ */ IRQn_Type irqn; if (USARTx == USART1) { // USART1 usart1_iface = iface; irqn = USART1_IRQn; RCC->APB2ENR |= RCC_APB2ENR_USART1EN; } else if (USARTx == USART2) { // USART2 usart2_iface = iface; irqn = USART2_IRQn; RCC->APB1ENR |= RCC_APB1ENR_USART2EN; } else { // USART3 usart3_iface = iface; irqn = USART3_IRQn; RCC->APB1ENR |= RCC_APB1ENR_USART3EN; } // Enable IRQ NVIC_EnableIRQ(irqn); // lower priority than SysTick, but high NVIC_SetPriority(irqn, 1); // function does the shifting /* Setup UART parameters. */ USART_InitTypeDef usart; USART_StructInit(&usart); usart.USART_BaudRate = baud; USART_Init(USARTx, &usart); /* Enable */ USART_Cmd(USARTx, ENABLE); // Enable Rx interrupt USART_ITConfig(USARTx, USART_IT_RXNE, ENABLE); // disable IRQ return iface; } // ---- IRQ handlers for chained writing and rx ---- /** * @brief Common USART irq handler * @param iface the interface at which the event occured */ static void usart_iface_irq_base(ComIface* iface) { USART_TypeDef* USARTx = opts(iface)->dev; if (USARTx->SR & USART_SR_RXNE) { // Byte received. uint8_t rxb = USARTx->DR & 0xFF; if (!cbuf_append(opts(iface)->rxbuf, &rxb)) { // Buffer overflow // Can't print debug msg, can cause deadlock } } if (USARTx->SR & USART_SR_TXE) { // Byte sent. uint8_t txb; // Send next byte (if buffer is NULL, cbuf_pop also returns false) if (cbuf_pop(opts(iface)->txbuf, &txb)) { USARTx->DR = txb; // send data } else { USART_ITConfig(USARTx, USART_IT_TXE, DISABLE); // disable IRQ } } // Clear ORE flag if set USART_ClearFlag(USARTx, USART_FLAG_ORE); } void USART1_IRQHandler(void) { usart_iface_irq_base(usart1_iface); } void USART2_IRQHandler(void) { usart_iface_irq_base(usart2_iface); } void USART3_IRQHandler(void) { usart_iface_irq_base(usart3_iface); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* dump_memory.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cbenoit <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/18 12:05:27 by cbenoit #+# #+# */ /* Updated: 2019/10/18 12:07:42 by cbenoit ### ########.fr */ /* */ /* ************************************************************************** */ #include "corewar.h" #include <unistd.h> #include "libft.h" #include <stdlib.h> void ft_putnbrhex(t_byte nb) { char res[2]; res[0] = "0123456789ABCDEF"[nb >> 4]; res[1] = "0123456789ABCDEF"[nb & 0x0f]; write(1, res, 2); } void dump_memory(t_main *main) { int j; j = 0; set_colors(main, COLOR_LIGHT_RED); while (j < MEM_SIZE) { write(1, " ", 1); ft_putnbrhex(main->vm->arena[j]); if (++j % 16 == 0) write(1, "\n", 1); } if (main->flag[BONUS_C]) write(1, COLOR_RESET, 4); free_all(main); exit(EXIT_SUCCESS); } static void print_dump_header(t_main *main, int j) { char *a; int i; if (!(a = ft_itoabase(j, "0123456789abcdef"))) disp_error(set_msg(EXIT_FAILURE, MALLOC_ERR, main), main); set_colors(main, COLOR_GREEN); write(1, "0x", 2); i = ft_strlen(a); set_colors(main, COLOR_LIGHT_GREEN); while (++i <= 4) write(1, "0", 1); ft_putstr(a); free(a); set_colors(main, COLOR_GREEN); write(1, " :", 3); set_colors(main, COLOR_LIGHT_RED); } void d_memory(t_main *main) { int j; j = 0; set_colors(main, COLOR_LIGHT_RED); while (j < MEM_SIZE) { if (j % 64 == 0) print_dump_header(main, j); write(1, " ", 1); ft_putnbrhex(main->vm->arena[j]); if (++j % 64 == 0) write(1, "\n", 1); } if (main->flag[BONUS_C]) write(1, COLOR_RESET, 4); free_all(main); exit(EXIT_SUCCESS); }
C
#include <stdio.h> //Following function will sort the array in Increasing (ascending) order void bubble_sort(int arr[], int n) { int i, j, tmp; for(i = 0; i < n-1; i++) { // Last i elements are already in place, so the inner loops will run until it reaches the last i elements for(j = 0; j < n-i-1; j++) { if(arr[j] > arr[j+1]) //To Sort in decreasing order, change the comparison operator to '<' { tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp; } } } } //Following is a slightly modified bubble sort function, which tracks the list with a flag to check if it is already sorted void modified_bubble_sort(int arr[], int n) { int i, j, tmp; for(i = 0; i < n-1; i++) { int flag = 0; //Taking a flag variable // Last i elements are already in place, so the inner loops will run until it reaches the last i elements for(j = 0; j < n-i-1; j++) { if(arr[j] > arr[j+1]) //To Sort in decreasing order, change the comparison operator to '<' { tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp; flag = 1; //Setting the flag, if swapping occurs } } if(!flag) //If not swapped, that means the list has already sorted { break; } } } void print_list(int arr[], int num_of_element) { int i; for(i = 0; i < num_of_element; i++) { printf("%d ", arr[i]); } printf("\n"); } int main(int argc, char const *argv[]) { int arr[] = {43, 1, 24, 56, 30, 5}; int num_of_element = sizeof(arr)/sizeof(int); printf("Initial List:\n"); print_list(arr, num_of_element); bubble_sort(arr, num_of_element); //modified_bubble_sort(arr, num_of_element); printf("Sorted list in ascending order: \n"); print_list(arr, num_of_element); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_lltoa.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lowczarc <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/12/07 20:52:30 by lowczarc #+# #+# */ /* Updated: 2018/01/07 19:00:21 by lowczarc ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" static int size_llutoa(unsigned long long int n) { unsigned long long int ret; ret = 0; while (n >= 10) { ret++; n /= 10; } ret++; return (ret); } static void ft_putinstr(char *s, unsigned long long n, int size) { while (size > 0) { size--; s[size] = (n % 10) + '0'; n = n / 10; } } char *ft_llutoa(unsigned long long int n, int size) { char *ret; if (size < size_llutoa(n) && !(n == 0 && size == 0)) size = size_llutoa(n); ret = malloc(sizeof(char) * (size + 1)); if (ret == NULL) return (NULL); ft_putinstr(ret, n, size); ret[size] = 0; return (ret); } char *ft_llitoa(long long int n, t_formaitem *format) { char *tmp; char *ret; int size; size = format->precision - 1 + (!(format->flags & 512) && format->precision != -1); tmp = ft_llutoa((n < 0) ? -n : n, size); ret = (n < 0) ? ft_strfreejoin(ft_strdup("-"), tmp) : tmp; return (ret); }
C
#include <stdio.h> #include "ws_6.c" int main() { unsigned int arr[8] = {1,7,100000,4,5,146,13}; int a= 3; int b= 5; int *p_a = &a; int *p_b = &b; float num = -118.625; printf("pow2: work %f \n", Pow2(5,0)); printf("pow2: work %f \n", Pow2(5,-1)); /*if(Pow2(5,0) != 5) { printf("pow2: error1 \n"); } if(Pow2(5,-1) == 1/10) { printf("pow2: work %f \n", Pow2(5,-1)); } */ if (PowOf2Loop(0) == 0) { printf ("PowOf2Loop Work %d\n", PowOf2Loop(0)); } else { printf ("PowOf2Loop Dont Work"); } if (PowOf2(8) == 1) { printf ("PowOf2 Work %d\n", PowOf2(8)); } else { printf ("PowOf2 Dont Work"); } if (AddOne(12) == 13) { printf ("AddOne Work %d\n", AddOne(12)); } else { printf ("AddOne Dont Work"); } if (ByteMirrorLoop(1000) == 398458880) { printf ("ByteMirrorLoop Work %d\n", ByteMirrorLoop(1000)); } else { printf ("ByteMirrorLoop Dont Work\n"); } if (ByteMirror(1000) == 398458880) { printf ("ByteMirror Work %d\n", ByteMirror(1000)); } else { printf ("ByteMirror Dont Work\n"); } Arry3BitOn(arr, 8); if (F1(35) == 1) { printf ("F1 Work %d\n", F1(35)); } else { printf ("F1 Dont Work"); } if (F2(6) == 1) { printf ("F2 Work %d\n", F2(6)); } else { printf ("F2 Dont Work"); } if (ClosestNum(849) == 848) { printf ("ClosestNum Work %d\n", ClosestNum(849)); } else { printf ("ClosestNum Dont Work"); } Swap(p_a, p_b); if (a == 5 && b == 3) { printf ("Swap Work\n"); } else { printf ("Swap dont Work\n"); } if (BitsOnLoop(100000) == 6) { printf ("BitsOnLoop Work %d\n", BitsOnLoop(100000)); } else { printf ("BitsOnLoop dont Work\n"); } if (BitsOn(100000) == 6) { printf ("BitsOn Work %d\n", BitsOn(100000)); } else { printf ("BitsOn dont Work\n"); } FloatBits(num); return 0; }
C
#include "data_structure.h" #include "error.h" STACK_S* BASE_CreateStack(INT iStackSize) { STACK_S* pstStack = NULL_PTR; if (iStackSize > iStackSize) { return ERROR_GENERAL_ERROR; } pstStack = (STACK_S*)BASE_Malloc(sizeof(STACK_S)); if (pstStack == NULL_PTR) { return ERROR_MALLOC_FAIL; } pstStack->pBase = (INT*)BASE_Malloc(sizeof(INT) * iStackSize); pstStack->iSize = iStackSize; pstStack->pTop = pstStack->pBase; return pstStack; } VOID BASE_StackPush(STACK_S* pstStack, INT iVal) { if (pstStack->pTop - pstStack->pBase == pstStack->iSize) { return ERROR_STACK_FULL; } *(pstStack->pTop++) = iVal; return; } INT BASE_StackPop(STACK_S* pstStack) { if (pstStack->pTop == pstStack->pBase) { return; } return *(pstStack->pTop--); } BOOL BASE_IsEmpty(STACK_S* pstStack) { return (pstStack->pTop == pstStack->pBase); } VOID BASE_DestoryStack(STACK_S* pstStack) { BASE_Free(pstStack->pBase); BASE_Free(pstStack); return; } TREE_S* BASE_CreateTree(VOID *pvData) { TREE_S* pstTreeRoot = NULL_PTR; pstTreeRoot = (TREE_S*)BASE_Malloc(sizeof(TREE_S)); if (NULL_PTR == pstTreeRoot) { return ERROR_MALLOC_FAIL; } pstTreeRoot->pvData = pvData; return pstTreeRoot; } ULONG BASE_AddTreeNode(TREE_S* pstTreeRoot, TREE_S* pstTreeNode, FIND_PARENT_NODE_FUNC pfFindParentNode) { TREE_S* pstParentNode = NULL_PTR; TREE_S* pstTmpNode = NULL_PTR; if (NULL_PTR == pstTreeRoot || NULL_PTR == pstTreeNode) { return ERROR_GENERAL_ERROR; } pstParentNode = (*pfFindParentNode)(pstTreeRoot, pstTreeNode); if (pstParentNode == NULL_PTR) { return ERROR_TREE_NO_PARENT; } if (NULL_PTR == pstParentNode->pstChildNode) { pstParentNode->pstChildNode = pstTreeNode; pstTreeNode->pstParentNode = pstParentNode->pstChildNode; return OK; } pstTmpNode = pstParentNode->pstChildNode; while (TRUE) { if (pstTmpNode->pstNextNode == NULL_PTR) { pstTmpNode->pstNextNode = pstTreeNode; pstTreeNode->pstParentNode = pstTmpNode; return OK; } pstTmpNode = pstTmpNode->pstNextNode; } } TREE_S* BASE_FindTreeNode(TREE_S* pstTreeRoot, VOID* pvData, COMPARE_NODE_FUNC pfFindNode) { TREE_S* pstTmpNode = NULL_PTR; TREE_S* pstTmpChildNode = NULL_PTR; pstTmpNode = pstTreeRoot; pstTmpChildNode = pstTreeRoot->pstChildNode; while (!pfFindNode(pvData, pstTmpNode->pvData)) { if (NULL_PTR == pstTmpNode->pstNextNode); } }
C
void insertionSort (int* vector, int size) { int i, j, key; for (j = 1; j < size; j++) { key = vector[j]; i = j - 1; while (i >= 0 && vector[i] > key) { vector[i + 1] = vector[i]; i = i - 1; } vector[i+1] = key; } }
C
/*--------------------------------------------------------------------------------------- MaxEle.c Program to find the maximum element in a matrix DIVYA RAJ.K 12-10-18 -----------------------------------------------------------------------------------------*/ #include<stdio.h> main() { int X[20][20],M,N,i,j,Max,Row=1,Col=1; system("clear"); printf("Program to find the maximum element in a matrix\n"); printf("\nEnter the number of rows: "); scanf("%d",&M); printf("\nEnter the number of columns: "); scanf("%d",&N); printf("Enter %d elements:\n",M*N); for(i=1;i<=M;i++){ for(j=1;j<=N;j++){ scanf("%d",&X[i][j]); } } Max=X[1][1]; for(i=1;i<=M;i++){ for(j=1;j<=N;j++){ if(Max<X[i][j]){ Max=X[i][j]; Row=i; Col=j; } } } printf("\nThe elements of the matrix are:\n"); for(i=1;i<=M;i++){ for(j=1;j<=N;j++){ printf("%d\t",X[i][j]); } printf("\n"); } printf("\nThe maximum number is %d present at row %d and column %d",Max,Row,Col); }
C
/* Test case by Paul Eggert <[email protected]> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <stdint.h> struct big { char *c; uint32_t cnt; }; struct big *array; int compare (void const *a1, void const *b1) { struct big const *a = a1; struct big const *b = b1; return strcmp(a->c, b->c); } int main (int argc, char **argv) { char *didi[] = { "there", "are", "two", "main", "types", "of", "memory", "you", "seem", "to", "be", "confusing" }; size_t array_members = sizeof(didi)/sizeof(*didi); array = (struct big *) malloc (array_members * sizeof (struct big)); printf("Number of strings: %d\n",array_members); if (array == NULL) { printf("Can't allocate memory for struct array"); exit(0); } printf("Initial strings:\n"); for (size_t i = 0; i < array_members; i++){ array[i].c = strdup(didi[i]); array[i].cnt = i; if (array[i].c == NULL) { printf("Can't allocate memory for string: %d\t%s",i,didi[i]); exit(0); } printf("\t%d:\t%s\n",array[i].cnt,array[i].c); } printf("________________\n"); printf("After sorting strings:\n"); qsort (array, array_members, sizeof *array, compare); for(size_t i = 0;i<array_members;i++){ printf("\t%d:\t%s\n",array[i].cnt,array[i].c); free(array[i].c); } free(array); return 0; }
C
#include "board.h" #include "retrociaa/m4/base/systick.h" #include "retrociaa/m4/base/mempool.h" #include "retrociaa/m4/base/semaphore.h" #include "retrociaa/m4/os/api.h" #include "retrociaa/m4/os/mutex.h" #include "appdata.h" OS_TaskRetVal taskInput (OS_TaskParam arg) { struct AppData *ad = (struct AppData *) arg; enum OS_Result r; (void) r; // Toma el mutex. r = OS_MUTEX_Lock (&ad->ledParams.mutex); // Setea inicio de la demora periodica. OS_TaskPeriodicDelay (0); while (1) { // Espera a que la tarea que maneja los leds termine de prenderlos. // Si esta es la 1er iteracion no hay nada que esperar ya que el mutex // fue tomado arriba. r = OS_TaskWaitForSignal (OS_TaskSignalType_MutexLock, &ad->ledParams.mutex, OS_WaitForever); // Actualiza estado de los botones. const uint32_t BTNS = Buttons_GetStatus (); const bool B1 = !(BTNS & TEC1_PRESSED); const bool B2 = !(BTNS & TEC2_PRESSED); const bool B1RF = getButtonAction (B1, &ad->measurements.b1); const bool B2RF = getButtonAction (B2, &ad->measurements.b2); // Se tomo el rise/fall de los dos botones? if (B1RF && B2RF) { ad->measurements.finished = OS_GetTicks (); // Obtiene tiempos y determina el led que corresponde prender. getEdges (&ad->measurements, &ad->ledParams); measurementsRestart (&ad->measurements); // Desbloquea la tarea LED. r = OS_MUTEX_Unlock (&ad->ledParams.mutex); // Y cede el procesador. OS_TaskYield (); } // Fall/Rise de B1 sin Fall de B2 o viceversa resetea las mediciones else if ((B1RF && ad->measurements.b2.fall == OS_TicksUndefined) || (B2RF && ad->measurements.b1.fall == OS_TicksUndefined)) { measurementsRestart (&ad->measurements); // Demora periodica de 40 milisegundos. r = OS_TaskPeriodicDelay (40); } else { // Demora periodica de 40 milisegundos. r = OS_TaskPeriodicDelay (40); } } return 0; } OS_TaskRetVal taskLed (OS_TaskParam arg) { struct LedParams *ledParams = (struct LedParams *) arg; enum OS_Result r; (void) r; while (1) { // Espera a que la tarea de input determine un nuevo trabajo. r = OS_TaskWaitForSignal (OS_TaskSignalType_MutexLock, &ledParams->mutex, OS_WaitForever); // Prepara el mensaje a enviar por UART sendMessage (ledParams); // Prende el led correspondiente la cantidad de tiempo indicada y // lo apaga pasada esa demora. Board_LED_Set (ledParams->index, true); OS_TaskDelay (ledParams->fallTime + ledParams->riseTime); Board_LED_Set (ledParams->index, false); // Desbloquea la tarea de input y cede el procesador. OS_MUTEX_Unlock (&ledParams->mutex); OS_TaskYield (); } return 0; } OS_TaskRetVal taskUart (OS_TaskParam arg) { struct LedParams *ledParams = (struct LedParams *) arg; enum OS_Result r; (void) r; while (1) { while (UART_SendPendingCount (&ledParams->uart)) { UART_Send (&ledParams->uart); } r = OS_TaskDelay (50); } return 0; } OS_TaskRetVal boot (OS_TaskParam arg) { struct AppData *ad = (struct AppData *) arg; enum OS_Result r; if ((r = appDataInit(ad)) != OS_Result_OK) { return 1; } if ((r = OS_TaskStart (ad->stacks.taskInput, MEMPOOL_BlockSize(ad->stacks.taskInput), taskInput, ad, OS_TaskPriority_Kernel1, g_TaskInputName)) != OS_Result_OK) { return 2; } if ((r = OS_TaskStart (ad->stacks.taskLed, MEMPOOL_BlockSize(ad->stacks.taskLed), taskLed, &ad->ledParams, OS_TaskPriority_Kernel1, g_TaskLedName)) != OS_Result_OK) { return 3; } if ((r = OS_TaskStart (ad->stacks.taskUart, MEMPOOL_BlockSize(ad->stacks.taskUart), taskUart, &ad->ledParams, OS_TaskPriority_Kernel1, g_TaskUartName)) != OS_Result_OK) { return 4; } return 0; } int main () { Board_Init (); SystemCoreClockUpdate (); SYSTICK_SetPeriod_ms (1); // LPC_USART2 Chip_SCU_PinMuxSet (7, 1, (SCU_MODE_INACT | SCU_MODE_FUNC6)); Chip_SCU_PinMuxSet (7, 2, (SCU_MODE_INACT | SCU_MODE_INBUFF_EN | SCU_MODE_FUNC6)); uint8_t initBuffer [OS_InitBufferSize ()] ATTR_DataAlign8; struct AppData ad; OS_Init (initBuffer); OS_Start (boot, &ad); Board_LED_Set (LED_RED, true); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <stdint.h> int get_bit(const uint32_t, const uint32_t); /* * Problem 01.b. Bitwise: Extract Bit #3 * * Using bitwise operators, write an expression for finding the value of the * bit #3 of a given unsigned integer. The bits are counted from right to left, * starting from bit #0. The result of the expression should be either 1 or 0. * Examples: * * ----------------------------------------- * n | binary representation | Result | * -----------------------------------------| * 5 | 00000000 00000101 | 0 | * -----------------------------------------| * 0 | 00000000 00000000 | 0 | * -----------------------------------------| * 15 | 00000000 00001111 | 1 | * -----------------------------------------| * 5343 | 00010100 11011111 | 1 | * -----------------------------------------| * 62241 | 11110011 00100001 | 0 | * -----------------------------------------| */ int main() { uint32_t n; printf("n = "); scanf("%u", &n); printf("\nResult\n"); printf("%d\n", get_bit(n, 3)); return (EXIT_SUCCESS); } int get_bit(const uint32_t num, const uint32_t pos) { if((8 * sizeof(uint32_t)) <= pos) return -1; if(((num >> pos) & 1) == 1) return 1; else return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "queue.h" #define QUEUE_SIZE 100 struct queue_type { int contents[QUEUE_SIZE]; int first; int last; int num_elements; }; static void terminate(const char *message) { printf("%s\n", message); exit(EXIT_FAILURE); } Queue create(void) { Queue q = malloc(sizeof(struct queue_type)); if (q == NULL) terminate("Error in create: stack could not be create."); q->first = 0; q->last = 0; q->num_elements = 0; return q; } void destroy(Queue q) { free(q); } void make_empty(Queue q) { q->first = 0; q->last = 0; q->num_elements = 0; } bool is_empty(Queue q) { return q->num_elements == 0; } bool is_full(Queue q) { return q->num_elements == QUEUE_SIZE; } void push(Queue q, int i) { if (is_full(q)) terminate("Error in push: stack is full."); if (q->last >= QUEUE_SIZE) q->last = q->last % QUEUE_SIZE; q->num_elements++; q->contents[q->last++] = i; } int pop(Queue q) { if (is_empty(q)) terminate("Error in pop: stack is empty."); if (q->first >= QUEUE_SIZE) q->first = q->first % QUEUE_SIZE; q->num_elements--; return q->contents[q->first++]; }
C
#include <stdio.h> #include <math.h> unsigned set_n(unsigned x, int pos, int n) { //需要设为1的个数 ^(0<<n) //需要从第几位开始 (^(0<<n)) << pos unsigned j = 0; for (int i = 0; i < n; i++) {//从第0位到第(n-1)位均为1 j += pow(2, i); } return x | (j << pos); } unsigned reset_n(unsigned x, int pos, int n) { unsigned j = 0; for (int i = 0; i < n; i++) {//从第0位到第(n-1)位均为1 j += pow(2, i); } return x & ~(j << pos); } unsigned inverse_n(unsigned x, int pos, int n) { unsigned j = 0; for (int i = 0; i < n; i++) {//从第0位到第(n-1)位均为1 j += pow(2, i); } return x ^ (j<< pos); } int main (void) { //10001 = 17 //11111 = 31 //10101 = 21 printf("x=17, pos=1, n=3 应为 111111 = 31 实际是: %d\n", set_n(17, 1, 3)); printf("x=31, pos=1, n=3 应为 10001 = 17 实际是: %d\n", reset_n(31, 1, 3)); printf("x=21, pos=1, n=3 应为 11011 = 27 实际是: %d\n", inverse_n(21, 1, 3)); return 0; }
C
/* =========================================================== #File: win32_fileio.c # #Date: 16 March 2021 # #Revision: 1.0 # #Creator: Omid Miresmaeili # #Description: copying file with win32 fileio vs c stdio # #Notice: (C) Copyright 2021 by Omid. All Rights Reserved. # =========================================================== */ #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <tchar.h> #if 0 // c copy file int main(int argc, char * args []) { char buf[100]; FILE * in; FILE * out; size_t nread = 0; size_t nwritten = 0; fopen_s(&in, "f1.txt", "rb"); fopen_s(&out, "f2.txt", "wb"); if (in && out) { while ((nread = fread(buf, 1, _countof(buf), in)) > 0) { nwritten = fwrite(buf, 1, nread, out); if (nread != nwritten) { perror("Fatal error"); return 4; } } fclose(out); fclose(in); } return(0); } #else int main (int argc, char * argv []) { char buf[100]; HANDLE in; HANDLE out; DWORD nread = 0; DWORD nwritten = 0; in = CreateFile( _T("f1.txt"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); out = CreateFile( _T("f2.txt"), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); if (INVALID_HANDLE_VALUE != in && INVALID_HANDLE_VALUE != out) { while (ReadFile(in, buf, _countof(buf), &nread, NULL) && nread > 0) { WriteFile(out, buf, nread, &nwritten, NULL); if (nread != nwritten) { printf("Fatal Error: %x\n", GetLastError()); return 1; } } } CloseHandle(out); CloseHandle(in); return(0); } #endif
C
/* Gary Williams * COMPE 375-01 * Lab 4 Due: 2/24/17 * * Overview: * For this laboratory assignment we were required to transmit the characters of our RedID * through the USART port on the ATmega328PB. We were also required us to set the baud rate * to 9600 and to set the data packet length to 8 data bits and 1 stop bit. After * transmitting the characters of our ID, we were to send a carriage return followed by a * linefeed and then wait 500 milliseconds before sending the string out again. * */ #define F_CPU 16000000UL #include <avr/io.h> #include <util/delay.h> void USART_init(void); int main (void) { char redid[]= {'8','0','3','1','6','2','4','9','7'}; USART_init(); UCSR0B |= (1<<TXEN0); //Set USART to transmit while(1){ for(int i=0; i<sizeof(redid); i++){ while(!(UCSR0A & (1<<UDRE0))); //Wait for the data register to be free UDR0 = redid[i]; } while(!(UCSR0A & (1<<UDRE0))); UDR0 = 0x0D; //Send carriage return while(!(UCSR0A & (1<<UDRE0))); UDR0 = 0x0A; //Send line feed while(!(UCSR0A & (1<<UDRE0))); _delay_ms(500); //Delay between transmission strings } return 0; } void USART_init(void){ UBRR0L = 103; //Set the baudrate to 9600 UCSR0C |= (1<<UCSZ01) | (1<<UCSZ00); //Set data size to 8 bit; default 1 stop bit }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strrchr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ntai <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/03/05 20:39:49 by ntai #+# #+# */ /* Updated: 2018/03/27 21:20:40 by ntai ### ########.fr */ /* */ /* ************************************************************************** */ /* ** strrchr returns the a pointer ** to the last occurence of c ** ** ** while (run till string ends) ** if right character ** track that location ** ** if end of string AND \0 is right character ** return location to that null ** ** return tracker ** ** NOTE: we still return NULL if wanted character ** is not found. Tracker is initiated to NULL ** so if c was never found, tracker will ** still be NULL. */ #include "libft.h" char *ft_strrchr(const char *s, int c) { char *tracker; tracker = NULL; while (*s) { if (*s == c) tracker = (char *)s; ++s; } if (c == '\0') return ((char *)s); return (tracker); }
C
#include <stdio.h> #define NUMER0_DE_TENTATIVAS 5 int main() { printf("\n"); printf("\n"); printf("######################################\n"); printf("## Bem vindo ao jogo de adivinhação ##\n"); printf("######################################\n"); printf("\n"); printf("\n"); int numero_secreto = 50; int chute; for(int i = 1; i <= NUMER0_DE_TENTATIVAS; i++) { printf("Qual é o seu chute? "); scanf("%d", &chute); printf("Você chutou %d \n", chute); printf("Tentativa %d de %d\n", i, NUMER0_DE_TENTATIVAS); int acertou = chute == numero_secreto; if(chute < 0) { printf("Você não pode digitar números negativos!\n"); i--; continue; } if(acertou) { printf("Parabéns!!! Você acertou.\n"); break; } else { if (chute > numero_secreto) { printf("O número que você escolheu é maior do que o secreto.\n"); } else { printf("O número que você escolheu é menor do que o secreto.\n"); } } } printf("Fim de jogo!\n"); }
C
#include "adc.h" void adc_config(){ ADCON0 = 0x28; //AN10 channel only ADCON1 = 0xC6; //result right justified, Fosc/4 source (1.33 us Tad), VREFs __delay_ms(2); //general aquisition time for channel selection } uint16_t adc_read(){ ADCON0bits.ADON = 1; //ADC on ADCON0bits.GO_nDONE = 1; //set initalize bit while(ADCON0bits.GO_nDONE); //wait while conversion is in progress ADCON0bits.ADON = 0; //ADC off return (uint16_t)(ADRESH << 8 | ADRESL); //return result in lower 10 bits } uint8_t read_temp(bool f){ //read adc result and convert to rounded temperature representation if(f) return (adc_read()*(uint32_t)144 + 512)/1023 + 32; //F else return (adc_read()*(uint32_t)80 + 512)/1023; //C } bool check_temp(bool f){ //checks if temp is above threshold (different results for different units) if(f) return (bool)(read_temp(f) >= TEMP); else return (bool)(read_temp(f) >= ((TEMP-32)*5)/9); }
C
#include <stdio.h> #include <stdlib.h> int main() { int i,j,h,c,Dig; char Tel[10]; char Parte1[4]; char Parte2[4]; Dig = 0; printf("Digite seu telefone: \n"); gets(Tel); for(i=0; Tel[i] != '\0'; i++){ Dig++; if(Tel[i] == '-'){ Dig--; } } if(Dig==7){ printf("numero com 7 digitos, o numero 3 sera acrescentado a frente.\n "); for(j=8; j>0 ; j--){ Tel[j] = Tel[j-1]; } Tel[0] = '3'; } for(h=0; Tel[h] != '\0'; h++){ if(Tel[h] == '-'){ printf("%s",Tel); return 0; } } for(c=0; c<4 ; c++){ Parte1[c] = Tel[c]; Parte2[c] = Tel[c+4]; } printf("%s - %s",Parte1,Parte2); return 0; }
C
// Created by Ameer Ali #include <stdio.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_attr.h" #include "driver/mcpwm.h" #include "soc/mcpwm_reg.h" #include "soc/mcpwm_struct.h" #define SERVO_MIN_PULSEWIDTH 780 //Minimum pulse width in microsecond #define SERVO_MAX_PULSEWIDTH 2190 //Maximum pulse width in microsecond #define SERVO_MAX_DEGREE 120 //Maximum angle in degree upto which servo can rotate //has 120 degree rotation, 60 in each direction //Interrupt for MCPWM for possible integration later maybe we use smephores to pass between task when we want //this running ///** // * @brief Register MCPWM interrupt handler, the handler is an ISR. // * the handler will be attached to the same CPU core that this function is running on. // * // * @param mcpwm_num set MCPWM unit(0-1) // * @param fn interrupt handler function. // * @param arg user-supplied argument passed to the handler function. // * @param intr_alloc_flags flags used to allocate the interrupt. One or multiple (ORred) // * ESP_INTR_FLAG_* values. see esp_intr_alloc.h for more info. // * @param arg parameter for handler function // * @param handle pointer to return handle. If non-NULL, a handle for the interrupt will // * be returned here. // * // * @return // * - ESP_OK Success // * - ESP_ERR_INVALID_ARG Function pointer error. // */ //esp_err_t mcpwm_isr_register(mcpwm_unit_t mcpwm_num, void (*fn)(void *), void *arg, int intr_alloc_flags, intr_handle_t *handle); void mcpwm_gpio_initialize() { printf("initializing mcpwm servo control gpio......\n"); mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM0A, 18); //Set GPIO 18 as PWM0A, to which servo is connected } /** * @brief Use this function to calcute pulse width for per degree rotation * * @param degree_of_rotation the angle in degree to which servo has to rotate * * @return * - calculated pulse width */ uint32_t servo_per_degree_init(uint32_t degree_of_rotation) { uint32_t cal_pulsewidth = 0; cal_pulsewidth = (SERVO_MIN_PULSEWIDTH + (((SERVO_MAX_PULSEWIDTH - SERVO_MIN_PULSEWIDTH) * (degree_of_rotation)) / (SERVO_MAX_DEGREE))); return cal_pulsewidth; } //Use this function whenever you want the servo back in the "locked" position void lockup () { uint32_t locked = 0; uint32_t angle; printf("Angle of rotation: %d\n", locked); angle = servo_per_degree_init(locked); printf("pulse width: %dus\n", angle); mcpwm_set_duty_in_us(MCPWM_UNIT_0, MCPWM_TIMER_0, MCPWM_OPR_A, angle); vTaskDelay(10); //Here for safety } //Use this function whenever you wan the servo in the "unlocked" position void unlocked () { uint32_t unlock = SERVO_MAX_DEGREE; uint32_t angle; printf("Angle of rotation: %d\n", unlock); angle = servo_per_degree_init(unlock); printf("pulse width: %dus\n", angle); mcpwm_set_duty_in_us(MCPWM_UNIT_0, MCPWM_TIMER_0, MCPWM_OPR_A, angle); vTaskDelay(10); //Here for safety } /** * @brief Configure MCPWM module */ void mcpwm_servo_control_init(void ) { //uint32_t angle, count; //1. mcpwm gpio initialization mcpwm_gpio_initialize(); //2. initial mcpwm configuration printf("Configuring Initial Parameters of mcpwm......\n"); mcpwm_config_t pwm_config; pwm_config.frequency = 50; //frequency = 50Hz, i.e. for our servo motor time period should be 20ms pwm_config.cmpr_a = 0; //duty cycle of PWMxA = 0 pwm_config.cmpr_b = 0; //duty cycle of PWMxb = 0 pwm_config.counter_mode = MCPWM_UP_COUNTER; pwm_config.duty_mode = MCPWM_DUTY_MODE_0; mcpwm_init(MCPWM_UNIT_0, MCPWM_TIMER_0, &pwm_config); //Configure PWM0A & PWM0B with above settings }
C
#include <stdio.h> int main() { int n = 6, i, factor, sum=0; for(i =1; i < n ; i++) { if(n % i ==0) { sum = sum + i; } } if(n == sum) printf("%d is perfect number\n", n); else printf("%d is not perfect number\n", n); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include "ifindex.h" #define red "\033[0;31m" /* 0 -> normal ; 31 -> red */ #define cyan "\033[0;36m" /* 1 -> bold ; 36 -> cyan */ #define green "\033[0;32m" /* 4 -> underline ; 32 -> green */ #define blue "\033[0;34m" /* 9 -> strike ; 34 -> blue */ #define black "\033[0;30m" #define brown "\033[0;33m" #define magenta "\033[0;35m" #define gray "\033[0;37m" #define none "\033[0m" /* to flush the previous property */ #define MAX_LIST_SIZE 10 #define ELEMENT_MAX_VALUE 15 void test_query(void) { ListDB ifindex = listdb_random(10, MAX_LIST_SIZE, ELEMENT_MAX_VALUE); ListDB queries = listdb_random(3, 5, 10); listdb_apply_to_all(&ifindex, list_sort_by_item); listdb_apply_to_all(&ifindex, list_unique); listdb_apply_to_all(&queries, list_sort_by_item); listdb_apply_to_all(&queries, list_unique); printf("%s=========================\nInverted File\n=========================\n", red); listdb_print(&ifindex); printf("%s=========================\nQueries\n=========================\n", brown); listdb_print(&queries); ListDB results = ifindex_query_multi(&ifindex, &queries); printf("\n%s=========================\nResult\n=========================\n", cyan); listdb_print(&results); printf("%s", none); } int main() { srand((long int) time(NULL)); test_query(); return 0; }