language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <stdlib.h> #include "LinkedList.h" #include "Controller.h" #include "Employee.h" int menu(); int main() { LinkedList* listaEmpleados = ll_newLinkedList(); char salir='n'; do { switch(menu()) { case 1: system("cls"); if(ll_isEmpty(listaEmpleados)==1) { controller_loadFromText("data.csv", listaEmpleados); } else { printf("Ya se realizo la carga de datos anteriormente\n\n"); system("pause"); } break; case 2: system("cls"); if(ll_isEmpty(listaEmpleados)==1) { controller_loadFromBinary("data.bin", listaEmpleados); } else { printf("Ya se realizo la carga de datos anteriormente\n\n"); system("pause"); } break; case 3: controller_addEmployee(listaEmpleados); break; case 4: if(ll_isEmpty(listaEmpleados)==1){ system("cls"); printf("--- No hay empleados cargados en sistema ---\n\n"); system("pause"); }else{ controller_editEmployee(listaEmpleados); } break; case 5: if(ll_isEmpty(listaEmpleados)==1){ system("cls"); printf("--- No hay empleados cargados en sistema ---\n\n"); system("pause"); }else{ controller_removeEmployee(listaEmpleados); } break; case 6: if(ll_isEmpty(listaEmpleados)==1){ system("cls"); printf("--- No hay empleados cargados en sistema ---\n\n"); system("pause"); }else{ system("cls"); printf("--- Listado de empleados ---\n\n"); controller_ListEmployee(listaEmpleados); } break; case 7: if(ll_isEmpty(listaEmpleados)==1){ system("cls"); printf("--- No hay empleados cargados en sistema ---\n\n"); system("pause"); }else{ controller_sortEmployee(listaEmpleados); } break; case 8: if(ll_isEmpty(listaEmpleados)==1) { system("cls"); printf("--- No hay datos para guardar ---\n\n"); system("pause"); } else { if(controller_saveAsText("data.csv", listaEmpleados)) { system("cls"); printf("---Datos guardados correctamente---\n\n"); system("pause"); } else { system("cls"); printf("--- Error al guardar los datos ---\n\n"); system("pause"); } } break; case 9: //guardar binario if(ll_isEmpty(listaEmpleados)==1) { system("cls"); printf("--- No hay datos para guardar ---\n\n"); system("pause"); } else { if(controller_saveAsBinary("data.bin", listaEmpleados)) { system("cls"); printf("--- Datos guardados correctamente ---\n\n"); system("pause"); } else { system("cls"); printf("--- Error al guardar los datos ---\n\n"); system("pause"); } } break; case 10: printf("Confirma salida? (ingrese y/n) "); fflush(stdin); scanf("%c", &salir); ll_deleteLinkedList(listaEmpleados); break; default: printf("Opcion invalida\n\n"); system("pause"); break; } } while(salir == 'n'); return 0; } int menu() { int opcion; system("cls"); printf("***** Menu de Opciones *****\n\n"); printf("1. Cargar datos de empleados desde el archivo de texto\n"); printf("2. Cargar datos de empleados desde el archivo binario\n"); printf("3. Alta empleado\n"); printf("4. Modificar datos de empleado\n"); printf("5. Baja empleado\n"); printf("6. Listar empleados\n"); printf("7. Ordenar empleados\n"); printf("8. Guardar datos de empleados en modo texto\n"); printf("9. Guardar datos de empleados en binario\n"); printf("10. Salir\n\n"); printf("Ingrese opcion: "); scanf("%d", &opcion); return opcion; }
C
/*question 9*/ /*find centre,radiusand area of intersection of plane and sphere * plane a*x+b*y+c*z+d=0 * sphere x*x+y*y+z*z+e*x+f*y+g*z+h=0*/ #include<stdio.h> #include<math.h> void main() { float a,b,c,d,e,f,g,h,j,k,l,m,r,p,q; printf("the value of a,b,c,d,e,f,g,h"); scanf("%f%f%f%f%f%f%f%f",&a,&b,&c,&d,&e,&f,&g,&h); j=(-e)/2; k=(-f)/2; l=(-g)/2; printf("the centre of sphere is%f %f %f\n",j,k,l); m=(a*j+b*k+c*l+d)/sqrt(a*a+b*b+c*c); printf("the distance of centre to plane is %f\n",m); r=sqrt(((-e)/2)*((-e)/2)+((-f)/2)*((-f)/2)+((-g)/2)*((-g)/2)-h); printf("the radius of the sphere is%f\n",r); p=sqrt((r*r)-(m*m)); printf("the radius of circle is%f\n",p); q=(3.14)*p*p; printf("the area of circle is%f\n",q); }
C
/* ** еԪ,ʹȫǰ,żȫں */ #define _CRT_SECURE_NO_WARNINGS #include "stdio.h" #include "stdlib.h" #define LEN 11 int arr_new[LEN] = { 0 }; /*---ӡ---*/ void arr_display(int arr[]) { for (int i = 0; i < LEN; ++i) { printf("%-3d", arr[i]); } printf("\n"); } /*------*/ void modi_arr(int arr[]) { int odd_count = 0; for (int i = 0; i < LEN; ++i) { /*---деǰ---*/ if (arr[i] % 2 == 1) { arr_new[odd_count] = arr[i]; ++odd_count; } } int even_count = odd_count; for (int i = 0; i < LEN; ++i) { /*---żдеĺ---*/ if (arr[i] % 2 == 0) { arr_new[even_count] = arr[i]; ++even_count; } } } int main() { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; printf("ǰ: \n"); arr_display(arr); modi_arr(arr); printf(": \n"); arr_display(arr_new); system("pause"); return 0; }
C
#include <sys/wait.h> #include <unistd.h> #include <sys/timeb.h> #include <time.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "semaphores.h" #include "shared_memory.h" int main (int argc, char* argv[]){ int sem_p1; int sem_enc1; int sem_chan; int sem_p2; //create the semaphores we will need //check the other files to understand what these functions do sem_p1=SemCreate((key_t)45655,1,1); sem_enc1=SemCreate((key_t)45656,1,0); sem_chan=SemCreate((key_t)45657,1,0); sem_p2=SemCreate((key_t)45659,1,0); int Shm_p1_id; //arguments for shared memory creation (enc1) data *Shm_p1_ptr; key_t key_p1=1034; Shm_p1_id = SharedCreate(key_p1); //chech this functions at shared_memory.c Shm_p1_ptr = SharedAttach(Shm_p1_id); //chech this functions at shared_memory.c int Shm_enc1_id; //arguments for shared memory creation (enc1) data *Shm_enc1_ptr; key_t key_enc1=1035; Shm_enc1_id = SharedCreate(key_enc1); //chech this functions at shared_memory.c Shm_enc1_ptr = SharedAttach(Shm_enc1_id); //chech this functions at shared_memory.c char str[100];//used to transfer the checksum int Shm_chan_id; //arguments for shared memory creation (enc1) data *Shm_chan_ptr; key_t key_chan=1036; Shm_chan_id = SharedCreate(key_chan); //chech this functions at shared_memory.c Shm_chan_ptr = SharedAttach(Shm_chan_id); //chech this functions at shared_memory.c int number=1;//used when p2 sends a message Shm_enc1_ptr->p1_p2=1; //we set if for chan to do its thing when p1 sends a message while(Shm_enc1_ptr->running){ SemDown(sem_enc1,0); if(Shm_enc1_ptr->running==0){ break; } int altered=0; if(Shm_enc1_ptr->p1_p2==1){ printf("enc1 -> P2 \n"); //compute the checksum check other files to see that the function does compute_md5(Shm_enc1_ptr->id,str); //we transport the message to the next shared memory memcpy(Shm_chan_ptr->id,Shm_enc1_ptr->id,sizeof(Shm_enc1_ptr->id)); memcpy(Shm_chan_ptr->checksum,str,sizeof(str)); Shm_chan_ptr->p1_p2=1; //up the next semaphore in line so that the next process starts SemUp(sem_chan,0); //we just print sth for the examiner to see xD printf("this is the end of enc1\n"); }else if(Shm_enc1_ptr->p1_p2==2){ printf("enc1 -> P1 \n"); for(int count=0;count<sizeof(Shm_enc1_ptr->id);count++){ if(Shm_enc1_ptr->id[count]=='X'){ altered=1; } } if(altered==1){ altered=0;//reset it to get the new message printf("this message has been subject to noise so it is canceled\n"); SemUp(sem_p2,0); //message is not send to p2 and process p1 asks for a new one }else{ printf("this message didnt get chnanged\n"); memcpy(Shm_p1_ptr->id,Shm_enc1_ptr->id,sizeof(Shm_enc1_ptr->id)); Shm_p1_ptr->p1_p2=2; SemUp(sem_p1,0); } } Shm_p1_ptr->running=1; Shm_enc1_ptr->running=1; Shm_chan_ptr->running=1; } //delete everything after we are done //each process deletes its own things SemDel(sem_enc1); SharedDetach(Shm_enc1_ptr); SharedDelete(Shm_enc1_id); return 0; }
C
#include <stdio.h> #define MAX 100 int op[MAX]; void Show(int *w,int len) { printf("===================================\n"); int i = 0; for(i = 0; i < len; i++) { printf("物品 %d 在第 %d 个船上,重量为 %d\n",i+1,op[i]+1,w[i]); } } void Fun(int weight,int rw,int lw,int *x,int *w,int w1,int w2,int i,int len) { if(i >= len) { if(rw <= w1 && lw <= w2) { int j = 0; for(j = 0; j < len; j++) { op[j] = x[j]; } Show(w,len); } } else { x[i] = 0; Fun(weight,rw,lw+w[i],x,w,w1,w2,i+1,len); x[i] = 1; Fun(weight,rw+w[i],lw,x,w,w1,w2,i+1,len); } } int main() { int w[] = {10,40,40}; int w1 = 50,w2 = 50; int len = sizeof(w)/sizeof(w[0]); int x[MAX]; Fun(100,0,0,x,w,w1,w2,0,len); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_parse_fun.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tdieumeg <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/02/16 17:54:42 by tdieumeg #+# #+# */ /* Updated: 2014/02/16 17:54:45 by tdieumeg ### ########.fr */ /* */ /* ************************************************************************** */ #include "RTv1.h" void ft_fillplane(t_list **list, t_obj **olist) { t_plane *plane; plane = ft_planenew(ft_get_vect(list), ft_get_point(list)); ft_objpushfront(olist, plane, O_PLANE, ft_get_color(list)); } void ft_fillsphere(t_list **list, t_obj **olist) { int i; t_sphere *sphere; sphere = ft_spherenew(ft_atoi((*list)->content), ft_atoi((*list)->next->content), ft_atoi((*list)->next->next->content), ft_atoi((*list)->next->next->next->content)); i = 0; while (i++ < 4) *list = (*list)->next; ft_objpushfront(olist, sphere, O_SPHERE, ft_get_color(list)); } void ft_fillcylinder(t_list **list, t_obj **olist) { t_cylinder *cylinder; cylinder = ft_cylindernew(ft_get_point(list), ft_get_vect(list), ft_atoi((*list)->content)); *list = (*list)->next; ft_objpushfront(olist, cylinder, O_CYLINDER, ft_get_color(list)); } void ft_fillcone(t_list **list, t_obj **olist) { t_cone *cone; cone = ft_conenew(ft_get_point(list), ft_get_vect(list), ft_atoi((*list)->content), (ft_atoi((*list)->next->content) / 180.0) * M_PI); *list = (*list)->next; ft_objpushfront(olist, cone, O_CONE, ft_get_color(list)); }
C
/* Write a program that has a global counter that increments every 1 second and the counter resets every time there is a SIGINT signal. SIGQUIT and SIGTERM should be ignored. Remember to manage critical regions in the main loop */ #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <signal.h> #include <unistd.h> #include <signal.h> int counter = 0; void sigintHandler(int sig); // handler function for signal int main(void) { sigset_t sigmask; struct sigaction action; printf("Pid=%d\n", getpid()); /* Handle SIGINT */ action.sa_handler = sigintHandler; sigemptyset(&action.sa_mask); action.sa_flags = SA_RESTART; sigaction(SIGINT, &action, NULL); /* IGNORE SIGQUIT */ action.sa_handler = SIG_IGN; sigaction(SIGQUIT, &action, NULL); sigaction(SIGTERM, &action, NULL); sigemptyset(&sigmask); sigaddset(&sigmask, SIGINT); while(1) { sleep(1); printf("Counting = %d\n", counter); /* Blocking state */ sigprocmask(SIG_BLOCK, &sigmask, NULL); counter++; sigprocmask(SIG_UNBLOCK, &sigmask, NULL); } return EXIT_SUCCESS; } void sigintHandler(int sig) { counter = 0; }
C
#include<mpi.h> #include<stdio.h> #include<string.h> #define comm MPI_COMM_WORLD int main(int argc, char const *argv[]) { int root=0; int a; int rank,size; MPI_Init(NULL, NULL); MPI_Status status; MPI_Comm_rank(comm,&rank); MPI_Comm_size(comm,&size); if (rank==root) { printf("enter a number\n"); scanf("%d",&a); MPI_Ssend(&a,1,MPI_INT,rank+1,rank,comm); printf("process %d: %d sent to process %d\n",rank,a,rank+1); MPI_Recv(&a,1,MPI_INT,size-1,size-1,comm,&status); printf("process %d: %d recieved from process %d\n",rank,a,size-1); } else{ MPI_Recv(&a,1,MPI_INT,rank-1,rank-1,comm,&status); a=a+1; MPI_Ssend(&a,1,MPI_INT,(rank+1)%size,rank,comm); printf("process %d: %d sent to process %d\n",rank,a,(rank+1)%size); } MPI_Finalize(); return 0; }
C
/* * Functions in relation to accessing and minimizing * the space consumption of a (unsigned short) */ #include "bitPacking.h" void packBits(unsigned short *toPack, int packSize, LeftOver *LO) { unsigned short mask = 0; unsigned short prev_LO = LO->data; /*& ((1 << LO->size) -1);*/ int LO_prevSize = LO->size; /* toPack takes 8 bits, LO takes others */ LO->size = (packSize - 8 + LO_prevSize); mask = (1 << LO->size) -1; /* mask of bits to send to LO */ LO->data = (*toPack) & mask; /* copy toPack Leftovers */ /* shift toPack to remove bits saved in LO */ (*toPack) >>= LO->size; /* Logical Right Shift */ /* shift so that prev_LO does not overwite meaningfull toPack bits */ prev_LO <<= (8 - LO_prevSize); /* at most shifts 8 */ /* mask size (pS - LO) at LSB */ mask = (1 << (8 - LO_prevSize)) -1; /* add the contents of (prev Left Over) to toPack */ (*toPack) = ( (*toPack) & mask ) + prev_LO; } /* * Note that unloadChar is restricted to the size of a * char, but is a unsigned short to allow bit operations with other shorts */ int unloadLeftOver(LeftOver *LO, unsigned short *unloadChar) { short mask; (*unloadChar) = 0; if(LO->size >= 8) { LO->size -= 8; /* create a mask of the upper 8 MSBs */ mask = ((1 << 8) -1) << (LO->size); (*unloadChar) = ( LO->data & mask ) >> LO->size; /* keep only the last bits to remain in LO */ LO->data &= (1 << LO->size) -1; return 1; } return 0; } int releaseLeftOver(LeftOver * LO, unsigned short *unloadChar){ short mask; (*unloadChar) = 0; if(LO->size > 0) { LO->size -= 8; /* create a mask of the upper 8 MSBs */ mask = ((1 << 8) -1) << (LO->size); (*unloadChar) = ( LO->data & mask ) >> LO->size; /* keep only the last bits to remain in LO */ LO->data &= (1 << LO->size) -1; return 1; } return 0; }
C
#include <stdio.h> typedef struct point { int x; int y; } P; int main() { P p; p.x = 10; p.y = 20; printf("%d, %d", p.x, p.y); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<limits.h> #include "./PES1UG19CS393_H.h" //utility function to setup and return a graph struct ptr graph* createGraph(int V) { graph* new = (graph*)malloc(sizeof(graph)); new->v = V; new->array = (list*)malloc(V * sizeof(list)); for (int i = 0; i < V; ++i) { new->array[i].head = NULL; } return new; } //utility function to malloc and return a adj list node node* createNode(int adj,int weight) { node* new=(node*)malloc(sizeof(node)); new->data=adj; new->wt=weight; new->next=NULL; return new; } //utility fn to add an edge //the edge is added in the reverse direction as per this //implementation of dijkstra void createLink(graph* graph, int src,int dest,int weight) { node* new=createNode(src,weight); new->next = graph->array[dest].head; graph->array[dest].head = new; } //utility fn to print the graph //for debugging void printGraph(graph* g) { for(int i=0;i<g->v;i++) { printf("Node %d:",i); node* cur=g->array[i].head; while(cur!=NULL) { printf("(%d,%d)->",cur->data,cur->wt); cur=cur->next; } printf("\n"); } } // A utility function to create and return a min heap node heapNode* newheapNode(int v,int wt) { heapNode* new =(heapNode*)malloc(sizeof(heapNode)); new->v = v; new->wt = wt; return new; } // A utility function to create and return a new minHeap MinHeap* createMinHeap(int capacity) { MinHeap* minHeap =(struct minHeap*)malloc(sizeof(MinHeap)); minHeap->pos = (int *)malloc(capacity * sizeof(int)); minHeap->size = 0; minHeap->capacity = capacity; minHeap->array =(struct heapNode**)malloc(capacity *sizeof(struct heapNode*)); return minHeap; } //function to rectify the min heap after each deletion void heapify(struct minHeap* minHeap,int idx) { int smallest, left, right; smallest = idx; left = 2 * idx + 1; right = 2 * idx + 2; if (left < minHeap->size && minHeap->array[left]->wt < minHeap->array[smallest]->wt) { smallest = left; } if (right < minHeap->size && minHeap->array[right]->wt < minHeap->array[smallest]->wt) { smallest = right; } if (smallest != idx) { // The nodes to be swapped in min heap heapNode *smallestNode = minHeap->array[smallest]; heapNode *idxNode = minHeap->array[idx]; // Swap positions minHeap->pos[smallestNode->v] = idx; minHeap->pos[idxNode->v] = smallest; // Swap nodes swapHeapNodes(&minHeap->array[smallest],&minHeap->array[idx]); heapify(minHeap, smallest); } } //Function to swap to heap nodes void swapHeapNodes(heapNode** n1,heapNode** n2) { heapNode* temp = *n1; *n1 = *n2; *n2 = temp; } //utility function to check if heap empty to terminate the dijkstra loop. int isEmpty(struct minHeap* minHeap) { return minHeap->size == 0; } //utility function to return the root element(here the minmum element in the min heap) struct heapNode* returnRoot(struct minHeap* minHeap) { if (isEmpty(minHeap)) { return NULL; } // Store the root node struct heapNode* root = minHeap->array[0]; // Replace root node with last node struct heapNode* lastNode = minHeap->array[minHeap->size - 1]; minHeap->array[0] = lastNode; // Update position of last node minHeap->pos[root->v] = minHeap->size-1; minHeap->pos[lastNode->v] = 0; // Reduce heap size and heapify root minHeap->size=minHeap->size - 1; heapify(minHeap, 0); return root; } //Function to decrease the distance values of heap nodes. void decreaseKey(struct minHeap* minHeap,int v, int wt) { // Get the index of v in heap array int i = minHeap->pos[v]; // Get the node and update its wt value minHeap->array[i]->wt = wt; while (i && minHeap->array[i]->wt < minHeap->array[(i - 1) / 2]->wt) { // Swap this node with its parent minHeap->pos[minHeap->array[i]->v] = (i-1)/2; minHeap->pos[minHeap->array[(i-1)/2]->v] = i; swapHeapNodes(&minHeap->array[i],&minHeap->array[(i - 1) / 2]); i = (i - 1) / 2; } } //check if node is in the min heap. int isInMinHeap(struct minHeap *minHeap, int v) { if (minHeap->pos[v] < minHeap->size) { return 1; } return 0; } //utility function to print the path void printPath(int parent[], int j) { // Base Case : If j is source if (parent[j] == - 1) return; printf("%d ", j); printPath(parent, parent[j]); } // A utility function used for outputting void printSolution(int wt[], int n,int parent[],int src) { for (int i = 1; i < n-1; i++) { if(wt[i]!=INT_MAX) { printf("%d ",i); printPath(parent, i); printf("%d %d\n",src,wt[i]); } else { printf("%d NO PATH\n",i); } } } /*The driver function which performs the dijkstras algorithm on the graph */ void dijkstra(graph* graph, int src) { // Get the number of vertices in graph int V = graph->v; int wt[V]; //stores distances of the nodes from source. int parent[V]; //stores the parent ele of each node. struct minHeap* minHeap = createMinHeap(V); //initilizations. for (int v = 0; v < V; ++v) { wt[v] = INT_MAX; minHeap->array[v] = newheapNode(v,wt[v]); minHeap->pos[v] = v; } parent[src] = -1; // Make wt value of src vertex // as 0 so that it is extracted first minHeap->array[src] =newheapNode(src, wt[src]); minHeap->pos[src] = src; wt[src] = 0; decreaseKey(minHeap, src, wt[src]); // Initially size of min heap is equal to V minHeap->size = V; while (!isEmpty(minHeap)) { // Extract the vertex with minimum distance value struct heapNode* minHeapNode = returnRoot(minHeap); // Store the extracted vertex number int u = minHeapNode->v; node* cur = graph->array[u].head; while (cur != NULL) { int v = cur->data; if (isInMinHeap(minHeap, v) && wt[u] != INT_MAX && cur->wt + wt[u] < wt[v]) { wt[v] = wt[u] + cur->wt; // update distance value in min heap decreaseKey(minHeap, v, wt[v]); parent[v] = u; } cur = cur->next; } } // print the calculated shortest distances printSolution(wt, V,parent,src); }
C
/* * Delta programming language */ #include "DeltaInstruction.h" #include "delta/compiler/compiler.h" struct DeltaInstruction new_DeltaInstruction0(char *name, DeltaByteCode bc) { struct DeltaInstruction d; d.func = name; d.bc = bc; d.args = 0; d.arg = NULL; return d; } struct DeltaInstruction new_DeltaInstruction1(char *name, DeltaByteCode bc, int destination) { struct DeltaInstruction d; d.func = name; d.bc = bc; d.args = 1; d.arg = (int*) calloc(d.args, sizeof(int)); d.arg[0] = destination; return d; } struct DeltaInstruction new_DeltaInstruction2(char *name, DeltaByteCode bc, int destination, int source1) { struct DeltaInstruction d; d.func = name; d.bc = bc; d.args = 2; d.arg = (int*) calloc(d.args, sizeof(int)); d.arg[0] = destination; d.arg[1] = source1; return d; } struct DeltaInstruction new_DeltaInstruction3(char *name, DeltaByteCode bc, int destination, int source1, int source2) { struct DeltaInstruction d; d.func = name; d.bc = bc; d.args = 3; d.arg = (int*) calloc(d.args, sizeof(int)); d.arg[0] = destination; d.arg[1] = source1; d.arg[2] = source2; return d; } struct DeltaInstruction new_DeltaInstructionN(char *name, DeltaByteCode bc) { struct DeltaInstruction d; d.func = name; d.bc = bc; // we don't just assign the pointer we copy the data so that theres no danger of the vaues // changing later and also it saves space. d.args = arg_count[arg_depth]; d.arg = (int*) calloc(d.args, sizeof(int)); int i; for(i = 0; i < d.args; ++i) d.arg[i] = arg_ptr[arg_depth][i]; return d; }
C
#ifndef _UILOW_H #define _UILOW_H enum uilow_ret { UI_OK, UI_ERR }; typedef unsigned int uilow_chtype; // Low-level UI functions /// Initialize the low-level UI void uilow_init(void); /// Deinitialize the low-level UI void uilow_end(void); /// Move to a position on the display enum uilow_ret uilow_move(int y, int x); /// Add a character, then advance the cursor enum uilow_ret uilow_addch(uilow_chtype ch); /// Move and add a character, then advance the cursor enum uilow_ret uilow_mvaddch(int y, int x, uilow_chtype ch); /// Add a string of characters, then advance the cursor enum uilow_ret uilow_addstr(const char *str); /// Move, add a string of characters, then advance the cursor enum uilow_ret uilow_mvaddstr(int y, int x, const char *str); /// Get the current cursor position void uilow_getyx(int *y, int *x); /// Get the width and height void uilow_getmaxyx(int *y, int *x); #endif // _UILOW_H
C
/* * tcpechosrv.c - A concurrent TCP echo server using threads */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* for fgets */ #include <strings.h> /* for bzero, bcopy */ #include <unistd.h> /* for read, write */ #include <sys/socket.h> /* for socket use */ #include <signal.h> /* for signals */ #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #include <pthread.h> #include "headers/helper_functions.h" #include "headers/http_errors.h" #include "headers/request_handlers.h" #include "headers/httpechosrv.h" /** * Main function: Sets the signal handler, creates the listening port to get requests and opens new threads on request */ int main(int argc, char **argv) { // Install signal handler for SIGINT struct sigaction custom_handler; custom_handler.sa_handler = sigint_handler; sigaction(SIGINT, &custom_handler, NULL); int listenfd, *connfdp, port, clientlen = sizeof(struct sockaddr_in); struct sockaddr_in clientaddr; pthread_t tid; // There should be an arg detailing port number. ie: ./out [PORT] if (argc != 2) { fprintf(stderr, "usage: %s <port>\n", argv[0]); exit(0); } port = atoi(argv[1]); // Opens new port on which program listens to listenfd = open_listenfd(port); while (1) { connfdp = malloc(sizeof(int)); // Accepts client connection - Gets first connection on listenfd socket and creates a new dedicated socket for client. // If no connections then block until one comes // https://www.ibm.com/support/knowledgecenter/SSLTBW_2.3.0/com.ibm.zos.v2r3.bpxbd00/accept.htm *connfdp = accept(listenfd, (struct sockaddr *)&clientaddr, &clientlen); pthread_create(&tid, NULL, thread, connfdp); } } /** * Main function for threads; Argument is the socket file descriptor. First parses the incoming request, * then goes to the corresponding request handler (GET or POST) */ void *thread(void *vargp) { int connfd = *((int *)vargp); // Makes it so that when this specific thread exits system can free the used resources without waiting pthread_detach(pthread_self()); free(vargp); request *req = malloc(sizeof(request)); memset(req->path, 0, sizeof(req->path)); memset(req->http_version, 0, sizeof(req->http_version)); memset(req->connection, 0, sizeof(req->connection)); req->connfd = connfd; parse_request(req); if (req->request_type == 1) { handle_get_request(req); } else if (req->request_type == 2) { handle_post_request(req); } else { send500(req); } free(req); close(connfd); return NULL; } /** * SIGINT handler to exit gracefully */ void sigint_handler(int signal) { printf("\nWebserver is shutting down.\n"); exit(SIGINT); } /* * open_listenfd - open and return a listening socket on port * Returns -1 in case of failure */ int open_listenfd(int port) { int listenfd, optval = 1; struct sockaddr_in serveraddr; /* Create a socket descriptor */ if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) return -1; /* Eliminates "Address already in use" error from bind. */ if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval, sizeof(int)) < 0) return -1; /* listenfd will be an endpoint for all requests to port on any IP address for this host */ bzero((char *)&serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); serveraddr.sin_port = htons((unsigned short)port); if (bind(listenfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0) return -1; /* Make it a listening socket ready to accept connection requests */ if (listen(listenfd, LISTENQ) < 0) return -1; return listenfd; } /* end open_listenfd */
C
/* * lcd.h * * Created on: Sep 4, 2019 * Author: Joseph Hanna */ #ifndef LCD_H_ #define LCD_H_ #include <avr/io.h> #include <util/delay.h> /* Set a certain bit in any register */ #define SET_BIT(REG,BIT) (REG|=(1<<BIT)) /* Clear a certain bit in any register */ #define CLEAR_BIT(REG,BIT) (REG&=(~(1<<BIT))) /* Toggle a certain bit in any register */ #define TOGGLE_BIT(REG,BIT) (REG^=(1<<BIT)) /* Rotate right the register value with specific number of rotates */ #define ROR(REG,num) ( REG= (REG>>num) | (REG<<(8-num)) ) /* Rotate left the register value with specific number of rotates */ #define ROL(REG,num) ( REG= (REG<<num) | (REG>>(8-num)) ) /* Check if a specific bit is set in any register and return true if yes */ #define BIT_IS_SET(REG,BIT) ( REG & (1<<BIT) ) /* Check if a specific bit is cleared in any register and return true if yes */ #define BIT_IS_CLEAR(REG,BIT) ( !(REG & (1<<BIT)) ) /* LCD HW Pins */ #define RS PD4 #define RW PD5 #define E PD6 #define LCD_CTRL_PORT PORTD #define LCD_CTRL_PORT_DIR DDRD #define LCD_DATA_PORT PORTC #define LCD_DATA_PORT_DIR DDRC /* LCD Commands */ #define CLEAR_COMMAND 0x01 #define HOME 0x02 #define TWO_LINE_LCD_Eight_BIT_MODE 0x38 #define CURSOR_OFF 0x0C #define CURSOR_ON 0x0E #define SET_CURSOR_LOCATION 0x80 void LCD_sendCommand(unsigned char command); void LCD_displayCharacter(unsigned char data); void LCD_displayString(const char *Str); void LCD_init(void); void LCD_clearScreen(void); void LCD_displayStringRowColumn(unsigned char row,unsigned char col,const char *Str); void LCD_goToRowColumn(unsigned char row,unsigned char col); void LCD_intgerToString(int data); #endif /* LCD_H_ */
C
#include <string.h> #include "hecdssInternal.h" #include "heclib.h" /** * Function: getDateAndTime * * Use: Public * * Description: Returns the date and time from params in a time series struct. * * Declaration: int getDateAndTime(int time, int timeGranularitySeconds, int julianBaseDate, char *dateString, int sizeOfDateString, char* hoursMins, int sizeofHoursMins); * * Parameters: int time * The time value to convert to character, given in timeGranularitySeconds since baseDate. * "1" is one second past midnight. "0" doesn't exist, as midnight belongs to the end * of the day, by convention, and midnight is the number SECS_IN_1_DAY. * secondsPastMidnight varies from 1 to SECS_IN_1_DAY. * * int timeGranularitySeconds * The number of seconds each unit in time represents, * MINUTE_GRANULARITY (60) or SECOND_GRANULARITY (1) or * HOUR_GRANULARITY (3600) or DAY_GRANULARITY (86400) * * int julianBaseDate * The Julian base date, which when appropriatly aded to the time, give the full correct * date and time. * * char dateString[20] * The character string to return the date in. Must be dimensioned to 13. * * int sizeOfDateString * The length of the string. Must be at least 13. * * char hoursMins[9] * The character string to return the hours and minutes in. Must be dimensioned to 9. * * int sizeofHoursMins * The length of the string. Must be at least 9. * * * Returns: None * * Author: Bill Charley * Date: 2012 * Organization: US Army Corps of Engineers, Hydrologic Engineering Center (USACE HEC) * All Rights Reserved * **/ int getDateAndTime(int time, int timeGranularitySeconds, int julianBaseDate, char *dateString, int sizeOfDateString, char* hoursMins, int sizeofHoursMins) { int numberInDay; int days; int timeOfDay; int julian; long long granularity; // Convert minutes or seconds to days and seconds granularity = (long long)timeGranularitySeconds; if (granularity < 1) granularity = MINUTE_GRANULARITY; numberInDay = (int)(SECS_IN_1_DAY / granularity); days = time / numberInDay; julian = julianBaseDate + days; // Now start day and seconds timeOfDay = time - (days * numberInDay); if (timeOfDay < 1) { julian--; timeOfDay += numberInDay; } if (timeGranularitySeconds == SECOND_GRANULARITY) { secondsToTimeString(timeOfDay, 0, 2, hoursMins, sizeofHoursMins); } else if (timeGranularitySeconds == MINUTE_GRANULARITY) { minutesToHourMin(timeOfDay, hoursMins, sizeofHoursMins); } else { // Get minutes timeOfDay *= (timeGranularitySeconds / SECS_IN_1_MINUTE); minutesToHourMin(timeOfDay, hoursMins, sizeofHoursMins); } julianToDate(julian, 4, dateString, sizeOfDateString); return 0; }
C
# Description ====================================================================================================================================== Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space characters only. For example, Given s = "Hello World", return 5. --------------------------------------------------------------------------------------------------------------------------------------- # Solution int lengthOfLastWord(char* s) { int length=strlen(s); int index=0; int i; while(length>=0 && s[length-1]==' ') { length--; } for(i=0; i<length; i++) { if(s[i]!=' ') { index++; } else { index=0; } } return index; }
C
//switch #include <cs50.h> #include <stdio.h> int main (void) { // Promt user for ancwer char c = get_char(" G(g) or N(n): "); char c2 = get_char("G(g) or N(n): "); // Check answer switch (c) { case 'n': case 'N': printf("Никита\n"); break; case 'G': case 'g': printf("Жанна\n"); break; } switch(c2) { case 'g': case 'n': case 'G': case 'N': printf("Жанна+Никита"); break; } }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <assert.h> size_t my_strlen(const char* str) //ָΪԪظ { assert(str != NULL); char *p = str; while (*p != '\0') { p++; } return p - str; } //size_t my_strlen(const char* str) //ʱ //{ // assert(str != NULL); // if (*str == '\0') // return 0; // else // return 1 + my_strlen(str + 1); //} //size_t my_strlen(const char* str) //{ // int count = 0; // // assert(str != NULL); // while (*str++ != '\0') // { // count++; // } // return count; //} int main() { char *p = "hello"; int num = my_strlen(p); printf("%d\n", num); system("pause"); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> void swap(int* a, int* b) { int temp; temp = *a; *a = *b; *b = temp; } int main() { int a = 0; int b = 0; printf("֣"); scanf("%d %d", &a, &b); swap(&a, &b); printf("a = %d b = %d", a, b); system("pause"); }
C
#include <stdlib.h> #include <stdio.h> #include <errno.h> #include <assert.h> #ifndef QUEUE_Q_H #define QUEUE_Q_H typedef struct Item { int val; struct Item *prev; struct Item *next; } Item; typedef struct Queue { Item *head; Item *tail; } Queue; void PrintAction(char *act, Item *item) { if (item != NULL) printf("Action: %s %d\n", act, item->val); else printf("Action: %s\n", act); } void PrintQueue(Queue *queue) { Item *cur = queue->head; printf("Queue: ["); while (cur != NULL) { if (cur != queue->head) printf(", "); printf("%d", cur->val); if (cur == queue->tail) break; cur = cur->next; } printf("]\n"); } Item *NewItem(int val) { Item *item = (Item *) malloc(sizeof(Item)); item->val = val; item->prev = NULL; item->next = NULL; return item; } void FreeItem(Item *item) { free(item); } Queue *NewQueue() { Queue *queue = (Queue *) malloc(sizeof(Queue)); queue->head = NULL; queue->tail = NULL; return queue; } void AddQueue(Queue *queue, Item *item) { PrintAction("Add", item); if (queue->head == NULL) { queue->head = item; queue->tail = item; item->prev = item; item->next = item; } else { item->next = queue->head; item->prev = queue->tail; queue->head->prev = item; queue->tail->next = item; queue->tail = item; } PrintQueue(queue); } Item *DelQueue(Queue *queue) { if (queue->head == NULL) { perror("queue empty error!!"); exit(EXIT_FAILURE); } else { if (queue->head == queue->tail) { Item *res = queue->head; queue->head = queue->tail = NULL; res->prev = res->next = NULL; PrintAction("Del", res); PrintQueue(queue); return res; } else { Item *res = queue->head; Item *next = res->next; Item *prev = res->prev; next->prev = prev; prev->next = next; queue->head = next; res->prev = res->next = NULL; PrintAction("Del", res); PrintQueue(queue); return res; } } } void RotateQ(Queue *queue) { PrintAction("Rotate", NULL); if (queue->head == NULL) { perror("queue empty error!!"); exit(EXIT_FAILURE); } queue->head = queue->head->next; queue->tail = queue->tail->next; PrintQueue(queue); } #endif //QUEUE_Q_H
C
/*PROGRAM TO FIND SUM OF DIGITS OF A GIVEN NUMBER*/ #include<stdio.h> void main() { /*declaring variables*/ int i,n; int sum=0, temp; printf("enter a number to find sum of its digits\n"); scanf("%d",&n); while(n!=0){ temp=n%10; sum+=temp; n=n/10; } printf("sum of the digits of a given number is%d\n",sum); } /*.....................................................................................................................*/
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* parse_types.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: iserzhan <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/07/07 22:50:18 by iulias #+# #+# */ /* Updated: 2020/07/28 17:32:31 by iserzhan ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" size_t parse_format(char *str, va_list ap, t_format *format) { int len; len = 0; if ((format->precision >= 0) || (format->minus && format->zero)) format->zero = 0; if (*str == 'd' || *str == 'i') len = parse_int(va_arg(ap, int), format); if (*str == 'u' || *str == 'x' || *str == 'X') len = parse_int_unsigned(str, va_arg(ap, unsigned int), format); if (*str == '%') len = print_char('%', format); if (*str == 's') len = parse_str(va_arg(ap, char *), format); if (*str == 'c') len = print_char((char)va_arg(ap, int), format); if (*str == 'p') len = parse_pointer((unsigned long)va_arg(ap, void *), format); return (len); } int parse_pointer(unsigned long nbr, t_format *format) { char *temp; char *str; int size; str = convert_pointer(format, nbr, 16); temp = str; size = ft_strsize(str); if (format->precision > size || (format->zero && (format->width > size))) { str = ft_substr(str, 2, size - 2); free(temp); format->pointer = 1; } return (ft_print(str, format)); } int parse_int(int nbr, t_format *format) { char *nstr; char *temp; if (nbr < 0 && ((format->precision >= ft_size(nbr)) || (format->zero && (format->width > ft_size(nbr))))) { if (nbr == MIN_INT) { nstr = ft_itoa(nbr); temp = nstr; nstr = ft_substr(nstr, 1, 10); free(temp); format->nbr_sign = 1; return (ft_print(nstr, format)); } nbr = nbr * -1; format->nbr_sign = 1; } if (format->precision == 0 && nbr == 0) format->empty++; nstr = ft_itoa(nbr); return (ft_print(nstr, format)); } int parse_int_unsigned(char *str, unsigned int nbr, t_format *format) { char *nstr; int i; nstr = NULL; i = 0; if (format->precision == 0 && nbr == 0) format->empty++; if (*str == 'u') nstr = ft_itoa_unsigned(nbr); else if (*str == 'x' || *str == 'X') { nstr = ft_itoa_base(nbr, 16); if (*str == 'X') { while (nstr[i]) { nstr[i] = (char)ft_toupper(nstr[i]); i++; } } } return (ft_print(nstr, format)); } int parse_str(char *nstr, t_format *format) { char *temp; if (!nstr) { nstr = ft_strdup("(null)"); if (format->precision == 0) format->empty++; } else nstr = ft_strdup(nstr); temp = nstr; if (format->precision < ft_strsize(nstr) && format->precision != -1) { nstr = ft_substr(nstr, 0, format->precision); free(temp); temp = 0; } if (format->precision == 0) format->empty++; if (format->precision > ft_strsize(nstr)) format->precision = -1; return (ft_print(nstr, format)); }
C
#include <math.h> #include <stdint.h> float fabsf(float x) { union { float f; uint32_t i; } u = {x}; u.i &= 0x7fffffff; return u.f; }
C
#include <stdio.h> #include <assert.h> #include "mil.h" #define STACK_SIZE_MAX (65536) typedef enum { INT_VALUE_TYPE, STRING_VALUE_TYPE } ValueType; typedef struct { ValueType type; union { int int_value; char *string_value; } u; } Value; static Value st_stack[STACK_SIZE_MAX]; static Value st_variable[VAR_MAX]; void mvm_execute(void){ int pc = 0; int sp = 0; while (pc < g_bytecode_size) { switch (g_bytecode[pc]) { case OP_PUSH_INT: st_stack[sp].type = INT_VALUE_TYPE; st_stack[sp].u.int_value = (int)g_bytecode[pc+1]; sp++; pc += 2; break; case OP_PUSH_STRING: st_stack[sp].type = STRING_VALUE_TYPE; st_stack[sp].u.string_value = g_str_pool[g_bytecode[pc+1]]; sp++; pc += 2; break; case OP_ADD: st_stack[sp-2].u.int_value = st_stack[sp-2].u.int_value + st_stack[sp-1].u.int_value; sp--; pc++; break; case OP_SUB: st_stack[sp-2].u.int_value = st_stack[sp-2].u.int_value - st_stack[sp-1].u.int_value; sp--; pc++; break; case OP_MUL: st_stack[sp-2].u.int_value = st_stack[sp-2].u.int_value * st_stack[sp-1].u.int_value; sp--; pc++; break; case OP_DIV: st_stack[sp-2].u.int_value = st_stack[sp-2].u.int_value / st_stack[sp-1].u.int_value; sp--; pc++; break; case OP_MINUS: st_stack[sp-1].u.int_value = -st_stack[sp-1].u.int_value; pc++; break; case OP_EQ: st_stack[sp-2].u.int_value = st_stack[sp-2].u.int_value == st_stack[sp-1].u.int_value; sp--; pc++; break; case OP_NE: st_stack[sp-2].u.int_value = st_stack[sp-2].u.int_value != st_stack[sp-1].u.int_value; sp--; pc++; break; case OP_GT: st_stack[sp-2].u.int_value = st_stack[sp-2].u.int_value > st_stack[sp-1].u.int_value; sp--; pc++; break; case OP_GE: st_stack[sp-2].u.int_value = st_stack[sp-2].u.int_value >= st_stack[sp-1].u.int_value; sp--; pc++; break; case OP_LT: st_stack[sp-2].u.int_value = st_stack[sp-2].u.int_value < st_stack[sp-1].u.int_value; sp--; pc++; break; case OP_LE: st_stack[sp-2].u.int_value = st_stack[sp-2].u.int_value <= st_stack[sp-1].u.int_value; sp--; pc++; break; case OP_PUSH_VAR: st_stack[sp] = st_variable[(int)g_bytecode[pc+1]]; sp++; pc += 2; break; case OP_ASSIGN_TO_VAR: st_variable[(int)g_bytecode[pc+1]] = st_stack[sp-1]; sp--; pc += 2; break; case OP_JUMP: pc = (int)g_bytecode[pc+1]; break; case OP_JUMP_IF_ZERO: if (!st_stack[sp-1].u.int_value) { pc = (int)g_bytecode[pc+1]; } else { pc += 2; } sp--; break; case OP_GOSUB: st_stack[sp].u.int_value = pc + 2; sp++; pc = (int)g_bytecode[pc+1]; break; case OP_RETURN: pc = st_stack[sp-1].u.int_value; sp--; break; case OP_PRINT: if(st_stack[sp-1].type == INT_VALUE_TYPE){ printf("%d\n", st_stack[sp-1].u.int_value); }else if(st_stack[sp-1].type == STRING_VALUE_TYPE){ printf("%s\n", st_stack[sp-1].u.string_value); } sp--; pc++; break; default: assert(0); } } }
C
/* * File: file_reader.h * * Brief: Simple file reader utility that provides an easy and intuitive way to * load a file's contents into memory. * * LICENSE: MIT * * Author: Alexander DuPree * * https://github.com/AlexanderJDupree/File_Reader */ #ifndef FILE_READER_H #define FILE_READER_H #include <stdio.h> #include <stddef.h> typedef struct File_Reader { const char* contents; size_t size; } File_Reader; int is_file(const char* file_path); File_Reader open_file(const char* file_path); int close_reader(File_Reader* reader); // Uses file stream and fseek to determine file size size_t get_size(FILE* file); #endif
C
//-ӡ100-200֮ #include<stdio.h> #include<math.h> int aaa(int pi) { int j = 0; for (int j = 2; j <= sqrt(pi); j++) { if (pi % j == 0) return 0; } return 1; } int sum = 0; int main() { //ӡ100-200֮ int i = 0; for (int i = 100; i < 200; i++) { if (aaa(i) == 1) { printf("%d\n", i); sum++; } } printf("sum=%d\n", sum); return 0; }
C
#include<stdio.h> #include<stdlib.h> #define COMPARE(x,y) ((x) < (y)? -1: ((x)==(y))? 0:1) void sort(int *arr1, int n); int BinarySearch(int arr1[],int searchnum, int left, int right); void main() { FILE *fin=fopen("input.txt","rt"); FILE *fout=fopen("ouput.txt","wt"); int *arr1; int i,n,m; int left,right; fscanf(fin,"%d",&n); fscanf(fin,"%d",&m); arr1 = (int*)malloc(sizeof(int)*n); for(i=0;i<n;i++) { fscanf(fin,"%d",&arr1[i]); } sort(arr1,n); left=0; right=n-1; for(i=0;i<n;i++) { fprintf(fout,"%d ",arr1[i]); } fprintf(fout,"\n"); fprintf(fout,"%d\n",BinarySearch(arr1,m,left,right)); free(arr1); fclose(fin); fclose(fout); } void sort(int *arr1, int n) { int i, j; int temp; for(i=0;i<n-1;i++) { for(j=i+1;j<n;j++) if(arr1[j] < arr1[i]) { temp = arr1[j]; arr1[j]=arr1[i]; arr1[i]=temp; } } } int BinarySearch(int arr1[],int searchnum, int left, int right) { int middle; while(left<=right) { middle=(left+right)/2; switch(COMPARE(arr1[middle],searchnum)) { case -1: left = middle+1; break; case 0: return middle+1; case 1: right = middle -1; } } return -1; }
C
/** * \file fenetre.c * \brief Implémente les fonctions de fenetre.h * \author Pauline.M * \version 1.0 * \date 01 mai 2019 * * Implémente les fonctions utiles à l'affichage du jeu. */ #include "fenetre.h" #include <SDL.h> #include <SDL_ttf.h> #include <stdio.h> #include <stdlib.h> #include "developpement.h" #include "partie.h" #include "get_plateau.h" #include "architecture.h" #include "tuile.h" #include "carte.h" #include "developpement.h" #include "probabilite.h" #include "place_infra.h" #include "affiche_joueur.h" #include "SDL_erreur.h" #include "affiche_texte.h" #include "set_partie.h" #define WINDOWW 1920 #define WINDOWH 950 #define RED 64 #define GREEN 159 #define BLUE 255 /** * \fn SDL_Window* InitFenetre() * \brief Fonction créant une fenêtre. * * * \param aucun * \return Affiche une fenêtre */ SDL_Window* InitFenetre(){ SDL_Window *window = NULL; if(TTF_Init()!=0){ fprintf(stderr, "Erreur d'initialisation TTF : %s\n", TTF_GetError()); } if(SDL_Init(SDL_INIT_VIDEO)!=0) SDL_ExitWithError("Initialisation SDL impossible"); //Creation de la fenetre en fullscreen et rendu if((window = SDL_CreateWindow("Catane",SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOWW, WINDOWH, SDL_WINDOW_FULLSCREEN_DESKTOP)) == NULL) SDL_ExitWithError("Impossible de creer la fenetre"); return window; } /** * \fn SDL_Renderer* updateFenetre(Partie* p, SDL_Window* window) * \brief Fonction mettant à jour le plateau de jeu en fonction de la partie * * * \param p, la partie de jeu * \param window, la fenêtre du jeu * \return le nouveau renderer */ void updateFenetre(Partie* p, SDL_Window* window){ SDL_DestroyRenderer(SDL_GetRenderer(window)); SDL_Renderer* renderer = NULL; renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE); //Couleur fond if(SDL_SetRenderDrawColor(renderer, RED, GREEN, BLUE, SDL_ALPHA_OPAQUE) != 0) SDL_ExitWithError("Impossible de changer la couleur du rendu"); SDL_Rect rectangle; rectangle.x = 0; rectangle.y = 0; rectangle.w = WINDOWW; rectangle.h = WINDOWH; if(SDL_RenderFillRect(renderer, &rectangle) != 0) SDL_ExitWithError("Impossible de remplir un rectangle"); if(renderer == NULL) SDL_ExitWithError("Creation rendu echouée"); AfficheDe(window, p); AfficheChevalier(renderer); AfficheMonopole(renderer); AfficheInvention(renderer); AfficheRouteDev(renderer); AfficheUniversite(renderer); AfficheGrandeArmee(renderer); AfficheGrandeRoute(renderer); AfficheTuilePlateau(p,renderer); AfficheRandomProbaPlateau(p,renderer); AfficheTuile(renderer); AfficheCarteArgile(renderer); AfficheCarteBle(renderer); AfficheCarteBois(renderer); AfficheCarteMouton(renderer); AfficheCarteRoche(renderer); AfficheVoleur(p, renderer); AfficheJoueur(renderer); AfficheListeJoueurs(p,renderer); AfficheSkip(renderer); AfficheHelp(renderer); AfficheBoutonDev(renderer); AfficheBoutonRoute(renderer); AfficheBoutonColonie(renderer); AfficheBoutonVille(renderer); Affiche_Infrastructures(p,renderer); AfficheNbCarte(p, renderer); AfficheNbReussiteChevalier(p, renderer); AfficheNbReussiteRoute(p, renderer); SDL_RenderPresent(renderer); AfficheTexte_MAJ(window); } /** * \fn void destroyFenetre(SDL_Window* window) * \brief Fonction détruisant la fenêtre et le renderer, et permettant de quitter SDL. * * * \param window, la fenêtre du jeu * \return aucun */ void destroyFenetre(SDL_Window* window){ TTF_Quit(); SDL_DestroyRenderer(SDL_GetRenderer(window)); SDL_DestroyWindow(window); SDL_Quit(); } /** * \fn void AfficheSkip(SDL_Renderer* renderer) * \brief Fonction affichant le bouton pour passer son tour * * * \param renderer, le rendu actuel * \return aucun */ void AfficheSkip(SDL_Renderer* renderer) { SDL_Surface *image = NULL; SDL_Texture *skip = NULL; image = SDL_LoadBMP("../images/skip.bmp"); if(image == NULL) SDL_ExitWithError("Impossible de charger l'image skip.bmp"); skip = SDL_CreateTextureFromSurface(renderer, image); SDL_FreeSurface(image); if(skip == NULL) SDL_ExitWithError("impossible de creer la texture"); SDL_Rect rectskip; if(SDL_QueryTexture(skip, NULL, NULL, &rectskip.w, &rectskip.h) != 0) SDL_ExitWithError("Impossible de charger la texture"); rectskip.x = 300; rectskip.y = 820; if(SDL_RenderCopy(renderer, skip, NULL, &rectskip) !=0) SDL_ExitWithError("Impossible d'afficher la texture"); SDL_RenderPresent(renderer); } /** * \fn void AfficheDe(SDL_Renderer* renderer) * \brief Fonction affichant le dé * * * \param renderer, le rendu actuel * \return aucun */ void AfficheDe(SDL_Window* window, Partie* partie) { SDL_Renderer* renderer = SDL_GetRenderer(window); TTF_Font* police = TTF_OpenFont("../fonts/Vogue.ttf", 100); if(police == NULL) SDL_ExitWithError("Echec du chargement de la police Vogue.ttf"); SDL_Color couleur = {255, 255, 255, SDL_ALPHA_OPAQUE}; int lancer = get_des(partie); char de[20] = ""; if(SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE) != 0) SDL_ExitWithError("Impossible de changer la couleur du rendu"); SDL_Rect rectde; rectde.x = 1570; rectde.y = 110; rectde.w = 100; rectde.h = 100; SDL_Rect rect; rect.x = 1596; rect.y = 125; rect.w = 100; rect.h = 100; if(SDL_RenderFillRect(renderer, &rectde) != 0) SDL_ExitWithError("Impossible de remplir un rectangle"); if((lancer == 10) | (lancer == 11) | (lancer == 12)){ rect.x = 1572; } sprintf(de, "%d", lancer); SDL_Surface* surfde = TTF_RenderText_Blended(police, de, couleur); if(surfde == NULL) SDL_ExitWithError("Echec de la creation de la surface du de"); SDL_Texture* textde = SDL_CreateTextureFromSurface(renderer, surfde); if(textde == NULL) SDL_ExitWithError("Echec de la creation de la texture du de"); SDL_QueryTexture(textde, NULL, NULL, &rect.w, &rect.h); SDL_RenderCopy(renderer, textde, NULL, &rect); TTF_CloseFont(police); } /** * \fn void AfficheHelp(SDL_Renderer* renderer) * \brief Fonction affichant le bouton "?" (help) * * * \param renderer, le rendu actuel * \return aucun */ void AfficheHelp(SDL_Renderer* renderer) { SDL_Surface *image = NULL; SDL_Texture *help = NULL; image = SDL_LoadBMP("../images/help.bmp"); if(image == NULL) SDL_ExitWithError("Impossible de charger l'image help.bmp"); help = SDL_CreateTextureFromSurface(renderer, image); SDL_FreeSurface(image); if(help == NULL) SDL_ExitWithError("impossible de creer la texture"); SDL_Rect recthelp; if(SDL_QueryTexture(help, NULL, NULL, &recthelp.w, &recthelp.h) != 0) SDL_ExitWithError("Impossible de charger la texture"); recthelp.x = 1875; recthelp.y = 0; if(SDL_RenderCopy(renderer, help, NULL, &recthelp) !=0) SDL_ExitWithError("Impossible d'afficher la texture"); } /** * \fn void Help(SDL_Renderer* renderer) * \brief Fonction affichant l'aide du jeu * * * \param renderer, le rendu actuel * \return aucun */ void Help(SDL_Window* w) { SDL_Renderer* renderer = SDL_GetRenderer(w); SDL_Surface *image = NULL; SDL_Texture *help = NULL; image = SDL_LoadBMP("../images/aide.bmp"); if(image == NULL) SDL_ExitWithError("Impossible de charger l'image aide.bmp"); help = SDL_CreateTextureFromSurface(renderer, image); SDL_FreeSurface(image); if(help == NULL) SDL_ExitWithError("impossible de creer la texture"); SDL_Rect recthelp; if(SDL_QueryTexture(help, NULL, NULL, &recthelp.w, &recthelp.h) != 0) SDL_ExitWithError("Impossible de charger la texture"); recthelp.x = 0; recthelp.y = 0; if(SDL_RenderCopy(renderer, help, NULL, &recthelp) !=0) SDL_ExitWithError("Impossible d'afficher la texture"); SDL_RenderPresent(renderer); } /** * \fn void AfficheJetonVoleur(Partie* p, double x, double y, SDL_Renderer* renderer, double posimx, double posimy) * \brief Fonction affichant le jeton du voleur * * * \param p, la partie de jeu actuel * \param x et y les coordonnées du noeud recherché * \param renderer, le rendu actuel * \param posimx et posimy les position en pixel dans la fenetre * \return aucun */ void AfficheJetonVoleur(Partie* p, double x, double y, SDL_Renderer* renderer, double posimx, double posimy) { int v = getVoleur(p, x, y); if (v!= 1) return; else { SDL_Surface *image = NULL; SDL_Texture *voleur = NULL; image = SDL_LoadBMP("../images/voleur.bmp"); if(image == NULL) SDL_ExitWithError("Impossible de charger l'image voleur.bmp"); voleur = SDL_CreateTextureFromSurface(renderer, image); SDL_FreeSurface(image); if(voleur == NULL) SDL_ExitWithError("impossible de creer la texture"); SDL_Rect rectvoleur; if(SDL_QueryTexture(voleur, NULL, NULL, &rectvoleur.w, &rectvoleur.h) != 0) SDL_ExitWithError("Impossible de charger la texture"); rectvoleur.x = posimx; rectvoleur.y = posimy; if(SDL_RenderCopy(renderer, voleur, NULL, &rectvoleur) !=0) SDL_ExitWithError("Impossible d'afficher la texture"); } } /** * \fn void AfficheVoleur(Partie* p, SDL_Renderer* renderer) * \brief Fonction affichant le voleur * * * \param p, la partie actuelle * \param renderer, le rendu actuel * \return aucun */ void AfficheVoleur(Partie* p, SDL_Renderer* renderer) { AfficheJetonVoleur(p, -1, 2, renderer, 792, 152); AfficheJetonVoleur(p, 0, 2, renderer, 928, 152); AfficheJetonVoleur(p, 1, 2, renderer, 1063, 152); AfficheJetonVoleur(p, -1.5, 1, renderer, 724, 270); AfficheJetonVoleur(p, -0.5, 1, renderer, 860, 270); AfficheJetonVoleur(p, 0.5, 1, renderer, 996, 270); AfficheJetonVoleur(p, 1.5, 1, renderer, 1130, 270); AfficheJetonVoleur(p, -2, 0, renderer, 656, 388); AfficheJetonVoleur(p, -1, 0, renderer, 792, 388); AfficheJetonVoleur(p, 0, 0, renderer, 928, 388); AfficheJetonVoleur(p, 1, 0, renderer, 1063, 388); AfficheJetonVoleur(p, 2, 0, renderer, 1198, 388); AfficheJetonVoleur(p, -1.5, -1, renderer, 724, 506); AfficheJetonVoleur(p, -0.5, -1, renderer, 860, 506); AfficheJetonVoleur(p, 0.5, -1, renderer, 996, 506); AfficheJetonVoleur(p, 1.5, -1, renderer, 1130, 506); AfficheJetonVoleur(p, -1, -2, renderer, 792, 624); AfficheJetonVoleur(p, 0, -2, renderer, 928, 624); AfficheJetonVoleur(p, 1, -2, renderer, 1063, 624); }
C
#include <libsystem/Assert.h> #include "kernel/node/Connection.h" #include "kernel/node/Socket.h" static FsNode *socket_openConnection(FsSocket *socket) { FsNode *connection = fsconnection_create(); list_pushback(socket->pending, fsnode_ref(connection)); return connection; } static bool socket_FsNodeCanAcceptConnectionCallback(FsSocket *socket) { return list_any(socket->pending); } static FsNode *socket_FsNodeAcceptConnectionCallback(FsSocket *socket) { assert(list_any(socket->pending)); FsNode *connection; list_pop(socket->pending, (void **)&connection); if (connection->accept) { connection->accept(connection); } return connection; } static void socket_destroy(FsSocket *socket) { list_destroy_with_callback(socket->pending, (ListDestroyElementCallback)fsnode_deref); } FsNode *socket_create(void) { FsSocket *socket = __create(FsSocket); fsnode_init(FSNODE(socket), FILE_TYPE_SOCKET); FSNODE(socket)->open_connection = (FsNodeOpenConnectionCallback)socket_openConnection; FSNODE(socket)->can_accept_connection = (FsNodeCanAcceptConnectionCallback)socket_FsNodeCanAcceptConnectionCallback; FSNODE(socket)->accept_connection = (FsNodeAcceptConnectionCallback)socket_FsNodeAcceptConnectionCallback; FSNODE(socket)->destroy = (FsNodeDestroyCallback)socket_destroy; socket->pending = list_create(); return FSNODE(socket); }
C
/**************************************************************** **** **** This program file is part of the book **** `Parallel programming with MPI and OpenMP' **** by Victor Eijkhout, [email protected] **** **** copyright Victor Eijkhout 2012-7 **** **** OpenMP Exercise **** ****************************************************************/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <omp.h> int main() { int N = 2999*3001; // Exercise: // -- turn the factor-testing block into a task // -- run your program several times. // for i in `seq 1 1000` ; do ./taskfactor ; done | grep -v 2999 // why does it find the wrong solution? try to fix this int factor=0; #pragma omp parallel #pragma omp single for (int f=2; f<4000; f++) { /**** your code here ****/ { // see if `f' is a factor if (N%f==0) { // found factor! /**** your code here ****/ factor = f; } } if (factor>0) break; } if (factor>0) printf("Found a factor: %d\n",factor); else printf("Prime number!\n"); return 0; }
C
// uthash.c #include <string.h> /* strcpy */ #include <stdlib.h> /* malloc */ #include <stdio.h> /* printf */ #include <assert.h> #include "uthash.h" const int MAX_DATA = 12000000; struct kv { char *key; double val; UT_hash_handle hh; }; char i2ch[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'B', 'c', 'D', 'e', 'F'}; int get_first_digit(double d) { while(d > 10) { d /= 10; } return (int)(d); } char* to_rhex(int v) { char* hex = malloc(sizeof(char)*9); // because INT_MAX can be divided by 16 maximum 8 times assert(hex != NULL); memset(hex,0,9); int ctr = 0; while(v > 0) { hex[ctr++] = i2ch[v%16]; v /= 16; } return hex; } char* to_str(int v) { int len = snprintf(NULL,0,"%d",v); char *res = malloc(len+1); assert(res != NULL); snprintf(res, len+1, "%d", v); return res; } int set_or_inc(struct kv** m, char* key, int set, int inc, int *ctr) { struct kv* item = 0; HASH_FIND_STR(*m, key, item); if(!item) { item = malloc(sizeof(*item)); assert(item != NULL); item->key = key; item->val = (double)(set); //HASH_ADD_KEYPTR(hh, *m, item->key, strlen(item->key), item) ; HASH_ADD_STR(*m, key, item); return 0; } else { item->val += (double)(inc); *ctr += 1; return 1; // key not used } } int main() { struct kv *m = NULL; int dup1 =0, dup2 =0, dup3 =0; for(int z = MAX_DATA; z > 0; z--) { int val2 = MAX_DATA - z; int val3 = MAX_DATA*2 - z; char *key1 = to_str(z); char *key2 = to_str(val2); char *key3 = to_rhex(val3); if(set_or_inc(&m, key1, z, val2, &dup1)) free(key1); if(set_or_inc(&m, key2, val2, val3, &dup2)) free(key2); if(set_or_inc(&m, key3, val3, z, &dup3)) free(key3); } printf("%d %d %d\n",dup1, dup2, dup3); int total = 0, verify = 0, count = 0; struct kv *tmp, *item; HASH_ITER(hh, m, item, tmp) { total += get_first_digit(item->val); verify += strlen(item->key); count += 1; HASH_DEL(m,item); free(item->key); free(item); } printf("%d %d %d\n",total, verify, count); }
C
#include <stdio.h> #include <string.h> #define INPUTMAX 20 #define OUTPUTMAX 40 void convert_string(char [INPUTMAX+1],char [OUTPUTMAX+1]); int main(void){ char str[INPUTMAX+1]; char dest[OUTPUTMAX+1]; int len; printf("Enter the input: "); fgets(str,INPUTMAX+1,stdin); len = strlen(str); if (str[len-1] == '\n') str[len-1] = '\0'; convert_string(str,dest); printf("DEST: %s\n",dest); } void convert_string(char str[INPUTMAX+1],char dest[OUTPUTMAX+1]){ int i; int length = strlen(str); int counter = 0; for (i=0;i<length;i++){ if (i == length-1){ dest[counter++] = str[i]; dest[counter] = '\0'; } else if (str[i] == ' '){ continue; } else{ dest[counter++] = str[i]; dest[counter++] = '*'; } } }
C
#include<stdio.h> #include<string.h> int main(void) { int x,z; char word[40]; printf("请输入一个单词\n"); scanf("%s",word); x=strlen(word)-1; for(z=x;z>=0;z--) printf("%c",word[z]); printf("\n"); return 0; }
C
#include<stdio.h> int ref_bias_fp32(float* in_data, float* out_data, float* bias, int size, int channels, float scale, int zero_point) { for(int c = 0; c < channels; c++){ float* out_ptr = out_data + c*size; float* in_ptr = in_data + c*size; for(int i = 0; i < size; i++) { out_ptr[i] = in_ptr[i] + bias[c]; } } return 0; }
C
/**************************************************************************** Description: Program to test shared memory using mmap in this program parent and child shares ptr. It is to show how shared memory is shared between parent and child. comment semaphore functions and run with 1000 times loops Compailation: This is application program. Compile this program along with semaphore library program. Comments send to: [email protected] ****************************************************************************/ # include <stdio.h> # include <sys/mman.h> # include <sys/types.h> # include <fcntl.h> main(int argc, char **argv) { int fd, i, nloop, zero = 0; int *ptr; int semid; if(argc!= 3) printf("Usage :a.out <pathname> <#loops>\n"); nloop = atoi(argv[2]); fd = open(argv[1], O_CREAT|O_RDWR,0600); write(fd, &zero, sizeof(int)); ptr=mmap(NULL,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0); close(fd); semid=sem_create(1234, 1); setbuf(stdout, NULL); if(fork()==0){ for(i = 0;i < nloop; i++){ sem_wait(semid); printf("child: %d",(*ptr)++); sem_signal(semid); } exit(0); } //sleep(1); for(i = 0;i < nloop; i++){ sem_wait(semid); printf("parent: %d",(*ptr)++); sem_signal(semid); } exit(0); } /* Try the same program using shmat and shmdt system calls*/
C
#include "../SequStack.h" #include <stdio.h> Status PrintChar(SElemType e); //遍历函数的功能函数,打印字符 void LineEdit(char back, char clear); //行编辑 Status PrintChar(SElemType e) { printf("%c", e); return OK; } void LineEdit(char back, char clear) { SqStack stack; char ch; SElemType e; InitStack(&stack); do { ch = getchar(); if (ch == back)Pop(&stack, &e); else if (ch == clear)ClearStack(&stack); else if (ch == '\n') { StackTraverse(stack, PrintChar); printf("\n"); ClearStack(&stack); } else if (ch != EOF) Push(&stack, ch); } while (ch != EOF); StackTraverse(stack, PrintChar); DestroyStack(&stack); } int main() { LineEdit('#','@'); return 0; }
C
/* Include-file defining data types used by message subsystem */ #ifndef __MESSAGES__ #define __MESSAGES__ #include "global.h" /* ---------------------------------------------------------------- */ /* Declarations of global variables declared for messages */ /* ---------------------------------------------------------------- */ /* Declarations of data types for messages */ /* data type for the possible types of messages */ typedef enum { msg_kill, msg_sleep, msg_wakeup, msg_pause, msg_alert } msgType_t; #define MSG_NUMTYPES 5 // Number of message types // In dieser Demo gibt es nur fnf Nachritentypen, das ist unrealistisch klein. // Ihre Implementierung soll auch mit einigen zig bis // zu ca. 200 Nachrichtentypen effizient zumgehen knnen. // Legen Sie Datentypen und Implementierung entsprechend aus. /* data type for the message payload */ /* currently this is the most generic data type and it might be adapted*/ typedef void* msgData_t; /* data type for the message return value */ /* negative values indicate unsuccessful execution (error) */ /* positive values and zero indicate successful execution */ typedef int msgReturn_t; /* data type for function pointer to the handler for a message type */ //int (*msgHandler_t) (void); typedef msgReturn_t (*msgHandler_t) (msgData_t); /* ---------------------------------------------------------------- */ /* Declarations of functions for messages */ /** * @brief: function to iniaitlise the message system, called by the os * * This function initialises the message system, i.e. creates and initialises * all data structured used by this part of the OS. * It must be called during boot-up of the OS * * @return The function returns an integer value typed msgReturn_t * negative values indicate an error * zero and positive values indicate success */ msgReturn_t msg_init(void); /** * @brief: function to register for a certain message type * * By calling this function, the named process is registered for the given * message type. The OS will call the handler-function that is passed. * The handler must be part of the process with the given PID. * This function is intended to be called by a process to register itself. * * @param pid the PID of the process that is registered for a message * @param msgType the type of the message that the process shall react to * must be one of the types given by the enum msgType_t * @param myHandler a function pointer to the function inside the process * with the given PID. The handler must be of the prototype * given by msgHandler_t * @return The function returns an integer value typed msgReturn_t * negative values indicate an error * zero and positive values indicate success */ msgReturn_t msg_register(pid_t pid, msgType_t msgType, msgHandler_t myHandler); /** * @brief: function to send a message to a process * * By calling this function, a message of the given type with the given * content is sent to the target process * This function can be used by authorised user processes and the OS core * REMEMBER: In this demo the authorisation is not checked. * * @param pid the PID of the process that is registered for a message * @param msgType the type of the message to be sent * must be one of the types given by the enum msgType_t * @param msgData pointer to the payload of the message. * The payload must be of the prototype given by msgHandler_t * @return The function returns an integer value typed msgReturn_t * negative values indicate an error * zero and positive values indicate success */ msgReturn_t msg_send(pid_t receiverPid, msgType_t msgType, msgData_t msgData); /** * @brief: function to send a message to all registered processes * * By calling this function, a message of the given type with the given * content is sent via broadcast to all processes that are registered to * messages of this type. There is no acknowledge to the entity initiating * the broadcast. * * @param msgType the type of the message to be sent * must be one of the types given by the enum msgType_t * @param msgData pointer to the payload of the message. * The payload must be of the prototype given by msgHandler_t * @return none */ void msg_broadcast(msgType_t msgType, msgData_t msgData); #endif
C
# include <stdlib.h> # include <stdio.h> # include <string.h> /* * See ../README.md */ /* * Run as: cc -o ch-2.o ch-2.c; ./ch-2.o < input-file */ # define DIFF_PER_MINUTE 11 /* Half degrees */ # define MIN_PER_HOUR 60 # define FULL_CIRCLE 720 /* Half degrees */ int main (void) { int hours, minutes; while (scanf ("%d:%d", &hours, &minutes) == 2) { int angle = (DIFF_PER_MINUTE * (hours * MIN_PER_HOUR + minutes)) % FULL_CIRCLE; if (2 * angle >= FULL_CIRCLE) { angle = FULL_CIRCLE - angle; } printf ("%d", angle / 2); if (angle % 2) { printf (".5"); } printf ("\n"); } return (0); }
C
#include <stdio.h> void recursive(int n) { if(n!=1) recursive(n-1); printf("%d\n", n); } int main() { recursive(5); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define MAXINPUT 100 typedef struct node { int val; struct node * next; } node_t; int is_number(char* str) { int result = 1; int length; length = strlen(str); for (int i = 0; i < length; i++) if (!isdigit(str[i])) { result = 0; break; } return result; } int print_list(node_t * head ) { node_t * current = NULL; current = head; while(1) { printf("%d\n", current->val); if(current->next != NULL) { current = current->next; } else { break; } } } node_t * fill_list() { node_t * head = NULL; node_t * tmp = NULLnode_t; node_t * last = NULL; int x; char input[MAXINPUT] = ""; while(1) { printf("enter next numder: "); scanf("%s", input); if (!is_number(input)) { printf("error: not a number!\n"); break; } x = atoi(input); if (x <= 0) { printf("close input!\n"); break; } tmp = malloc(sizeof(node_t)); if (tmp == NULL) { return head; } if(head == NULL) { head = tmp; } tmp->val = x; tmp->next = NULL; if(last != NULL){ last->next = tmp; } last = tmp; } return head; } int main() { node_t * head1 = NULL; node_t * head2 = NULL; head1 = fill_list(); head2 = fill_list(); if(head1 != NULL) { printf("list contains:\n"); print_list(head1); } if(head2 != NULL) { printf("list contains:\n"); print_list(head2); } return 0; }
C
#include<stdio.h> int heap_k=-1; void addnode(int*,int, int**); int ExtractMin(int*, int**); void adjust_heap(int*, int**); void addnode(int* heap, int node, int** mat) { heap_k++; int child=heap_k; int parent=(child-1)/2; while(child>0 && PTY(heap[parent])<PTY(node)) { heap[child]=heap[parent]; child=parent; parent=(child-1)/2; } heap[child]=node; } int ExtractMin(int* heap, int** mat) { int temp; temp=heap[heap_k]; heap[heap_k]=heap[0]; heap[0]=temp; adjust_heap(heap, mat); return heap[heap_k--]; } void adjust_heap(int* heap, int** mat) { int parent=0,node=heap[parent],i=2*parent+1; while(i<heap_k) { if(i+1<heap_k) { if(PTY(heap[i+1])>PTY(heap[i])) i++; } if(PTY(node)<PTY(heap[i])) { heap[parent]=heap[i]; parent=i; i=2*parent+1; } else break; } heap[parent]=node; } void printheap(int* heap) { int i; for(i=0;i<=heap_k;i++) printf("%d ",heap[i]); printf("\n"); }
C
struct Gsymbol* GLookup(char * name) { struct Gsymbol *temp=Ghead; while(temp!=NULL) { if(strcmp(name,temp->name)==0) return temp; temp=temp->next; } return NULL; } void GInstall(char *name, struct Typetable *type,struct Classtable *cptr,int size,int s2,struct Paramstruct *paramlist) { if(GLookup(name)!=NULL) { printf("Variable is already defined %s\n",name); exit(1); } struct Gsymbol *new=(struct Gsymbol*)malloc(sizeof(struct Gsymbol)); new->name=(char *)malloc(sizeof(name)); strcpy(new->name,name); new->type=type; new->cptr=cptr; new->size=size*s2; new->s2=s2; new->paramlist=paramlist; new->binding=varadrs; varadrs=varadrs+size; if(func==1) { new->flabel=flabel; flabel++; } if(Ghead==NULL) { new->next=NULL; Ghead=new; return; } new->next=Ghead; Ghead=new; } void printsymtab() { printf("Global Symbol Table\n"); printf("========================================================\n"); struct Gsymbol *temp=Ghead; printf("flabel %s %s %s %s\n","name","type","size","binding" ); while(temp!=NULL) { if(temp->type==NULL) printf("%d %s %s %d %d\n",temp->flabel,temp->name,temp->cptr->name,temp->size,temp->binding); else printf("%d %s %s %d %d\n",temp->flabel,temp->name,temp->type->name,temp->size,temp->binding); temp=temp->next; } } struct Lsymbol *LLookup(char * name) { struct Lsymbol *temp=Lhead; while(temp!=NULL) { if(strcmp(temp->name,name)==0) return temp; temp=temp->next; } return NULL; } void LInstall(char *name, struct Typetable *type) { if(LLookup(name)!=NULL) { printf("local Variable is already defined %s\n",name); exit(1); } struct Lsymbol *new=(struct Lsymbol*)malloc(sizeof(struct Lsymbol)); new->name=(char *)malloc(sizeof(name)); strcpy(new->name,name); new->type=type; if(arg==1) { new->binding=padrs; padrs--; } else { new->binding=lvaradrs; lvaradrs++; } if(Lhead==NULL) { new->next=NULL; Lhead=new; return; } new->next=Lhead; Lhead=new; } void PInstall(char *name,struct Typetable *type,int passtype) { struct Paramstruct *new=(struct Paramstruct *)malloc(sizeof(struct Paramstruct)),*temp; new->name=(char *)malloc(sizeof(name)); strcpy(new->name,name); new->type=type; new->next=NULL; new->passtype=passtype; if(Phead==NULL) { Phead=new; return; } temp=Phead; while(temp->next!=NULL) temp=temp->next; temp->next=new; } void TypeTableCreate() { struct Typetable *new=(struct Typetable*)malloc(sizeof(struct Typetable)); new->name=(char *)malloc(4); strcpy(new->name,"int"); new->size=1; new->fields=NULL; new->next=NULL; Thead=new; TInstall("intptr",1,NULL); TInstall("str",1,NULL); TInstall("strptr",1,NULL); TInstall("bool",1,NULL); TInstall("void",0,NULL); TInstall("arrint",0,NULL); TInstall("arrstr",0,NULL); //TInstall("tuple",0,NULL); } struct Typetable* TLookup(char *name) { Ttemp=Thead; while(Ttemp!=NULL) { if(strcmp(Ttemp->name,name)==0) return Ttemp; Ttemp=Ttemp->next; } return NULL; } struct Typetable* TInstall(char *name,int size,struct Fieldlist *fields) { struct Typetable *new=(struct Typetable*)malloc(sizeof(struct Typetable)),*Ttemp; new->name=(char *)malloc(sizeof(name)); strcpy(new->name,name); new->size=size; new->fields=fields; new->next=NULL; Ttemp=Thead; while(Ttemp->next!=NULL) Ttemp=Ttemp->next; Ttemp->next=new; return new; } struct Fieldlist* FLookup(struct Typetable *type,char *name) { Ftemp=type->fields; while(Ftemp!=NULL) { if(strcmp(Ftemp->name,name)==0) return Ftemp; Ftemp=Ftemp->next; } return NULL; } void FInstall(char *name,int index,struct Typetable *type) { struct Fieldlist *new=(struct Fieldlist*)malloc(sizeof(struct Fieldlist)); new->name=(char *)malloc(sizeof(name)); strcpy(new->name,name); new->fieldindex=index; new->type=type; if(Fhead==NULL) { new->next=NULL; Fhead=new; return; } new->next=Fhead; Fhead=new; } int Getsize(struct Typetable *type) { return type->size; } struct Classtable *CLookup(char *name) { if(name==NULL) return NULL; Ctemp=Chead; while(Ctemp!=NULL) { if(strcmp(name,Ctemp->name)==0) return Ctemp; Ctemp=Ctemp->next; } return NULL; } struct Classtable *CInstall(char *name,char *parentclassname) { struct Classtable *new=(struct Classtable *)malloc(sizeof(struct Classtable)); new->name=(char *)malloc(sizeof(name)); strcpy(new->name,name); new->Memberfield=NULL; new->Vfuncptr=NULL; //printf("C2\n"); new->parentptr=CLookup(parentclassname); new->class_index=clscnt++; new->fieldcount=0; new->menthodcount=0; //printf("C3\n"); if(Chead==NULL) { new->next=NULL; Chead=new; return new; } new->next=Chead; Chead=new; return new; } struct Fieldlist *CFLookup(struct Classtable *cptr,char *name) { Ftemp=cptr->Memberfield; while(Ftemp!=NULL) { //printf("%s\n",Ftemp->name); if(strcmp(Ftemp->name,name)==0) return Ftemp; Ftemp=Ftemp->next; } return NULL; } void Class_Finstall(struct Classtable *cptr,char *type,char *name) { if(CMLookup(cptr,name)!=NULL) {printf("variable already declared\n");exit(1);} struct Fieldlist *new=(struct Fieldlist *)malloc(sizeof(struct Fieldlist)); new->name=(char *)malloc(sizeof(name)); strcpy(new->name,name); Ttemp=TLookup(type); if(Ttemp==NULL) { Ctemp=CLookup(type); if(Ctemp==NULL) {printf("Unkown Field type %s at %d\n",type,lcnt);exit(1);} new->cptr=Ctemp; new->type=NULL; } else { new->type=Ttemp; new->cptr=NULL; } new->fieldindex=(cptr->fieldcount)++; if((cptr->Memberfield)==NULL) { new->next=NULL; (cptr->Memberfield)=new; return; } new->next=(cptr->Memberfield); (cptr->Memberfield)=new; } struct Memberfunclist *CMLookup(struct Classtable *cptr,char *name) { Mtemp=cptr->Vfuncptr; while(Mtemp!=NULL) { //printf("%s\n",Mtemp->name); if(strcmp(Mtemp->name,name)==0) return Mtemp; Mtemp=Mtemp->next; } return NULL; } void Class_Minstall(struct Classtable *cptr,char *name,struct Typetable *type,struct Paramstruct *paramlist) { if(CMLookup(cptr,name)!=NULL) {printf("Over loading not permitted\n");exit(1);} struct Memberfunclist *new=(struct Memberfunclist *)malloc(sizeof(struct Memberfunclist)); new->name=(char *)malloc(sizeof(name)); strcpy(new->name,name); new->type=type; new->paramlist=paramlist; new->funcposition=(cptr->menthodcount)++; //printf("%d %s %s\n",new->funcposition,name,cptr->name); new->flabel=flabel++; if((cptr->Vfuncptr)==NULL) { new->next=NULL; (cptr->Vfuncptr)=new; return; } new->next=(cptr->Vfuncptr); (cptr->Vfuncptr)=new; } void validateparams(struct Typetable *type,struct Classtable *cptr,char *name,struct Paramstruct *paramlist) { if(cptr==NULL) { printf("c1\n"); struct Gsymbol *temp=GLookup(name); if(temp==NULL) { yyerror("Function undeclared"); exit(1); } if((temp->type!=type)) //return type check { yyerror("return type mismatch"); exit(1); } Ptemp=temp->paramlist; while(Ptemp!=NULL&&paramlist!=NULL) { if(strcmp(Ptemp->name,paramlist->name)!=0) { yyerror("Parameter name mismatch"); exit(1); } if(Ptemp->type!=paramlist->type) { yyerror("Parameter type mismatch"); exit(1); } Ptemp=Ptemp->next; paramlist=paramlist->next; } if(Ptemp!=NULL) { yyerror("Less number of arguments"); exit(1); } if(paramlist!=NULL) { yyerror("More number of arguments"); exit(1); } } else { //printf("c2 %s %s\n",cptr->name,name); struct Memberfunclist *temp=CMLookup(cptr,name); if(temp==NULL) { yyerror("Member Function undeclared"); exit(1); } if((temp->type!=type)) //return type check { //printf("%s %s\n",temp->type->name,type->name); yyerror("return type mismatch"); exit(1); } Ptemp=temp->paramlist; while(Ptemp!=NULL&&paramlist!=NULL) { if(strcmp(Ptemp->name,paramlist->name)!=0) { yyerror("Parameter name mismatch"); exit(1); } if(Ptemp->type!=paramlist->type) { yyerror("Parameter type mismatch"); exit(1); } Ptemp=Ptemp->next; paramlist=paramlist->next; } if(Ptemp!=NULL) { yyerror("Less number of arguments"); exit(1); } if(paramlist!=NULL) { yyerror("More number of arguments"); exit(1); } } //printf("valid\n"); } void print1() { printf("TYPE TABLE\n"); printf("============================================\n"); Ttemp=Thead; while(Ttemp!=NULL) { printf("%s %d\n",Ttemp->name,Ttemp->size); Ftemp=Ttemp->fields; while(Ftemp!=NULL){ printf("<---> %d %s %s\n",Ftemp->fieldindex,Ftemp->name,Ftemp->type->name); Ftemp=Ftemp->next; } Ttemp=Ttemp->next; } } void print2() { printf("CLASS TABLE\n"); printf("==============================================\n"); Ctemp=Chead; while(Ctemp!=NULL) { printf("class %d %s %d %d\n",Ctemp->class_index,Ctemp->name,Ctemp->fieldcount,Ctemp->menthodcount); Ftemp=Ctemp->Memberfield; while(Ftemp!=NULL){ if(Ftemp->type!=NULL) printf("%d %s %s\n",Ftemp->fieldindex,Ftemp->name,Ftemp->type->name); else printf("%d %s %s\n",Ftemp->fieldindex,Ftemp->name,Ftemp->cptr->name); Ftemp=Ftemp->next; } Mtemp=Ctemp->Vfuncptr; while(Mtemp!=NULL) { printf("%d %s %s %d\n",Mtemp->funcposition,Mtemp->name,Mtemp->type->name,Mtemp->flabel); Mtemp=Mtemp->next; } Ctemp=Ctemp->next; } } void printL() { Ltemp=Lhead; if(Ltemp==NULL) printf("L NULL\n"); while(Ltemp!=NULL) { printf("%d %s %s\n",Ltemp->binding,Ltemp->name,Ltemp->type->name); Ltemp=Ltemp->next; } }
C
#include <stdio.h> #include <regex.h> #include<string.h> /** *下载地址: *https://sourceforge.net/projects/gnuwin32/files/regex/2.7/(regex-2.7-bin.zip) *下载完包解压后: *将lib中的libregex.dll.a和libregex.la放进MinGW的lib目录,将regex2.dll放进程序所在目录。 * *libraries 要添加配置regex *动态链接库文件regex2.dll需要放在exe文件下面 */ int main9() { // regex(); regex2(); // char *str="aaabbbccc"; // char *dst; // printf("err:%s\n",replace(str,"bbb","")); printf("------------over"); return 0; } /* 取子串的函数 */ //char* substr (const char*str, unsigned start, unsigned end) //{ //unsigned n = end - start; //char *stbuf; //strncpy(stbuf, str + start, n); //return stbuf; //} void regex2(){ char *bematch = "aaaaahttp://baiducomz bhttp://34123qwerqezcom http://liyuancomzadfzhttp://1liyuancomz"; char *pattern = "(http://[a-zA-Z0-9]+[com])"; char errbuf[1024]; char match[1024]; regex_t reg; int err,nm = 10; regmatch_t pmatch[nm]; // if(regcomp(&reg,pattern,REG_EXTENDED) < 0){ if(regcomp(&reg,pattern,REG_EXTENDED) < 0){ regerror(err,&reg,errbuf,sizeof(errbuf)); printf("err:%s\n",errbuf); } err = regexec(&reg,bematch,nm,pmatch,0); if(err == REG_NOMATCH){ printf("no match\n"); exit(-1); }else if(err){ regerror(err,&reg,errbuf,sizeof(errbuf)); printf("err:%s\n",errbuf); exit(-1); } // while(err != REG_NOMATCH){ // char *m=substr(bematch,pmatch[0].rm_so,pmatch[0].rm_eo); // printf("找到的字符串:%s",m); // //执行替换 //// replace(bematch,ret,""); //// err = regexec(&reg,bematch,nm,pmatch,0); // // // } // for(int i=0;i<10 && pmatch[i].rm_so!=-1;i++){ while(err != REG_NOMATCH){ int len = pmatch[0].rm_eo-pmatch[0].rm_so; // printf("数字%d",i); memset(match,'\0',sizeof(match)); memcpy(match,bematch+pmatch[0].rm_so,len); printf("打印%s\n",match); // char *m2=substr(bematch,pmatch[0].rm_so,pmatch[0].rm_eo); // printf("打印m2%s\n",m2); char *m=replace(bematch,match,""); bematch=m; // match=substr(bematch,pmatch[0].rm_so,pmatch[0].rm_eo); // printf("打印2%s\n",m); err = regexec(&reg,bematch,nm,pmatch,0); // printf("xxxx:%s\n",substr(bematch,pmatch[0].rm_so,pmatch[0].rm_eo)); } // } } void regex(){ char *bematch = "[email protected]"; char *pattern = "^h{3,10}(.*)@.{5}.(.*)"; char errbuf[1024]; char match[100]; regex_t reg; int err,nm = 10; regmatch_t pmatch[nm]; // if(regcomp(&reg,pattern,REG_EXTENDED) < 0){ if(regcomp(&reg,pattern,NULL) < 0){ regerror(err,&reg,errbuf,sizeof(errbuf)); printf("err:%s\n",errbuf); } err = regexec(&reg,bematch,nm,pmatch,0); if(err == REG_NOMATCH){ printf("no match\n"); exit(-1); }else if(err){ regerror(err,&reg,errbuf,sizeof(errbuf)); printf("err:%s\n",errbuf); exit(-1); } for(int i=0;i<10 && pmatch[i].rm_so!=-1;i++){ int len = pmatch[i].rm_eo-pmatch[i].rm_so; if(len){ memset(match,'\0',sizeof(match)); memcpy(match,bematch+pmatch[i].rm_so,len); printf("%s\n",match); } } }
C
#include <stdio.h> #include <time.h> int main(void){ enum Week {sun, mon, tue, wed, thu, fri, sat}; enum Week today; struct tm *p; time_t t; time(&t); p = localtime(&t); today = p -> tm_wday; switch(today){ case mon: case tue: case wed: case thu: case fri: printf("干活! T_T\n"); break; case sat: case sun: printf("放假!^_^\n"); break; default: printf("Error!\n"); } return 0; }
C
//https://github.com/hzyitc/armbian-onecloud/issues/52 #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <fcntl.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/select.h> #include <pthread.h> #include <unistd.h> #include <sched.h> #include <string.h> #define PLPM_BASE 0xc8100014 #define __IO volatile void *var_addr_satr=0; unsigned int var_addr_size=0; unsigned int *gpioaddr; void *gpio_base= 0; int gpio_init(void) { int fd; unsigned int addr_start,addr_offset; unsigned int PageSize,PageMask; fd = open("/dev/mem",O_RDWR); if(fd < 0) { return -1; } PageSize = sysconf(_SC_PAGESIZE); PageMask = ~(PageSize-1); //printf("take PageSize=%d\n",PageSize); addr_start = PLPM_BASE & PageMask ; addr_offset= PLPM_BASE & ~PageMask; var_addr_size = PageSize*2; var_addr_satr = (void*) mmap(0, var_addr_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, addr_start); if(var_addr_satr == MAP_FAILED) { return -1; } gpio_base = var_addr_satr; gpio_base += addr_offset; //printf("take var addr = 0x%8x\n",(unsigned int)var_addr_satr); //printf("make gpio_base = 0x%8x\n",(unsigned int)gpio_base); close(fd); return 0; } int gpio_deinit(void) { int fd; fd = open("/dev/mem",O_RDWR); if(fd < 0) { return -1; } if(munmap(var_addr_satr,var_addr_size) == 0) { //printf("remove var addr ok\n"); } else { //printf("remove var addr erro\n"); } close(fd); return 0; } void red_on(void) { unsigned int temp; temp = *(gpioaddr+4)|0x00040000; *(gpioaddr+4)=temp; } void red_off(void) { *(gpioaddr+4) = *(gpioaddr+4)&(~0x00040000); } void red_toggle(void) { unsigned char c; c = (*(gpioaddr+4)&0x00040000)>>18; if (c == 0) { red_on(); } else { red_off(); } } void green_on(void) { *(gpioaddr+4) = *(gpioaddr+4)|0x00080000; } void green_off(void) { *(gpioaddr+4) = *(gpioaddr+4)&(~0x00080000); } void green_toggle(void) { unsigned char c; c = (*(gpioaddr+4)&0x00080000)>>19; if (c == 0) { green_on(); } else { green_off(); } } void blue_on(void) { *(gpioaddr+4) = *(gpioaddr+4)|0x00100000; } void blue_off(void) { *(gpioaddr+4) = *(gpioaddr+4)&(~0x00100000); } void blue_toggle(void) { unsigned char c; c = (*(gpioaddr+4)&0x00100000)>>20; if (c == 0) { blue_on(); } else { blue_off(); } } unsigned char key_scan(void) { unsigned char key=0; key=((*(gpioaddr+5)&0x00000020)>>5); return key; } int main(int argc,char * argv[]) { if (argc < 2 || argc > 4) { printf("led [red|green|blue] [0|1]\n"); return 1; } unsigned int temp; if (gpio_init() != 0) { printf("gpio_init failed\n"); return -1; } gpioaddr = (unsigned int *)gpio_base; // Turn off GPIOAO_4,GPIOAO_5 reuse temp = *gpioaddr&(~0x01800066); *gpioaddr = temp; // Enable GPIOAO_2,GPIOAO_3,GPIOAO_4 output,GPIOAO_5 input temp = *(gpioaddr+4)&(~0x0000001c); *(gpioaddr+4) = temp; temp = *(gpioaddr+4)|0x00000020; *(gpioaddr+4) = temp; if (argc == 2) { if (strcmp((const char*)argv[1],"red")==0) red_toggle(); if (strcmp((const char*)argv[1],"green")==0) green_toggle(); if (strcmp((const char*)argv[1],"blue")==0) blue_toggle(); } if (argc == 3) { if (strcmp((const char*)argv[1],"red")==0) { if (strcmp((const char*)argv[2],"0")==0) { red_off(); } else { red_on(); } } if (strcmp((const char*)argv[1],"green")==0) { if (strcmp((const char*)argv[2],"0")==0) { green_off(); } else { green_on(); } } if (strcmp((const char*)argv[1],"blue")==0) { if (strcmp((const char*)argv[2],"0")==0) { blue_off(); } else { blue_on(); } } } gpio_deinit( ); return 0; }
C
/* * 20134220 Jeong hyun, Woo * BasicUDPServer.c */ #include <sys/socket.h> #include <sys/stat.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <ctype.h> #include <time.h> #include <signal.h> #define MAXBUF 2048 #define PORT 24220 void sigHandler(int sigNo); int main(int argc, char** argv) { int serviceCount = 0; int sockfd; socklen_t addrlen; struct sockaddr_in addr, cliaddr; char buf[MAXBUF]; char ip[MAXBUF]; int option; time_t currentTime; struct tm tm; /* ctrl + c handler */ signal(SIGINT,(void*)sigHandler); if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { return 1; } memset((void*)&addr, 0x00, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(PORT); addrlen = sizeof(cliaddr); if((bind(sockfd,(struct sockaddr*)&addr,addrlen)) == -1) { return 1; } printf("The server is ready to receive on port %d\n",PORT); for(;;){ memset(buf, 0x00, MAXBUF); /* receive command from client */ recvfrom(sockfd,(void*)&buf,sizeof(buf),0,(struct sockaddr*)&cliaddr,&addrlen); printf("Connection requested from ('%s', %d)\n", inet_ntoa(cliaddr.sin_addr), cliaddr.sin_port); option = atoi(buf); printf("Command %d\n",option); /* command 1 ~ 5 */ switch(option) { case 1: memset(buf,0x00,MAXBUF); /* receive sentence */ recvfrom(sockfd,(void*)&buf,sizeof(buf),0,(struct sockaddr*)&cliaddr,&addrlen); /* lowercase to uppercase */ for(int i = 0; buf[i] != '\0' ; i++) { buf[i] = toupper(buf[i]); } /* send uppercase-sentence */ sendto(sockfd, (void*)buf, sizeof(buf), 0, (struct sockaddr*)&cliaddr,addrlen); serviceCount++; break; case 2: memset(buf, 0x00, MAXBUF); memset(ip,0x00,MAXBUF); /* format : xxx.xxx.xxx.xxx,PORT */ sprintf(buf,"%d",cliaddr.sin_port); strcpy(ip,inet_ntoa(cliaddr.sin_addr)); strcat(ip,","); strcat(ip,buf); /* send client's ip & port info with format "xxx.xxx.xxx.xxx,PORT" */ sendto(sockfd, (void*)ip, sizeof(ip), 0, (struct sockaddr*)&cliaddr,addrlen); serviceCount++; break; case 3: memset(buf,0x00,MAXBUF); /* get server's current time */ currentTime = time(NULL); tm = *localtime(&currentTime); /* send server's current time with format "YYYY-MM-DD HH:MM:SS" */ sprintf(buf, "%04d-%02d-%02d %02d:%02d:%02d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); sendto(sockfd, (void*)buf, sizeof(buf), 0, (struct sockaddr*)&cliaddr,addrlen); serviceCount++; break; case 4: serviceCount++; /* send server's service count */ sprintf(buf,"%d",serviceCount); sendto(sockfd, (void*)buf, sizeof(buf), 0, (struct sockaddr*)&cliaddr,addrlen); break; default : break; } } close(sockfd); return 0; } void sigHandler(int sigNo) { printf("\nBye bye~\n"); exit(1); }
C
/* ʵ4-2-6 ַ 15 ֣ ҪдnɴдĸAʼɵַС ʽ һиһn1n<7 ʽ nɴдĸAʼɵַСʽÿĸ涼һո 4 A B C D E F G H I J */ #include<stdio.h> #define return return int main() { char c ='A'; int N; scanf("%d",&N); for(int i=0;i<N;i++){ for(int j=i;j<N;j++){ printf("%c ",c); c++; } printf("\n"); } return 0; }
C
//注册已知文件系统的GUID. #include <filesystem/filesystem.h> #include <filesystem/fhhfs.h> #include <memory/memory.h> #include <drivers/devicetree.h> #include <common/printk.h> //根目录设备文件的设备树地址。 char g_root_device_path[64]; const GUID* g_registered_filesystems[] = { &FzOS_ROOT_PARTITION_GUID }; int (*registered_filesystem_mounts[])(GPTPartition* partition,const char* position) = { fhhfs_mount }; _Static_assert(sizeof(registered_filesystem_mounts)==sizeof(g_registered_filesystems),"Registered FS types & mounts don't match!"); int mount(GPTPartition* partition,const char* position) { for(int i=0;i<(sizeof(g_registered_filesystems)/sizeof(GUID*));i++) { if(!memcmp(&partition->type,g_registered_filesystems[i],sizeof(GUID))) { return registered_filesystem_mounts[i](partition,position); } } return FzOS_ERROR; } int mount_root_partition() { if(g_root_device_path[0]=='\0') { return FzOS_ERROR; } GPTPartitionTreeNode* partition = (GPTPartitionTreeNode*)device_tree_resolve_by_path(g_root_device_path,nullptr,DT_RETURN_IF_NONEXIST); if(partition==nullptr) { return FzOS_ERROR; } U64 ret = mount(&partition->partition,"/"); if(ret == FzOS_SUCCESS) { printk(" Got root at %s.\n",g_root_device_path); return FzOS_SUCCESS; } return FzOS_ERROR; } //人可以,至少先应该卸载根目录。 int unmount_all_mounted_filesystems() { int result=FzOS_SUCCESS; //TODO:卸载全部其他文件系统! FileSystemTreeNode* rootfs_node = (FileSystemTreeNode*)device_tree_resolve_by_path("/",nullptr,DT_RETURN_IF_NONEXIST); if(rootfs_node!=nullptr&&rootfs_node->node.type==DT_FILESYSTEM) { result = rootfs_node->fs.unmount(&(rootfs_node->fs)); } return result; }
C
/* ** get_side.c for function to know the orientation of a wall in /home/gaspar_q/rendu/Igraph/MUL_2014_wolf3d ** ** Made by quentin gasparotto ** Login <[email protected]> ** ** Started on Sat Dec 13 10:42:40 2014 quentin gasparotto ** Last update Sat Dec 20 14:28:03 2014 quentin gasparotto */ #include <math.h> #include "./include/wolf.h" #include "./include/minilibx_objects.h" double get_angle(t_system *sys, t_point2d fld_ind) { t_point2d vector; if (sys->pos.x >= ((int)fld_ind.x + 1) * 100.0) { vector.x = ((int)fld_ind.x + 1) * 100.0 - sys->pos.x; if (sys->pos.y >= ((int)fld_ind.y + 1) * 100.0) vector.y = ((int)fld_ind.y + 1) * 100 - sys->pos.y; else vector.y = (int)fld_ind.y * 100.0 - sys->pos.y; } else { vector.x = (int)fld_ind.x * 100.0 - sys->pos.x; if (sys->pos.y <= (int)fld_ind.y * 100.0) vector.y = (int)fld_ind.y * 100.0 - sys->pos.y; else vector.y = ((int)fld_ind.y + 1) * 100.0 - sys->pos.y; } return (atan(vector.y / vector.x)); } int check_left(t_system *sys, t_point2d bef_vec, t_point2d fld_ind, double angle) { double ref_angle; ref_angle = get_angle(sys, fld_ind); if ((int)bef_vec.x == (int)fld_ind.x - 1 && sys->field->char_field[(int)fld_ind.y][(int)fld_ind.x - 1] != sys->bk) { if ((int)bef_vec.y == (int)fld_ind.y - 1 && sys->field->char_field[(int)fld_ind.y - 1][(int)fld_ind.x] != sys->bk) { if (angle > ref_angle) return (EAST); else return (NORTH); } if ((int)bef_vec.y == (int)fld_ind.y + 1 && sys->field->char_field[(int)fld_ind.y + 1][(int)fld_ind.x] != sys->bk) { if (angle > ref_angle) return (SOUTH); else return (EAST); } } return (0); } int check_right(t_system *sys, t_point2d bef_vec, t_point2d fld_ind, double angle) { double ref_angle; ref_angle = get_angle(sys, fld_ind); if ((int)bef_vec.x == (int)fld_ind.x + 1 && sys->field->char_field[(int)fld_ind.y][(int)fld_ind.x + 1] != sys->bk) { if ((int)bef_vec.y == (int)fld_ind.y - 1 && sys->field->char_field[(int)fld_ind.y - 1][(int)fld_ind.x] != sys->bk) { if (angle > ref_angle) return (NORTH); else return (WEST); } if ((int)bef_vec.y == (int)fld_ind.y + 1 && sys->field->char_field[(int)fld_ind.y + 1][(int)fld_ind.x] != sys->bk) { if (angle > ref_angle) return (WEST); else return (SOUTH); } } return (0); } int check_front(t_system *sys, t_point2d bef_vec, t_point2d fld_ind) { if ((int)bef_vec.x == (int)fld_ind.x - 1 && sys->field->char_field[(int)fld_ind.y][(int)fld_ind.x - 1] != sys->bk) return (EAST); else if ((int)bef_vec.x == (int)fld_ind.x + 1 && sys->field->char_field[(int)fld_ind.y][(int)fld_ind.x + 1] != sys->bk) return (WEST); else if ((int)bef_vec.y == (int)fld_ind.y - 1 && sys->field->char_field[(int)fld_ind.y - 1][(int)fld_ind.x] != sys->bk) return (NORTH); else if ((int)bef_vec.y == (int)fld_ind.y + 1 && sys->field->char_field[(int)fld_ind.y + 1][(int)fld_ind.x] != sys->bk) return (SOUTH); else return (BLACK); } int get_side(t_system *sys, int k, t_streight streight) { t_point2d bef_vec; int side; double angle; bef_vec.x = (sys->pos.x + (streight.vec.x / 100) * k) / 100.0; bef_vec.y = (sys->pos.y + (streight.vec.y / 100) * k) / 100.0; while (k >= 0) { bef_vec.x = (sys->pos.x + (streight.vec.x / 100) * k) / 100.0; bef_vec.y = (sys->pos.y + (streight.vec.y / 100) * k) / 100.0; if (sys->field->char_field[(int)bef_vec.y][(int)bef_vec.x] != sys->bk) k = 0; k = k - 1; } angle = atan(streight.vec.y / streight.vec.x); side = check_left(sys, bef_vec, streight.result, angle); if (side == 0) side = check_right(sys, bef_vec, streight.result, angle); if (side == 0) side = check_front(sys, bef_vec, streight.result); return (side); }
C
/* C program to remove spaces from a string */ #include<stdio.h> void remove_white_spaces(char *str) { int i = 0, j = 0; while (str[i]) { if (str[i] != ' ') str[j++] = str[i]; i++; } str[j] = '\0'; puts(str); } int main() { char str[50]; printf("\n\t Enter a string : "); fgets(str,20,stdin); remove_white_spaces(str); //printf("\n%s",str); return 0; }
C
#include <stdio.h> int main() { int n=4,i,j,c=10; for(i=0;i<n;i++) { printf("\n"); //salto de linea para cada renglon for(j=i;j<n-1;j++) printf(" "); //espacios for(j=i;j>0;j--)//numeros printf("%d",c-j); printf("%d",c); //cifra columna for(j=1;j<i+1;j++)//numeros printf("%d",c-j); for(j=i;j<n-1;j++) printf(" "); //espacios } return 0; }
C
/* Author:- KARSHIL SHETH Objective:-TO PERFROM THE MULTIPLICATION OF A MATRIX. Date:- 11-02-2018 */ void main() { int i,j,a[3][3],b[3][3],d,c[3][3],k; clrscr(); printf("\n Enter 1st matrix of 9 elements : \n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { scanf("%d",&a[i][j]); } } printf("\n Enter 2nd matrix of 9 elements ; \n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { scanf("%d",&b[i][j]); } } printf("\n your 1st matrix is : \n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("%d ",a[i][j]); } printf("\n"); } printf("\n Your 2nd matrix is : \n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("%d ",b[i][j]); } printf("\n"); } printf("\n Multiplication of the matrix is : \n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { d=0; for(k=0;k<3;k++) { d=d+a[i][k]*b[k][j]; } c[i][j]=d; } } printf("\n Matrix is : \n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("%d ",c[i][j]); } printf("\n"); } getch(); }
C
#include<stdio.h> void main() { int data[10],j; printf("Enter 4 bits of data one by one\n"); scanf("%d",&data[3]); scanf("%d",&data[5]); scanf("%d",&data[6]); scanf("%d",&data[7]); //Calculation of parity bits data[1]=data[3]^data[5]^data[7]; //P1 = D3 D5 D7 printf("Parity Bit at P1 %d\n",data[1]); data[2]=data[3]^data[6]^data[7]; //P2 = D3 D6 D7 printf("Parity Bit at P2 %d\n",data[2]); data[4]=data[5]^data[6]^data[7]; //P4 = D5 D6 D7 printf("Parity Bit at P4 %d\n",data[4]); printf("\nEncoded data is\n"); for(j=7;j>0;j--) printf("%d ",data[j]); printf("\n"); int dataatrec[10],c,c1,c2,c3,i; printf("Enter received data bits one by one :"); for(i=0;i<7;i++) scanf("%d",&dataatrec[i]); c1=dataatrec[6]^dataatrec[4]^dataatrec[2]^dataatrec[0]; // C1 = P1 D3 c2=dataatrec[5]^dataatrec[4]^dataatrec[1]^dataatrec[0]; // C2 = P2 D3 c3=dataatrec[3]^dataatrec[2]^dataatrec[1]^dataatrec[0]; // C4 = P4 D5 c=c3*4+c2*2+c1 ;//calculating decimal value if(c==0) printf("No error while transmission of data\n"); else { printf("Error on position: %d",c); printf("\nData received : "); for(i=0;i<7;i++) printf("%d",dataatrec[i]); printf("\nCorrect message is: "); //if errorneous bit is 0 we complement it else vice versa if(dataatrec[7-c]==0) dataatrec[7-c]=1; else dataatrec[7-c]=0; for (i=0;i<7;i++) printf("%d",dataatrec[i]); } }
C
/* ADS1115_sample.c - 12/9/2013. Written by David Purdie as part of the openlabtools initiative Initiates and reads a single sample from the ADS1115 (without error handling) edited by Zach Richard to work with the TRAPSat Custom IO board for the RockSat-x 2016 mission. * changed address to 0x49 (previously 0x48) * changed int main() to float ads1115_read() * changed printf("Voltage Reading %f (V) \n", (float)val*4.096/32767.0); to return (float)val*4.096/32767.0; USE: * Function accepts an integer from 0 to 3 to select which pin to read from * Function returns the reading from the chosen pin in mV */ #include "ADS1115_read.h" float ads1115_read(int pin) { // only accept valid pin values if (pin > 3) return (float)(0); // not sure if this will work, I just want to return an error immediately -Zach int ADS_address = 0x49; // Address of our device on the I2C bus int I2CFile; uint8_t writeBuf[3]; // Buffer to store the 3 bytes that we write to the I2C device uint8_t readBuf[2]; // 2 byte buffer to store the data read from the I2C device uint8_t ads_read_pin; // Buffer to use as a mask to select ADS input int16_t val; // Stores the 16 bit value of our ADC conversion I2CFile = open("/dev/i2c-1", O_RDWR); // Open the I2C device ioctl(I2CFile, I2C_SLAVE, ADS_address); // Specify the address of the I2C Slave to communicate with // These three bytes are written to the ADS1115 to set the config register and start a conversion writeBuf[0] = 1; // This sets the pointer register so that the following two bytes write to the config register writeBuf[1] = 0xC3; // This sets the 8 MSBs of the config register (bits 15-8) to 11000011 -- C can be changed to C-F to select the channel to read. Default as C for AIN0 writeBuf[2] = 0x03; // This sets the 8 LSBs of the config register (bits 7-0) to 00000011 // Set the pin to be read from based on input parameter switch (pin) { case 0 : ads_read_pin = 0x40; break; case 1 : ads_read_pin = 0x50; break; case 2 : ads_read_pin = 0x60; break; case 3 : ads_read_pin = 0x70; break; default: ads_read_pin = 0x40; break; } writeBuf[1] |= ads_read_pin; // mask other set flags, only change the read pin // Initialize the buffer used to read data from the ADS1115 to 0 readBuf[0]= 0; readBuf[1]= 0; // Write writeBuf to the ADS1115, the 3 specifies the number of bytes we are writing, // this begins a single conversion write(I2CFile, writeBuf, 3); // Wait for the conversion to complete, this requires bit 15 to change from 0->1 while ((readBuf[0] & 0x80) == 0) // readBuf[0] contains 8 MSBs of config register, AND with 10000000 to select bit 15 { read(I2CFile, readBuf, 2); // Read the config register into readBuf } writeBuf[0] = 0; // Set pointer register to 0 to read from the conversion register write(I2CFile, writeBuf, 1); read(I2CFile, readBuf, 2); // Read the contents of the conversion register into readBuf val = readBuf[0] << 8 | readBuf[1]; // Combine the two bytes of readBuf into a single 16 bit result close(I2CFile); return (float)val*4096/32767.0 ; // return the Voltage read in Volts }
C
/*- * Licensed under the SPDX BSD-2-Clause identifier. * Use is subject to license terms, as specified in the LICENSE file. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <errno.h> #include <unistd.h> #include <getopt.h> #include <xbps.h> static void __attribute__((noreturn)) usage(bool fail) { fprintf(stdout, "Usage: xbps-digest [options] [file] [file+N]\n" "\n" "OPTIONS\n" " -h, --help Show usage\n" " -m, --mode <sha256> Selects the digest mode, sha256 (default)\n" " -V, --version Show XBPS version\n" "\nNOTES\n" " If [file] not set, reads from stdin\n"); exit(fail ? EXIT_FAILURE : EXIT_SUCCESS); } int main(int argc, char **argv) { int c; char sha256[XBPS_SHA256_SIZE]; const char *mode = NULL, *progname = argv[0]; const struct option longopts[] = { { "mode", required_argument, NULL, 'm' }, { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'V' }, { NULL, 0, NULL, 0 } }; while ((c = getopt_long(argc, argv, "m:hV", longopts, NULL)) != -1) { switch (c) { case 'h': usage(false); /* NOTREACHED */ case 'm': mode = optarg; break; case 'V': printf("%s\n", XBPS_RELVER); exit(EXIT_SUCCESS); case '?': default: usage(true); /* NOTREACHED */ } } argc -= optind; argv += optind; if (mode && strcmp(mode, "sha256")) { /* sha256 is the only supported mode currently */ fprintf(stderr, "%s: unsupported digest mode\n", progname); exit(EXIT_FAILURE); } if (argc < 1) { if (!xbps_file_sha256(sha256, sizeof sha256, "/dev/stdin")) exit(EXIT_FAILURE); printf("%s\n", sha256); } else { for (int i = 0; i < argc; i++) { if (!xbps_file_sha256(sha256, sizeof sha256, argv[i])) { fprintf(stderr, "%s: couldn't get hash for %s (%s)\n", progname, argv[i], strerror(errno)); exit(EXIT_FAILURE); } printf("%s\n", sha256); } } exit(EXIT_SUCCESS); }
C
/* * util.c * * Created on: Sep 5, 2019, 11:46:19 AM * Author: Joshua Fehrenbach */ #include "util.h" #include <string.h> #include <ctype.h> #include <dirent.h> #include <sys/stat.h> static const unsigned char * const binary_alphabet = (const unsigned char*)"01"; static const unsigned char * const octal_alphabet = (const unsigned char*)"01234567"; static const unsigned char * const hex_alphabet = (const unsigned char*) "0123456789abcdefABCDEF"; static const unsigned char * const base64_alphabet = (const unsigned char*) "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; #define XX 0xff static const unsigned char octal_table[64] = { XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, 0, 1, 2, 3, 4, 5, 6, 7, XX, XX, XX, XX, XX, XX, XX, XX }; static const unsigned char hex_table[128] = { XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, XX, XX, XX, XX, XX, XX, XX, 16, 17, 18, 19, 20, 21, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, 10, 11, 12, 13, 14, 15, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX }; static const unsigned char base64_table[128] = { XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, 62, XX, XX, XX, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, XX, XX, XX, XX, XX, XX, XX, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, XX, XX, XX, XX, XX, XX, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, XX, XX, XX, XX, XX }; #undef XX size_t binary_encode(unsigned char *dst, const uint8_t *src, size_t length) { size_t ret = length*8; uint8_t x; while (length-- != 0) { x = *src++; dst[0] = (x & 0x80) ? '1' : '0'; dst[1] = (x & 0x40) ? '1' : '0'; dst[2] = (x & 0x20) ? '1' : '0'; dst[3] = (x & 0x10) ? '1' : '0'; dst[4] = (x & 0x08) ? '1' : '0'; dst[5] = (x & 0x04) ? '1' : '0'; dst[6] = (x & 0x02) ? '1' : '0'; dst[7] = (x & 0x01) ? '1' : '0'; dst += 8; } *dst = '\0'; return ret; } size_t octal_encode(unsigned char *dst, const uint8_t *src, size_t length) { size_t ret = (length/3)*8; if (length % 3 == 2) { dst[0] = octal_alphabet[(src[0] >> 7) & 0x1]; dst[1] = octal_alphabet[(src[0] >> 4) & 0x7]; dst[2] = octal_alphabet[(src[0] >> 1) & 0x7]; dst[3] = octal_alphabet[((src[0] << 2) & 0x4) | ((src[1] >> 6) & 0x3)]; dst[4] = octal_alphabet[(src[1] >> 3) & 0x7]; dst[5] = octal_alphabet[(src[1] >> 0) & 0x7]; dst += 6; src += 2; length -= 2; ret += 6; } else if (length % 3 == 1) { dst[0] = octal_alphabet[(src[0] >> 6) & 0x3]; dst[1] = octal_alphabet[(src[0] >> 3) & 0x7]; dst[2] = octal_alphabet[(src[0] >> 0) & 0x7]; dst += 3; src++; length--; ret += 3; } length /= 3; while (length-- != 0) { dst[0] = octal_alphabet[(src[0] >> 5) & 0x7]; dst[1] = octal_alphabet[(src[0] >> 2) & 0x7]; dst[2] = octal_alphabet[((src[0] << 1) & 0x6) | ((src[1] >> 7) & 0x1)]; dst[3] = octal_alphabet[(src[1] >> 4) & 0x7]; dst[4] = octal_alphabet[(src[1] >> 1) & 0x7]; dst[5] = octal_alphabet[((src[1] << 2) & 0x4) | ((src[2] >> 6) & 0x3)]; dst[6] = octal_alphabet[(src[2] >> 3) & 0x7]; dst[7] = octal_alphabet[(src[2] >> 0) & 0x7]; dst += 8; src += 3; } *dst = '\0'; return ret; } size_t hex_encode(unsigned char *dst, const uint8_t *src, size_t length) { size_t ret = length*2; uint8_t x; while (length-- != 0) { x = *src++; dst[0] = hex_alphabet[(x >> 4) & 0xf]; dst[1] = hex_alphabet[(x >> 0) & 0xf]; dst += 2; } *dst = '\0'; return ret; } size_t base64_encode(unsigned char *dst, const uint8_t *src, size_t length) { size_t ret = ((length+2)/3)*4; size_t left = length % 3; length /= 3; while (length-- != 0) { dst[0] = base64_alphabet[(src[0] >> 2) & 0x3f]; dst[1] = base64_alphabet[((src[0] << 4) & 0x30) | ((src[1] >> 4) & 0x0f)]; dst[2] = base64_alphabet[((src[1] << 2) & 0x3c) | ((src[2] >> 6) & 0x03)]; dst[3] = base64_alphabet[src[2] & 0x3f]; dst += 4; src += 3; } if (left > 0) { dst[0] = base64_alphabet[(src[0] >> 2) & 0x3f]; if (left == 1) { dst[1] = base64_alphabet[(src[0] << 4) & 0x3f]; dst[2] = '='; } else { dst[1] = base64_alphabet[((src[0] << 4) & 0x30) | ((src[1] >> 4) & 0x0f)]; dst[2] = base64_alphabet[(src[1] << 2) & 0x3f]; } dst[3] = '='; dst += 4; } *dst = '\0'; return ret; } size_t binary_decode(uint8_t *dst, const unsigned char *src) { uint8_t x; size_t length = strspn((const char*)src, (const char *)binary_alphabet); size_t ret = (length+7)/8; if (length % 8 != 0) { x = 0; while (length % 8 != 0) { x <<= 1; if (*src++ == '1') { x |= 1; } length--; } *dst++ = x; } length /= 8; while (length-- != 0) { x = (src[0] == '1') << 7; x |= (src[1] == '1') << 6; x |= (src[2] == '1') << 5; x |= (src[3] == '1') << 4; x |= (src[4] == '1') << 3; x |= (src[5] == '1') << 2; x |= (src[6] == '1') << 1; x |= (src[7] == '1') << 0; *dst++ = x; src += 8; } return ret; } size_t octal_decode(uint8_t *dst, const unsigned char *src) { size_t length = strspn((const char *)src, (const char *)octal_alphabet); size_t ret = (length/8)*3; if (length % 8 != 0) { uint8_t x, y, z; if (length % 8 > 6 || (length % 8 == 6 && octal_table[*src] > 1)) { x = y = z = 0; while (length % 8 != 0) { x = ((x << 3) & 0xf8) | ((y >> 5) & 0x07); y = ((y << 3) & 0xf8) | ((z >> 5) & 0x07); z = ((z << 3) & 0xf8) | (octal_table[*src++] & 0x07); length--; } dst[0] = x; dst[1] = y; dst[2] = z; dst += 3; ret += 3; } else if (length % 8 > 3 || (length % 8 == 3 && octal_table[*src] > 3)) { x = y = 0; while (length % 8 != 0) { x = ((x << 3) & 0xf8) | ((y >> 5) & 0x07); y = ((y << 3) & 0xf8) | (octal_table[*src++] & 0x07); length--; } dst[0] = x; dst[1] = y; dst += 2; ret += 2; } else { x = 0; while (length % 8 != 0) { x = ((x << 3) & 0xf8) | (octal_table[*src++] & 0x07); length--; } *dst++ = x; ret++; } } length /= 8; while (length-- != 0) { dst[0] = ((octal_table[src[0]] << 5) & 0xe0) | ((octal_table[src[1]] << 2) & 0x1c) | ((octal_table[src[2]] >> 1) & 0x03); dst[1] = ((octal_table[src[2]] << 7) & 0x80) | ((octal_table[src[3]] << 4) & 0x70) | ((octal_table[src[4]] << 1) & 0x0e) | ((octal_table[src[5]] >> 2) & 0x01); dst[2] = ((octal_table[src[5]] << 6) & 0xc0) | ((octal_table[src[6]] << 3) & 0x38) | ((octal_table[src[7]] << 0) & 0x07); } return ret; } size_t hex_decode(uint8_t *dst, const unsigned char *src) { size_t length = strspn((const char *)src, (const char *)hex_alphabet); size_t ret = (length+1)/2; if (length % 2 != 0) { *dst++ = hex_table[*src++] & 0x0f; } length /= 2; while (length-- != 0) { *dst++ = ((hex_table[src[0]] << 4) & 0xf0) | (hex_table[src[1]] & 0x0f); src += 2; } return ret; } size_t base64_decode(uint8_t *dst, const unsigned char *src) { size_t length = strspn((const char *)src, (const char *)base64_alphabet); size_t ret = (length/4)*3; if (length % 4 == 1) { fprintf(stderr, "Invalid Base64 String; Cannot have a length of 1 (mod 4)\n"); exit(-1); } else if (length % 4 != 0) { ret += (length % 4) - 1; /* 2 or 3 extra digits give 1 or 2 extra byte(s) */ } while (length >= 4) { dst[0] = ((base64_table[src[0]] << 2) & 0xfc) | ((base64_table[src[1]] >> 4) & 0x03); dst[1] = ((base64_table[src[1]] << 4) & 0xf0) | ((base64_table[src[2]] >> 2) & 0x0f); dst[2] = ((base64_table[src[2]] << 6) & 0xc0) | (base64_table[src[3]] & 0x3f); dst += 3; src += 4; length -= 4; } if (length > 0) { dst[0] = ((base64_table[src[0]] << 2) & 0xfc) | ((base64_table[src[1]] >> 4) & 0x03); if (length == 3) { dst[1] = ((base64_table[src[1]] << 4) & 0xf0) | ((base64_table[src[2]] >> 2) & 0x0f); } } return ret; } size_t binary_encode_size(size_t bytes) { return 8*bytes; } size_t octal_encode_size(size_t bytes) { return ((bytes+2)/3)*8; } size_t hex_encode_size(size_t bytes) { return 2*bytes; } size_t base64_encode_size(size_t bytes) { return ((bytes+2)/3)*4; } size_t binary_decode_size(const unsigned char *src) { return (strspn((const char *)src, (const char *)binary_alphabet)+7)/8; } size_t octal_decode_size(const unsigned char *src) { size_t length = strspn((const char *)src, (const char *)octal_alphabet); if (length % 8 > 6 || (length % 8 == 6 && octal_table[*src] > 1)) { return 3 + (length/8)*3; } else if (length % 8 > 3 || (length % 8 == 3 && octal_table[*src] > 3)) { return 2 + (length/8)*3; } else if (length % 8 != 0) { return 1 + (length/8)*3; } else { return (length/8)*3; } } size_t hex_decode_size(const unsigned char *src) { return (strspn((const char *)src, (const char *)hex_alphabet)+1)/2; } size_t base64_decode_size(const unsigned char *src) { size_t length = strspn((const char *)src, (const char *)base64_alphabet); if (length % 4 == 0) { return (length/4)*3; } else if (length % 4 == 1) { fprintf(stderr, "Invalid Base64 String; Cannot have a length of 1 (mod 4)\n"); exit(-1); } return (length/4)*3 + (length % 4) - 1; } const struct encode_struct binary = { "Binary", &binary_encode, &binary_decode, &binary_encode_size, &binary_decode_size }; const struct encode_struct octal = { "Octal", &octal_encode, &octal_decode, &octal_encode_size, &octal_decode_size }; const struct encode_struct hexadecimal = { "Hexadecimal", &hex_encode, &hex_decode, &hex_encode_size, &hex_decode_size }; const struct encode_struct base64 = { "Base64", &base64_encode, &base64_decode, &base64_encode_size, &base64_decode_size }; const struct encode_struct *encoder; void encode_filename(char *dst, const char *src) { if (*src == '-') { *dst++ = '\\'; *dst++ = '-'; src++; } while (*src != '\0') { if (*src == '\\') { *dst++ = '\\'; *dst++ = '\\'; } else if (*src == '\n') { *dst++ = '\\'; *dst++ = 'n'; } else { *dst++ = *src; } src++; } *dst = '\0'; } void decode_filename(char *dst, const char *src) { while (*src != '\0') { if (*src == '\\') { if (*(src+1) == '\\') { *dst++ = '\\'; src++; } else if (*(src+1) == 'n') { *dst++ = '\n'; src++; } else if (*(src+1) == '-') { *dst++ = '-'; src++; } else { *dst++ = *src; } } else { *dst++ = *src; } src++; } *dst = '\0'; } void print_encoded_filename(const char *fn) { if (*fn == '-') { fputs("\\-", stdout); ++fn; } while (*fn != '\0') { if (*fn == '\\') { fputs("\\\\", stdout); } else if (*fn == '\n') { fputs("\\n", stdout); } else { putchar(*fn); } ++fn; } } void inplace_decode_filename(char *fn) { while (*fn != '\0') { /* Loop for out == fn (no escaped character found yet, so no copy needed) */ if (*fn++ == '\\') { /* Check for escape sequence, delegating to decode_filename if one is found */ if (*fn == '\\') { #if 0 *(fn-1) = '\\'; #endif decode_filename(fn, fn+1); return; } else if (*fn == 'n') { *(fn-1) = '\n'; decode_filename(fn, fn+1); return; } else if (*fn == '-') { *(fn-1) = '-'; decode_filename(fn, fn+1); return; } } } } const char* get_hash_digest_tag(hash_alg alg) { /* Array of const-pointers to const chars (array of static strings) */ static const char *const algname[] = { NULL, #include "algname.h" }; if (0 < alg && alg <= SHA3_512) { return algname[alg]; } else { return NULL; } } int get_hash_check(FILE *in, const char *in_name, hash_alg alg, char *filename, char *hashval) { char buffer[FILENAME_MAX*3/2+1]; char *buffp; const char *alg_tag; size_t length, t; do { /* Need to use fgets since the file name may contain whitespace */ if (fgets(buffer, sizeof(buffer)-1, in) == NULL) { return 0; /* No input, or error occurred */ } length = strlen(buffer); buffp = buffer; /* Remove Leading Whitespace */ while (isspace(*buffp) && length > 0) { ++buffp; --length; } } while (length == 0); /* Skip blank lines */ /* Remove Trailing Whitespace */ while (isspace(buffp[length-1])) { /* No need to check length in the loop condition, * since we know this is not a blank line */ buffp[--length] = '\0'; } /* Remove "Name:" identifier before file name */ if (memcmp("Name:", buffp, 5) != 0) { fprintf(stderr, "Hash check file \"%s\" has invalid format;" " skipping the remainder of the file\n", in_name); return 0; } buffp += 5; length -= 5; /* Remove Leading Whitespace again */ while (isspace(*buffp) && length > 0) { ++buffp; --length; } if (length == 0) { fprintf(stderr, "Hash check file \"%s\" has invalid format;" " skipping the remainder of the file\n", in_name); return 0; } /* Decode file name */ decode_filename(filename, buffp); /* Read line with hash value, recycling the input buffer */ do { if (fgets(buffer, sizeof(buffer)-1, in) == NULL) { fprintf(stderr, "Hash check file \"%s\" has invalid format;" " skipping the remainder of the file\n", in_name); return 0; } length = strlen(buffer); buffp = buffer; /* Remove Leading Whitespace */ while (isspace(*buffp) && length > 0) { ++buffp; --length; } } while (length == 0); /* Skip blank lines */ /* Remove Trailing Whitespace */ while (isspace(buffp[length-1])) { /* No need to check length in the loop condition, * since we know this is not a blank line */ buffp[--length] = '\0'; } /* Check and remove algorithm identifier before hash value */ alg_tag = get_hash_digest_tag(alg); t = strlen(alg_tag); if (memcmp(buffp, alg_tag, t) != 0) { fprintf(stderr, "Digest type mismatch in hash check file \"%s\";" " skipping the remainder of the file\n", in_name); return 0; } buffp += t + 1; /* +1 to remove ':' after algorithm identifier */ length -= t + 1; /* Remove Leading Whitespace again */ while (isspace(*buffp) && length > 0) { ++buffp; --length; } if (length == 0) { fprintf(stderr, "Hash check file \"%s\" has invalid format;" " skipping the remainder of the file\n", in_name); return 0; } /* Copy hash value hashval */ strcpy(hashval, buffp); return 1; } void hash_dir(struct hash_struct *hash, const char *dirname) { struct dirent *ent; char *path; size_t pathlen; DIR *dir = opendir(dirname); if (dir == NULL) { fprintf(stderr, "Directory \"%s\" can't be opened\n", dirname); exit(-1); } /* Set up a buffer with the directory name and room for an entry's name */ pathlen = strlen(dirname); path = malloc(pathlen + NAME_MAX + 2); strcpy(path, dirname); path[pathlen++] = '/'; /* Hash the contents of a directory */ while ((ent = readdir(dir)) != NULL) { if (strcmp(".", ent->d_name) == 0 || strcmp("..", ent->d_name) == 0) { /* Skip entry for current and parent directory, if they exist */ continue; } /* Send the next entry to hash_file, which calls this function again if the * entry was another directory */ strcpy(path + pathlen, ent->d_name); /* Copy the entry's name into the buffer */ hash_file(hash, path); } closedir(dir); free(path); } void hash_file(struct hash_struct *hash, const char *filename) { struct stat st; /* Check whether the file is an actual file */ if (stat(filename, &st)) { /* Could not read file attributes */ hash_file_err: fprintf(stderr, "File \"%s\" can't be opened\n", filename); exit(-1); } if (S_ISDIR(st.st_mode)) { /* Argument is a directory, so send to hash_dir */ hash_dir(hash, filename); } else { /* Argument is a file */ FILE *in = fopen(filename, "rb"); if (in == NULL) { goto hash_file_err; } hash_filep(hash, in); print_file_hash(hash, filename); fclose(in); } } void hash_filep(struct hash_struct *hash, FILE *in) { size_t bytes; char buffer[4096]; if (in == NULL) { fputs("hash_filep has NULL input file pointer\n", stderr); return; } /* Read up to 4KB at a time, and process the read bytes */ while ((bytes = fread(buffer, 1, 4096, in)) != 0) { hash->update(hash->ctx, (uint8_t*)buffer, bytes); } /* Finalize and retrieve the digest value */ hash->digest(hash->ctx, hash->hashval, hash->digest_size); } void print_file_hash(const struct hash_struct *hash, const char *filename) { fputs("Name: ", stdout); print_encoded_filename(filename); printf("\n%s: ", get_hash_digest_tag(hash->alg)); print_hash(hash); puts("\n"); } void print_hash(const struct hash_struct *hash) { unsigned char tmp[512+1]; /* max of 512 binary digits, plus null-terminator */ encoder->encode_func(tmp, hash->hashval, hash->digest_size); fputs((char*)tmp, stdout); }
C
#include<stdio.h> #define MAX 5 typedef int tVector[MAX]; tVector vector; float sumarVector(tVector, int); int main( ){ vector [0]=10.50; vector [1]=2.50; vector [2]=12.50; vector [3]=5.20; vector [4]=32.10; printf("suma es: %.2f", sumarVector(vector, 0)); return 0; } float sumarVector(tVector pVector, int i){ if (i < MAX){ return vector[i]+sumarVector(pVector,i+1); } }
C
/************************************************************************** * SHA1 declarations **************************************************************************/ #define SHA1_SIZE 20 /** * This structure will hold context information for the SHA-1 * hashing operation */ typedef unsigned long uint32_t; typedef unsigned short uint16_t; typedef unsigned char uint8_t; typedef struct { uint32_t Intermediate_Hash[SHA1_SIZE/4]; /* Message Digest */ uint32_t Length_Low; /* Message length in bits */ uint32_t Length_High; /* Message length in bits */ uint16_t Message_Block_Index; /* Index into message block array */ uint8_t Message_Block[64]; /* 512-bit message blocks */ } SHA1_CTX; void SHA1_Init(SHA1_CTX *); void SHA1_Update(SHA1_CTX *, const uint8_t * msg, int len); void SHA1_Final(uint8_t *digest, SHA1_CTX *);
C
#include <stdio.h> #include <stdlib.h> // malloc #include <string.h> // memset #include <stdint.h> // uintxx_t types #include <fcntl.h> // open #include <unistd.h> // write #define WIDTH 100 #define HEIGHT 160 int main (int argc, const char * argv[]) { uint8_t * bitmap = NULL; uint8_t * p = NULL; uint32_t counter = 0; uint32_t x0 = WIDTH / 4; int fd = -1; size_t bytes_to_write = 0; ssize_t bytes_written = 0; bitmap = (uint8_t *) malloc(WIDTH * HEIGHT * sizeof(uint8_t)); if( bitmap != NULL ) { // initialize bitmap to black memset(bitmap, 0, WIDTH * HEIGHT * sizeof(uint8_t)); // set middle point to white bitmap[HEIGHT / 2 * WIDTH + WIDTH / 2] = 0xFF; // draw white line at y = height/3 memset(bitmap + HEIGHT / 3 * WIDTH, 0xFE, WIDTH * sizeof(uint8_t)); // draw line at x = x0 p = bitmap + x0; counter = HEIGHT; while( counter-- ) { *p = 0x80; p += WIDTH; } // draw line x = y p = bitmap; counter = WIDTH > HEIGHT ? HEIGHT : WIDTH; while( counter-- ) { *p = 0xC0; p += WIDTH + 1; } fd = open("premier test.data", O_CREAT | O_TRUNC | O_WRONLY | O_APPEND #ifdef WIN32 | O_BINARY #else // WIN32 , S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH #endif // WIN32 ); if( fd != -1 ) { bytes_to_write = HEIGHT * WIDTH * sizeof(uint8_t); bytes_written = write(fd, bitmap, bytes_to_write); if( bytes_written == bytes_to_write ) { printf("data sucessfully written\n"); } else printf("data write failed\n"); close(fd); } else printf("file open failed\n"); free(bitmap); } else printf("bitmap allocation failed\n"); #ifdef WIN32 system("pause"); #endif return 0; }
C
#include <stdio.h> #include <string.h> #include <assert.h> #include <stdlib.h> #define MAX_CHAR_NUM 26 #define MAX_KEY_WORD 36 char freq_of_char[MAX_CHAR_NUM] = {0}; static char *static_site[] = {"do", "end", "else", "case", "downto", "goto", "to", "otherwise", "type", "while", "const", "div", "and", "set", "or", "of", "mod", "file", "record", "packed", "not", "then", "procedure", "with", "repeat", "var", "in", "array", "if", "nil", "for", "begin", "until", "label", "function", "program"}; char *static_site_in_order[MAX_KEY_WORD] = {NULL}; struct static_sites { char char1; char char2; char *str; char strlengh; char key_value; } ss[MAX_KEY_WORD] = {{'d','o',"do", 2}, {'e','d',"end", 3}, {'e','e',"else", 4}, {'c','e',"case", 4}, {'d','o',"downto", 6}, {'g','o',"goto", 4}, {'t','o',"to", 2}, {'o','e',"otherwise", 9}, {'t','e',"type", 4}, {'w','e',"while", 5}, {'c','t',"const", 5}, {'d','v',"div", 3}, {'a','d',"and", 3}, {'s','t',"set", 3}, {'o','r',"or", 2}, {'o','f',"of", 2}, {'m','d',"mod", 3}, {'f','e',"file", 4}, {'r','d',"record", 6}, {'p','d',"packed", 6}, {'n','t',"not", 3}, {'t','n',"then", 4}, {'p','e',"procedure", 9}, {'w','h',"with", 4}, {'r','t',"repeat", 6}, {'v','r',"var", 3}, {'i','n',"in", 2}, {'a','y',"array", 5}, {'i','f',"if", 2}, {'n','l',"nil", 3}, {'f','o',"for", 3}, {'b','n',"begin", 5}, {'u','l',"until", 5}, {'l','l',"label", 5}, {'f','n',"function", 8}, {'p','m',"program", 7}}; struct static_sites *ssp[MAX_KEY_WORD] = {NULL}; struct freq_char { unsigned char c; unsigned char freq; unsigned char key; }; struct freq_char *freq_of_char_in_order[MAX_CHAR_NUM] = {NULL}; struct freq_char *freq_of_char_in_alph[MAX_CHAR_NUM] = {NULL}; struct freq_char *c_c = freq_of_char_in_order; void calc_string(char *one_str) { int num = strlen(one_str); int key = num + (*one_str - 'a') + (*(one_str + num - 1) - 'a'); // printf("str(%s) \t= len(%d), key(%d, %d)\n", one_str, num, (*one_str - 'a'), (*(one_str + num - 1) - 'a')); freq_of_char[*one_str - 'a']++; freq_of_char[*(one_str + num - 1) - 'a']++; } void swap(struct freq_char **first, struct freq_char **second) { long temp = *first; *first = *second; *second = (struct freq_char *)temp; } void qsort_freq(int mid_pos, int num) { int i = 0; int m = mid_pos; struct freq_char *tmp = NULL; if (mid_pos >= num) { return; } for (i = mid_pos + 1; i <= num; i++) { if (freq_of_char_in_order[i]->freq >= freq_of_char_in_order[mid_pos]->freq) { swap(&freq_of_char_in_order[++m], &freq_of_char_in_order[i]); } } //printf("%*s|%*s|\n", (mid_pos<<1), "", (m<<1) - (mid_pos<<1) - 1, ""); swap(&freq_of_char_in_order[mid_pos], &freq_of_char_in_order[m]); qsort_freq(mid_pos, m - 1); qsort_freq(m + 1, num); } void order_freq() { int i = 0; struct freq_char *fc = NULL; /* we need to order char by freq. */ for (; i < MAX_CHAR_NUM; i++) { fc = (struct freq_char *)malloc(sizeof(struct freq_char)); if (fc == NULL) { printf("malloc error!\n"); exit(-1); } fc->freq = freq_of_char[i]; fc->c = i + 'a'; fc->key = 0; freq_of_char_in_order[i] = fc; freq_of_char_in_alph[i] = fc; } qsort_freq(0, MAX_CHAR_NUM - 1); #if 0 /* we could delete these code, we don't use it anymore */ /* ordering string by char's freq. */ for (i = 0;i < sizeof(static_site)/sizeof(char *); i++) { insert_into_tree(static_site[i]); } #endif } void order_freq_of_word() { int i = 0; int j = 0; int s = 0; int num = 0; for (; i < MAX_CHAR_NUM; i++) { for (j = 0; j <= i; j++) { // printf("==== > %c %c\n",freq_of_char_in_order[i]->c, freq_of_char_in_order[j]->c); for (s = 0; s < MAX_KEY_WORD; s++) { if ((ss[s].char1 == freq_of_char_in_order[i]->c) && (ss[s].char2 == freq_of_char_in_order[j]->c)) { printf("num = %d, %s\n", num, ss[s].str); static_site_in_order[num] = static_site[s]; ssp[num] = &ss[s]; num++; continue; } else if ((ss[s].char2 == freq_of_char_in_order[i]->c) && (ss[s].char1 == freq_of_char_in_order[j]->c)) { printf("num = %d, %s\n", num, ss[s].str); static_site_in_order[num] = static_site[s]; ssp[num] = &ss[s]; num++; continue; } else { continue; } } } } for (i = 0; i < MAX_KEY_WORD; i++) printf("%d = %s\n",i, static_site_in_order[i]); } char check_collision(char num) { int i = 0; for (; i < num; i++) { //printf("<%s> <%s>\n", ssp[i]->str, ssp[num]->str); if (ssp[i]->key_value == ssp[num]->key_value) { //printf("-------->%s, %s collision\n", ssp[i]->str, ssp[num]->str); return 1; } } return 0; } char update_keyvalue(int i) { while (check_collision(i)) { /* * We should update key value here * And we need to check collision once we update key value */ ssp[i]->key_value = ssp[i]->key_value + 1; } } void processing_char() { int i = 0; char c_c = 0; // current char for (; i < MAX_KEY_WORD; i++) { ssp[i]->key_value = freq_of_char_in_alph[ssp[i]->char1 - 'a']->key + freq_of_char_in_alph[ssp[i]->char2 - 'a']->key + ssp[i]->strlengh; printf("[%s = %c ... %d ... %c] = %d\n", ssp[i]->str, ssp[i]->char1, ssp[i]->strlengh, ssp[i]->char2, ssp[i]->key_value); } for (i = 0; i < MAX_KEY_WORD; i++) { update_keyvalue(i); #if 0 if (c_c == ssp[i]->char1) { } else if (c_c == ssp[i]->char2) { } #endif } for (i = 0; i < MAX_KEY_WORD; i++) { printf("[%s = %c ... %d ... %c] = %d\n", ssp[i]->str, ssp[i]->char1, ssp[i]->strlengh, ssp[i]->char2, ssp[i]->key_value); } } int hash_func(char *str) { /* hash value = key length + first character + last charater */ unsigned char key = 0; key = strlen(str); key += (*str + *(str + key - 1)); return key; } int main(int argc, char *argv[]) { int i = 0; while (i < sizeof(static_site)/sizeof(char *)) { calc_string(static_site[i++]); } order_freq(); for (i = 0; i < MAX_CHAR_NUM; i++) { printf("%c = %d\n", freq_of_char_in_order[i]->c, freq_of_char_in_order[i]->freq); } order_freq_of_word(); processing_char(); // print_freq_by_tree(tree_root); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include "utilities.h" #include "powerbag.h" #include "seriesoperation.h" void *workerWrapper(void *p_voidedbag); void workerOptimization(PowerBag *p_bag); int main(int argc, char *argv[]) { int code = 0, initialRuns, activeWorkers, scheduledJobs, assetIndex, assetNum, rtnNum; int quantity = 1, workersNum = 1; double *p_assetRtn = NULL, *p_fakeRtn = NULL, *p_mean = NULL, epsSd, *v = NULL, orgProp; double lambda, tolerance; int j, theWorker; char gotone; FILE *input; char buffer[100]; PowerBag **pp_bag = NULL, *p_bag = NULL; pthread_t *p_threadArray; pthread_mutex_t output; pthread_mutex_t *p_synchroArray; if(argc != 6){ printf(" usage: rpower data_filename parameters_filename workersNum job_quantity lambda\n"); code = 1; goto BACK; } /* read parameters */ input = fopen(argv[2], "r"); if (input == NULL){ printf("cannot read %s\n",argv[2]); code=2; goto BACK; } fscanf(input, "%s", buffer); fscanf(input, "%s", buffer); assetNum = atoi(buffer); fscanf(input, "%s", buffer); fscanf(input, "%s", buffer); rtnNum = atoi(buffer)-1; fscanf(input, "%s", buffer); fscanf(input, "%s", buffer); epsSd = atof(buffer); if (epsSd <= 0){ printf("Standard deviation must be positive.\n"); code = 1; goto BACK; } fscanf(input, "%s", buffer); fscanf(input, "%s", buffer); orgProp = atof(buffer); fscanf(input, "%s", buffer); fscanf(input, "%s", buffer); tolerance = atof(buffer); fclose(input); workersNum = atoi(argv[3]); quantity = atoi(argv[4]); sscanf(argv[5], "%lf", &lambda); printf("\n%d workers will work on %d jobs.\n", workersNum, quantity); /* read data and obtain average return of assets */ p_assetRtn = (double *)calloc(assetNum*rtnNum, sizeof(double)); p_mean = (double *)calloc(assetNum, sizeof(double)); code = readAssetObsGetMean(argv[1], p_assetRtn, p_mean, assetNum, rtnNum); if(code) goto BACK; /* output mutex, common to everybody */ pthread_mutex_init(&output, NULL); /** **/ /* psynchronization mutex, unique to each worker */ p_synchroArray = (pthread_mutex_t *)calloc(workersNum, sizeof(pthread_mutex_t)); if(!p_synchroArray){ printf("could not create mutex array\n"); code = NOMEMORY; goto BACK; } for(j = 0; j < workersNum; j++) pthread_mutex_init(&p_synchroArray[j], NULL); /* create bag */ pp_bag = (PowerBag **)calloc(workersNum, sizeof(PowerBag *)); if(!pp_bag){ printf("could not create bag array\n"); code = NOMEMORY; goto BACK; } /* create thread */ p_threadArray = (pthread_t *)calloc(workersNum, sizeof(pthread_t)); if(!p_threadArray){ printf("could not create thread array\n"); code = NOMEMORY; goto BACK; } /* create v*/ v = (double *)calloc(assetNum, sizeof(double)); if (!v){ printf("could not create v\n"); code = NOMEMORY; goto BACK; } drawNormalVector(v, assetNum, 1); /* create fake return array */ p_fakeRtn = (double *)calloc(assetNum*rtnNum, sizeof(double)); if (!p_fakeRtn){ printf("could not create fake return array\n"); code = NOMEMORY; goto BACK; } /* assign values to bags and launch threads.*/ for(j = 0; j < workersNum; j++){ pp_bag[j] = (PowerBag *)calloc(1, sizeof(PowerBag)); p_bag = pp_bag[j]; if(!p_bag){ printf("cannot allocate bag for ID %d\n", j); code = NOMEMORY; goto BACK; } p_bag->rtnNum = rtnNum; p_bag->assetNum = assetNum; if((code = PWRallocatespace(p_bag))){ printf("cannot allocate space to arrays in worker%d.\n", workersNum); code = NOMEMORY; goto BACK; } p_bag->ID = j; p_bag->lambda = lambda; p_bag->tolerance = tolerance; p_bag->p_mean = p_mean; p_bag->status = PREANYTHING; p_bag->command = STANDBY; p_bag->p_synchro = &p_synchroArray[j]; p_bag->p_outputMutex = &output; printf("\nabout to launch thread for worker %d\n", j); pthread_create(&p_threadArray[j], NULL, &workerWrapper, (void *) p_bag); } /* start jobs */ initialRuns = (workersNum < quantity) ? workersNum : quantity; for(theWorker = 0; theWorker < initialRuns; theWorker++){ p_bag = pp_bag[theWorker]; pthread_mutex_lock(&p_synchroArray[theWorker]); if((code = timeSeriesPerturb(p_assetRtn, p_bag, v, epsSd, orgProp))) goto BACK; pthread_mutex_unlock(&p_synchroArray[theWorker]); pthread_mutex_lock(&output); printf("\n*****master: worker %d will run experiment %d\n", theWorker, theWorker); pthread_mutex_unlock(&output); /** tell the worker to work **/ pthread_mutex_lock(&p_synchroArray[theWorker]); p_bag->command = WORK; p_bag->status = WORKING; p_bag->jobNumber = theWorker; pthread_mutex_unlock(&p_synchroArray[theWorker]); } scheduledJobs = activeWorkers = initialRuns; while(activeWorkers > 0){ /** check the workers' status **/ gotone = 0; for(theWorker = 0; theWorker < workersNum; theWorker++){ pthread_mutex_lock(&p_synchroArray[theWorker]); p_bag = pp_bag[theWorker]; if(p_bag->status == DONEWITHWORK){ pthread_mutex_lock(&output); printf("\nmaster: worker %d is done with job %d\n\nOptimal variables:\n", p_bag->ID, p_bag->jobNumber); for (assetIndex = 0; assetIndex < assetNum; assetIndex++){ if (p_bag->p_optimal[assetIndex] > 0.0001){ printf("x%d = %.9e\n", assetIndex, p_bag->p_optimal[assetIndex]); } } pthread_mutex_unlock(&output); if(scheduledJobs >= quantity){ /** tell worker to quit **/ pthread_mutex_lock(&output); printf("\nmaster: telling worker %d to quit\n", p_bag->ID); pthread_mutex_unlock(&output); p_bag->command = QUIT; p_bag->status = QUIT; --activeWorkers; } else { gotone = 1; } } else if(p_bag->status == PREANYTHING){ pthread_mutex_lock(&output); printf("\nmaster: worker %d is available\n", theWorker); pthread_mutex_unlock(&output); gotone = 1; } pthread_mutex_unlock(&p_synchroArray[theWorker]); if(gotone) break; sleep(2); } /** at this point we have run through all workers **/ if(gotone){ /** if we are here, "theWorker" can work **/ p_bag = pp_bag[theWorker]; /*TODO: added mutex*/ pthread_mutex_lock(&p_synchroArray[theWorker]); if((code = timeSeriesPerturb(p_assetRtn, p_bag, v, epsSd, orgProp))) goto BACK; pthread_mutex_unlock(&p_synchroArray[theWorker]); pthread_mutex_lock(&output); printf("\nmaster: worker %d will run experiment %d\n", theWorker, scheduledJobs); pthread_mutex_unlock(&output); /** tell the worker to work **/ pthread_mutex_lock(&p_synchroArray[theWorker]); p_bag->command = WORK; p_bag->status = WORKING; p_bag->jobNumber = scheduledJobs; pthread_mutex_unlock(&p_synchroArray[theWorker]); ++scheduledJobs; } } BACK: if(p_assetRtn) free(p_assetRtn); if(p_fakeRtn) free(p_fakeRtn); if(p_mean) free(p_mean); if(v) free(v); for(theWorker = 0; theWorker < workersNum; theWorker++){ if (pp_bag[theWorker]){ pthread_join(p_threadArray[theWorker], NULL); PWRfreespace(pp_bag[theWorker]); if (pp_bag[theWorker]) free(pp_bag[theWorker]); } } if(pp_bag) free(pp_bag); if(p_threadArray) free(p_threadArray); if(p_synchroArray) free(p_synchroArray); return code; } void *workerWrapper(void *p_voidedBag) { PowerBag *p_bag = (PowerBag *) p_voidedBag; workerOptimization(p_bag); return (void *) &p_bag->ID; }
C
/* * This file implements enrichment from an arbitrary, custom enrichment * channel parameterized by the user in VICE singlezone simulations. */ #include <stdlib.h> #include "../singlezone.h" #include "../callback.h" #include "../channel.h" #include "../utils.h" #include "channel.h" /* * Determine the rate of mass enrichment of a given element at the current * timestep from all arbitrary enrichment channels. * * Parameters * ========== * sz: The SINGLEZONE object for the current simulation * e: The element to find the rate of mass enrichment for * * Returns * ======= * The time-derivative of the arbitrary enrichment channels mass enrichment * term * * header: channel.h */ extern double mdot(SINGLEZONE sz, ELEMENT e) { unsigned short i; double mdot_ = 0; for (i = 0lu; i < e.n_channels; i++) { unsigned long j; for (j = 0l; j < sz.timestep; j++) { /* Entrainment to be handled in vice/src/singlezone/element.c */ mdot_ += (get_yield((*e.channels[i]), scale_metallicity(sz, j)) * (*sz.ism).star_formation_history[j] * (*e.channels[i]).rate[sz.timestep - j] ); } } return mdot_; } /* * Obtain the IMF-integrated fractional mass yield of a given element from * its internal yield table. * * Parameters * ========== * e: The element to find the yield for * Z: The metallicity to look up on the grid * * Returns * ======= * The interpolated yield off of the stored yield grid within the CHANNEL * struct. * * header: channel.h */ extern double get_yield(CHANNEL ch, double Z) { return callback_1arg_evaluate(*ch.yield_, Z); } /* * Normalize the rate once it is set according to an arbitrary normalization * by the user in python. * * Parameters * ========== * e: The ELEMENT struct to normalize the rate for. * length: The length of the e -> channels[i] -> rate array * * header: channel.h */ extern void normalize_rates(ELEMENT *e, unsigned long length) { unsigned short i; for (i = 0u; i < (*e).n_channels; i++) { unsigned long j; double sum = 0; for (j = 0lu; j < length; j++) { sum += (*(*e).channels[i]).rate[j]; } for (j = 0lu; j < length; j++) { e -> channels[i] -> rate[j] /= sum; } } }
C
#include "holberton.h" /** * _strlen_recursion(:)? (- leng)? * * @s: input char * Return: a */ int _strlen_recursion(char *s) { if (*s != '\0') { int a = 0; a += 1; return (a + _strlen_recursion(++s)); } else return (0); }
C
/* * err.c * * Created on: Jul 28, 2019 * Author: jan */ #include "err.h" void error(char* msg){ fprintf(stderr, "%s: %s\n", msg, strerror(errno)); exit(1); }
C
#include "common.h" /* The plaintext case for I/O is really easy. Call the openssl BIO_* functions and return. */ /*********************************************************************************************************************** * * remote_read_plaintext() * * Input: A pointer to our remote_io_helper object, a pointer to the buffer we want to fill, and the count of characters * we should try to read. * Output: The count of characters succesfully read, or an error code. (man BIO_read for more information.) * * Purpose: Fill our buffer, but this is the simple plaintext wrapper case. Nothing fancy here. * **********************************************************************************************************************/ int remote_read_plaintext(struct remote_io_helper *io, void *buff, size_t count){ return(BIO_read(io->connect, buff, count)); } /*********************************************************************************************************************** * * remote_write_plaintext() * * Input: A pointer to our remote_io_helper object, a pointer to the buffer we want to empty, and the count of * characters we should try to write. * Output: The count of characters succesfully written, or an error code. (man BIO_write for more information.) * * Purpose: Empty our buffer, but this is the simple plaintext wrapper case. Nothing fancy here. * **********************************************************************************************************************/ int remote_write_plaintext(struct remote_io_helper *io, void *buff, size_t count){ return(BIO_write(io->connect, buff, count)); } /*********************************************************************************************************************** * * remote_read_encrypted() * * Input: A pointer to our remote_io_helper object, a pointer to the buffer we want to fill, and the count of characters * we should try to read. * Output: The count of characters succesfully read, or an error code. (man BIO_read for more information.) * * Purpose: Fill our buffer. This is the SSL encrypted case. * * Note: This function won't return until it has satisfied the request to read count characters, or encountered an error * trying. It assumes the socket is ready for action (either blocking, or has just passed a select() call.) If it * cannot fulfill the requested character count initially, it will call select() itself in a loop until it can. * **********************************************************************************************************************/ int remote_read_encrypted(struct remote_io_helper *io, void *buff, size_t count){ int retval; fd_set fd_select; int ssl_error = SSL_ERROR_NONE; do{ /* We've already been through the loop once, but now we need to wait for the socket to be ready. */ if(ssl_error != SSL_ERROR_NONE){ FD_ZERO(&fd_select); FD_SET(io->remote_fd, &fd_select); if(ssl_error == SSL_ERROR_WANT_READ){ if(select(io->remote_fd + 1, &fd_select, NULL, NULL, NULL) == -1){ print_error(io, "%s: %d: select(%d, %lx, NULL, NULL, NULL): %s\n", \ program_invocation_short_name, io->controller, \ io->remote_fd + 1, (unsigned long) &fd_select, strerror(errno)); return(-1); } }else /* if(ssl_error == SSL_ERROR_WANT_WRITE) */ { if(select(io->remote_fd + 1, NULL, &fd_select, NULL, NULL) == -1){ print_error(io, "%s: %d: select(%d, NULL, %lx, NULL, NULL): %s\n", \ program_invocation_short_name, io->controller, \ io->remote_fd + 1, (unsigned long) &fd_select, strerror(errno)); return(-1); } } } retval = SSL_read(io->ssl, buff, count); switch(SSL_get_error(io->ssl, retval)){ case SSL_ERROR_NONE: case SSL_ERROR_ZERO_RETURN: return(retval); break; case SSL_ERROR_WANT_READ: ssl_error = SSL_ERROR_WANT_READ; break; case SSL_ERROR_WANT_WRITE: ssl_error = SSL_ERROR_WANT_WRITE; break; default: return(-1); } } while(ssl_error); return(-1); } /*********************************************************************************************************************** * * remote_write_encrypted() * * Input: A pointer to our remote_io_helper object, a pointer to the buffer we want to empty, and the count of * characters we should try to write. * Output: The count of characters succesfully written, or an error code. (man BIO_write for more information.) * * Purpose: Empty our buffer, but this is the simple plaintext wrapper case. Nothing fancy here. * * Note: This function won't return until it has satisfied the request to write count characters, or encountered an * error trying. It assumes the socket is ready for action (either blocking, or has just passed a select() call.) If * it cannot fulfill the requested character count initially, it will call select() itself in a loop until it can. * **********************************************************************************************************************/ int remote_write_encrypted(struct remote_io_helper *io, void *buff, size_t count){ int retval; fd_set fd_select; int ssl_error = SSL_ERROR_NONE; do{ /* We've already been through the loop once, but now we need to wait for the socket to be ready. */ if(ssl_error != SSL_ERROR_NONE){ FD_ZERO(&fd_select); FD_SET(io->remote_fd, &fd_select); if(ssl_error == SSL_ERROR_WANT_READ){ if(select(io->remote_fd + 1, &fd_select, NULL, NULL, NULL) == -1){ print_error(io, "%s: %d: select(%d, %lx, NULL, NULL, NULL): %s\n", \ program_invocation_short_name, io->controller, \ io->remote_fd + 1, (unsigned long) &fd_select, strerror(errno)); return(-1); } }else /* if(ssl_error == SSL_ERROR_WANT_WRITE) */ { if(select(io->remote_fd + 1, NULL, &fd_select, NULL, NULL) == -1){ print_error(io, "%s: %d: select(%d, NULL, %lx, NULL, NULL): %s\n", \ program_invocation_short_name, io->controller, \ io->remote_fd + 1, (unsigned long) &fd_select, strerror(errno)); return(-1); } } } retval = SSL_write(io->ssl, buff, count); switch(SSL_get_error(io->ssl, retval)){ case SSL_ERROR_NONE: case SSL_ERROR_ZERO_RETURN: return(retval); break; case SSL_ERROR_WANT_READ: ssl_error = SSL_ERROR_WANT_READ; break; case SSL_ERROR_WANT_WRITE: ssl_error = SSL_ERROR_WANT_WRITE; break; default: return(-1); } } while(ssl_error); return(-1); } /*********************************************************************************************************************** * * remote_printf() * * Input: A pointer to our remote_io_helper object, and the fmt specification as you would find in a normal printf * statement. * Output: The count of characters succesfully printed. * * Purpose: Provide a printf() style wrapper that will do the right thing down our socket. * **********************************************************************************************************************/ int remote_printf(struct remote_io_helper *io, char *fmt, ...){ int retval; char buff[BUFFER_SIZE]; va_list list_ptr; va_start(list_ptr, fmt); /* XXX Add a loop here in case we need to print something longer than BUFFER_SIZE. */ memset(buff, 0, BUFFER_SIZE); if((retval = vsnprintf(buff, BUFFER_SIZE - 1, fmt, list_ptr)) < 0){ print_error(io, "%s: %d: vsnprintf(%lx, %d, %lx, %lx): %s\n", \ program_invocation_short_name, io->controller, \ (unsigned long) buff, BUFFER_SIZE - 1, (unsigned long) fmt, (unsigned long) list_ptr, \ strerror(errno)); return(retval); } io->remote_write(io, buff, retval + 1); va_end(list_ptr); return(retval); } /*********************************************************************************************************************** * * print_error() * * Input: A pointer to our remote_io_helper object, and the fmt specification as you would find in a normal printf * statement. * Output: The count of characters succesfully printed. * * Purpose: Provide a wrapper that allows us to just call print_error() and have the correct thing happen regardless of * being a target or a controller. This simplifies the error reporting code greatly. * **********************************************************************************************************************/ int print_error(struct remote_io_helper *io, char *fmt, ...){ int retval = 0; va_list list_ptr; va_start(list_ptr, fmt); if(io->controller){ if((retval = vfprintf(stderr, fmt, list_ptr)) < 0){ print_error(io, "%s: %d: vfprintf(stderr, %lx, %lx): %s\n", \ program_invocation_short_name, io->controller, \ (unsigned long) fmt, (unsigned long) list_ptr, \ strerror(errno)); } fflush(stderr); }else{ retval = remote_printf(io, fmt, list_ptr); } return(retval); }
C
#ifndef LIST_H_ #define LIST_H_ struct list { void* value; struct list* rest; }; typedef void (*list_for_each_fn)(void* obj, void* value); void list_init(struct list* self, void* value, struct list* rest); struct list* list_new(void* value, struct list* rest); void list_for_each(struct list* self, list_for_each_fn* callback); void list_for_each2(struct list* self, list_for_each_fn callback, void* callback_data); void list_free(struct list* self); struct list* list_push(struct list** handle, void* value); void* list_pop(struct list** handle); void* list_nth(struct list* self, int index); #endif
C
/* mpd_signbit -- Signbit of a MPD number */ #include "mpd-impl.h" int mpd_signbit (mpd_srcptr x) { if (MPD_CLASS(x) == MPD_CLASS_NEG_ZERO) { MPD_RET(-1); } if (MPD_CLASS(x) == MPD_CLASS_POS_ZERO) { MPD_RET(1); } MPD_RET(MPD_SIGN(x)); }
C
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { int t; scanf("%d",&t); while(t--) { int i,n,a[100000],sumc=0,flag=0,sumnc=0,max=0; scanf("%d",&n); for(i=0;i<n;i++)scanf("%d",&a[i]); for(i=0;i<n;i++) { if(a[i]<0)flag=1; else {flag=0;break;} } for(i=0;i<n;i++) { if(a[i]>0)sumc+=a[i]; }max=a[0]; for(i=0;i<n;i++) { sumnc+=a[i]; if(sumnc<0)sumnc=0; if(max<sumnc) {max=sumnc;} } if(flag==1){sumc=a[0];max=a[0];} printf("%d %d\n",max,sumc); } return 0; }
C
#include "PID.h" /* The parameters that we will use is: goal_rpm -> the input of the user. local variable at GUI.c curr_rpm -> it 120000/freq. we measure it and we can not change it. goal_dutycycle -> we don't have this parameter. it is unkown and "curr_dutycycle" will reach that by iteration curr_dutycycle -> we calculate this with PID controller. local vatiable at PID.c */ int16_t Error; int16_t Error_pre=0; float Error_integral=0; int16_t Error_deri=0; uint16_t curr_dutycycle = 100; float P = 0.01; float I = 0.03; float D = 0.001; float PID_var; float K=0.01; uint16_t next_dutycycle; void PID_get_nextdutycycle(uint16_t * GUI_dutycycle, uint16_t curr_RPM, uint16_t goal_RPM){ PID_calc_dutycycle(curr_RPM, goal_RPM); *GUI_dutycycle = curr_dutycycle; } void PID_calc_dutycycle(uint16_t curr_RPM, uint16_t goal_RPM){ Error = curr_RPM - goal_RPM; Error_integral += Error*0.001; Error_deri = Error - Error_pre; Error_pre = Error; PID_var = P*Error + I*Error_integral + D*Error_deri; curr_dutycycle -= PID_var; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <SDL.h> #include "util-graphics.h" Uint32 get_pixel32( SDL_Surface *surface, int x, int y ) { //Convert the pixels to 32 bit Uint32 *pixels = (Uint32 *)surface->pixels; //Get the requested pixel return pixels[ ( y * surface->w ) + x ]; } void put_pixel32( SDL_Surface *surface, int x, int y, Uint32 pixel ) { //Convert the pixels to 32 bit Uint32 *pixels = (Uint32 *)surface->pixels; //Set the pixel pixels[ ( y * surface->w ) + x ] = pixel; } /* * Return the pixel value at (x, y) * NOTE: The surface must be locked before calling this! */ Uint32 getpixel(SDL_Surface *surface, int x, int y) { int bpp = surface->format->BytesPerPixel; /* Here p is the address to the pixel we want to retrieve */ Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp; switch (bpp) { case 1: return *p; case 2: return *(Uint16 *)p; case 3: if (SDL_BYTEORDER == SDL_BIG_ENDIAN) return p[0] << 16 | p[1] << 8 | p[2]; else return p[0] | p[1] << 8 | p[2] << 16; case 4: return *(Uint32 *)p; default: return 0; /* shouldn't happen, but avoids warnings */ } } void putpixel(SDL_Surface *surface, int x, int y, Uint32 pixel) { int bpp = surface->format->BytesPerPixel; /* Here p is the address to the pixel we want to set */ Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp; switch (bpp) { case 1: *p = pixel; break; case 2: *(Uint16 *)p = pixel; break; case 3: if (SDL_BYTEORDER == SDL_BIG_ENDIAN) { p[0] = (pixel >> 16) & 0xff; p[1] = (pixel >> 8) & 0xff; p[2] = pixel & 0xff; } else { p[0] = pixel & 0xff; p[1] = (pixel >> 8) & 0xff; p[2] = (pixel >> 16) & 0xff; } break; case 4: *(Uint32 *)p = pixel; break; default: break; /* shouldn't happen, but avoids warnings */ } }
C
// El siguiente codigo se realizo con la guia del siguiente tutorial: https://www.youtube.com/watch?v=fNerEo6Lstw&feature=youtu.be #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <pthread.h> #define BUFFER_SZ 250 // Variables globales volatile sig_atomic_t flag = 0; int sockfd = 0; char nombre[20]; // Quitar saltos de línea de un arreglo de caracteres void quitar_salto_linea(char* arr, int length) { for (int i = 0; i < length; i++) { // trim \n if (arr[i] == '\n') { arr[i] = '\0'; break; } } } /* Atrapar Ctrl+C y salir*/ void salir_ctrl_c(int sig) { flag = 1; } /* Función de thread para enviar */ void enviar_mensaje() { char mensaje[BUFFER_SZ] = {}; char buffer[BUFFER_SZ + 20] = {}; // Inicializar el buffer con el tamaño del nombre + mensaje while(1) { fflush(stdout); fgets(mensaje, BUFFER_SZ, stdin); quitar_salto_linea(mensaje, BUFFER_SZ); if (strcmp(mensaje, "bye") == 0) { // Si el mensaje es bye, se termina el thread break; } else { sprintf(buffer, "%s: %s\n", nombre, mensaje); send(sockfd, buffer, strlen(buffer), 0); } bzero(mensaje, BUFFER_SZ); // Vaciar mensaje bzero(buffer, BUFFER_SZ + 20); // Vaciar buffer } salir_ctrl_c(2); } /* Función de thread para recibir */ void recibir_mensaje() { char mensaje[BUFFER_SZ] = {}; while (1) { int receive = recv(sockfd, mensaje, BUFFER_SZ, 0); if (receive > 0) { if (strcmp(mensaje, "Bye desde el server.") == 0) { // Si el mensaje es bye, se termina el thread flag = 2; break; } else if (strcmp(mensaje, "Servidor lleno.") == 0) { // Si el mensaje es bye, se termina el thread flag = 3; break; } printf("> %s", mensaje); fflush(stdout); } else if (receive == 0) { // Si no se recibe nada, no se imprime break; } memset(mensaje, 0, sizeof(mensaje)); } } int main(int argc, char **argv){ if(argc != 2){ printf("Uso: %s <port>\n", argv[0]); return EXIT_FAILURE; } char *ip = "127.0.0.1"; // IP de host int port = atoi(argv[1]); // Puerto signal(SIGINT, salir_ctrl_c); // Asignar función de salida a Ctrl+C printf("Ingresa tu nombre: "); fgets(nombre, 20, stdin); quitar_salto_linea(nombre, strlen(nombre)); // Quitar salto de línea a nombre /* Validar longitu del nombre */ if (strlen(nombre) > 20 || strlen(nombre) < 2){ printf("Nombre tiene que tener entre 2 20 caracteres.\n"); return EXIT_FAILURE; } struct sockaddr_in server_addr; /* Configurar socket */ sockfd = socket(AF_INET, SOCK_STREAM, 0); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr(ip); server_addr.sin_port = htons(port); /* Conectar al servidor */ int err = connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)); if (err == -1) { printf("[Cliente]: ERROR conexión.\n"); return EXIT_FAILURE; } /* Enviar nombre a servidor*/ send(sockfd, nombre, 20, 0); /* Crear hilo para enviar mensaje */ pthread_t send_msg_thread; if (pthread_create(&send_msg_thread, NULL, (void *) enviar_mensaje, NULL) != 0){ printf("[Cliente]: ERROR hilo.\n"); return EXIT_FAILURE; } /* Crear hilo para recibir mensaje */ pthread_t recv_msg_thread; if (pthread_create(&recv_msg_thread, NULL, (void *) recibir_mensaje, NULL) != 0){ printf("[Cliente]: ERROR hilo.\n"); return EXIT_FAILURE; } while (1){ if(flag == 1){ printf("\nSesión finalizada.\n"); break; } else if (flag == 2) { printf("\nBye desde el server.\n"); break; } else if (flag == 3) { printf("\nServidor lleno. Vuelva más tarde.\n"); break; } } close(sockfd); return EXIT_SUCCESS; }
C
#include<stdio.h> void main() { int a[10]; int i=0; printf("Enter the array elements(value should not be more than 5): "); for(i=0;i<5;i++) scanf("%d ",&a[i]); int b[10]; for(i=0;i<10;i++) { if(b[a[i]]<0) { printf("Duplicates exist %d !!!",a[i]); return; } else b[a[i]]=-a[i]; } }
C
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #define NUM_THREADS 7 void *PrintThread(void *id) { long idt; idt = (long) id; printf("Thread %ld\n", idt+1); pthread_exit(NULL); } void CallThread(long nt, pthread_t *t){ int rc; rc = pthread_create(t, NULL, PrintThread, (void *) nt); if(rc){ printf("Falha ao criar Thrade %ld, cod: %d\n", nt, rc); exit(-1); } } int main(int argc, char *argv[]) { long i; pthread_t threads[NUM_THREADS]; for(i=0; i<NUM_THREADS; i++){ CallThread(i, &threads[i]); switch (i){ case 0: pthread_join(threads[i],NULL); break; case 1: pthread_join(threads[i],NULL); break; case 4: pthread_join(threads[i-2],NULL); pthread_join(threads[i-1],NULL); pthread_join(threads[i],NULL); break; case 5: pthread_join(threads[i],NULL); break; case 6: pthread_join(threads[i],NULL); break; } } }
C
#include <stdio.h> #include <conio2.h> #include <stdlib.h> #include <windows.h> // Definioes de movimentao da cobra #define LIMITE_COBRA 101 #define CIMA 80 #define BAIXO 72 #define DIREITA 77 #define ESQUERDA 75 #define ESC 27 #define CABECA 0 #define CAUDA 1 #define POS_INICIAL_CABECA 3 #define POS_INICIAL_CAUDA 2 #define POS_INICIAL_CY 13 typedef struct { int x; int y; } COORDENADA; typedef struct { COORDENADA posicoes[LIMITE_COBRA]; char dir; int tam_cobra; } COBRA; void muda_direcao (COBRA *snake) { switch (snake->dir) { case 'b': snake->posicoes[CABECA].y--; break; case 'c': snake->posicoes[CABECA].y++; break; case 'd': snake->posicoes[CABECA].x ++; break; case 'e': snake->posicoes[CABECA].x --; break; } } void nova_direcao (COBRA *snake, char seta) { switch (seta) // SWITCH QUE VAI RETORNA A PRXIMA COORDENADA DA COBRA { case BAIXO: if (snake->dir != 'c') snake->dir = 'b'; break; case CIMA: if (snake->dir != 'b') snake->dir = 'c'; break; case DIREITA: if (snake->dir != 'e') snake->dir = 'd'; break; case ESQUERDA: if (snake->dir != 'd') snake->dir = 'e'; break; } } void desenha_snake (COORDENADA cabeca_cobra) { textcolor (RED); textbackground(GREEN); putchxy(cabeca_cobra.x,cabeca_cobra.y, 'o'); // IMPRIME A COBRA textcolor(WHITE); textbackground(BLACK); } void movimenta_snake (COBRA snake) { char seta; //char vai_para = 'd'; int x, i; int velocidade = 150; int sair =1; // tamanho inicial que sempre cinco snake.tam_cobra = 5; // posio inicial onde a cobra vai nascer snake.posicoes[CABECA].x = POS_INICIAL_CABECA; snake.posicoes[CABECA].y = POS_INICIAL_CY; snake.posicoes[CAUDA].x = POS_INICIAL_CAUDA; snake.posicoes[CAUDA].y = POS_INICIAL_CY; //Direo inicial da cobra snake.dir = 'd'; while (seta != ESC) { while(seta != ESC &&!(seta = kbhit())&& sair) // LAO QUE FAZ A COBRA SE MOVER PARA UMA DIREO AT QUE UMA TECLA SEJA PRESSIONADA { for( i = snake.tam_cobra; i > 0; i--) // LAO PARA VER AS LTIMAS POSIES QUE SERO APAGADAS { snake.posicoes[i].x = snake.posicoes[i - 1].x; snake.posicoes[i].y = snake.posicoes[i - 1].y; } muda_direcao(&snake); ///Lao que vai movendo a cobra putchxy(snake.posicoes[snake.tam_cobra].x,snake.posicoes[snake.tam_cobra].y, ' '); // APAGA A LTIMA POSIO DA COBRA desenha_snake(snake.posicoes[CABECA]); // IMPRIME A COBRA Sleep(velocidade); // VELOCIDADE DA COBRA ///Testa se a cobra colidiu com ela mesma for(i = 1; i < snake.tam_cobra; i++) { if (snake.posicoes[CABECA].x == snake.posicoes[i].x && snake.posicoes[CABECA].y == snake.posicoes[i].y) sair = 0; } } seta = getch(); if (seta == -32) seta = getch(); nova_direcao(&snake, seta); } } int main() { COBRA snake_principal; // depois ser escolhido nas opes //CHAMA MENU INICIAL movimenta_snake(snake_principal); return 0; }
C
#include <stdio.h> void print(int n); int main() { int n; printf("Enter the value of n: "); scanf("%d", &n); print(n); return 0; } void print(int n){ int ans =0; int i=1; for(int j=0;j<n;j++){ ans = ans + (i*i); i=i+2; } printf("Sum of first %d numbers is %d",n,ans); }
C
#include <stdarg.h> #include <stddef.h> #include <setjmp.h> #include <cmocka.h> int __wrap_getchar(void) { return (int)mock(); } #define BOOLEAN int #define FALSE 0 #define TRUE 1 int get_word(char *s, int len_max, BOOLEAN b_print); void test_get_word_hello (void ** state) { char word[256] = {0}; will_return(__wrap_getchar, (int)'h'); will_return(__wrap_getchar, (int)'e'); will_return(__wrap_getchar, (int)'l'); will_return(__wrap_getchar, (int)'l'); will_return(__wrap_getchar, (int)'o'); will_return(__wrap_getchar, (int)' '); assert_int_equal(get_word(word, 256-1, FALSE), 5); assert_string_equal(word, "hello"); } void test_get_word_max (void ** state) { char word[256] = {0}; will_return(__wrap_getchar, (int)'h'); will_return(__wrap_getchar, (int)'e'); will_return(__wrap_getchar, (int)'l'); will_return(__wrap_getchar, (int)'l'); will_return(__wrap_getchar, (int)'o'); will_return(__wrap_getchar, (int)' '); assert_int_equal(get_word(word, 3, FALSE), 5); assert_string_equal(word, "hel"); } int main (void) { const struct CMUnitTest tests [] = { cmocka_unit_test (test_get_word_hello), cmocka_unit_test (test_get_word_max), }; return cmocka_run_group_tests (tests, NULL, NULL); }
C
/* CP05_13.C */ /* Testing Associativity of unary operator */ #include<stdio.h> #include<conio.h> void main() { int x = 10; printf("\n x = %d ++x = %d x = %d",x, ++x, x ); getch(); }
C
#include <stdio.h> void ft_div_mod(int a, int b, int *div, int *mod); int main() { int div = 0; int mod = 0; int a = 11; int b = 4; ft_div_mod(a, b, &div, &mod); printf("Quotient de (%d modulo %d) = %d", a , b, div); printf("\nReste de (%d modulo %d) = %d\n", a, b, mod); return 0; }
C
// // Created by Mookel on 16/9/6. // Email : [email protected] // Copyright (c) 2016 jlu.edu. All rights reserved. // dfa.c : // #include <compiler.h> #include "globals.h" #include "dfa.h" #include "terp.h" #include "print.h" typedef struct _DFA_STATE{ unsigned group: 8; /*group id, used by minimize*/ unsigned mark : 1; /*mark used by make_dtran*/ char *accept; int anchor; SET_S *set; /*Set of NFA states represented by this DFA state.*/ }DFA_STATE; PRIVATE DFA_STATE *_dstates; PRIVATE ROW *_dtran; PRIVATE int _nstates; PRIVATE DFA_STATE *_last_marked; #ifdef DEBUG PRIVATE void ps(SET_S *set) { putchar('{'); set_print(set, fprintf, stdout); printf("}\n"); } PRIVATE void pstate(DFA_STATE *state) { printf("_dstates[%ld] ", (long)(state - _dstates)); if(state->mark) printf("marked "); if(state->accept) printf("accepting %s<%s>%s", state->anchor & START ? "^" : "", state->accept, state->anchor & END ? "$" : ""); ps(state->set); } #endif /* * Return a pointer to an unmarked state in _dstates, if no such state * exists, return null. Print an asterisk for each state to tell the * user that the program hasn't died while the table is being constructed. * */ PRIVATE DFA_STATE *get_unmarked() { for(; _last_marked < &_dstates[_nstates]; ++_last_marked){ if(!_last_marked ->mark){ putc('*', stderr); fflush(stderr); if(g_verbose > 1) { fputs("-----------------\n", stdout); printf("working on DFA state %d = NFA states: ", (int)(_last_marked - _dstates)); set_print(_last_marked->set, fprintf, stdout); putchar('\n'); } return _last_marked; } } return NULL; } PRIVATE int in_dstates(SET_S *NFA_set) { DFA_STATE *p; DFA_STATE *end = &_dstates[_nstates]; for(p = _dstates; p < end; ++p) { if(SET_IS_EQUIV(NFA_set, p->set)) return (int)(p - _dstates); } return -1; } PRIVATE int add_to_dstates(SET_S *NFA_set, char *accept, int anchor) { int nextstate; if(_nstates > (DFA_MAX - 1)) com_ferr("Too many DFA states\n"); nextstate = _nstates++; D(if(g_verbose > 1)) D(printf("Adding new DFA state (%d)\n", nextstate);) _dstates[nextstate].set = NFA_set; _dstates[nextstate].accept = accept; _dstates[nextstate].anchor = anchor; return nextstate; } PRIVATE void make_trans(int sstate) { SET_S *NFA_set; /*Set of NFA states that define the next DFA state*/ DFA_STATE *current; /*state currently being expanded.*/ int nextstate; /*goto DFA state for current char*/ char *isaccept; int anchor; int c; /* * Initially _dstates contains a single, unmarked, start state formed by * taking the epision closure of the NFA start state. So, _dstates[0] is * the DFA start state. * */ NFA_set = set_new(); SET_ADD(NFA_set, sstate); _nstates = 1; _dstates[0].set = e_closure(NFA_set, &_dstates[0].accept, &_dstates[0].anchor); _dstates[0].mark = 0; while(current = get_unmarked()) { D(printf("New unmarked state:\n\t");) D(pstate(current);) current->mark = 1; for(c = MAX_CHARS; --c >= 0;){ if(NFA_set = move(current->set, c)) NFA_set = e_closure(NFA_set, &isaccept, &anchor); if(!NFA_set) { /*no move.*/ nextstate = F; } else if ((nextstate = in_dstates(NFA_set)) != -1) { /*has current in trans table.*/ /*do nothing*/ } else { /*no current in table.*/ nextstate = add_to_dstates(NFA_set, isaccept, anchor); } _dtran[current - _dstates][c] = nextstate; D(if(g_verbose > 1 && nextstate != F) \ printf("Dfa state %d goes to %d on %s\n", \ current-_dstates, nextstate, sys_bin_to_ascii(c, 1));) } } putc('\n', stderr); } /* * Turns an NFA with the indicated start state(sstate) into a DFA and * returns the number of states in the DFA transition table. *dfap is * modified to pointed at that transition table and *acceptp is modified * to point at an array of accepting states(indexed by state number). * dfa() discards all the memory used for the initial NFA.(Now we have * gc module, there is no need to release the memory.) * */ PUBLIC int dfa(fp_input_t input_func, ROW *dfap[], ACCEPT **acceptp) { ACCEPT *accept_states; int i; int start; start = nfa(input_func); _nstates = 0; _dstates = (DFA_STATE*) GC_MALLOC(DFA_MAX * sizeof(DFA_STATE)); _dtran = (ROW *) GC_MALLOC(DFA_MAX * sizeof(ROW)); _last_marked = _dstates; if(g_verbose) fputs("making DFA: ", stdout); if(!_dstates || !_dtran) com_ferr("No memeory for DFA transition matrix!"); make_trans(start); free_nfa(); _dtran = (ROW*)GC_REALLOC(_dtran, _nstates * sizeof(ROW)); accept_states = (ACCEPT *)GC_MALLOC(_nstates * sizeof(ACCEPT)); if(!accept_states || !_dtran) com_ferr("dfa: Out of memeory!!"); for(i = _nstates; --i >= 0; ){ accept_states[i].string = _dstates[i].accept; accept_states[i].anchor = _dstates[i].anchor; } GC_FREE(_dstates); *dfap = _dtran; *acceptp = accept_states; if(g_verbose) { printf("\n%d out of %d DFA states in initial machine.\n", _nstates, DFA_MAX); printf("%ld bytes required for uncompressed tables.\n\n", _nstates * MAX_CHARS * sizeof(TTYPE) + _nstates * sizeof(TTYPE)); if(g_verbose > 1) { printf("The un-minimized DFA looks like this: \n\n"); pheader(stdout, _dtran, _nstates, accept_states); } } return _nstates; }
C
#include <stdio.h> #include "error.h" #include "instruction.h" //! Forme imprimable des codes oprations const char *cop_names[] = { "ILLOP", //!< Instruction illgale "NOP", //!< Instruction sans effet "LOAD", //!< Chargement d'un registre "STORE", //!< Rangement du contenu d'un registre "ADD", //!< Addition un registre "SUB", //!< Soustraction d'un registre "BRANCH", //!< Branchement conditionnel ou non "CALL", //!< Appel de sous-programme "RET", //!< Retour de sous-programme "PUSH", //!< Empilement sur la pile d'excution "POP", //!< Dpilement de la pile d'excution "HALT", //!< Arrt (normal) du programme }; //! Forme imprimable des conditions const char *condition_names[] = { "NC", //!< Pas de condition (nrachement inconditionnel) "EQ", //!< gal 0 "NE", //!< Diffrent de 0 "GT", //!< Strictement positif "GE", //!< Positif ou nul "LT", //!< Strictement ngatif "LE", //!< Ngatif ou null }; //! Impression d'une instruction sous forme lisible (dsassemblage) /*! * \param instr l'instruction imprimer * \param addr son adresse */ void print_instruction(Instruction instr, unsigned addr) { Code_Op cop = instr.instr_generic._cop; if (cop > LAST_COP) error(ERR_UNKNOWN, addr); printf("%s ", cop_names[cop]); if (cop == ILLOP || cop == NOP || cop == RET || cop == HALT) return; if (cop == BRANCH || cop == CALL) { if (instr.instr_generic._regcond > LAST_CONDITION) error(ERR_CONDITION, addr); printf("%s, ", condition_names[instr.instr_generic._regcond]); } else if(cop != PUSH && cop != POP) { printf("R%02u, ", instr.instr_generic._regcond); } if (instr.instr_generic._immediate) { printf("#%d", instr.instr_immediate._value); } else if (instr.instr_generic._indexed) { printf("%d[R%02u]", instr.instr_indexed._offset, instr.instr_indexed._rindex); } else { printf("@0x%04x", instr.instr_absolute._address); } }
C
/* -------------------------------- MarkdownLatex markdownlatex.c -------------------------------- Copyright 2014 Jacob Causon Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <stdio.h> #include <stdlib.h> #include "lexer.h" #include "parserstringops.h" #include "tableProcessor.h" #include "stdvals.h" #include "versionData.h" #include "markdownlatex.h" #define BUF_SIZE 128 #define END_OF_LINE_BUFFER_SIZE 50 #define TEMP_FILE "temp_markdownlatex_file~" const char* colorData = #include "colorData.txt" ; int bufferSize = BUF_SIZE; // Note that endOfLineBuff overflows are handled by ignoring any future additions to the buffer // This will cause errors but to keep the code a bit easier to read we are just going to give it a // Large enough size so under normal operation there will be enough space // The only way to cause this to happen is to have over 50 headers within headers which isn't even // Valid in markdown and even if they do it will simply generate a bad tex file and not break anything char endOfLineBuff[END_OF_LINE_BUFFER_SIZE]; //Are we are currently in a list? char inList = FALSE; char inBold = FALSE; char inItalic = FALSE; char inUnderline = FALSE; char inStrikethrough = FALSE; char isCode = FALSE; char inNumberList = FALSE; char inBlockMath = FALSE; char inInlineMath = FALSE; char inComment = FALSE; char pageBreakPlaced = FALSE; int quoteBlockDepth = 0; //Have we found some markdown (rather than a comment at the start of the page) char markdownStarted = FALSE; char inInitialCommentBlock = FALSE; char displayTitle = FALSE; //How many empty new lines have we seen in a row? int groupedNewLineCount = 0; // Libary usage is stored in these variables so we can only include things which are actualy needed char reqLib_code = false; char reqLib_table = false; char reqLib_images = false; char reqLib_math = false; void outOfMemoryError() { fprintf(stderr, "Out of memory\nUnable to continue\n"); exit(100); } void printHelp() { printf("\nMarkdown latex v %s\n\n", VERSION); putchar('\n'); printf(" -o <FILE>\n"); printf(" Specifies the latex output file\n"); putchar('\n'); printf(" -s <SIZE>\n"); printf(" Specifies the font size of the output file.\n"); printf(" Note: The only valid sizes are '10pt', '11pt' and '12pt' currently\n"); putchar('\n'); printf(" -d <DOCUMENT>\n"); printf(" Specifies the type of latex document to make.\n"); printf(" eg. 'report'\n"); putchar('\n'); printf(" -m <MARGIN>\n"); printf(" Specifies the size of the margins\n"); printf(" eg. '10mm' or '1in\n"); putchar('\n'); printf(" -c <COLORFILE>\n"); printf(" Specifies a color file to be used to highlight code\n"); printf(" See the online documentation for more information\n"); putchar('\n'); printf(" -l\n"); printf(" Set orientation to landscape\n"); putchar('\n'); printf(" -p\n"); printf(" Set orientation to portrait\n"); putchar('\n'); } int parseLine(char* string, int stringLength, FILE* in, FILE* out) { int endOfLineIndex = 0; int i = 0; if(string[0] == '\n' || string[0] == '\0') { groupedNewLineCount++; if(!pageBreakPlaced && groupedNewLineCount >= 4) { fprintf(out, "\\newpage\n"); pageBreakPlaced = TRUE; } }else if(groupedNewLineCount > 0) { groupedNewLineCount = 0; pageBreakPlaced = FALSE; } //Do the things which are only valid if they apear at the start of a line // Symbol lineStart = lex(string); if(lineStart.type == MATH && string[lineStart.loc+3] == '\0') { reqLib_math = TRUE; if(inBlockMath) { fprintf(out, "\\end{displaymath}"); inBlockMath = FALSE; } else { fprintf(out, "\\begin{displaymath}"); inBlockMath = TRUE; } return 0; //Success } if(lineStart.type == COMMENT_OPEN && !markdownStarted) { inInitialCommentBlock = TRUE; return 0; } if(lineStart.type == COMMENT_CLOSE && inInitialCommentBlock) { inInitialCommentBlock = FALSE; if(displayTitle) { fprintf(out, "\\maketitle\\pagebreak"); } return 0; } else if(!markdownStarted) { markdownStarted = TRUE; } if(inInitialCommentBlock) { //Processes the initial comment block which can contain information about things (eg. the cover page) if(compareSub("title:", string, 6) == 0) { fprintf(out, "\\title{"); int i=6; //start after the "title:" while(string[i] != '\n' && string[i] != '\0') { putc(string[i], out); i++; } putc('}', out); displayTitle = TRUE; } else if(compareSub("author:", string, 7) == 0) { fprintf(out, "\\author{"); int i=7; //start after the "title:" while(string[i] != '\n' && string[i] != '\0') { putc(string[i], out); i++; } putc('}', out); } else if(compareSub("date:", string, 5) == 0) { fprintf(out, "\\date{"); int i=5; //start after the "title:" while(string[i] != '\n' && string[i] != '\0') { putc(string[i], out); i++; } putc('}', out); } return 0; } if(lineStart.type == QUOTE_BLOCK && !isCode) { int qC = 1; int j = lineStart.loc+1; Symbol s = lex(string+1); while(s.type == QUOTE_BLOCK) { qC++; j += s.loc+1; s = lex(string+j); } i = j; if(qC > quoteBlockDepth) { //we have just gone into a block for(int k=qC; k>quoteBlockDepth; k--) { fprintf(out, "\n\\begin{quote}\n"); } quoteBlockDepth = qC; } else if(qC < quoteBlockDepth) { //we have just gone into a block for(int k=qC; k<quoteBlockDepth; k++) { fprintf(out, "\n\\end{quote}\n"); } quoteBlockDepth = qC; } //return 0; } else if(quoteBlockDepth > 0 && string[0] != '\0') { for(int k=0; k<quoteBlockDepth; k++) { fprintf(out, "\n\\end{quote}\n"); } quoteBlockDepth = 0; } if(inList) { if((lineStart.type == ITEMIZE && lineStart.loc < 2) || (lineStart.type == ITALIC && lineStart.loc == 0)) { fprintf(out, "\\item "); i++; //return TRUE; } else if(groupedNewLineCount > 1) { //We just found the end of the list fprintf(out, "\\end{itemize}\n"); inList = FALSE; } } else { //We aren't in a list but we just found a new one if((lineStart.type == ITEMIZE && lineStart.loc < 2) || (lineStart.type == ITALIC && lineStart.loc == 0)) { inList = TRUE; fprintf(out, "\\begin{itemize}\n\\item");//, buf, 0); i++; //writeStringToBuffer(string, buf, 5); //return; } } if(inNumberList) { if(lineStart.type == ENUMERATE && lineStart.loc < 2) { fprintf(out, "\\item "); while(string[i] != ' ') i++; //return TRUE; } else { //We just found the end of the list fprintf(out, "\\end{enumerate}\n"); inNumberList = FALSE; } } else { //We aren't in a list but we just found a new one // And btw if there is a * (Italic) at the start then it is probubly a list if(lineStart.type == ENUMERATE && lineStart.loc < 2) { inNumberList = TRUE; fprintf(out, "\\begin{enumerate}\n\\item");//, buf, 0); while(string[i] != ' ') i++; } } if(lineStart.type == HORIZONTAL_RULE && lineStart.loc < 2) { fprintf(out, "\\hrulefill"); return 0; } if(lineStart.type == TABLE_COL_SEP) { processTable(string, in, out); reqLib_table = true; return 0; } //Go deeper into the string looking for symbols for(; i<stringLength; i++) { //Lex from the current character Symbol s = lex(string + i); s.loc += i; //change loc to be in terms of string //Move up to next symbol the lexer while( i < s.loc ) { if(!inComment) putc(string[i], out); i++; } ///////////////////////////////////////////////////////////////// // Statement handling each possible token // ///////////////////////////////////////////////////////////////// if(inComment && s.type != COMMENT_CLOSE) { i++; //Keep going until we find a comment close } else if(isCode || s.type == CODE) { reqLib_code = true; if(isCode && s.type == CODE) { fprintf(out, "\\end{lstlisting}"); isCode = FALSE; i += 2; } else if(!isCode){ char bufCode[10]; int iC = 3; while(string[iC] != '\0' && string[iC] != '\n' && string[iC] != ' ' && iC<10) { bufCode[iC-3] = string[iC]; iC++; } bufCode[iC-3] = '\0'; fprintf(out, "\\begin{lstlisting}[frame=single,language=%s]", bufCode); isCode = TRUE; i += 3; i += iC; break; } else { // We are in a code block so just output the contents raw putc(string[i], out); } } else if((inInlineMath && s.type != MATH) || inBlockMath) { reqLib_math = TRUE; //else keep going until we find the end of the math block putc(string[i], out); } else { switch(s.type) { case ESCAPE: putc(string[i+1], out); i += 1; break; case H1: fprintf(out, "\\section*{"); if(endOfLineIndex < END_OF_LINE_BUFFER_SIZE) { writeStringToBuffer("}", endOfLineBuff, endOfLineIndex); endOfLineIndex += 1; //length added to end of line } break; case H2: fprintf(out, "\\subsection*{"); if(endOfLineIndex < END_OF_LINE_BUFFER_SIZE) { writeStringToBuffer("}", endOfLineBuff, endOfLineIndex); endOfLineIndex += 1; //length added to end of line } i += 1; //Go past the extra character we looked fowards too break; case H3: fprintf(out, "\\subsubsection*{"); if(endOfLineIndex < END_OF_LINE_BUFFER_SIZE) { writeStringToBuffer("}", endOfLineBuff, endOfLineIndex); endOfLineIndex += 1; //length added to end of line } i += 2; //Go past the extra characters we looked fowards too break; case LINE_BREAK: fprintf(out, "\n\\vspace{2mm}"); break; case BOLD: if(inBold) { putc('}', out); inBold = FALSE; i += 1; } else { fprintf(out, "\\textbf{"); inBold = TRUE; i += 1; } break; case STRIKETHROUGH: if(inStrikethrough) { putc('}', out); inStrikethrough = FALSE; i += 1; } else { fprintf(out, "\\sout{"); inStrikethrough = TRUE; i += 1; } break; case ITALIC: if(inItalic) { putc('}', out); inItalic = FALSE; } else { fprintf(out, "\\textit{"); inItalic = TRUE; } break; case UNDERLINE: if(inUnderline) { putc('}', out); inUnderline = FALSE; } else { fprintf(out, "\\underline{"); inUnderline = TRUE; } break; case QUOTE_LEFT: fprintf(out, "``"); break; case QUOTE_RIGHT: fprintf(out, "''"); break; case APOSTROPHE_LEFT: fprintf(out, "`"); break; case APOSTROPHE_RIGHT: fprintf(out, "'"); break; case IMAGE: reqLib_images = true; fprintf(out, "\\includegraphics[width=10cm, height=10cm, keepaspectratio]{"); //Move up to the url ignoring the alt text while(string[i] != '(') { i++; } i++; while(string[i+1] != '"' && string[i] != ')') { putc(string[i], out); i++; } while(string[i] != ')') { i++; } i++; fprintf(out, "}\n\n"); break; case LINK: ; //Decliration can't follow a label so here is a empty statment int j = 1; while(string[i+j] != ']') { j++; } char* namebuf = (char*) malloc(j * sizeof(char)); j = 1; while(string[i+j] != ']') { namebuf[j-1] = string[i+j]; j++; } namebuf[j-1] = '\0'; fprintf(out, "\\href{"); j+=2; while(string[i+j] != ')') { putc(string[i+j], out); j++; } fprintf(out, "}{%s} ", namebuf); free(namebuf); i += j; break; case MATH: reqLib_math = TRUE; fprintf(out, "$"); i += 2; inInlineMath = !inInlineMath; break; case COMMENT_OPEN: inComment = true; i += 2; break; case COMMENT_CLOSE: inComment = false; i += 2; break; //Symbols which need to be commented out for latex case AMP: case DOLLAR: putc('\\', out); putc(string[i], out); break; default: putc(string[i], out); break; } } } //Write anything which has been delayed till the end of line has been reached (eg. close any headings) if(endOfLineIndex > 0) { endOfLineBuff[endOfLineIndex] = '\0'; fprintf(out, "%s", endOfLineBuff); } return 0; } void paramiterError(char* error) { printf("\nParamiter error: %s\n", error); exit(1); } int main ( int argc, char *argv[] ) { char* outFile = NULL; char* inFile = NULL; //Set the default values char* fontSize = "11pt"; char* marginSize = "1.5in"; char* documentType = "report"; char* orientation = "portrait"; char* colorFile = NULL; // Go over paramiters and update the settings if provided for(int i=1; i<argc; i++) { if(!compare(argv[i], "-h") || !compare(argv[i], "--help")) { printHelp(); exit(0); } else if(!compare(argv[i], "-o")) { if(i == argc-1) paramiterError("Output file not specified"); outFile = argv[++i]; } else if(!compare(argv[i], "-d")) { if(i == argc-1) paramiterError("Font size not specified"); fontSize = argv[++i]; } else if(!compare(argv[i], "-d")) { if(i == argc-1) paramiterError("Document type not specified"); documentType = argv[++i]; } else if(!compare(argv[i], "-m")) { if(i == argc-1) paramiterError("Margin size not specified"); marginSize = argv[++i]; } else if(!compare(argv[i], "-c")) { if(i == argc-1) paramiterError("Color file not specified"); colorFile = argv[++i]; } else if(!compare(argv[i], "-l")) { orientation = "landscape"; } else if(!compare(argv[i], "-p")) { orientation = "portrait"; } else { inFile = argv[i]; } } if (argv[argc-1][0] == '-' && argv[argc-1][1] == 'v') { printf("------------------------------\n markdownlatex\n Version: %s\n------------------------------\n", VERSION); return 0; } // Set default file streams and change if a different one is provided FILE *fp = stdin; FILE *fout = stdout; FILE *foutTemp = NULL; if( inFile != NULL) { fp = fopen(inFile, "r"); // error check this! } //else leave as stdin if(outFile != NULL) { fout = fopen(outFile, "w"); } //else leave as stout foutTemp = fopen(TEMP_FILE, "w"); char* buf = malloc(bufferSize * sizeof(char)); if(buf == NULL) { outOfMemoryError(); } // Write to a temp file // This is so we can know what libaries we need to put in the header // These file will be copied into the actual file later and then deleted int getLineReturnCode = getLineFile(buf, bufferSize, fp); while( getLineReturnCode > 0 ) { //If we have a buffer overflow if(getLineReturnCode == 2) { //Double buffer size in event of buffer overflow buf = (char*)realloc(buf, (bufferSize * sizeof(char) * 2)); if(buf == NULL) { outOfMemoryError(); } int oldSize = bufferSize; bufferSize *= 2; //Try to read off the rest of the line //Note the -1 is to ignore the \0 added by getLineFile(); getLineReturnCode = getLineFile(buf+oldSize-1, oldSize+1, fp); } else { parseLine(buf, getStringLength(buf), fp, foutTemp); putc('\n', foutTemp); getLineReturnCode = getLineFile(buf, bufferSize, fp); } } if(inList) { fprintf(foutTemp, "\\end{itemize}\n"); } fclose(foutTemp); //Required libaries fprintf(fout, "\\documentclass[%s,a4paper,oneside,%s]{%s}\n\\usepackage{hyperref}\n\\usepackage[margin=%s]{geometry}\n\\usepackage{ulem}\n", fontSize, orientation, documentType, marginSize); // Optional libaries if(reqLib_code || reqLib_table) { fprintf(fout, "\\usepackage[table]{xcolor}\n\\definecolor{tableShade}{gray}{0.9}\n"); } if(reqLib_code) { fprintf(fout, "\\usepackage{listings}\n"); char success = false; if(colorFile != NULL) { FILE* colorFileFile = fopen(colorFile, "r"); if(colorFileFile != NULL) { fprintf(fout, "\\lstset{"); copyFileContents(colorFileFile, fout); fprintf(fout, "}\n"); success = true; } } if(!success) { //use the default fprintf(fout, "%s\n", colorData); } } if(reqLib_table) { fprintf(fout, "\\usepackage{tabularx}\n"); } if(reqLib_images) { fprintf(fout, "\\usepackage{graphicx}\n"); } if(reqLib_math) { fprintf(fout, "\\usepackage{amsmath}\n"); } fprintf(fout, "\\begin{document}\n\n\n"); //Write the temp file into the actual file FILE* finTemp = fopen(TEMP_FILE, "r"); copyFileContents(finTemp, fout); remove(TEMP_FILE); fprintf(fout, "\\end{document}\n\n\n"); fprintf(fout, "%%\n"); fprintf(fout, "%% COMPILED WITH MARKDOWN LATEX\n"); fprintf(fout, "%% %s\n", VERSION); fprintf(fout, "%%\n"); fprintf(fout, "%% https://github.com/jake314159/markdown-latex\n"); fprintf(fout, "%%\n"); fprintf(fout, "%%\n"); fprintf(fout, "%% Compile notes: (v=%d.%d.%d,buf=%dBto%dB,margin=%s,doc=%s)\n", V_MAJOR, V_MINOR, V_PATCH, BUF_SIZE, bufferSize, marginSize,documentType); fprintf(fout, "%%\n\n\n"); free(buf); return 0; }
C
/************************************************************************* > File Name: 8-1.c > Author: chendi > Mail: [email protected] > Created Time: 2014年07月24日 星期四 11时10分22秒 ************************************************************************/ #include<stdio.h> #include<errno.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<stdlib.h> #include<unistd.h> #include<pthread.h> void *thread(void *arg) { pthread_t newthid; newthid=pthread_self(); printf("this is a new thread,thread ID=%u\n",newthid); } int main(void) { pthread_t thid; printf("main thread,ID is %u\n",pthread_self()); if(pthread_create(&thid,NULL,thread,NULL)!=0) { printf("thread creation failed\n"); exit(1); } sleep(1); printf("%u",thid); exit(0); }
C
#include<stdio.h> #include<string.h> typedef struct{ int s,f; } Tile; int N,M,flag,taken[20]; Tile T[20],tArr[20]; void swap(int *a,int *b){ int tmp; tmp=*a; *a=*b; *b=tmp; } int isValid(Tile tmp,int i){ if(tArr[i-1].f==tmp.s){ tArr[i]=tmp; return 1; } else if(tArr[i-1].f==tmp.f && i!=N+1){ swap(&tmp.s,&tmp.f); tArr[i]=tmp; return 1; } else return 0; } void findAnswer(int sz){ int j; if(flag) return; if(sz==N+1 && isValid(tArr[N+1],sz)){ flag=1; return; } if(sz>N) return; for(j=1;j<=M;j++){ if(!taken[j] && isValid(T[j],sz)){ taken[j]=1; findAnswer(sz+1); taken[j]=0; } } } int main(){ int i; while(scanf("%d",&N)==1 && N){ scanf("%d",&M); scanf("%d%d%d%d",&tArr[0].s,&tArr[0].f,&tArr[N+1].s,&tArr[N+1].f); for(i=1;i<=M;i++){ scanf("%d %d",&T[i].s,&T[i].f); } flag=0; memset(taken,0,sizeof taken); findAnswer(1); if(flag) puts("YES"); else puts("NO"); } }
C
#include <stdio.h> int main(void) { char arr[] = "Hello, Wolrd!"; char str[100]; int len, i; char *p; len = sizeof(arr); p=arr+len -2; for(i=0; i<len-1; i++){ str[i] = *p--; } printf("%s\n", arr); printf("%s", str); }
C
#include <stdio.h> /* */ /*ϸμ round.h*/ /* */ /* FxΪҪFyΪҪ뵽Сǰλ : F_round(3.1415926,0.3); ˼Ϊ3.1415926뵽С3λ F_round(3141592.6,3.0); ˼Ϊ3141592.6뵽Сǰ3λ */ /* bug!!! Сֻܵ6λ ԭʱδ֪ 2019/10/29 */ double D_round(double Dx, double Dy) { long long array[11] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000}; if(Dy > 0) { if (Dy == 1) { int Ix = (int)(Dx + 0.5); return Ix; } else if(Dy > 1) { int Ix = Dx; int Iy = Dy; int c = (Ix-(Ix%array[Iy-2]))/array[Iy-2]; if(c%10 >=5) c=(c+10)/10; c = c*array[Iy-1]; return c; } else if(Dy < 1) { int Iy = (int)(Dy*10); double b = array[Iy]; long long d = (long long)(Dx*array[Iy+1]); if(d % 10 >= 5) d=(d+10)/10; double c = d/b; return c; } } } /*ת*/ /*ϸ change.c*/ long long MC_change(long long LLx) { long long array[2] = {10000LL, 100000000LL}; char DanWei[][3] = {"ǧ","","ʮ","",""}; char Shu[][3] = {"","һ","","","","","","","",""}; char gewei[10][2] = {""}; char yiwei[10][2] = {""}; char wanwei[10][2] = {""}; int i, j, s; int ge = LLx; int wan = LLx/array[0]; int yi = LLx/array[1]; s = 0; if(wan>0) s=1; if(yi >0) s=2; switch(s) { case 2: { for(i=0; i<=1; i++) { yiwei[0][i] = Shu[(yi/1000)%10][i]; yiwei[1][i] = DanWei[0][i]; yiwei[2][i] = Shu[(yi/100)%10][i]; yiwei[3][i] = DanWei[1][i]; yiwei[4][i] = Shu[(yi/10)%10][i]; yiwei[5][i] = DanWei[2][i]; yiwei[6][i] = Shu[(yi/1)%10][i]; } for(i=0; i<=6; i++) { printf("%c%c",yiwei[i][0],yiwei[i][1]); } printf("%c%c",DanWei[4][0],DanWei[4][1]); } case 1: { for(i=0; i<=1; i++) { wanwei[0][i] = Shu[(wan/1000)%10][i]; wanwei[1][i] = DanWei[0][i]; wanwei[2][i] = Shu[(wan/100)%10][i]; wanwei[3][i] = DanWei[1][i]; wanwei[4][i] = Shu[(wan/10)%10][i]; wanwei[5][i] = DanWei[2][i]; wanwei[6][i] = Shu[(wan/1)%10][i]; } for(i=0; i<=6; i++) { printf("%c%c",wanwei[i][0],wanwei[i][1]); } printf("%c%c",DanWei[3][0],DanWei[3][1]); } case 0: { for(i=0; i<=1; i++) { gewei[0][i] = Shu[(ge/1000)%10][i]; gewei[1][i] = DanWei[0][i]; gewei[2][i] = Shu[(ge/100)%10][i]; gewei[3][i] = DanWei[1][i]; gewei[4][i] = Shu[(ge/10)%10][i]; gewei[5][i] = DanWei[2][i]; gewei[6][i] = Shu[(ge/1)%10][i]; } for(i=0; i<=6; i++) { printf("%c%c",gewei[i][0],gewei[i][1]); } printf("\n"); } } return; }
C
#include <stdlib.h> #include <string.h> #include "disemvowel.h" #include <stdio.h> int isval(char *str1) { int len; char *result; int a; a = strlen(str1); len = 0; result = str1; for (int i = 0; i < a; i++){ if (result[i] == 'a' || result[i] == 'e' || result[i] == 'i' || result[i] == 'o' || result[i] == 'u' || result[i] == 'A' || result[i] == 'E' || result[i] == 'I' || result[i] == 'O' || result[i] == 'U') { len++; } } return len; } char *disemvowel(char *str) { char *result; char *newString; int len; int j; len = strlen(str); result = str; newString = (char*) calloc(len-isval(result)+1, sizeof(char)); j = 0; for (int i = 0; i < len; i++){ if (result[i] == 'a' || result[i] == 'e' || result[i] == 'i' || result[i] == 'o' || result[i] == 'u' || result[i] == 'A' || result[i] == 'E' || result[i] == 'I' || result[i] == 'O' || result[i] == 'U') { // result[i] = ""; } else { newString[j] = result[i]; j++; } } newString[len-isval(result)] = '\0'; return newString; }
C
#include<stdio.h> #include<string.h> #include"inode_test.h" typedef unsigned int u32; #define PAGE_SIZE 4096 #define DIR_LEN 20 #define O_RD (1 << 0) #define O_RDWR (1 << 1) #define O_CREATE (1 << 2) #define O_DEL (1 << 3) union dir_block { struct dir_entry d[20]; char b[PAGE_SIZE]; }; union first_block{ struct super_block sb; char b[PAGE_SIZE]; }; struct block { char b[PAGE_SIZE]; }; union root_block { struct inode i; char b[PAGE_SIZE]; }; int write_block(FILE *f, u32 block_nr, char *b, u32 size) { fseek(f, sizeof(char) * size * block_nr , SEEK_SET); if (fwrite(b, sizeof(char), size, f) != size) printf("error\n"); } int main() { union first_block fb; FILE *f; union root_block rb; memset(&fb, 0, sizeof(fb)); struct super_block *sb = &fb.sb; sb->inode_num = 100; sb->inode_used = 2; sb->block_num = 100; sb->block_used = 12; sb->magic = 0xf321; sb->inode_block_off = 3; sb->inode_block_num = 10; /* 14 bit contain real content */ sb->inode_bitmap_block = 1; sb->block_bitmap_block = 2; sb->root_node = 3; f = fopen("test_backen.bin", "w"); if (fwrite(&fb, sizeof(fb), 1, f) != 1) printf("error\n"); //memset(&fb, 0, sizeof(fb)); /* int i = 1; for(; i<100; i++) fwrite(&fb, sizeof(fb), 1, f); */ memset(&rb, 0, sizeof(rb)); struct inode *id = &rb.i; id->type = DIR_TYPE; id->mode = O_RDWR; id->index = 0; id->used = 1; id->zone[0] = 13; /* /dev */ id ++; id->type = DIR_TYPE | DEV_TYPE; id->mode = O_RDWR; id->index = 1; id->used = 1; id->zone[0] = 14; write_block(f, sb->root_node ,rb.b, sizeof(rb)); union dir_block db; db.d[0].inode_idx = 0; sprintf(db.d[0].name, "."); db.d[1].inode_idx = 0; sprintf(db.d[1].name, ".."); db.d[2].inode_idx = 1; sprintf(db.d[2].name, "dev"); write_block(f, 13, db.b, sizeof(db)); /* /dev */ memset(&db, 0, sizeof(db)); db.d[0].inode_idx = 0; sprintf(db.d[0].name, "."); db.d[1].inode_idx = 0; sprintf(db.d[1].name, ".."); write_block(f, 14, db.b, sizeof(db)); struct block bb; memset(&bb, 0, sizeof(bb)); bb.b[0] = 0x3; write_block(f, sb->inode_bitmap_block, bb.b, sizeof(bb)); memset(&bb, 0, sizeof(bb)); // 0 - 14 bb.b[0] = 0xff; bb.b[1] = 0x7f; write_block(f, sb->block_bitmap_block, bb.b, sizeof(bb)); fclose(f); return 0; }
C
/* ITS240-01 Lab 01 Ch5p236pe8 02/08/2017 Daniel Kuckuck refer to the book: Book Identification #; Inventory Balance at begining of month; Number of copies receieved during the month; Number of copies sold during month. Use a while loop so only 3 books are requested. Output should be: New Balance = Inventory at the beginning of the month + Number of copies received during the month - Number of copies sold during the month */ #include <stdio.h> #define MAXCOUNT 3 main() { //define variables int bookId = 0, invStart = 0, invAdd = 0, invSold = 0, count = 1; while (count <= MAXCOUNT) { printf("\nPlease enter your Book's identification number --> "); scanf("%d", &bookId); printf("\nPlease enter Book's starting inventory --> "); scanf("%d", &invStart); printf("\nPlease enter Books added to inventory --> "); scanf("%d", &invAdd); printf("\nPlease enter Books sold --> "); scanf("%d", &invSold); printf("\nID:%d New Balance: %d = inentory balance at the beginning of the month: %d.\n + Number of copies received during the month: %d.\n - Number of copies sold during the month: %d.\n", bookId, invStart + invAdd - invSold, invStart, invAdd, invSold); count++; } return 0; }
C
// // mysh.c // P2 // // Created by Terry Shao on 2/8/14. // Copyright (c) 2014 Terry Shao. All rights reserved. // #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <limits.h> #include <sys/types.h> #include <sys/wait.h> #include <errno.h> #define SEQUENTIAL 1 #define PARALLEL 2 #define SINGLE 0 #define NORMAL 0 #define PIPE 1 #define REDIR 2 typedef struct job{ char ** cmds[10]; char on_duty; int nPipes; char *redir; }Job; void printErr(){ char error_message[30] = "An error has occurred\n"; write(STDERR_FILENO, error_message, strlen(error_message)); } void parcmd (char * toPar, char * result[]) { int i = 0; int j; char *arg = strtok (toPar, " \t"); while (arg) { result[i] = arg; i++; arg = strtok (NULL, " \t"); } for (j = 0; j < i; j++) { result[j] = strtok (result[j], "\""); while (result[j] == NULL){ result[j]++; } } for (j = i;j < 10; j++) { result[j] = 0; } } int parRePi (int num ,char * toPar, Job result[]) { char * j = 0; int i = 0; char * c[10]; result[num].nPipes = 0; result[num].redir = 0; if ( (j = strchr (toPar, '>') ) && !strchr (toPar, '|') ) { if (strchr (j + 1, '>') ) { printErr(); return -1; } char * arg = strtok (toPar, ">"); char * red = strtok (NULL, ">"); if ((result[num].redir = strtok (red, " ")) == NULL) { printErr(); return -1; } if (strtok (NULL, " ") ) { printErr(); return -1; } parcmd (arg, result[num].cmds[0]); i++; } j = 0; if ( (j = strchr (toPar, '|') ) ) { if ( (j = strchr(j + 1, '>') ) ) { if (strchr(j + 1, 'l') ) { printErr(); return -1; } } c[result[num].nPipes] = strtok (toPar, "|"); while (c[result[num].nPipes]) { result[num].nPipes++; c[result[num].nPipes] = strtok (NULL, "|"); } result[num].nPipes--; for (i = 0; i < result[num].nPipes; i++) { parcmd (c[i], result[num].cmds[i]); } if (strchr (c[i], '>') ) { c[i] = strtok (c[i], ">"); char * red = strtok (NULL, ">"); if ((result[num].redir = strtok (red, " ")) == NULL) { printErr(); return -1; } if (strtok (NULL, " ") ) { printErr(); return -1; } } parcmd (c[i], result[num].cmds[i]); i++; for (;i < 10; i++) { result[num].cmds[i][0] = NULL; } }else{ int k; if (result[num].redir) { k = 2; }else{ k = 1; } for (; k < 10; k++) { result[num].cmds[k][0] = NULL; } if (!result[num].redir) parcmd (toPar, result[num].cmds[0]); } if (result[num].redir) { result[num].redir = strtok (result[num].redir, "\""); while (result[num].redir == NULL) { result[num].redir++; } } result[num].on_duty = 1; return NORMAL; } int sepMultCmd (char * toSep, Job result[]) { if (strchr (toSep, ';') && strchr (toSep, '+') ) write (STDERR_FILENO, ";, +\n", 4); if (strchr (toSep, ';') ) { int i = 0; int j; char *argt[10]; argt[0] = strtok (toSep, ";"); while (argt[i]) { i++; argt[i] = strtok (NULL, ";"); } for (j = 0; j < i; j++) { if (parRePi (j, argt[j], result) == -1) { return -1; } } return SEQUENTIAL; }else if (strchr (toSep, '+') ) { int i = 0; int j; char *argt[10]; argt[0] = strtok (toSep, "+"); while (argt[i]) { i++; argt[i] = strtok (NULL, "+"); } for (j = 0; j < i; j++) { if (parRePi (j, argt[j], result) == -1) { return -1; } } return PARALLEL; }else{ if (parRePi (0, toSep, result) == -1) { return -1; } return SINGLE; } return 0; } void exeByMode (Job toExe[], int mode, pid_t id) { int i = 0; int j = 0; pid_t pid; switch (mode) { case SEQUENTIAL:{ while (toExe[j].on_duty) { if (strcmp(*toExe[j].cmds[0], "quit") == 0) { exit (0); }else if (strcmp (*toExe[j].cmds[0] , "pwd") == 0) { if (toExe[j].cmds[0][1]) { printErr(); j++; continue; } char tmp[PATH_MAX + 1]; getcwd (tmp, PATH_MAX + 1); write (STDOUT_FILENO, tmp, sizeof (char) * strlen (tmp) ); write (STDOUT_FILENO, "\n", sizeof (char) ); j++; continue; }else if (strcmp (*toExe[j].cmds[0], "cd") == 0) { if (toExe[j].cmds[0][1] == NULL) { chdir (getenv ("HOME") ); }else if (chdir (toExe[j].cmds[0][1]) != 0) { printErr(); j++; continue; } j++; continue; } pid = fork (); if (pid < 0) { printErr(); exit (1); }else if (pid == 0) { pid_t pids; int fd[2]; int in = STDIN_FILENO; for (i = 0; i < toExe[j].nPipes; i++) { if (pipe (fd) < 0) { printErr(); exit (1); } pids = fork(); if (pids < 0) { printErr(); }else if (pids == 0) { dup2 (in, STDIN_FILENO); dup2 (fd[1], STDOUT_FILENO); close (fd[0]); execvp (*toExe[j].cmds[i], toExe[j].cmds[i]); printErr(); exit (1); }else{ while (wait (NULL) != -1 || errno != ECHILD) {} close (fd[1]); in = fd[0]; } } if (in != STDIN_FILENO) { dup2 (fd[0], STDIN_FILENO); close (fd[0]); } if (toExe[j].redir){ int fdo = open(toExe[j].redir, O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU); if (fdo < 0) { printErr(); exit (1); } dup2 (fdo, STDOUT_FILENO); close (fdo); } execvp (*toExe[j].cmds[i], toExe[j].cmds[i]); printErr(); exit (0); }else{ while (wait (NULL) != -1 || errno != ECHILD) {} } j++; } break; } case PARALLEL:{ while (toExe[j].on_duty) { pid = fork (); if (pid < 0) { printErr(); exit (1); break; }else if (pid == 0) break; j++; } if (getpid () != id) { pid_t pids; int fd[2]; int in = STDIN_FILENO; for (i = 0; i < toExe[j].nPipes; i++) { if (pipe (fd) < 0) { printErr(); exit (1); } pids = fork(); if (pids < 0) { printErr(); }else if (pids == 0) { dup2 (in, STDIN_FILENO); dup2 (fd[1], STDOUT_FILENO); close (fd[0]); execvp (*toExe[j].cmds[i], toExe[j].cmds[i]); printErr(); exit (1); }else{ while (wait (NULL) != -1 || errno != ECHILD) {} close (fd[1]); in = fd[0]; } } if (in != STDIN_FILENO) { dup2 (fd[0], STDIN_FILENO); close (fd[0]); } if (toExe[j].redir){ int fdo = open(toExe[j].redir, O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU); if (fdo < 0) { printErr(); exit (1); } dup2 (fdo, STDOUT_FILENO); close (fdo); } execvp (*toExe[j].cmds[i], toExe[j].cmds[i]); printErr(); exit (0); }else{ while (wait (NULL) != -1 || errno != ECHILD) {} } break; } case SINGLE:{ if (strcmp(*toExe[0].cmds[0], "quit") == 0) { exit (0); }else if (strcmp (*toExe[0].cmds[0] , "pwd") == 0) { if (toExe[0].cmds[0][1]) { printErr(); } char tmp[PATH_MAX + 1]; getcwd (tmp, PATH_MAX + 1); write (STDOUT_FILENO, tmp, sizeof (char) * strlen (tmp) ); write (STDOUT_FILENO, "\n", sizeof (char) ); }else if (strcmp (*toExe[0].cmds[0], "cd") == 0) { if (toExe[0].cmds[0][1] == NULL) { if (chdir (getenv ("HOME") ) != 0) { printErr(); } }else if (chdir (toExe[0].cmds[0][1]) != 0) { printErr(); } i++; } pid = fork (); if (pid < 0) { printErr(); exit (1); }else if (pid == 0) { pid_t pids; int fd[2]; int in = STDIN_FILENO; for (; i < toExe[0].nPipes; i++) { if (pipe (fd) < 0) { printErr(); exit (1); } pids = fork(); if (pids < 0) { printErr(); }else if (pids == 0) { dup2 (in, STDIN_FILENO); dup2 (fd[1], STDOUT_FILENO); close (fd[0]); execvp (*toExe[0].cmds[i], toExe[0].cmds[i]); printErr(); exit (1); }else{ while (wait (NULL) != -1 || errno != ECHILD) {} close (fd[1]); in = fd[0]; } } if (in != STDIN_FILENO) { dup2 (fd[0], STDIN_FILENO); close (fd[0]); } if (toExe[j].redir){ int fdo = open(toExe[j].redir, O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU); if (fdo < 0) { printErr(); exit (1); } dup2 (fdo, STDOUT_FILENO); close (fdo); } execvp (*toExe[0].cmds[i], toExe[0].cmds[i]); printErr(); exit (1); }else{ while (wait (NULL) != -1 || errno != ECHILD) {} } break; } } } int main (int argc, const char * argv[]) { if (argc > 2) { printErr(); exit (1); } FILE * fp = NULL; char bmode = 0; if (argc == 2) { fp = fopen (argv[1], "r"); if (fp == NULL) { printErr(); exit (1); } bmode = 1; } Job jobs[20]; int i, j, k; for (i = 0; i < 20; i++) { for (j = 0; j < 10; j++) { jobs[i].cmds[j] = malloc (50); } } pid_t id = getpid (); char mode; while (1) { char cmd[1000] = {0}; for (i = 0; i < 20; i++) { if (jobs[i].on_duty == 1) { for (j = 0; j < 10; j++) { for (k = 0; k < 50; k++) jobs[i].cmds[j][k] = NULL; } } jobs[i].on_duty = 0; jobs[i].nPipes = 0; jobs[i].redir = 0; } if (bmode) { if (fgets (cmd, 1000, fp) == NULL){ exit (0); } write (STDOUT_FILENO, cmd, strlen(cmd)); if (cmd[512] != 0 && cmd[512] != '\n') { cmd[512] = 0; printErr(); continue; } }else{ write (STDOUT_FILENO, "537sh> ", sizeof (char) * 7); fgets (cmd, 1000, stdin); if (cmd[512] != 0 && cmd[512] != '\n') { cmd[512] = 0; printErr(); continue; } } if (*cmd == '\n') continue; if (cmd[strlen (cmd) - 1] == '\n') { cmd[strlen (cmd) - 1] = 0; } if ( (mode = sepMultCmd (cmd, jobs) ) == -1) continue; if (mode == PARALLEL) { int i = 0; char err = 0; while (*jobs[i].cmds[0]) { int j; for (j = 0; j < 10; j++){ if (*jobs[i].cmds[j]) { if (strcmp (*jobs[i].cmds[j], "quit") == 0 || strcmp (*jobs[i].cmds[j], "pwd") == 0 || strcmp (*jobs[i].cmds[j], "cd") == 0) { err = 1; } } } i++; } if (err == 1) { printErr(); continue; } } if (*jobs->cmds[1] == NULL && jobs[0].redir == 0 && *jobs[1].cmds[0] == NULL) { if (*jobs->cmds[0] == NULL) continue; if (strcmp (*jobs->cmds[0], "quit") == 0) { exit (0); }else if (strcmp (*jobs->cmds[0] , "cd") == 0) { if (jobs->cmds[0][1] == NULL) { chdir (getenv ("HOME") ); }else if (chdir (jobs->cmds[0][1]) != 0) { printErr(); continue; } continue; }else if (strcmp (*jobs->cmds[0] , "pwd") == 0) { if (jobs->cmds[0][1]) { printErr(); continue; } char tmp[PATH_MAX + 1]; getcwd (tmp, PATH_MAX + 1); write (STDOUT_FILENO, tmp, sizeof (char) * strlen (tmp) ); write (STDOUT_FILENO, "\n", sizeof (char) ); continue; } } exeByMode (jobs, mode, id); } for (i = 0; i < 50; i++) { for (j = 0; j < 10; j++) { free (jobs[i].cmds[j]); } } return 0; }
C
/* the answer is 983 */ //2014.11.23// /* 1000以下の自然数nにおいて 1 / n の巡回節は最高で n - 1桁となる。 10^m - 1 を割り切ることができればそのnの巡回節はm桁となる。 */ #include<stdio.h> #include<math.h> int main(void){ int i,cycle,maxCycle = 0,Remainder; for(i = 3; i < 1000; i += 2){ Remainder = 0; cycle = 1;//1にしないと結果が合わない 理由は不明 if(i % 5 == 0) i += 2; while(1){ Remainder = (Remainder * 10 + 9) % i; cycle ++; if(Remainder == 0){ if(maxCycle < cycle) maxCycle = cycle; break; } } } printf("%d\n",maxCycle); getchar(); return 0; }
C
///Programa de evolución de un sistema ferromagnético en función de la temperatura (Ising) # include <stdio.h> # include <math.h> # include "gsl_rng.h" //Librería para generación de números aleatorios para compilar un programa //con la librería anterior de números aleatorios tengo que añadirle al comando //de compilación típico:gcc random.c -o random.exe -lm -O3 //la ubicacion de la libreria externa: -L/usr/lib/x86_64-linux-gnu -lgsl -lgslcblas -lm //quedando finalmente:gcc random.c -o random.exe -lm -O3 -L/usr/lib/x86_64-linux-gnu -lgsl -lgslcblas -lm //como comando de compilacion. # define temp 1.5 // es la temperatura del sistema, la variamos entre 0º y 5º # define N 128 // defino fuera el tamaño de las matrices por si quiero cambiarlo rápido # define TIEMPO_MONTECARLO 1000000 // es el número de pasos montecarlo, defino fuera por lo mismo # define TIEMPO_CALCULO 100 # define numero_temperaturas 10 //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////funciones///////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// void INICIAL(int matriz[N][N], FILE *file); // es una funcion que me genera una configuracion // inicial aleatoria de espines en una matriz de NxN nodos, cada nodo sería // el spin de una particula distinta. Luego me lo escribe en un archivo void CAMBIO(int matriz[N][N],double T); // aquí está el meollo del programa, haciendo // el posible cambio de signo a un solo spin por cada ejecución de esta función. // Ese posible cambio se dará si se complen las condiciones escritas en la función // la propia función ya realiza el cambio void ESCRIBIR(int matriz[N][N], FILE *file); // función para escribir mi matriz en un fichero //para cada paso montecarlo double CALCULAR_MN(int s[N][N]); //una función que calcula la magnetización promedio cada TIEMPO_CALCULO pasos montecarlo durante TIEMPO_MONTECARLO pasos. // solo requiere la configuración de la red en ese momento double CALCULAR_EN(int s[N][N]); //una función que calcula la energía promedio cada TIEMPO_CALCULO pasos montecarlo durante TIEMPO_MONTECARLO pasos. // solo requiere la configuración de la red en ese momento double CALCULAR_CN(int s[N][N]); //una función que calcula el calor específico promedio cada TIEMPO_CALCULO pasos montecarlo durante TIEMPO_MONTECARLO pasos. // solo requiere la configuración de la red en ese momento void FUNCION_CORRELACION(double f[1+N/2], int s[N][N]); //Es una función que calcula la función de correlación de nuestra matriz //(cuanto y a qué distancia están relacionados entre sí los elementos de la red). //////////////////////////////////////////////////////////////////////////////// ///// Tengo que declarar mi variable aleatoria fuera del main, así será una///// ///// variable general y podré usarla en distintas funciones sin problema.///// //////////////////////////////////////////////////////////////////////////////// gsl_rng *tau; int main() { int i,j,k,l,m,cont; //Variables auxiliares double p,x,y,z;//Variables auxiliares double mn,en,cn; //variables que me servirán para guardar los valores // de magnetización, energía interna y calor específico respectivamente, // para luego hacer el promedio. double desmn, desen; int s[N][N]; //matriz que recoge todos los espines double f[1+N/2],g[1+N/2];//arrays que utilizo para calcular la función de correlación extern gsl_rng *tau; //Puntero al estado del número aleatorio double T;// mi variable temperatura, ejecutar el programa a diferentes temperaturas. int semilla=413785; //Semilla del generador de números aleatorios FILE *f1, *f2, *f3, *f4; // punteros a ficheros f1=fopen("estado_inicial413785.txt","w"); //abro fichero para el estado inicial f2=fopen("estados_413785.txt","w"); //abro fichero donde escribiré los estados f3=fopen("soluciones_promedio.txt","w");//guardo la en,mn,cn f4=fopen("correlacion.txt","w");//guardo la función de correlación /////////////////////////////////////////////////////////////////////// //para utilizar los numeros aleatorios generados con gsl tengo que // //inicializar la semilla y el puntero, después podré generar números // /////////////////////////////////////////////////////////////////////// tau=gsl_rng_alloc(gsl_rng_taus); //Inicializamos el puntero gsl_rng_set(tau,semilla); //Inicializamos la semilla INICIAL(s,f1); fclose(f1); T=temp; for(l=0;l<=numero_temperaturas;l++){//es un ciclo for para que el programa lo calcule todo a diferentes temperaturas. m=1;// inicializo el contador m que cada 100 pasos montecarlos calcula lo que me piden y escribe en fichero. cont=0;//contador que me sirve para al final de mi programa hacer el promedio total. for(k=1;k<=TIEMPO_MONTECARLO;k++) // son 1000000 pasos montecarlos en este caso { for(j=1;j<=N*N;j++) // N*N posibles cambios que ejecuta un paso montecarlo { CAMBIO(s,T); } if(m==TIEMPO_CALCULO) { x=CALCULAR_MN(s);//calculo la magnetización en este momento mn=mn+x;//la sumo junto a las demás magnetizaciones que voy calculando en los distintos pasos montecarlos y=CALCULAR_EN(s);//calculo la energía en=en+y;//la voy sumando z=CALCULAR_CN(s);//calculo el calor específico cn=cn+z;//lo voy sumando FUNCION_CORRELACION(f,s);//calculo la función de correlación for(i=1;i<=N/2;i++) { g[i]=g[i]+f[i];//la voy sumando } ESCRIBIR(s,f2); m=0; cont=cont+1; } m++; } //ahora calculo los promedios// mn=mn/(1.0*cont); cn=((cn/cont)-en*en/(cont*cont))/(N*N*T); en=en/(2.0*N*cont); for(i=1;i<=N/2;i++) { g[i]=g[i]/(N*N*cont); fprintf(f4, "%lf\t%lf\n", g[i],temp ); } //los imprimo cada uno en un fichero printf("%lf\t%lf\t%lf\t%i\n",mn,en,cn,l); fprintf(f3, "%lf\t%lf\t%lf\t%lf\n",T,mn,en,cn ); T=T+0.2;// aumento la temperatura y vuelvo a calcularlo todo. } fclose(f2); fclose(f3); fclose(f4); return 0; } void INICIAL(int matriz[N][N],FILE *file) { int i,j; // contadores int a; // variable aleatoria //extern gsl_rng *tau; //Puntero al estado del número aleatorio for(i=0;i<N;i++) { for(j=0;j<N;j++) { //a=gsl_rng_uniform_int(tau,2); // numero entero entre 0 y 1; //if(a==0) // {matriz[i][j]=-1;} //así obtengo los espines -1 //else {matriz[i][j]=1;} //así obtengo los espines 1 if(j!=N-1) {fprintf(file,"%i\t", matriz[i][j]);} //escribo la matriz en el fichero de texto estado_inicialSEMILLA.txt // con un formato de que en cada nueva fila, haga un salto de linea // y escriba la siguiente fila en la linea siguiente (aunque yo no // lo veré en mi fichero de texto en este formato por el tamaño de mi pantalla) else {fprintf(file,"%i\n", matriz[i][j]);} // los datos de una misma fila vienen separados por un tabulador } } return; } void CAMBIO(int matriz[N][N],double T) { int i,j; //contadores double p,E,x; // E hace referencia a la diferencia de energía entre un estado // y el siguiente estado, p sería la probabilidad de que dicho paso ocurriera // x es un número aleatorio entre 0 y 1 extern gsl_rng *tau; //Puntero al estado del número aleatorio i=gsl_rng_uniform_int(tau,N); //número aleatorio entero [0,63] j=gsl_rng_uniform_int(tau,N); //número aleatorio entero [0,63] // Así escogería un spin aleatorio de la matriz[64][64] que luego evaluaría // para ver si cambia. //////////////////////////////////////////////////////////////////////////// // Tengo el problema de las condiciones de contorno // // lo vamos a resolver a continuación con condiciones if, hay 8 casos // // especiales y el general // //////////////////////////////////////////////////////////////////////////// if(i==0 && j==0) //caso [0,0] { E=2*matriz[i][j]*(matriz[i+1][j]+matriz[N-1][j]+matriz[i][j+1]+ matriz[i][N-1]); // así se calcula la variación de energía entre dos //estados en un paso de markov en concreto para el punto [0,0], el caso //general lo he puesto el último } else if(i==0 && j==N-1) // caso [0,63] { E=2*matriz[i][j]*(matriz[i+1][j]+matriz[N-1][j]+matriz[i][0]+ matriz[i][j-1]); } else if(i==N-1 && j==0) //caso [63,0] { E=2*matriz[i][j]*(matriz[0][j]+matriz[i-1][j]+matriz[i][j+1]+ matriz[i][N-1]); } else if((i==N-1) && (j==N-1)) // caso [63,63] { E=2*matriz[i][j]*(matriz[0][j]+matriz[i-1][j]+matriz[i][0]+ matriz[i][j-1]); } else if(i==0) { E=2*matriz[i][j]*(matriz[i+1][j]+matriz[N-1][j]+matriz[i][j+1]+ matriz[i][j-1]); } else if(j==0) { E=2*matriz[i][j]*(matriz[i+1][j]+matriz[i-1][j]+matriz[i][j+1]+ matriz[i][N-1]); } else if(i==N-1) { E=2*matriz[i][j]*(matriz[0][j]+matriz[i-1][j]+matriz[i][j+1]+ matriz[i][j-1]); } else if(j==N-1) { E=2*matriz[i][j]*(matriz[i+1][j]+matriz[i-1][j]+matriz[i][0]+ matriz[i][j-1]); } else { E=2*matriz[i][j]*(matriz[i+1][j]+matriz[i-1][j]+matriz[i][j+1]+ matriz[i][j-1]);// así se calcula la variación de energía entre dos //estados en un paso de markov } p=exp(-E/T); // así se calcula la probabilidad de que dicho paso ocurra. if(p>1) // si la probabilidad saliera mayor que uno yo la igualo a 1 porque no puede ser mayor {p=1;} x=gsl_rng_uniform(tau); //número aleatorio real [0,1] es el que evalua si //dicho paso de markov se produce if(x<p) {matriz[i][j]=-1*matriz[i][j];} // hago el cambio si x<p en caso contrario el // sistema no cambia return; } void ESCRIBIR(int matriz[N][N], FILE *file) { int i,j; // contadores for(i=0;i<N;i++) { for(j=0;j<N;j++) { if((j==N-1) && (i==N-1)) { fprintf(file,"%i\t%i\t%i\n", i,j, matriz[i][j]); } else { fprintf(file,"%i\t%i\t%i\t", i,j, matriz[i][j]); //escribo la matriz en el fichero de texto estado_inicialSEMILLA.txt // con un formato de que escribo todos la x la y y el espín seguidos // y toda la matriz seguida, el salto de linea se da entre matrices // diferentes } } } return; } double CALCULAR_MN(int s[N][N]) { int i,j; double sol; sol=0.0; for(i=0;i<N;i++) { for(j=0;j<N;j++) { sol=sol+s[i][j]; } } sol=fabs(sol*1.0)/(N*N); return sol; } double CALCULAR_EN(int matriz[N][N]) { int i,j; double E; E=0.0; for(i=0;i<N;i++) { for(j=0;j<N;j++) { //////////////////////////////////////////////////////////////////////////// // Tengo el problema de las condiciones de contorno // // lo vamos a resolver a continuación con condiciones if, hay 8 casos // // especiales y el general // //////////////////////////////////////////////////////////////////////////// if(i==0 && j==0) //caso [0,0] { E=E-0.5*matriz[i][j]*(matriz[i+1][j]+matriz[N-1][j]+matriz[i][j+1]+ matriz[i][N-1]); // así se calcula la energía en un paso determinado //en concreto para el punto [0,0], el caso general lo he puesto el último } else if(i==0 && j==N-1) // caso [0,63] { E=E-0.5*matriz[i][j]*(matriz[i+1][j]+matriz[N-1][j]+matriz[i][0]+ matriz[i][j-1]); } else if(i==N-1 && j==0) //caso [63,0] { E=E-0.5*matriz[i][j]*(matriz[0][j]+matriz[i-1][j]+matriz[i][j+1]+ matriz[i][N-1]); } else if((i==N-1) && (j==N-1)) // caso [63,63] { E=E-0.5*matriz[i][j]*(matriz[0][j]+matriz[i-1][j]+matriz[i][0]+ matriz[i][j-1]); } else if(i==0) { E=E-0.5*matriz[i][j]*(matriz[i+1][j]+matriz[N-1][j]+matriz[i][j+1]+ matriz[i][j-1]); } else if(j==0) { E=E-0.5*matriz[i][j]*(matriz[i+1][j]+matriz[i-1][j]+matriz[i][j+1]+ matriz[i][N-1]); } else if(i==N-1) { E=E-0.5*matriz[i][j]*(matriz[0][j]+matriz[i-1][j]+matriz[i][j+1]+ matriz[i][j-1]); } else if(j==N-1) { E=E-0.5*matriz[i][j]*(matriz[i+1][j]+matriz[i-1][j]+matriz[i][0]+ matriz[i][j-1]); } else { E=E-0.5*matriz[i][j]*(matriz[i+1][j]+matriz[i-1][j]+matriz[i][j+1]+ matriz[i][j-1]);// así se calcula la variación de energía entre dos //estados en un paso de markov } } } return E; } double CALCULAR_CN(int s[N][N]) { double E; E=CALCULAR_EN(s);//utiliza la función que calcula la energía. return E*E; } void FUNCION_CORRELACION(double f[1+N/2], int s[N][N]) { int i,j,k; double a; for(k=1;k<=(N/2);k++) { for(i=0;i<N;i++) { for(j=0;j<N;j++) // la distancia maxima entre dos puntos de la red en la misma //fila es N/2 porque la red tiene los extremos conectados. { //si tenemos un s[i][j], cercano al final de la linea, tendremos que empezarla de nuevo, es decir if((k+i)<N) { f[k]=f[k]+s[i][j]*s[i+k][j]; } if((k+i)>=N) { f[k]=f[k]+s[i][j]*s[k+i-N][j]; } } } } return; }
C
/****************************************************************************** * File : Main program * Author : VNP02 *****************************************************************************/ //#include "stm32f0xx.h" #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include "usart.h" void assert_strequal( int test, char* b, char* expected, char* message ); //comment the following line to test your fixed point solution instead of the given example //#define RUN_FLOAT 1 char buffer[20]; //for printing int passed = 0; #ifdef RUN_FLOAT typedef float fixed; //note that still one testcase fails because float is not accurate enough! //typedef double fixed; //more precision floatint point type passes all tests #define float_to_fixed(a) (a) //float does not need conversion fixed calc_average( fixed* array, int8_t lenght) { int8_t hour; fixed sum = 0; for ( hour=0; hour<lenght; hour++) { sum += *array++; } return sum / lenght; //float does not need rounding } void to_string( fixed number ) { sprintf(buffer, "%.1f", number); //printing takes care of rounding } #else //your fixed point arithmetic code goes here // Q7.8 = 1 bit sign, 7 bit integer value, 8 bit fractional part typedef int16_t fixed; #define SHIFT_AMOUNT (8) // 8 bit shift #define SHIFT_MASK ((1 << SHIFT_AMOUNT) - 1) // 0000 0000 . 1111 1111 = 255 // make the correct conversion macro #define float_to_fixed(a) ((fixed)((a) * (1 << SHIFT_AMOUNT))) // Multiply with 256 #define frac_part(a) ((a) & SHIFT_MASK) // Retrieve fractional part of fixed point number #define frac_fixed(a) (frac_part(a) * 10) // Multiply integer value fractional part by 10 to not lose it after reverting back to int #define frac_rounded(a) (frac_fixed(a) + float_to_fixed(0.6)) // Add 0.6(fixed notation) to fixed point fractional part #define frac_real(a) (frac_rounded(a) / (1 << SHIFT_AMOUNT)) // Devide by 256 to convert back to notation presentable in int // implement this code yourself fixed calc_average( fixed* array, int8_t lenght) { // your code goes here int8_t hour; int32_t sum = 0; for ( hour=0; hour<lenght; hour++) // Calculate every element of array { sum += *array++; // Dereference every array position to retrieve value } return sum / lenght; // Calculate average } // implement this code yourself void to_string( fixed number ) { sprintf(buffer, "%d.%1d", (number / (1 << SHIFT_AMOUNT)), // Devide by 256 to retrieve real value (7 bits value, 1 bit sign = 8 bits) frac_real(number)); // Use frac_real(a) macro to retrieve fractional part of number input (8 bit value + 8 bit fraction = 16 bits total) } #endif // RUN_FLOAT struct testcase { int aantalgetallen; float invoer[5]; char* verwachtte_uitvoer; char* melding; }; const int nrofTestcases = 9; struct testcase testcases[] = { //nrvalues input output test { 1, {1, 0, 0, 0, 0}, "1.0", "simple" }, { 1, {0.1, 0, 0, 0, 0}, "0.1", "simple" }, { 2, {36.3, 36.3, 0, 0, 0}, "36.3", "average" }, { 2, {36.3, 36.4, 0, 0, 0}, "36.4", "average with rounding" }, { 3, {36.3, 36.4, 0, 0, 0}, "24.2", "average with rounding" }, { 5, {100, 100, 100, 100, 100}, "100.0", "overflow" }, { 5, {-20, -20, -20, -20, -20}, "-20.0", "underflow" }, { 2, {-20, -19, 0, 0, 0}, "-19.5", "rounding negative values" }, { 2, {-20, 20, 0, 0, 0}, "0.0", "negative + positive number " } }; // ---------------------------------------------------------------------------- // Main // ---------------------------------------------------------------------------- int main(void) { int test, j; fixed avg; fixed hourly_temperatures[ 24 ]; //USART_init(); //USART_clearscreen(); #ifdef RUN_FLOAT USART_putstr("This is testcode for floating point arithmetic\n"); #else //USART_putstr("This is testcode for fixed point arithmetic\n"); #endif //USART_putstr("The output of the testcases is\n\n"); for ( test=0; test<nrofTestcases; test++) { //do each test struct testcase thistest = testcases[test]; //fill values array for (j=0; j<thistest.aantalgetallen; j++) { hourly_temperatures[j] = float_to_fixed(thistest.invoer[j]); } avg = calc_average( hourly_temperatures, thistest.aantalgetallen ); to_string( avg ); assert_strequal( test, buffer, thistest.verwachtte_uitvoer, thistest.melding ); } USART_putstr( "\nYou passed " ); USART_putint( passed ); USART_putstr( " of the tests\n" ); USART_putstr("Ready"); //ready while(1); } void assert_strequal( int test, char* b, char* expected, char* message ) { USART_putstr( "TEST: " ); USART_putint( test+1 ); if ( strncmp( b, expected, 10 ) != 0 ) //check the first 10 digits for equality { USART_putstr( " FAIL: " ); USART_putstr( b ); USART_putstr( " != " ); USART_putstr( expected ); USART_putstr( " " ); USART_putstr( message ); } else { USART_putstr( " PASS: " ); USART_putstr( b ); USART_putstr( " = " ); USART_putstr( expected ); passed++; } USART_putstr( "\n" ); }
C
#include "AST.h" ////////////////////////////////// // I/O Interface ostream& operator <<(ostream &o, const ASTExpression &a) { // Concatenates an ASTExpression object to an ostream. // // This works by delegating the job back to the ASTExpression node. a.ASTPrint(o); return o; } ////////////////////////////////// // ASTExpression methods int ASTExpression::getline() { return linenum; } int ASTExpression::getchar() { return charnum; } ////////////////////////////////// // ASTInteger methods ASTInteger::ASTInteger(int i, int line_init, int char_init) :ASTExpression(line_init,char_init),value(i) { // The ASTInteger constructor uses the superclass initializer // to initialize its superclass linenum and charnum. It // also initializes value from its argument. // No other code is necessary. value = i; } void ASTInteger::ASTPrint(ostream &o) const { // To print an integer ASTExpression, print the integer // value associated with it. o << value; } ASTString::ASTString(string i, int line_init, int char_init) :ASTExpression(line_init,char_init),value(i) { // The ASTInteger constructor uses the superclass initializer // to initialize its superclass linenum and charnum. It // also initializes value from its argument. // No other code is necessary. value = i; } void ASTString::ASTPrint(ostream &o) const { // To print an integer ASTExpression, print the integer // value associated with it. o << value; } //GarnetPtr //ASTInteger::eval() const //{ // // To evaluate an integer, make a garnet integer object. // // An integer is a primitive, so I call the make_prim // return make_object_from_prim(value); //} void ASTFloat::ASTPrint(ostream &o) const { o << value; } void ASTIdentifier::ASTPrint(ostream &o) const { o << id; } void ASTExpressionListSimple::ASTPrint(ostream &o) const { o << "(" << *expr << ")"; } void ASTExpressionListCompound::ASTPrint(ostream &o) const { o << "(" << *expr_list << "; \n" << *expr << ")"; } ////////////////////////////////// // ASTArgList methods ASTExpression * ASTArgList::head() { cerr << "Don't know how to take the head of this arglist" << endl; abort(); } ASTExpression * ASTArgList::tail() { cerr << "Don't know how to take the tail of this arglist" << endl; abort(); } ////////////////////////////////// // ASTArgListSimple methods ASTExpression * ASTArgListSimple::head() { return expr; } void ASTArgListSimple::ASTPrint(ostream &o) const { o << *expr; } ////////////////////////////////// // ASTArgListCompound methods ASTExpression * ASTArgListCompound::head() { return list_head; } ASTExpression * ASTArgListCompound::tail() { return list_tail; } void ASTArgListCompound::ASTPrint(ostream &o) const { o << *list_head<< ", " << *list_tail; } void ASTArgListEmpty::ASTPrint(ostream &o) const { // define appropriately } void ASTMethodCall::ASTPrint(ostream &o) const { o << methodName << "(" << *arglist << ")"; } GarnetPtr ASTEval() { //evaluate the GarnetPtr in question } GarnetPtr ASTInteger::ASTEval() { return make_object_from_prim(value); } void ASTWhile::ASTPrint(ostream &o) const { o << "While " << *condition << " " << " do \n" << *body << "\n end" ; } void ASTFor::ASTPrint(ostream &o) const { o << "for " << *condition << " in "<< *arrayExp << " do \n" << *body << "\n end" ; } void ASTLoop::ASTPrint(ostream &o) const { o << "loop " << "{ \n" << *body << "\n }" ; } void ASTIf::ASTPrint(ostream &o) const { o << "if(" << *condition << ") do" << "\n" << *body << "\n end" << *hacky ; } void ASTelsif::ASTPrint(ostream &o) const { o << "elsif(" << *condition << ") then" << "{ \n" << *body << "\n}" << *hacky; } void ASTelse::ASTPrint(ostream &o) const { o << "else" << "{ \n" << *body << "\n}" ; } void ASTIfNo::ASTPrint(ostream &o) const { o << "end" ; }
C
#include <stdio.h> int main() { char names[][10] = {"jeetendra", "atharva"}; char *ptr = &names[0][0]; char (*ptr1)[10] = &names[0]; for(int i = 0 ; i < 2 ; i++) printf("%s %s\n", ptr++, *ptr1++); }
C
#include <msp430.h> #include "switches.h" #include "led.h" #include "buzzer.h" #include "stateMachines.h" char switch1_state, switch2_state, switch3_state, switch4_state; char switch_state_changed; /* effectively boolean */ switch_state = 0; static char switch_update_interrupt_sense() { char p2val = P2IN; /* update switch interrupt to detect changes from current buttons */ P2IES |= (p2val & SWITCHES);/* if switch up, sense down */ P2IES &= (p2val | ~SWITCHES);/* if switch down, sense up */ return p2val; } void switch_init()/* setup switch */ { P2REN |= SWITCHES;/* enables resistors for switches */ P2IE = SWITCHES;/* enable interrupts from switches */ P2OUT |= SWITCHES;/* pull-ups for switches */ P2DIR &= ~SWITCHES;/* set switches' bits for input */ switch_update_interrupt_sense(); } void switch_interrupt_handler() { char p2val = switch_update_interrupt_sense(); switch1_state = (p2val & SW1) ? 0 : 1; /* 0 when SW1 is up */ switch2_state = (p2val & SW2) ? 0 : 1; /* 0 when SW2 is up */ switch3_state = (p2val & SW3) ? 0 : 1; /* 0 when SW3 is up */ switch4_state = (p2val & SW4) ? 0 : 1; /* 0 when SW4 is up */ //this lets the stateMachine know what button is beign played if(switch1_state){ switch_state = 1; } if(switch2_state){ switch_state = 2; } if(switch3_state){ switch_state = 3; } if(switch4_state){ switch_state = 4; } switch_state_changed = 1; }
C
/* mechanics.h * * */ #ifndef MECHANICS_H #define MECHANICS_H #include "lpc_types.h" #define PI 3.14159265 // Pi #define MIDDLE_SENSOR 0 // Middle sensor #define RIGHT_SENSORS 1 // Right sensors #define LEFT_SENSORS 2 // Left Sensors #define FRONT_ANALOG 3 // Analog sensor in the front #define LEFT_F_ANALOG 2 // Analog in the front right #define LEFT_B_ANALOG 0 // Analog in the back right #define RIGHT_F_ANALOG 1 // Analog in the back right #define RIGHT_B_ANALOG 4 // Analog in the back left #define LEFT_DIFFERENCE 8 // Distance between left sensors in cm #define RIGHT_DIFFERENCE 8.5 // Distance between right sensors in cm #define avg(x,y) {(x+y)/2} // Average macro #define CALIB_NUM 4 // Number of calibration points #define CALIB_RES 10 // Number of centimeters between calibration points #define WHEEL_RADIUS 1.5 // wheel radius in cm #define WHEEL_CIRCUM 9.424777961 // wheel circumfrunce in cm 2 pi r #define TOTAL_TICKS 8 // Number of ticks on the wheel #define TICK_TO_CM 1.178097245 // WHEEL_CIRCUM / TOTAL_TICKS #define DEFAULT_SPEED 20 // Default speed, this should be factored out in later updates #define k_y 0.5 // K_y used in wall following to calculate kapa #define k_theta 2.0 // K_@ used in wall following to calculate kapa, Has to be 4 * k_y struct wheel_enc { uint8_t direction; // Direction of the wheel. 0 - Forwards, 1 - backwards int64_t ticks; // Number of ticks per wheel }; struct wheel_enc left_wheel_enc; struct wheel_enc right_wheel_enc; /** * Generates sensors' look up table */ int generateLUT( void ); /** * Linear Interpolation using sensor lut and return cm from sensor values * * y = (x-x_0)(y_1-y_0)/(x_1-x_0) + y_0 * y0, **/ uint8_t getDist2(uint16_t sensor_value); float getDist(uint16_t sensor_value); /** * WHEEL ENCODER CONTROLS */ void tick_right_wheel(uint8_t numberOfTicks); void tick_left_wheel(uint8_t numberOfTicks); void tick_wheels(uint8_t numberOfTicks); void turn_right_wheel(uint8_t numberOfTurns); void turn_left_wheel(uint8_t numberOfTurns); void turn_wheels(uint8_t numberOfTurns); /** * Return the angle from teh difference between the sensors * * @param uint8_t indicating desired group of sensors, 0 - Middle sensor, 1 - Right Sensor, 2 - Left Sensor */ float getAngleFromSensors(uint8_t whichSensors); #endif //MECHANICS_H
C
#include <stdio.h> #include <GL/glut.h> void display(void){ glClear(GL_COLOR_BUFFER_BIT); glFlush(); } void resize(int w, int h){ glViewport(0,0,w,h); glLoadIdentity(); } void mouse(int button, int state, int x, int y){ switch(button){ case GLUT_LEFT_BUTTON: printf("left"); break; case GLUT_MIDDLE_BUTTON: printf("middle"); break; case GLUT_RIGHT_BUTTON: printf("right"); break; default: break; } printf("button is "); switch(state){ case GLUT_UP: printf("up"); break; case GLUT_DOWN: printf("down"); break; default: break; } printf(" at (%d, %d)\n",x,y); } void init(void){ glClearColor(1.0,1.0,1.0,1.0); } int main(int argc,char *argv[]){ glutInitWindowPosition(100,100); glutInitWindowSize(320,240); glutInit(&argc,argv); glutInitDisplayMode(GLUT_RGBA); glutCreateWindow(argv[0]); glutDisplayFunc(display); glutReshapeFunc(resize); glutMouseFunc(mouse); init(); glutMainLoop(); return 0; } /* glutMouseFunc(void (*func)(int button, int state, int x, int y)) 引数funcには,マウスのボタンが押されたときに実行する関数のポインタを与える. また,左上が原点である. */
C
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> int ecc(const uint32_t *words, size_t count) { int bit, ecc; uint32_t word, i; bit = 0xff00; ecc = 0; while (count--) { word = *words++; for (i = 0; i < 32; i++) { if (word & 0x80000000) { ecc ^= bit; } word = word * 2; bit += 0xff01; } } return ecc & 0xffff; } static int ascii2hex(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'A' && c <= 'F') return c - 'A' + 10; if (c >= 'a' && c <= 'f') return c - 'a' + 10; return -1; } static int ascii2byte(char *str) { int ret; ret = ascii2hex(*str++) << 4; ret |= ascii2hex(*str); return ret; } union { char b[32]; uint32_t l[8]; } buf; int main(int argc, char *argv[]) { int fd, i; char *input, *p; uint16_t the_ecc; if (argc != 2) { fprintf(stderr, "need file as argument\n"); return EXIT_FAILURE; } fd = open(argv[1], O_RDONLY); if (fd < 0) { perror("open"); return EXIT_FAILURE; } input = mmap(NULL, 64, PROT_READ, MAP_PRIVATE, fd, 0); if (input == NULL) { perror("mmap"); return EXIT_FAILURE; } p = input; for (i = 0; i < 32; i++) { buf.b[i] = ascii2byte(p); p += 2; } the_ecc = ecc(buf.l, sizeof(buf) / sizeof(uint32_t)); printf("0x%08x\n", buf.l[1]); printf("%04x\n", the_ecc); return EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #define LONGITUD_CADENA 30 /// 30 bytes -- 240 bits (Por palabra), "cambiar para cadenas mas largas" /* * Ejercicio con cadenas * a. Convertir cadenas a minusculas * b. Convertir cadenas a mayusculas * c. Contar vocales de cadena * d. Mostrar caracteres comunes entre dos cadenas * @author CPlayMasH * Fecha de creacion : 01 / 07 / 2014 ** Contenido puramente educativo ** */ void imprimirCadenas(char cadena1[], char cadena2[]); void ingresarCadenas(char cadena1[], char cadena2[]); void cadenasAMayusculas(char cadena1[], char cadena2[]); void cadenasAMinusculas(char cadena1[], char cadena2[]); void coincidenciasEntreCadenas(char cadena1[], char cadena2[]); void contarVocalesEnCadena(char cadena[]); int main() { char cadena1[LONGITUD_CADENA]; char cadena2[LONGITUD_CADENA]; char opcion; ingresarCadenas(cadena1, cadena2); printf("\n\t"); system("pause&cls"); do { imprimirCadenas(cadena1, cadena2); fflush(stdin); /// Limpia el buffer del teclado printf("\n >> Opciones :\n"); printf("\n\ta) Convertir ambas a mayusculas"); printf("\n\tb) Convertir ambas a minusculas"); printf("\n\tc) Contar cantidad de vocales en las palabras"); printf("\n\td) Indicar letras en comun entre las palabras"); printf("\n\te) Ingresar otras palabras"); printf("\n\tf) Salir del programa"); printf("\n\n >> Elija un opcion : "); scanf("%c", &opcion); system("cls"); switch (opcion) { case 'a': cadenasAMayusculas(cadena1, cadena2); imprimirCadenas(cadena1, cadena2); break; case 'b': cadenasAMinusculas(cadena1, cadena2); imprimirCadenas(cadena1, cadena2); break; case 'c': contarVocalesEnCadena(cadena1); contarVocalesEnCadena(cadena2); break; case 'd': imprimirCadenas(cadena1, cadena2); coincidenciasEntreCadenas(cadena1, cadena2); break; case 'e': fflush(stdin); ingresarCadenas(cadena1, cadena2); break; case 'f': printf("\n >>> No hay marcha atras !\n"); break; default: /// Simplemente se repite el bucle break; } printf("\n\t"); system("pause&cls"); } while (opcion != 'f'); return 0; } void ingresarCadenas(char cadena1[], char cadena2[]) { printf(" >> Ingresar palabra 1 : "); gets(cadena1); printf("\n >> Ingresar palabra 2 : "); gets(cadena2); } void imprimirCadenas(char cadena1[], char cadena2[]) { printf(" >> Palabra 1: %s\n", cadena1); printf(" >> Palabra 2: %s\n", cadena2); } void cadenasAMayusculas(char cadena1[], char cadena2[]) { int i; for (i = 0; cadena1[i] != '\0'; i++) cadena1[i] = toupper(cadena1[i]); /// Convierte a mayuscula el caracter for (i = 0; cadena2[i] != '\0'; i++) cadena2[i] = toupper(cadena2[i]); /// Convierte a mayuscula el caracter } void cadenasAMinusculas(char cadena1[], char cadena2[]) { int i; for (i = 0; cadena1[i] != '\0'; i++) cadena1[i] = tolower(cadena1[i]); /// Convierte a minuscula el caracter for (i = 0; cadena2[i] != '\0'; i++) cadena2[i] = tolower(cadena2[i]); /// Convierte a minuscula el caracter } void contarVocalesEnCadena(char cadena[]) { int a = 0, e = 0, i = 0, o = 0, u = 0; int j; for (j = 0; cadena[j] != '\0'; j++) { if (cadena[j] == 'a' || cadena[j] == 'A') a++; else if (cadena[j] == 'e' || cadena[j] == 'E') e++; else if (cadena[j] == 'i' || cadena[j] == 'I') i++; else if (cadena[j] == 'o' || cadena[j] == 'O') o++; else if (cadena[j] == 'u' || cadena[j] == 'U') u++; } printf("\n >> Palabra : %s\n", cadena); printf("\n\t >>> Vocales -> { a=%d, e=%d, i=%d, o=%d, u=%d }\n", a, e, i, o, u); } void coincidenciasEntreCadenas(char cadena1[], char cadena2[]) { char coincidencias[LONGITUD_CADENA]; int i, j, comunes = 0; for (i = 0; cadena1[i] != '\0'; i++) { for (j = 0; cadena1[j] != '\0'; j++) { if (cadena1[i] == cadena2[j]) { int l, repetido = 0; /// Si "repetido" es 1 entonces cadena1[i] ya esta dentro e las coincidencias for (l = 0; coincidencias[l] != '\0'; l++) { if (cadena1[i] == coincidencias[l]) { /// Busqueda de coincidencia en el arreglo "coincidencias" /// para evitar repetidos repetido = 1; break; } } if (repetido == 0) { /// Si "repetido" es 0 entonces se agrega una nueva coincidencia coincidencias[comunes] = cadena1[i]; comunes++; } break; } } } printf("\n >>> Caracteres en comun entre las palabras : { "); for (i = 0; i < comunes; i++) { printf("%c%s", coincidencias[i], ((i < comunes - 1) ? ", " : " ")); } printf("}\n\n >>> Cantidad de coincidencias : %d\n", comunes); }