language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* * NAME: Megan Chu * ID: A12814536 * LOGIN: cs12waot */ /* * Filename: hw5_C.c * Author: Megan Chu * Userid: A12814536 * Login: cs12waot * Description: allows user to specify array size, input elements in array, * and return the location and value of the maximum value * Date: Feburary 13, 2017 * Source of Help: Links from HW5 writeup * * NOTE: Need to press enter after entering each number before entering * next number * */ #include <stdio.h> /* function declaration */ /* Returns the index of max element */ int max_elem_location(int[], int); /* * Function prototype: int main() * Description: Main driver function. * Parameters: None. * Side Effects: Read from stdin and print to stdout * Error Conditions: None. * Return Value: 0 indicating successful termination */ int main() { int location; // index of largest element int size; // size of array int toAdd; // to fill array printf("Enter the number of elements that will be in the array\n"); scanf("%d", &size); // get an input (size of the array) from a user int input[size]; printf("Enter %d integers\n", size); //prompt for the numbers int i; int i; for(i = 0; i < size; i++) // add to an array { scanf("%d", &toAdd); // sets variable to user input input[i] = toAdd; // set array index to variable } location = max_elem_location(input, size); // find index of largest integer int value = input[location]; // store value of largest integer printf("Max element location = %d and value = %d.\n", location + 1, value); return 0; } /* * Function prototype: int int max_elem_location(int a[], int n) * Description: function to get the location (index) of the maximum element * in an array * Parameters: arg1 - int a[] -- the input array to be searched * arg2 - int n -- the size (length) of array * Side Effects: None. * Error Conditions: None. * Return Value: the location (index) of the maximum element in such array */ int max_elem_location(int a[], int n) { int i; int returnVal = a[0]; int returnInd = 0; for(i = 1; i < n; i++) // loop through array { if(a[i]>=returnVal) // if value at index greater than stored value { returnVal = a[i]; // store value at index returnInd = i; // set index to return } } return returnInd; }
C
/* 目的:递归函数 输入输出格式说明: 1,每一行末尾可见字符后面没有不可见字符; 2,每一行的末尾都有一个换行符,但是最后一行没有换行符; 3,如果只有一行,则末尾没有换行符; 4,所有标点符号均为西文标点符号。 题目描述:Collatz conjecture,又称为奇偶归一猜想、3n+1猜想:是指对于每一个正整数, 如果它是奇数,则对它乘3再加1,如果它是偶数,则对它除以2,如此循环,最终都能够得到1。 程序接受一输入正整数,设计递归函数计算f(n): f(n) = n/2 如果n为偶数 f(n) = 3*n+1 如果n为奇数 程序每调用一次,输出计算后的值。如果值不等于1,继续调用函数计算,直到函数值等于1为止。 程序记录调用函数的次数(可以在函数中定义一static变量来记录)。 程序输出的中间结果以一个空格分隔,最后打印输出函数调用的次数,末尾无换行。 输入样例: 10 输出样例:(最后一个数6是函数递归调用的次数,前面正好是6次调用所得的函数值。) 5 16 8 4 2 1 6 */ #include<stdio.h> void collatz(int n); int main() { int n; scanf("%d", &n); collatz(n); return 0; } void collatz(int n) { static int steps = -1; // Record the number of steps steps++; if (n == 1) { //printf("1 "); printf("%d", steps); // print out the steps at the end of process } else if (n % 2 == 0) // in case of even number { printf("%d ", n / 2); collatz(n / 2); } else // in case of odd number { printf("%d ", 3 * n + 1); collatz(3 * n + 1); } }
C
#include<stdio.h> #include<assert.h> char student_marks[10] = {20, 45, 49,50,42,23,1,18,34,33}; int add_grace(int marks); int main(){ int i,add,marks; for (i=0;i<10;i++) if(student_marks[i]!=50){ marks=add_grace(student_marks[i]); student_marks[i]=marks; } for (i=0;i<10;i++){ printf("%d", student_marks[i]); printf("\n"); } assert(add_grace(45) == 47); assert(add_grace(44) == 47); assert(add_grace(33) == 38); assert(add_grace(00) == 25); assert(add_grace(11) == 15); assert(add_grace(15) == 25); return 0; } int add_grace(int marks){ if(marks==49) return marks+1; if(marks>=45&&marks<49) return marks+2; if(marks>=40&&marks<=44) return marks+3; if(marks>=35&&marks<=39) return marks+4; if(marks>=30&&marks<=34) return marks+5; if(marks>=25&&marks<=29) return marks+6; if(marks<25) return marks+25; }
C
#include <stdio.h> int main() { int a,b, year = 0; do { printf("nhap vao tuoi cha :"); scanf("%d", &a); printf("nhap vao tuoi con :"); scanf("%d", &b); while(a != 2*b) { a++; b++; year++; } printf("vay sau %d thi tuoi cha gap 2 lan tuoi con", year); } while(a < 2*b); return 0; }
C
#include "test_libft.h" static int int_test(ssize_t i, char *text) { int rs0; int rs1; (void)text; i = 0; while (i < BUFF_SIZE) { rs0 = ft_isalnum(g_buff0[i]); rs1 = isalnum(g_buff0[i]); if (!((!rs0 && !rs1) || (rs0 && rs1))) { PRINT_FAIL; } i++; } PRINT_OK; return (1); } int test_isalnum(void) { int i = -1; int j = -300; char *name = "ft_isalnum"; while (++i < BUFF_SIZE) g_buff0[i] = j++; PRINT_NAME(name); TEST(int_test, name, 0, "-300 a 700"); return (0); }
C
#include<stdio.h> #include<stdlib.h> #define MAXLINE 1000 #define MAXCHLD 10 typedef struct node{ char ch; int stat; struct node *chld[MAXCHLD]; }node_t; node_t *new_node(){ node_t *node=(node_t *)malloc(sizeof(node_t)); node->stat=-1; for (int i=0;i<MAXCHLD;i++) node->chld[i]=NULL; return node; } node_t *str2tree(char s[]){ node_t *root,*st[MAXLINE]; int top=-1; for (int i=0;s[i];i++){ node_t *node; switch (s[i]){ case '(': st[++top]=node; st[top]->stat=0; break; case ',': st[top]->stat++; break; case ')': top--; break; default:{ node=new_node(); node->ch=s[i]; if (top==-1) root=node; else st[top]->chld[st[top]->stat]=node; }; } } return root; } node_t *tree2btree(node_t *t){ if (t==NULL || t->stat==-1) return t; for (int i=0;i<=t->stat;i++) tree2btree(t->chld[i]); for (int i=t->stat;i>=1;i--){ t->chld[i-1]->chld[1]=t->chld[i]; t->chld[i-1]->stat=1; t->chld[i]=NULL; } t->stat=0; return t; } void print(node_t *p){ if (p==NULL) return; else{ printf("%c",p->ch); if (p->stat==-1) return; printf("("); print(p->chld[0]); for (int i=1;i<=p->stat;i++){ printf(","); print(p->chld[i]); } printf(")"); } } node_t *merge_tree(node_t *t1,node_t *t2){ if (t1==NULL) return t2; if (t2==NULL) return t1; node_t *p=t1; while (p->stat==1) p=p->chld[p->stat]; p->stat=1; p->chld[1]=t2; return t1; } int main(int argc,char **argv){ node_t *btree=NULL; for (int i=1;i<argc;i++){ btree=merge_tree(btree,tree2btree(str2tree(argv[i]))); } print(btree); return 0; }
C
// // Sudoku.c // // // Created by Paul Adeyemi on 08.11.13. // // #include <stdio.h> #include <stdlib.h> #include <string.h> int sudokuarr[9][9]; int main() { int check=0; char c; char filepath[50]; int i, j; do { //Menü printf("Auswahl:\n(a)Test Raetzel 1\n(b)Test Raetzes 2\n(c)Filename Eingeben\n(e)Beenden\n"); scanf("%s",&c); switch (c) { case 'a' : raetsel1(); ausgabe(); //Wenn Sudoku Lösbar, dann ausgabe von gelöstem Sudoku // sonst ausgabe "NO SOLUTION" if(fillsudoku(sudokuarr, 0, 0)){ printf("Loesung:\n\n"); ausgabe(); } else{ printf("NO SOLUTION\n\n"); } break; case 'b' : raetsel2(); ausgabe(); //Wenn Sudoku Lösbar, dann ausgabe von gelöstem Sudoku // sonst ausgabe "NO SOLUTION" if(fillsudoku(sudokuarr, 0, 0)){ printf("Loesung:\n\n"); ausgabe(); }else{printf("NO SOLUTION\n\n");} break; case 'c' : filetoarray(); ausgabe(); //Wenn Sudoku Lösbar, dann ausgabe von gelöstem Sudoku // sonst ausgabe "NO SOLUTION" if(fillsudoku(sudokuarr, 0, 0)){ printf("Loesung:\n\n"); ausgabe(); }else{printf("NO SOLUTION\n\n");} break; case 'e': check=1; break; default: printf("\nFalsche Eingabe\n\n"); break; } fflush(stdin); } while (check==0); return EXIT_SUCCESS; } /** * Funktion gibt den Aktuellen Array aus */ int ausgabe(){ int i,j; for(i=0; i<9; ++i){ for(j=0; j<9; ++j) printf("%d ", sudokuarr[i][j]); printf("\n"); } } /** * Funktion liest file ein, und wandelt dessen Inhalt in ein Array um * * */ int filetoarray(void){ FILE *pInput; //open file char name[40]; printf("Which file do you want to read from? \n "); scanf("%s", name); pInput = fopen(name, "r"); char puffer[20]; int colum = 0, row = 0; char delimiter[] = ",;"; char *ptr; //Algorithmus zum einlesen eines Files in ein Array while (fgets(puffer, 20, pInput)) { ptr = strtok(puffer, delimiter); while (ptr != NULL) { sudokuarr[colum][row] = atoi(ptr); ptr = strtok(NULL, delimiter); row++; } row = 0; colum = colum + 1; } return 0; } /** * Funktion wandelt ein vorgefertigtes CSV File "raetsel1.csv" in einen Array um */ int raetsel1(void){ FILE *pInput; //open file char *name="./raetsel1.csv"; pInput = fopen(name, "r"); char puffer[20]; int colum = 0, row = 0; char delimiter[] = ",;"; char *ptr; //Algorithmus zum einlesen eines Files in ein Array while (fgets(puffer, 20, pInput)) { ptr = strtok(puffer, delimiter); while (ptr != NULL) { sudokuarr[colum][row] = atoi(ptr); ptr = strtok(NULL, delimiter); row++; } row = 0; colum = colum + 1; } return 0; } /** * Funktion wandelt ein vorgefertigtes CSV File "raetsel2.csv" in einen Array um */ int raetsel2(void){ FILE *pInput; //open file char *name="./raetsel2.csv"; pInput = fopen(name, "r"); char puffer[20]; int colum = 0, row = 0; char delimiter[] = ",;"; char *ptr; //Algorithmus zum einlesen eines Files in ein Array while (fgets(puffer, 20, pInput)) { ptr = strtok(puffer, delimiter); while (ptr != NULL) { sudokuarr[colum][row] = atoi(ptr); ptr = strtok(NULL, delimiter); row++; } row = 0; colum = colum + 1; } return 0; }
C
#include<conio.h> #include<stdio.h> #define max 100 void equation(int [],int); int main() { int a[max],i,n; clrscr(); printf("Enter the limit\n"); scanf("%d",&n); printf("Enter the numbers\n"); for(i=0;i<n;i++) scanf("%d",&a[i]); equation(a,n); getch(); return; } void equation(int a[],int n) { int i,j,k,p,q,r; for(k=0;k<n;k++) { for(i=0;i<n;i++) { for(j=0;j<n;j++) { p=a[i]*a[i]; q=a[j]*a[j]; r=a[k]*a[k]; if((p+q)==r) { printf("%d %d %d",i,j,k); getch(); exit(); } } } } }
C
#include "holberton.h" /** * is_palindrome - the function return palindrome. *@s: char the pointer * Return: Always 0. */ int is_palindrome(char *s) { int length; length = lengthc(s); if (length == 0) { return (1); } return (validate_palindrome(s, 0, length - 1)); } /** * lengthc - the function longtitu. *@str: char the pointer * Return: Always 0. */ int lengthc(char *str) { if (!!*str) { return (1 + lengthc(str + 1)); } return (0); } /** * validate_palindrome- the function for validate. *@str: char *@ini: integer *@fin: integer * Return: Always 0. */ int validate_palindrome(char str[], int ini, int fin) { if (ini >= fin) { return (1); } if (str[ini] != str[fin]) { return (0); } if (ini <= fin || ini < fin + 1) { return (validate_palindrome(str, ++ini, --fin)); } return (1); }
C
#include <stdio.h> #include "wich.h" /* translation of Wich code: func f() { var x = "cat" + "dog" print(x) print(x[1]+x[3]) // x[i] returns a String with one character in it } f() */ void f() { // var x = "cat" + "dog" String *tmp1; String *tmp2; String *x = String_add(tmp1=String_new("cat"), tmp2=String_new("dog")); // print(x) print_string(x); // print(x[1]+x[3]) String *tmp3; String *tmp4; String *tmp5; print_string( tmp5=String_add( tmp3=String_from_char(x->str[(1)-1]), tmp4=String_from_char(x->str[(3)-1]) ) ); // end of scope code; drop ref count by 1 for all [], string vars DEREF(x); DEREF(tmp1); DEREF(tmp2); DEREF(tmp3); DEREF(tmp4); DEREF(tmp5); } int main(int argc, char *argv[]) { f(); }
C
#include"MyHeader.h" int main(int argc, char const *argv[]) { int iBrr[10]; int iCnt=0; for(iCnt=0;iCnt<10;iCnt++) { printf("Enter number at brr[%d]:",iCnt); scanf("%d",&iBrr[iCnt]); } DisplayReverse(iBrr,10); return 0; }
C
/*14.Construye un programa que permita ingresar las medidas de los lados de un rectángulo;el mismo debe emitir por pantalla su superficie y su perímetro.*/ #include <stdio.h> int main() { float lado_1, lado_2; printf("Por favor, Ingrese la medida del primer lado del rectángulo\n"); scanf("%f", &lado_1); printf("Ahora, ingrese la medida del segundo lado del rectángulo\n"); scanf("%f", &lado_2); float perimetro = lado_1*2 + lado_2*2; float superficie= (lado_1*lado_2); printf("El perímetro del rectángulo es de %.2f", perimetro, "cm.\n"); printf("La superficie del rectángulo es de %.2f", superficie, "cm.\n"); return 0; };
C
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(void) { float m, mm, cm, dm, km; char ch; printf("Nhap vao do dai tinh theo met:\n"); scanf("%f", &m); printf("Chon don vi de doi: 1.mm, 2.cm, 3.dm, 4.km\n"); scanf("%c", &ch); ch = getchar(); m = m/1000; cm = m/100; dm = m/10; km = m*1000; switch(ch) { case '1': printf("Do dai tinh theo mm la: %f", mm); break; case '2': printf("Do dai tinh theo cm la:%f", dm); break; case '3': printf("Do dai tinh theo dm la:%f", dm); break; case '4': printf("Do dai tinh theo km la:%f", km); break; } }
C
// // main.c // BFS // // Created by 권택준 on 2020/04/06. // Copyright © 2020 권택준. All rights reserved. // #include <stdio.h> #include <stdlib.h> #define MAX_SIZE 1001 typedef struct _NODE{ int index; struct _NODE * next; }Node; typedef struct _queue{ Node * front; Node * rear; int count; }Queue; Node ** a; int c[MAX_SIZE]; void addfront(Node * root , int index){ Node * node = (Node *)malloc(sizeof(node)); node -> index = index; node -> next = root -> next; root -> next = node; } void queuePush(Queue * queue, int index){ Node * node = (Node *)malloc(sizeof(Node)); node -> index = index; node -> next = NULL; if(queue -> count == 0){ queue -> front = node; } else{ queue -> rear -> next = node; } queue -> rear = node; queue -> count++; } int queuePop(Queue * queue){ if(queue -> count == 0){ printf("큐 언더플로우"); return -9999; } Node * node = queue -> front; int index = node -> index; queue -> front = node -> next; free(node); queue -> count--; return index; } void bfs(int start){ Queue q; q.front = q.rear = NULL; q.count = 0; queuePush(&q, start); c[start] = 1; while(q.count != 0){ int x = queuePop(&q); printf("%d ",x); Node * cur = a[x] -> next; while(cur != NULL){ int next = cur -> index; if(!c[next]){ queuePush(&q, next); c[next] = 1; } cur = cur -> next; } } } int main(int argc, const char * argv[]) { // insert code here... int n,m; int x,y; scanf("%d %d",&n,&m); a = (Node **)malloc(sizeof(Node *) * MAX_SIZE); for(int i = 1; i <= n; i++){ a[i] = (Node *)malloc(sizeof(Node)); a[i] -> next = NULL; } for(int i = 0; i<m; i++){ scanf("%d %d",&x,&y); addfront(a[x], y); addfront(a[y], x); } bfs(1); return 0; }
C
// test single linked list implementation #include <stdio.h> #include <stdlib.h> struct node { int val; struct node *next; } *head = NULL; void list_insert(int x) { struct node *new_node; new_node = (struct node*)malloc(sizeof(struct node*)); new_node->val = x; if(head == NULL) { new_node->next = NULL; head = new_node; }else { new_node->next = head; head = new_node; } printf("\nNode inserted successfully at beginning\n"); } void list_search(int x) { while (head != NULL) { if(head->val == x) { printf("The key is found in the list\n"); return; } head = head->next; } printf("The Key is not found in the list\n"); } void list_remove() { if(head == NULL) printf("List is empty") ; else { struct node *temp = head; if(head->next == NULL){ head = NULL; free(temp); }else{ head = temp->next; free(temp); printf("\nNode deleted at the beginning\n\n"); } } } void list_remove_end() { if(head == NULL) printf("List is empty"); else { struct node *temp1 = head,*temp2; if(head->next == NULL) head = NULL; else { while (temp1->next != NULL) { temp2 = temp1; temp1 = temp1->next; } temp2->next = NULL; } free(temp1); printf("\nNode deleted at the end\n\n"); } } int main() { int n, choice, val, key; while(1) { printf("\n\nSingly Linked List Operations\n"); printf("1. Insert at beginning\n 2.Delete at beginning\n 3.Delete list at the end\n 4.Search\n 5. Display\n 6. Exit\n\nEnter your choice: "); scanf("%d", &choice); switch (choice){ case 1: printf("Enter the value to be insert: "); scanf("%d", &val); list_insert(val); break; case 2: list_remove(); break; case 3: list_remove_end(); break; case 4: printf("Enter the value which you want to search: "); scanf("%d", &key); list_search(key); break; case 5: break; case 6: exit(0); default: printf("\nWrong Choice, Please try again\n\n"); break; } } return 0; }
C
/* * LEDCube.c * * Created: 2017. 12. 17. 0:03:49 * Author : zoltan */ #define F_CPU 1000000UL #define DELAY 200 #define LED_LOW_DDR DDRA #define LED_HIGH_DDR DDRC #define LED_LOW PORTA #define LED_HIGH PORTC #define LAYERS PORTD #define LAYERS_DDR DDRD #include <avr/io.h> #include <avr/interrupt.h> #include <util/delay.h> #include <stdio.h> #include <stdlib.h> #include <time.h> static uint16_t cube[4] = {0x0001, 0x0001, 0x0001, 0x0001}; static uint8_t matrix[4][4][4]; //Berja a LED-et a cube tmbbe, de nem kapcsolja be void addLED(uint8_t n) { if ( (n % 16) > 7 ) cube[n/16] |= ( ((n%16)-8) << 2 ); else cube[n/16] |= (n%16); } //Trli a LED-et a cube tmbb?l, de nem kapcsolja ki void removeLED(uint8_t n) { if ( (n % 16) > 7 ) cube[n/16] &= ~( ((n%16)-8) << 2 ); else cube[n/16] &= ~(n%16); } //N. LED bekapcsolsa void setLED(uint8_t n) { LAYERS = (1 << (n / 16)); if ( (n % 16) > 7 ) { LED_HIGH |= (1 << ( (n%16) - 8) ); } else { LED_LOW |= (1 << (n%16)); } } //N. LED kikapcsolsa void resetLED(uint8_t n) { LAYERS = (1 << (n / 16)); if ( (n % 16) > 7 ) { LED_HIGH &= ~(1 << ( (n%16) - 8) ); } else { LED_LOW &= ~(1 << (n%16)); } } //LED-ek belltsa cube tmb alapjn void showPattern() { uint8_t i; for (i = 0; i < 4; i++) { LAYERS = (1 << i); LED_LOW = cube[i] & 0x00FF; LED_HIGH = (cube[i] & 0xFF00) >> 8; //_delay_ms(4); } } // int main(void) { //A, C, D portok --> kimenet LED_LOW_DDR = 0xFF; //LED-ek 0..7 LED_HIGH_DDR = 0xFF; //LED-ek 8..15 LAYERS_DDR = 0x0F; //Rtegek 0..4 //JTAG kikapcsolva MCUCSR |= (1<<JTD); uint8_t r1, r2; time_t t; srand((unsigned) time(&t)); while (1) { r1 = rand()%63; setLED(r1); _delay_ms(300); r2 = rand()%63; setLED(r2); _delay_ms(300); resetLED(r1); _delay_ms(300); resetLED(r2); _delay_ms(300); } }
C
/* * heapalloc.c * Copyright: 1997 Advanced RISC Machines Limited. All rights reserved. */ /* * $RCSfile: app_kernel/heapalloc.c $ * $Revision: 1.4 $ * $Date: 2006/02/24 12:02:09EST $ */ #include <stdlib.h> // Necessary for heap.h to include the correct heap1a information. The only software // available for download was of heap type 1, so this is your only choice. If this isn't // defined, nothing will be included and the attempt later on to define a heap descriptor // will fail. #include "heap.h" #define heapDescPtr __rt_heapdescriptor() extern Heap_Descriptor *__rt_heapdescriptor(void); //extern Heap_Descriptor *__rt_embeddedalloc_init(void *base, size_t size); extern void __rt_embeddedalloc_init(Heap_Descriptor *, void *base, size_t size); #ifdef HEAP_DEBUG void *HEAP_LinkRegisterValue = 0; extern void *operator new(size_t n) { size_t NewSize = n; __asm { mov r0,&HEAP_LinkRegisterValue str lr,[r0] } void *p = malloc(NewSize == 0 ? 1 : n); HEAP_LinkRegisterValue = 0; return p; } extern void operator delete(void *p) { free( p ); } #endif //extern Heap_Descriptor *__rt_embeddedalloc_init(void *base, size_t size) //{ // if (size <= sizeof(Heap_Descriptor)) // return NULL; // else // { Heap_Descriptor *hd = (Heap_Descriptor *)base; // Heap_Initialise(hd, NULL, NULL, NULL, NULL); // Heap_InitMemory(hd, hd+1, size - sizeof(Heap_Descriptor)); // return hd; // } //} extern void __rt_embeddedalloc_init(Heap_Descriptor *HeapDesc, void *base, size_t size) { Heap_Initialise(HeapDesc, NULL, NULL, NULL, NULL); Heap_InitMemory(HeapDesc, base, size); return; } /* <malloc> * Allocate the given number of bytes - return 0 if fails */ extern "C" void *malloc(size_t size) { size_t NewSize = size; #ifdef HEAP_DEBUG if( HEAP_LinkRegisterValue == 0 ) { __asm { mov r0,&HEAP_LinkRegisterValue str lr,[r0] } } #endif void *p = ( NewSize != 0 ) ? Heap_Alloc(heapDescPtr, NewSize) : NULL; #ifdef HEAP_DEBUG HEAP_LinkRegisterValue = 0; #endif return p; } /* <free> * Free the given block of bytes */ extern "C" void free(void *p) { if (p != NULL) { Heap_Free(heapDescPtr, p); } } extern "C" void *realloc(void *p, size_t size) { return p == NULL ? Heap_Alloc(heapDescPtr, size) : Heap_Realloc(heapDescPtr, p, size); } #include <string.h> /* <calloc> * Alloc a zero-filled block count*size bytes big */ extern "C" void *calloc(size_t count, size_t size) { void *r; /* * This code computes the 64 bit product of count * size to * verify that the product really is in range. */ unsigned m1 = (count >> 16) * (size & 0xffff); unsigned m2 = (count & 0xffff) * (size >> 16); unsigned len = (count & 0xffff) * (size & 0xffff); if ((m1 | m2) >> 16) return NULL; m1 += m2; if (m1 + (len >> 16) >= 0x10000) return NULL; len += m1 << 16; r = malloc(len); if (r != NULL) memset(r, 0, len); return r; } extern void __heapstats(int (*dprint)(char const *format, ...)) { Heap_Stats(dprint, heapDescPtr); } /* End of file heapalloc.c */
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_2__ TYPE_1__ ; /* Type definitions */ struct TYPE_2__ {int blkalgn; } ; /* Variables and functions */ scalar_t__ ar_next () ; int ar_write (scalar_t__,int) ; int blksz ; scalar_t__ buf ; scalar_t__ bufend ; scalar_t__ bufpt ; int exit_val ; TYPE_1__* frmt ; int /*<<< orphan*/ memcpy (scalar_t__,scalar_t__,int) ; int /*<<< orphan*/ paxwarn (int /*<<< orphan*/ ,char*) ; scalar_t__ wrcnt ; scalar_t__ wrlimit ; int buf_flush(int bufcnt) { int cnt; int push = 0; int totcnt = 0; /* * if we have reached the user specified byte count for each archive * volume, prompt for the next volume. (The non-standard -R flag). * NOTE: If the wrlimit is smaller than wrcnt, we will always write * at least one record. We always round limit UP to next blocksize. */ if ((wrlimit > 0) && (wrcnt > wrlimit)) { paxwarn(0, "User specified archive volume byte limit reached."); if (ar_next() < 0) { wrcnt = 0; exit_val = 1; return(-1); } wrcnt = 0; /* * The new archive volume might have changed the size of the * write blocksize. if so we figure out if we need to write * (one or more times), or if there is now free space left in * the buffer (it is no longer full). bufcnt has the number of * bytes in the buffer, (the blocksize, at the point we were * CALLED). Push has the amount of "extra" data in the buffer * if the block size has shrunk from a volume change. */ bufend = buf + blksz; if (blksz > bufcnt) return(0); if (blksz < bufcnt) push = bufcnt - blksz; } /* * We have enough data to write at least one archive block */ for (;;) { /* * write a block and check if it all went out ok */ cnt = ar_write(buf, blksz); if (cnt == blksz) { /* * the write went ok */ wrcnt += cnt; totcnt += cnt; if (push > 0) { /* we have extra data to push to the front. * check for more than 1 block of push, and if * so we loop back to write again */ memcpy(buf, bufend, push); bufpt = buf + push; if (push >= blksz) { push -= blksz; continue; } } else bufpt = buf; return(totcnt); } else if (cnt > 0) { /* * Oh drat we got a partial write! * if format doesn't care about alignment let it go, * we warned the user in ar_write().... but this means * the last record on this volume violates pax spec.... */ totcnt += cnt; wrcnt += cnt; bufpt = buf + cnt; cnt = bufcnt - cnt; memcpy(buf, bufpt, cnt); bufpt = buf + cnt; if (!frmt->blkalgn || ((cnt % frmt->blkalgn) == 0)) return(totcnt); break; } /* * All done, go to next archive */ wrcnt = 0; if (ar_next() < 0) break; /* * The new archive volume might also have changed the block * size. if so, figure out if we have too much or too little * data for using the new block size */ bufend = buf + blksz; if (blksz > bufcnt) return(0); if (blksz < bufcnt) push = bufcnt - blksz; } /* * write failed, stop pax. we must not create a bad archive! */ exit_val = 1; return(-1); }
C
#include<stdio.h> int main(void) { char string[]="DigitalSeries"; int i=0; while (string[i] != '0'){ i++; } printf("%d\n", i); return 0; }
C
#include <mpi.h> #include <stdio.h> #include <stdlib.h> /* time measurement for MPI_Bsend */ int main(int argc, char** argv) { MPI_Init(NULL, NULL); int a = 1; while(a < 256*256*256){ int world_rank; MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); int world_size; MPI_Comm_size(MPI_COMM_WORLD, &world_size); int size = a; char *buf = (char *)malloc(sizeof(int)*size*2+100); int bufsize = size*2+100; double t1; double t2; if (world_size < 2) { fprintf(stderr, "World size must be greater than 1 for %s\n", argv[0]); MPI_Abort(MPI_COMM_WORLD, 1); } int *data; data = malloc((sizeof(int))*size); if (world_rank == 0) { t1 = MPI_Wtime(); int b = 500; while (b--) { MPI_Buffer_attach(buf, bufsize); MPI_Bsend(data, size, MPI_INT, 1, 0, MPI_COMM_WORLD); MPI_Buffer_detach(buf, &bufsize); MPI_Recv(data, size, MPI_INT, 1, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } t2 = MPI_Wtime(); printf("%f\n", t2-t1); } else if (world_rank == 1) { int b = 500; while (b--) { MPI_Recv(data, size, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Buffer_attach(buf, bufsize); MPI_Bsend(data, size, MPI_INT, 0, 1, MPI_COMM_WORLD); MPI_Buffer_detach(buf, &bufsize); } } free(buf); free(data); a*=2; } MPI_Finalize(); }
C
#ifndef __TEST_MACRO_DEFINE_H__ #define __TEST_MACRO_DEFINE_H__ #define offsetof(type, member) ((unsigned long)(&((type *)0)->member)) #define member_entry(ptr, type, member) \ ((unsigned long)((char *)(ptr)+ offsetof(type, member)) #define member_size(type, member) (sizeof((type *)0)->member) #define struct_pad_dump(type_name, cur_member, next_ofs, pad_count) do {\ unsigned int cur_ofs = offsetof(type_name, cur_member);\ unsigned int cur_size = member_size(type_name, cur_member);\ unsigned int cur_tail = offsetof(type_name, cur_member) + member_size(type_name, cur_member);\ if(next_ofs > cur_tail){\ unsigned int pad_size = (next_ofs - cur_tail);\ pad_count+= pad_size;\ printf("[%d]%s\t:%08X %d -> %08X\n", cur_size, #cur_member, cur_ofs, pad_size, next_ofs);\ } else {\ printf("[%d]%s\t:%08X\n", cur_size, #cur_member, cur_ofs);\ }\ } while(0) #endif
C
#include<stdio.h> void main() { int num=0; scanf("%d",&num); int b=num; int i=0; int c[20]; while(b!=0) { c[i]=b%2; b=b/2; i++; } for(int j=i-1;j>=0;j--) { printf("%d",c[j]); } }
C
#include "shell.h" /** * Upath - Find path * @av: Double pointer to free * @env: Environment * @arv: Command * @x_av: Integer lenght command * @pfid: Integer pointer * * Description: Find path * Return: Nothing */ void Upath(char **av, char *env, char *arv, int x_av, int *pfid) { int x = 0, start, c_path = 0; char *s = "PATH", *exe, **path; for (x = 0; env[x] == s[x] && env[x] != '='; x++) ; if (x == 4) *pfid = 1; start = ++x; if (*pfid) { for (; env[x]; x++) { if (env[x] == ':') c_path++; } path = malloc(sizeof(char *) * (c_path + 2)); exe = path[fndp(c_path, &env[start], arv, x_av, start, path)]; if (!exe) { _free(path); return; } x = _strlen(exe); free(av[0]); av[0] = malloc(sizeof(char) * (x + 1)); x = 0; while (exe[x]) av[0][x] = exe[x], x++; av[0][x] = '\0'; x = 0; while (path[x] != NULL) free(path[x++]); free(path); } }
C
/* * util.c * * Status: T * * Created on: Feb 3, 2017 * Author: Fred * * Contains helper function implementations */ #include "util.h" /* Simple function to check if input is changed from last_value by at least threshold amount*/ BOOL int32U_changed_by_threshold(INT32U input, INT32U last_value, INT32U threshold) { if (input > last_value && input - last_value > threshold) return TRUE; if (last_value > input && last_value - input > threshold) return TRUE; return FALSE; } /* Simple function to check if two inputs differ by a certain percent * percent is input as an integer and it's accurate to * for example, to check 10 percent, input number 10 * the actual accuracy is defined by PERCENT_DIFF_ACCURACY */ BOOL int32U_differ_by_percent(INT32U src1, INT32U src2, INT32U percent, INT32U accuracy) { INT32U larger; INT32U smaller; if (src1 > src2) { larger = src1; smaller = src2; } else { larger = src2; smaller = src1; } if (larger == 0) return FALSE; INT32U diff = larger - smaller; INT32U avg = (larger + smaller) >> 1; if(avg == 0) return FALSE; INT32U result = (diff * accuracy) / avg; INT32U threshold = percent * accuracy / 100; if (result <= threshold) return FALSE; else return TRUE; } pwm_gen_module* get_tps_sensor_output_pwm(){ return get_new_pwm_module(PWM_GENERATOR_TPS_OUT_AVALON_SLAVE_PERIOD_BASE, PWM_GENERATOR_TPS_OUT_AVALON_SLAVE_DUTY_BASE, PWM_GENERATOR_TPS_OUT_AVALON_SLAVE_CONTROL_BASE, TPS_OUT_PWM_PERIOD_TICKS, 0); } void clean_alarm(alt_alarm** alarm_ref){ alt_alarm* alarm = *alarm_ref; if(alarm == NULL) return; alt_alarm_stop(alarm); free(alarm); *alarm_ref = NULL; } INT32U calc_percent(INT32U dividend, INT32U divisor, INT32U scale_factor){ return divisor * scale_factor / dividend; }
C
#include <pksm.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <string.h> int main(int argc, char **argv) { unsigned char version = *argv[0]; enum Generation gen; switch (version) { case 35: // red case 36: // green[jp]/blue[int] case 37: // blue[jp] case 38: // yellow[jp] gen = GEN_ONE; break; case 39: // gold case 40: // silver case 41: // crystal gen = GEN_TWO; break; case 1: // ruby case 2: // sapphire case 3: // emerald case 4: // fire red case 5: // leaf green gen = GEN_THREE; break; case 10: case 11: case 12: case 7: case 8: gen = GEN_FOUR; break; case 20: case 21: case 22: case 23: gen = GEN_FIVE; break; case 24: case 25: case 26: case 27: gen = GEN_SIX; break; case 30: case 31: case 32: case 33: gen = GEN_SEVEN; break; case 42: case 43: gen = GEN_LGPE; break; default: gui_warn("Sorry this version isn't supported yet by the script!"); return 1; } int maxSpecies, maxMoves, maxBalls, maxItems, maxIV = 32, maxAbility, maxSlots, slotsPerBox; unsigned int randomizedCount, maxLevel; int gen_party = gui_choice("Do you want to inject into your party?\nThis Will Generate 6 PKMN"); if (gen_party == 1) { randomizedCount = 6; } else { maxSlots = sav_get_max(MAX_SLOTS); slotsPerBox = maxSlots / sav_get_max(MAX_BOXES); char part2[80] = {0}; sprintf(part2, "How many pokemon should be generated?\nPossible: 1-%d", maxSlots); gui_warn(part2); gui_numpad(&randomizedCount, "Number of PKMN to generate.", 3); if (randomizedCount > maxSlots || randomizedCount == 0) { sprintf(part2, "You've inputted an invalid number\nYou must generate between 1-%d pokemon!", maxSlots); gui_warn(part2); return 1; } } int gen_eggs = 0; if (gen != GEN_ONE) { gen_eggs = gui_choice("Do you want to generate eggs?\nThis is for EggLocke runs"); } gui_warn("Please enter the max level\nyou would like to have your pokemon be!"); gui_numpad(&maxLevel, "Max level 1-100", 3); if (maxLevel <= 0 || maxLevel > 100) { gui_warn("You must choose a level\nbetween 1-100!"); return 1; } int gen_shiny = gui_choice("Do you want to randomize shininess?\nThis may cause the script to run long"); switch (gen) { case GEN_ONE: maxSpecies = 151; maxMoves = 165; maxIV = 16; break; case GEN_TWO: maxSpecies = 251; maxMoves = 251; maxItems = 255; maxIV = 16; break; case GEN_THREE: maxSpecies = 386; maxItems = (version == 4 || version == 5) ? 374 : (version == 3 ? 376 : 348); maxMoves = 354; maxBalls = 12; maxAbility = 77; break; case GEN_FOUR: maxSpecies = 493; maxBalls = 24; maxMoves = 467; maxAbility = 123; maxItems = (version == 11 || version == 10) ? 464 : (version == 12 ? 467 : 536); break; case GEN_FIVE: maxSpecies = 649; maxBalls = 25; maxMoves = 559; maxAbility = 164; maxItems = (version == 20 || version == 21) ? 632 : 638; break; case GEN_SIX: maxSpecies = 721; maxBalls = 25; maxItems = (version == 26 || version == 27) ? 775 : 717; maxMoves = (version == 26 || version == 27) ? 621 : 617; maxAbility = (version == 26 || version == 27) ? 191 : 188; break; case GEN_SEVEN: maxBalls = 26; maxMoves = 720; maxSpecies = (version == 32 || version == 33) ? 807 : 802; maxMoves = (version == 32 || version == 33) ? 728 : 720; maxItems = (version == 32 || version == 33) ? 959 : 920; maxAbility = (version == 32 || version == 33) ? 233 : 232; break; case GEN_LGPE: gen = GEN_LGPE; maxSpecies = 153; maxBalls = 26; slotsPerBox = 30; break; default: gui_warn("How'd you get here?"); return 1; } int randNick = gui_choice("Do you want to randomize nicknames?\nThis could produce weirdness."); gui_splash("Generating pokemon\nThis might take awhile!"); sav_box_decrypt(); srand(time(0) + version); char *data = malloc(pkx_box_size(gen)); for (int i = 0; i < randomizedCount; i++) { // Species ID int pokemonID = rand() % maxSpecies + 1; if (gen == GEN_LGPE) { if (pokemonID == 152) { pokemonID = 808; } else if (pokemonID == 153) { pokemonID = 809; } } pkx_generate(data, pokemonID); // Level pkx_set_value(data, gen, LEVEL, rand() % maxLevel + 1); // IVs pkx_set_value(data, gen, IV_HP, rand() % maxIV); pkx_set_value(data, gen, IV_ATK, rand() % maxIV); pkx_set_value(data, gen, IV_DEF, rand() % maxIV); pkx_set_value(data, gen, IV_SPEED, rand() % maxIV); pkx_set_value(data, gen, IV_SPATK, rand() % maxIV); pkx_set_value(data, gen, IV_SPDEF, rand() % maxIV); // Nature if (gen != GEN_ONE && gen != GEN_TWO) { pkx_set_value(data, gen, NATURE, rand() % 25); } if (gen != GEN_ONE) { // Gender pkx_set_value(data, gen, GENDER, rand() % 3); // Pokerus pkx_set_value(data, gen, POKERUS, rand() % 16, rand() % 5); } // Since LGPE is weird, we can't really do extra stuff for it. if (gen != GEN_LGPE) { for (int ii = 0; ii < 4; ii++) { int moveNum = rand() % maxMoves + 1; while (!sav_check_value(SAV_VALUE_MOVE, moveNum)) { moveNum = rand() % maxMoves + 1; } // Move pkx_set_value(data, gen, MOVE, ii, moveNum); // PP int ppUps = rand() % 3 + 1; pkx_set_value(data, gen, PP_UPS, ii, ppUps); pkx_set_value(data, gen, PP, ii, (rand() % max_pp(gen, moveNum, ppUps)) + 1); } // Held Item if (gen != GEN_ONE) { int itemNum = rand() % maxItems + 1; while (!sav_check_value(SAV_VALUE_ITEM, itemNum)) { itemNum = rand() % maxItems + 1; } pkx_set_value(data, gen, ITEM, itemNum); } if (gen != GEN_ONE && gen != GEN_TWO) { // Ability pkx_set_value(data, gen, ABILITY, rand() % maxAbility + 1); // Capture Ball pkx_set_value(data, gen, BALL, rand() % maxBalls + 1); } } // Shiny Status if (gen_shiny) { pkx_set_value(data, gen, SHINY, rand() % 2); } if (randNick == 1) { // Nickname char *species1 = i18n_species(pokemonID); char *species2 = i18n_species(rand() % maxSpecies + 1); int l1 = strlen(species1) / 2; int l2 = strlen(species2) / 2; char *name = malloc(l1 + l2 + 1); memcpy(name, species1, l1); memcpy(name + l1, species2 + l2, strlen(species2) - l2); name[l1 + l2] = '\0'; pkx_set_value(data, gen, NICKNAME, name); free(name); } if (gen_eggs == 1) { pkx_set_value(data, gen, EGG, 1); } if (gen_party == 1) { party_inject_pkx(data, gen, i); } else { sav_inject_pkx(data, gen, i / slotsPerBox, i % slotsPerBox, 0); } } free(data); sav_box_encrypt(); return 0; }
C
// tjadanel - C Programming 2nd Ed. // Chapter 5 - Program Exercise 5.11 // This program takes a two digit number and writes it out #include <stdio.h> int main(void) { int d1, d2; printf("Enter a two-digit number: "); scanf("%1d%1d", &d1, &d2); printf("You entered the number "); if (d1 == 1){ switch (d2) { case 0: printf("ten"); break; case 1: printf("eleven"); break; case 2: printf("twelve"); break; case 3: printf("thirteen"); break; case 4: printf("fourteen"); break; case 5: printf("fiveteen"); break; case 6: printf("sixteen"); break; case 7: printf("seventeen"); break; case 8: printf("eightteen"); break; case 9: printf("nineteen"); break; } } else { switch (d1) { case 2: printf("twenty"); break; case 3: printf("thirty"); break; case 4: printf("fourty"); break; case 5: printf("fifty"); break; case 6: printf("sixty"); break; case 7: printf("seventy"); break; case 8: printf("eighty"); break; case 9: printf("ninety"); break; } switch (d2) { case 1: printf("-one"); break; case 2: printf("-two"); break; case 3: printf("-three"); break; case 4: printf("-four"); break; case 5: printf("-five"); break; case 6: printf("-six"); break; case 7: printf("-seven"); break; case 8: printf("-eight"); break; case 9: printf("-nine"); break; } } printf(".\n"); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <unistd.h> #include <string.h> int main(int argc, char **argv) { int opt; const char *optstr = "n:"; long count = -1; int current, i, primecount = 0; while ((opt = getopt(argc, argv, optstr)) != -1) { switch (opt) { case 'n': count = strtol(optarg, NULL, 0); break; case '?': exit(1); } } if (count <= 0) { exit(1); } char *sieve = malloc(sizeof(char) * count); memset(sieve, 1, sizeof(char) * count); current = 2; while (current < count) { if (sieve[current]) { primecount++; for (i = current*2; i < count; i+=current) { sieve[i] = 0; } } current++; } printf("const long prime_table[%d] = { 2", primecount); for (i = 3; i < count; ++i) { if (sieve[i]) { printf(",%d", i); } } printf("\n};\n"); printf("const long prime_table_size = %d;\n", primecount); free(sieve); return 0; }
C
#include "holberton.h" int main(void) { char school[10] = "Holberton"; int i = 0; while (i < 9) { _putchar(school[i]); i++; } _putchar('\n'); return (0); }
C
#include <stdio.h> #include <stdlib.h> double divop(double orig, int slots) { if (slots == 1 || orig == 0) return orig; int od = slots & 1; double result = divop(orig / 2, od ? (slots + 1) >> 1 : slots >> 1); if (od) result += divop(result, slots); return result; } int main() { return 0; }
C
/* * Main source code file for lsh shell program * * You are free to add functions to this file. * If you want to add functions in a separate file * you will need to modify Makefile to compile * your additional functions. * * Add appropriate comments in your code to make it * easier for us while grading your assignment. * * Submit the entire lab1 folder as a tar archive (.tgz). * Command to create submission archive: $> tar cvf lab1.tgz lab1/ * * All the best */ #include <stdio.h> #include <stdlib.h> #include <readline/readline.h> #include <readline/history.h> #include "parse.h" #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include <signal.h> /* * Function declarations */ void PrintCommand(int, Command *); void PrintPgm(Pgm *); void RunCommand(Pgm *, char *,char *,int,int); void stripwhite(char *); void no_zombies(); /* When non-zero, this global means the user is done using this program. */ int done = 0; /* * Name: main * * Description: Gets the ball rolling... * */ void no_zombies(){ waitpid(-1, NULL, WNOHANG); } int main(void) { Command cmd; int n; //signal(SIGINT, SIG_IGN); //signal(SIGCHLD, no_zombies); while (!done) { //om pgm->next == NULL inge fler kommandon att exekvera //annars ska stdout från ett kopplas till stdin för ett annat char *line; line = readline("> "); if (!line) { /* Encountered EOF at top level */ done = 1; } else { /* * Remove leading and trailing whitespace from the line * Then, if there is anything left, add it to the history list * and execute it. */ stripwhite(line); if(*line) { add_history(line); /* execute it */ n = parse(line, &cmd); PrintCommand(n, &cmd); RunCommand(cmd.pgm,cmd.rstdout,cmd.rstdin,cmd.bakground,0); } } if(line) { free(line); } } return 0; } /* * Name: RunCommand * * */ void RunCommand(Pgm *p, char *out, char *in, int bg,int n){ int pipefd[2]; printf("%d \n",p->next); if(p->next != NULL){ printf("%d \n",123); pipe(pipefd); printf("%d \n",324); } pid_t pid; pid = fork(); if(pid<0){ printf("error \n"); } else if(pid == 0){ /*child*/ if(out != NULL){ int fd1 = creat(out , 0644) ; dup2(fd1, STDOUT_FILENO); close(fd1); } if(in != NULL){ int fd2 = open(in , O_RDONLY) ; dup2(fd2, STDIN_FILENO); close(fd2); } if(n != 0){ perror("in child"); close(pipefd[0]); dup2(pipefd[1],STDOUT_FILENO); close(pipefd[1]); //set my out to parents in } //if bg not set //setpgid(0,0) execvp((p->pgmlist)[0],(p->pgmlist)); if(p->next != NULL){ //recursion next //öppna en ny in och skicka med som out //till nästa runCommand // RunCommand(p->next,in,in,bg,n+1); } } else{ /*parent*/ //if bg is not set printf("in parent"); if(p->next != NULL){ printf("piping"); close(pipefd[1]); dup2(pipefd[0],STDIN_FILENO); close(pipefd[0]); } if (bg==0){ //not bg signal(SIGCHLD, SIG_DFL); wait(NULL); } else{ signal(SIGCHLD, no_zombies); } //wait(NULL); } } /* * Name: PrintCommand * * Description: Prints a Command structure as returned by parse on stdout. * */ void PrintCommand (int n, Command *cmd) { printf("Parse returned %d:\n", n); printf(" stdin : %s\n", cmd->rstdin ? cmd->rstdin : "<none>" ); printf(" stdout: %s\n", cmd->rstdout ? cmd->rstdout : "<none>" ); printf(" bg : %s\n", cmd->bakground ? "yes" : "no"); /*PrintPgm(cmd->pgm); check if bg set */ } /* * Name: PrintPgm * * Description: Prints a list of Pgm:s * */ void PrintPgm (Pgm *p) { if (p == NULL) { return; } else { char **pl = p->pgmlist; /* The list is in reversed order so print * it reversed to get right */ PrintPgm(p->next); printf(" ["); while (*pl) { printf("%s ", *pl++); } printf("]\n"); } } /* * Name: stripwhite * * Description: Strip whitespace from the start and end of STRING. */ void stripwhite (char *string) { register int i = 0; while (isspace( string[i] )) { i++; } if (i) { strcpy (string, string + i); } i = strlen( string ) - 1; while (i> 0 && isspace (string[i])) { i--; } string [++i] = '\0'; }
C
#include<stdio.h> void main(){ char name[100],addres[100],phonenumber[100]; printf("Please enter your detail below : \n"); printf("Enter your name :"); scanf("%s",name); printf("Enter your current adress:"); scanf("%s",addres); printf("Enter your Phone number :"); scanf("%s",phonenumber); printf("\n"); printf("Your detail :"); printf("Name : %s \n",name); printf("address : %s \n",addres); printf("Phone number : %s",phonenumber); }
C
/** * @FilePath: \undefinedd:\git\Algorithm_Library\CatalanNum\catalan.c * @brief: * @details: * @author: Lews Hammond * @Date: 2022-05-19 20:53:35 * @LastEditTime: 2022-05-19 21:01:28 * @LastEditors: Lews Hammond */ #include <stdio.h> unsigned long long catalan(unsigned int n) { unsigned long long num = 0; unsigned int i = 0; if (n <= 1) { return 1; } for (i = 0; i < n; i++) { num += catalan(i) * catalan(n - i - 1); } return num; } int main(void) { int i = 0; for (i = 1; i < 10; i++) { printf("%lld\n", catalan(i)); } return 0; }
C
#include<stdio.h> void encode(int n,int x[],char y[]) { int i,j,k=0; for(i=0;i<n;i++) { for(j=0;j<x[i];j++) { printf("%c",y[k]-3); k++; } printf(" "); } } int main() { int n; char y[100]; scanf("%s",y); scanf("%d",&n); int x[n]; int i; for(i=0;i<n;i++) { scanf("%d",&x[i]); } encode(n,x,y); return 0; }
C
#include "sorting.h" #include "../tpcontato/tpcontato.h" void dllist_insertion_sort(dl_node *llist, int (*cmp)(const void *, const void*)) { dl_node *p, *i; if (llist == NULL || llist->next == NULL) return; /* Iterates the llist */ for (i = llist; i != NULL; i = i->next) { for (p = i; p->prev != NULL && cmp(p->item, p->prev->item) < 0; p = p->prev) dllist_swap_nodes(p, p->prev); } } void dllist_selection_sort(dl_node *items, int (*cmp)(const void *, const void *)) { dl_node *i, *p, *key; for (i = items; i != NULL; i = i->next) { key = i; for (p = i->next; p != NULL; p = p->next) if (cmp(p->item, key->item) < 0) key = p; if (key != i) dllist_swap_nodes(i, key); } } dl_node* dllist_qs_partition(dl_node *beg, dl_node *end, int (*cmp)(const void *, const void *)) { dl_node *pivot = end, *swap = beg, *p; for (p = beg; p != end && p != NULL; p = p->next) { if (cmp(p->item, pivot->item) < 0) { dllist_swap_nodes(p, swap); swap = swap->next; } } dllist_swap_nodes(swap, pivot); return swap; } void dllist_quick_sort_req(dl_node *beg, dl_node *end, int (*cmp)(const void *, const void *)) { dl_node *p; if (beg != end && (beg != NULL || end != NULL) && beg != end->next) { p = dllist_qs_partition(beg, end, cmp); if (p != NULL && p->prev != NULL) dllist_quick_sort_req(beg, p->prev, cmp); if (p != NULL && p->next != NULL) dllist_quick_sort_req(p->next, end, cmp); } } void dllist_quick_sort(dl_node *llist, int (*cmp)(const void *, const void *)) { dl_node *end; for (end = llist; end->next != NULL; end = end->next); dllist_quick_sort_req(llist, end, cmp); } dl_node *dllist_merge_sort(dl_node **llist, int(*cmp)(const void *, const void *)) { dl_node *m, *left = NULL, *right = NULL, *next = NULL; int i, size; // Base-case if (*llist == NULL || (*llist)->next == NULL) return *llist; // Count until the end for (size = 0, m = *llist; m != NULL; size++, m = m->next); // Split items for (i = 0, m = *llist; m != NULL; i++, m = next) { next = m->next; if (i < (size) / 2) { dllist_append(&left, m); } else { dllist_append(&right, m); } } left = dllist_merge_sort(&left, cmp); right = dllist_merge_sort(&right, cmp); return dllist_merge_merge(left, right, cmp); } dl_node *dllist_merge_merge(dl_node *left, dl_node *right, int(*cmp)(const void *, const void *)) { dl_node *result = NULL, *next = NULL; while (left != NULL && right != NULL) { if (cmp(left->item, right->item) < 0) { next = left->next; dllist_append(&result, left); left = next; } else { next = right->next; dllist_append(&result, right); right = next; } } while (left != NULL) { next = left->next; dllist_append(&result, left); left = next; } while (right != NULL) { next = right->next; dllist_append(&result, right); right = next; } return result; }
C
#include <stdio.h> #include <unistd.h> int main() { unsigned char c = 0; while (c != 255) { printf("%d - %c , ", c,c++); usleep(1000000); } }
C
// Reference: 4-1 in Intel's 8080 Microprocessor System User's Manual //#include <sys/types.h> #include <stdio.h> // printf #include <stdlib.h> // exit() #include "8080.h" // get register pair inline uint16_t rpBC(struct i8080* cpu) { return cpu->B << 8 | cpu->C; }; inline uint16_t rpDE(struct i8080* cpu) { return cpu->D << 8 | cpu->E; }; inline uint16_t rpHL(struct i8080* cpu) { return cpu->H << 8 | cpu->L; }; // set register pair void srpBC(struct i8080* cpu, uint16_t val) { cpu->B = (val&0xFF00)>>8; cpu->C = val&0xFF; }; void srpDE(struct i8080* cpu, uint16_t val) { cpu->D = (val&0xFF00)>>8; cpu->E = val&0xFF; }; void srpHL(struct i8080* cpu, uint16_t val) { cpu->H = (val&0xFF00)>>8; cpu->L = val&0xFF; }; uint8_t getFlag(struct i8080 *cpu, enum flag flag) { return (cpu->flags >> flag) & 1; } void setFlag(struct i8080 *cpu, const uint8_t flag, const uint8_t val) { cpu->flags &= ~(1 << flag); // reset cpu->flags |= (1 << flag) * val; // set } void unimplemented(struct i8080 *cpu, uint8_t *memory) { printf("Unimplemented instruction, pc=%02x, mem[pc]=%02x\n", cpu->pc, memory[cpu->pc]); setFlag(cpu, HLT, 1); exit(1); } uint8_t parity(uint8_t val) { return ((val>>0) ^ (val>>1) ^ (val>>2) ^ (val>>3) ^ (val>>4) ^ (val>>5) ^ (val>>6) ^ (val>>7)) & 1; } // RST 0 means "jump to 0x0", RST 1 means "vector to 0x8" and so on #define RST(n) { \ memory[cpu->sp-1] = (cpu->pc & 0xFF00) >> 8; \ memory[cpu->sp-2] = (cpu->pc & 0x00FF); \ cpu->sp -= 2; \ cpu->pc = n*8; \ } void request_interrupt(struct i8080 *cpu, uint8_t *memory, uint8_t RST_n) { // if the CPU does not have interrupts enabled right now, ignore it //printf("Called %d\n", RST_n); if(!getFlag(cpu, EI)) return; //printf("LETS GOO\n"); // disable interrupts setFlag(cpu, EI, 0); RST(RST_n); } void execute_instruction(struct i8080 *cpu, uint8_t *memory, void (*out)(uint8_t,uint8_t)) { // TODO many instructions do not set AC flag at all #define SWAP(x,y) {x^=y;y^=x;x^=y;} #define D16 (b[2] << 8 | b[1]) #define gBC rpBC(cpu) #define gDE rpDE(cpu) #define gHL rpHL(cpu) #define sBC(x) srpBC(cpu, (x)) #define sDE(x) srpDE(cpu, (x)) #define sHL(x) srpHL(cpu, (x)) #define fZ(x) setFlag(cpu, Z, (x) == 0) #define fS(x) setFlag(cpu, S, ((x)&0x80) >> 7) #define fP(x) setFlag(cpu, P, !parity((x))) #define DAD(x) {setFlag(cpu, CY, gHL > 0xFFFF - x); sHL(gHL + x);} #define XRA(x) {cpu->A^=x; fZ(cpu->A); fS(cpu->A); fP(cpu->A); setFlag(cpu, CY, 0); setFlag(cpu, AC, 0);} #define ANA(x) {cpu->A&=x; fZ(cpu->A); fS(cpu->A); fP(cpu->A); setFlag(cpu, CY, 0); /* TODO AC */} #define ADD(x) {\ setFlag(cpu, CY, cpu->A > 255 - x);\ cpu->A += x;\ fZ(cpu->A); fS(cpu->A); fP(cpu->A);\ } #define ADC(x) {\ const uint16_t sum = cpu->A + x + getFlag(cpu, CY); \ setFlag(cpu, CY, sum > 255); \ fZ(cpu->A); fS(cpu->A); fP(cpu->A); \ } uint8_t* b = memory + cpu->pc; // setFlag(cpu, CY, cpu->B == 0); // will result in a borrow uint8_t bit; switch(b[0]) { /*NOP*/ case 0x00: /* do nothing :D */; cpu->pc += 1; break; /*LXI*/ case 0x01: cpu->B = b[2]; cpu->C = b[1]; cpu->pc += 3; break; /*STAX*/case 0x02: memory[gBC] = cpu->A; cpu->pc += 1; break; /*INX*/ case 0x03: sBC(gBC+1); cpu->pc += 1; break; case 0x04: unimplemented(cpu, memory); cpu->pc += 1; break; /*DCR*/ case 0x05: cpu->B --; fZ(cpu->B); fS(cpu->B); fP(cpu->B); cpu->pc += 1; break; /*MVI*/ case 0x06: cpu->B = b[1]; cpu->pc += 2; break; case 0x07: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x08: unimplemented(cpu, memory); cpu->pc += 1; break; /*DAD*/ case 0x09: DAD(gBC); cpu->pc += 1; break; case 0x0a: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x0b: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x0c: unimplemented(cpu, memory); cpu->pc += 1; break; /*DCR*/ case 0x0d: cpu->C --; fZ(cpu->C); fS(cpu->C); fP(cpu->C); cpu->pc += 1; break; /*MVI*/ case 0x0e: cpu->C = b[1]; cpu->pc += 2; break; case 0x0f: bit = cpu->A & 1; cpu->A >>= 1; cpu->A |= (bit << 8); setFlag(cpu, CY, bit); cpu->pc += 1; break; /*DEB*/ case 0x10: printf("DEB\n"); cpu->pc += 1; break; /*LXI*/ case 0x11: cpu->D = b[2]; cpu->E = b[1]; cpu->pc += 3; break; case 0x12: unimplemented(cpu, memory); cpu->pc += 1; break; /*INX*/ case 0x13: sDE(gDE+1); cpu->pc += 1; break; case 0x14: unimplemented(cpu, memory); cpu->pc += 1; break; /*DCR*/ case 0x15: cpu->D --; fZ(cpu->D); fS(cpu->D); fP(cpu->D); cpu->pc += 1; break; /*MVI*/ case 0x16: cpu->D = b[1]; cpu->pc += 2; break; case 0x17: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x18: unimplemented(cpu, memory); cpu->pc += 1; break; /*DAD*/ case 0x19: DAD(gDE); cpu->pc += 1; break; /*LDAX*/case 0x1a: cpu->A = memory[gDE]; cpu->pc += 1; break; case 0x1b: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x1c: unimplemented(cpu, memory); cpu->pc += 1; break; /*DCR*/ case 0x1d: cpu->E --; fZ(cpu->E); fS(cpu->E); fP(cpu->E); cpu->pc += 1; break; /*MVI*/ case 0x1e: cpu->E = b[1]; cpu->pc += 2; break; case 0x1f: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x20: unimplemented(cpu, memory); cpu->pc += 1; break; /*LXI*/ case 0x21: cpu->H = b[2]; cpu->L = b[1]; cpu->pc += 3; break; case 0x22: unimplemented(cpu, memory); cpu->pc += 3; break; /*INX*/ case 0x23: sHL(gHL + 1); cpu->pc += 1; break; case 0x24: unimplemented(cpu, memory); cpu->pc += 1; break; /*DCR*/ case 0x25: cpu->H --; fZ(cpu->H); fS(cpu->H); fP(cpu->H); cpu->pc += 1; break; /*MVI*/ case 0x26: cpu->H = b[1]; cpu->pc += 2; break; case 0x27: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x28: unimplemented(cpu, memory); cpu->pc += 1; break; /*DAD*/ case 0x29: DAD(gHL); cpu->pc += 1; break; case 0x2a: unimplemented(cpu, memory); cpu->pc += 3; break; case 0x2b: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x2c: unimplemented(cpu, memory); cpu->pc += 1; break; /*DCR*/ case 0x2d: cpu->L --; fZ(cpu->L); fS(cpu->L); fP(cpu->L); cpu->pc += 1; break; /*MVI*/ case 0x2e: cpu->L = b[1]; cpu->pc += 2; break; case 0x2f: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x30: unimplemented(cpu, memory); cpu->pc += 1; break; /*LXI*/ case 0x31: cpu->sp = D16; cpu->pc += 3; break; /*STA*/ case 0x32: memory[D16] = cpu->A; cpu->pc += 3; break; /*INX*/ case 0x33: cpu->sp ++; cpu->pc += 1; break; case 0x34: unimplemented(cpu, memory); cpu->pc += 1; break; /*DCR*/ case 0x35: memory[gHL] --; fZ(memory[gHL]); fS(memory[gHL]); fP(memory[gHL]); cpu->pc += 1; break; /*MVI*/ case 0x36: memory[gHL] = b[1]; cpu->pc += 2; break; case 0x37: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x38: unimplemented(cpu, memory); cpu->pc += 1; break; /*DAD*/ case 0x39: DAD(cpu->sp); cpu->pc += 1; break; /*LDA*/ case 0x3a: cpu->A = memory[D16]; cpu->pc += 3; break; case 0x3b: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x3c: unimplemented(cpu, memory); cpu->pc += 1; break; /*DCR*/ case 0x3d: cpu->A --; fZ(cpu->A); fS(cpu->A); fP(cpu->A); cpu->pc += 1; break; /*MVI*/ case 0x3e: cpu->A = b[1]; cpu->pc += 2; break; case 0x3f: unimplemented(cpu, memory); cpu->pc += 1; break; /* block of a lot of MOVs */ /*MOV*/ case 0x40: cpu->B = cpu->B; cpu->pc += 1; break; /*MOV*/ case 0x41: cpu->B = cpu->C; cpu->pc += 1; break; /*MOV*/ case 0x42: cpu->B = cpu->D; cpu->pc += 1; break; /*MOV*/ case 0x43: cpu->B = cpu->E; cpu->pc += 1; break; /*MOV*/ case 0x44: cpu->B = cpu->H; cpu->pc += 1; break; /*MOV*/ case 0x45: cpu->B = cpu->L; cpu->pc += 1; break; /*MOV*/ case 0x46: cpu->B = memory[gHL]; cpu->pc += 1; break; /*MOV*/ case 0x47: cpu->B = cpu->A; cpu->pc += 1; break; /*MOV*/ case 0x48: cpu->C = cpu->B; cpu->pc += 1; break; /*MOV*/ case 0x49: cpu->C = cpu->C; cpu->pc += 1; break; /*MOV*/ case 0x4a: cpu->C = cpu->D; cpu->pc += 1; break; /*MOV*/ case 0x4b: cpu->C = cpu->E; cpu->pc += 1; break; /*MOV*/ case 0x4c: cpu->C = cpu->H; cpu->pc += 1; break; /*MOV*/ case 0x4d: cpu->C = cpu->L; cpu->pc += 1; break; /*MOV*/ case 0x4e: cpu->C = memory[gHL]; cpu->pc += 1; break; /*MOV*/ case 0x4f: cpu->C = cpu->A; cpu->pc += 1; break; /*MOV*/ case 0x50: cpu->D = cpu->B; cpu->pc += 1; break; /*MOV*/ case 0x51: cpu->D = cpu->C; cpu->pc += 1; break; /*MOV*/ case 0x52: cpu->D = cpu->D; cpu->pc += 1; break; /*MOV*/ case 0x53: cpu->D = cpu->E; cpu->pc += 1; break; /*MOV*/ case 0x54: cpu->D = cpu->H; cpu->pc += 1; break; /*MOV*/ case 0x55: cpu->D = cpu->L; cpu->pc += 1; break; /*MOV*/ case 0x56: cpu->D = memory[gHL]; cpu->pc += 1; break; /*MOV*/ case 0x57: cpu->D = cpu->A; cpu->pc += 1; break; /*MOV*/ case 0x58: cpu->E = cpu->B; cpu->pc += 1; break; /*MOV*/ case 0x59: cpu->E = cpu->C; cpu->pc += 1; break; /*MOV*/ case 0x5a: cpu->E = cpu->D; cpu->pc += 1; break; /*MOV*/ case 0x5b: cpu->E = cpu->E; cpu->pc += 1; break; /*MOV*/ case 0x5c: cpu->E = cpu->H; cpu->pc += 1; break; /*MOV*/ case 0x5d: cpu->E = cpu->L; cpu->pc += 1; break; /*MOV*/ case 0x5e: cpu->E = memory[gHL]; cpu->pc += 1; break; /*MOV*/ case 0x5f: cpu->E = cpu->A; cpu->pc += 1; break; /*MOV*/ case 0x60: cpu->H = cpu->B; cpu->pc += 1; break; /*MOV*/ case 0x61: cpu->H = cpu->C; cpu->pc += 1; break; /*MOV*/ case 0x62: cpu->H = cpu->D; cpu->pc += 1; break; /*MOV*/ case 0x63: cpu->H = cpu->E; cpu->pc += 1; break; /*MOV*/ case 0x64: cpu->H = cpu->H; cpu->pc += 1; break; /*MOV*/ case 0x65: cpu->H = cpu->L; cpu->pc += 1; break; /*MOV*/ case 0x66: cpu->H = memory[gHL]; cpu->pc += 1; break; /*MOV*/ case 0x67: cpu->H = cpu->A; cpu->pc += 1; break; /*MOV*/ case 0x68: cpu->L = cpu->B; cpu->pc += 1; break; /*MOV*/ case 0x69: cpu->L = cpu->C; cpu->pc += 1; break; /*MOV*/ case 0x6a: cpu->L = cpu->D; cpu->pc += 1; break; /*MOV*/ case 0x6b: cpu->L = cpu->E; cpu->pc += 1; break; /*MOV*/ case 0x6c: cpu->L = cpu->H; cpu->pc += 1; break; /*MOV*/ case 0x6d: cpu->L = cpu->L; cpu->pc += 1; break; /*MOV*/ case 0x6e: cpu->L = memory[gHL]; cpu->pc += 1; break; /*MOV*/ case 0x6f: cpu->L = cpu->A; cpu->pc += 1; break; /*MOV*/ case 0x70: memory[gHL] = cpu->B; cpu->pc += 1; break; /*MOV*/ case 0x71: memory[gHL] = cpu->C; cpu->pc += 1; break; /*MOV*/ case 0x72: memory[gHL] = cpu->D; cpu->pc += 1; break; /*MOV*/ case 0x73: memory[gHL] = cpu->E; cpu->pc += 1; break; /*MOV*/ case 0x74: memory[gHL] = cpu->H; cpu->pc += 1; break; /*MOV*/ case 0x75: memory[gHL] = cpu->L; cpu->pc += 1; break; /*HLT*/ case 0x76: unimplemented(cpu, memory); cpu->pc += 1; break; /*MOV*/ case 0x77: memory[gHL] = cpu->A; cpu->pc += 1; break; /*MOV*/ case 0x78: cpu->A = cpu->B; cpu->pc += 1; break; /*MOV*/ case 0x79: cpu->A = cpu->C; cpu->pc += 1; break; /*MOV*/ case 0x7a: cpu->A = cpu->D; cpu->pc += 1; break; /*MOV*/ case 0x7b: cpu->A = cpu->E; cpu->pc += 1; break; /*MOV*/ case 0x7c: cpu->A = cpu->H; cpu->pc += 1; break; /*MOV*/ case 0x7d: cpu->A = cpu->L; cpu->pc += 1; break; /*MOV*/ case 0x7e: cpu->A = memory[gHL]; cpu->pc += 1; break; /*MOV*/ case 0x7f: cpu->A = cpu->A; cpu->pc += 1; break; // WTF why is this needed /*ADD*/ case 0x80: ADD(cpu->B ); cpu->pc += 1; break; /*ADD*/ case 0x81: ADD(cpu->C ); cpu->pc += 1; break; /*ADD*/ case 0x82: ADD(cpu->D ); cpu->pc += 1; break; /*ADD*/ case 0x83: ADD(cpu->E ); cpu->pc += 1; break; /*ADD*/ case 0x84: ADD(cpu->H ); cpu->pc += 1; break; /*ADD*/ case 0x85: ADD(cpu->L ); cpu->pc += 1; break; /*ADD*/ case 0x86: ADD(memory[gHL]); cpu->pc += 1; break; /*ADD*/ case 0x87: ADD(cpu->A ); cpu->pc += 1; break; /*ADC*/ case 0x88: ADC(cpu->B ); cpu->pc += 1; break; /*ADC*/ case 0x89: ADC(cpu->C ); cpu->pc += 1; break; /*ADC*/ case 0x8a: ADC(cpu->D ); cpu->pc += 1; break; /*ADC*/ case 0x8b: ADC(cpu->E ); cpu->pc += 1; break; /*ADC*/ case 0x8c: ADC(cpu->H ); cpu->pc += 1; break; /*ADC*/ case 0x8d: ADC(cpu->L ); cpu->pc += 1; break; /*ADC*/ case 0x8e: ADC(memory[gHL]); cpu->pc += 1; break; /*ADC*/ case 0x8f: ADC(cpu->A ); cpu->pc += 1; break; case 0x90: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x91: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x92: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x93: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x94: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x95: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x96: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x97: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x98: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x99: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x9a: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x9b: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x9c: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x9d: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x9e: unimplemented(cpu, memory); cpu->pc += 1; break; case 0x9f: unimplemented(cpu, memory); cpu->pc += 1; break; /*ANA*/ case 0xa0: ANA(cpu->B ); cpu->pc += 1; break; /*ANA*/ case 0xa1: ANA(cpu->C ); cpu->pc += 1; break; /*ANA*/ case 0xa2: ANA(cpu->D ); cpu->pc += 1; break; /*ANA*/ case 0xa3: ANA(cpu->E ); cpu->pc += 1; break; /*ANA*/ case 0xa4: ANA(cpu->H ); cpu->pc += 1; break; /*ANA*/ case 0xa5: ANA(cpu->L ); cpu->pc += 1; break; /*ANA*/ case 0xa6: ANA(memory[gHL]); cpu->pc += 1; break; /*ANA*/ case 0xa7: ANA(cpu->A ); cpu->pc += 1; break; /*XRA*/ case 0xa8: XRA(cpu->B ); cpu->pc += 1; break; /*XRA*/ case 0xa9: XRA(cpu->C ); cpu->pc += 1; break; /*XRA*/ case 0xaa: XRA(cpu->D ); cpu->pc += 1; break; /*XRA*/ case 0xab: XRA(cpu->E ); cpu->pc += 1; break; /*XRA*/ case 0xac: XRA(cpu->H ); cpu->pc += 1; break; /*XRA*/ case 0xad: XRA(cpu->L ); cpu->pc += 1; break; /*XRA*/ case 0xae: XRA(memory[gHL]); cpu->pc += 1; break; /*XRA*/ case 0xaf: XRA(cpu->A ); cpu->pc += 1; break; case 0xb0: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xb1: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xb2: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xb3: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xb4: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xb5: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xb6: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xb7: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xb8: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xb9: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xba: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xbb: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xbc: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xbd: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xbe: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xbf: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xc0: unimplemented(cpu, memory); cpu->pc += 1; break; /*POP*/ case 0xc1: cpu->C=memory[cpu->sp]; cpu->B=memory[cpu->sp+1]; cpu->sp += 2; ; cpu->pc += 1; break; /*JNZ*/ case 0xc2: if(!getFlag(cpu, Z)) { cpu->pc = D16; } else { cpu->pc += 3; } break; /*JMP*/ case 0xc3: cpu->pc = D16; break; case 0xc4: unimplemented(cpu, memory); cpu->pc += 3; break; /*PUSH*/case 0xc5: memory[cpu->sp-1] = cpu->B; memory[cpu->sp-2] = cpu->C; cpu->sp -= 2; cpu->pc += 1; break; /*ADI*/ case 0xc6: setFlag(cpu, CY, cpu->A > 255 - b[1]); cpu->A += b[1]; fZ(cpu->A); fS(cpu->A); fP(cpu->A); cpu->pc += 2; break; /*RST*/ case 0xc7: RST(0); break; /*RZ*/ case 0xc8: if(getFlag(cpu, Z) == 0) break; // else, waterfall to RET /*RET*/ case 0xc9: cpu->pc = ((uint16_t)memory[cpu->sp+1] << 8) | memory[cpu->sp]; cpu->sp += 2; break; case 0xca: unimplemented(cpu, memory); cpu->pc += 3; break; case 0xcb: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xcc: unimplemented(cpu, memory); cpu->pc += 3; break; /*CALL*/case 0xcd: cpu->pc += 3; // if CALL saved its own address in the stack, RET would call again // leading to infinite recursion. Instead, call saves the address of the next instruction memory[cpu->sp-1] = (cpu->pc & 0xFF00) >> 8; memory[cpu->sp-2] = (cpu->pc & 0x00FF); cpu->sp -= 2; cpu->pc = D16; break; case 0xce: unimplemented(cpu, memory); cpu->pc += 2; break; /*RST*/ case 0xcf: RST(1); break; case 0xd0: unimplemented(cpu, memory); cpu->pc += 1; break; /*POP*/ case 0xd1: cpu->E=memory[cpu->sp]; cpu->D=memory[cpu->sp+1]; cpu->sp += 2; cpu->pc += 1; break; case 0xd2: unimplemented(cpu, memory); cpu->pc += 3; break; /*OUT*/ case 0xd3: out(b[1], cpu->A); cpu->pc += 2; break; case 0xd4: unimplemented(cpu, memory); cpu->pc += 3; break; /*PUSH*/case 0xd5: memory[cpu->sp-1] = cpu->D; memory[cpu->sp-2] = cpu->E; cpu->sp -= 2; cpu->pc += 1; break; case 0xd6: unimplemented(cpu, memory); cpu->pc += 2; break; /*RST*/ case 0xd7: RST(2); break; case 0xd8: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xd9: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xda: unimplemented(cpu, memory); cpu->pc += 3; break; /*IN*/ case 0xdb: printf("IN %02x\n", b[1]); cpu->A = cpu->input_ports[b[1]]; cpu->pc += 2; break; case 0xdc: unimplemented(cpu, memory); cpu->pc += 3; break; case 0xdd: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xde: unimplemented(cpu, memory); cpu->pc += 2; break; /*RST*/ case 0xdf: RST(3); break; case 0xe0: unimplemented(cpu, memory); cpu->pc += 1; break; /*POP*/ case 0xe1: cpu->L=memory[cpu->sp]; cpu->H=memory[cpu->sp+1]; cpu->sp += 2; cpu->pc += 1; break; case 0xe2: unimplemented(cpu, memory); cpu->pc += 3; break; case 0xe3: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xe4: unimplemented(cpu, memory); cpu->pc += 3; break; /*PUSH*/case 0xe5: memory[cpu->sp-1] = cpu->H; memory[cpu->sp-2] = cpu->L; cpu->sp -= 2; cpu->pc += 1; break; case 0xe6: cpu->A &= b[1]; setFlag(cpu, CY, 0); cpu->pc += 2; break; /*RST*/ case 0xe7: RST(4); break; case 0xe8: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xe9: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xea: unimplemented(cpu, memory); cpu->pc += 3; break; /*XCHG*/case 0xeb: SWAP(cpu->H, cpu->D); SWAP(cpu->L, cpu->E); cpu->pc += 1; break; case 0xec: unimplemented(cpu, memory); cpu->pc += 3; break; case 0xed: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xee: unimplemented(cpu, memory); cpu->pc += 2; break; /*RST*/ case 0xef: RST(5); break; /*RP*/ case 0xf0: if(getFlag(cpu, P)) { printf("HERE %02x %02x\n", memory[cpu->sp+1], memory[cpu->sp]); cpu->pc = ((uint16_t)memory[cpu->sp+1] << 8) | memory[cpu->sp]; cpu->sp += 2; } else { cpu->pc += 1; } break; /*POP*/ case 0xf1: // POP PSW cpu->A = memory[cpu->sp+1]; setFlag(cpu, CY, (memory[cpu->sp] >> 0) & 1); setFlag(cpu, P , (memory[cpu->sp] >> 2) & 1); setFlag(cpu, AC, (memory[cpu->sp] >> 4) & 1); setFlag(cpu, Z , (memory[cpu->sp] >> 6) & 1); setFlag(cpu, S , (memory[cpu->sp] >> 7) & 1); cpu->sp += 2; cpu->pc += 1; break; case 0xf2: unimplemented(cpu, memory); cpu->pc += 3; break; /*DI*/ case 0xf3: setFlag(cpu, EI, 0); cpu->pc += 1; break; case 0xf4: unimplemented(cpu, memory); cpu->pc += 3; break; /*PUSH*/case 0xf5: // PUSH PSW - saves flags into memory memory[cpu->sp-1] = cpu->A; memory[cpu->sp-2] = (getFlag(cpu, CY) << 0) | (0 << 1) // TODO should be 1 per intel docs | (getFlag(cpu, P ) << 2) | (0 << 3) | (getFlag(cpu, AC) << 4) // TODO change to getFlag(cpu, AC) when AC is working correctly | (0 << 5) | (getFlag(cpu, Z ) << 6) | (getFlag(cpu, S ) << 7); cpu->sp -= 2; cpu->pc += 1; break; case 0xf6: unimplemented(cpu, memory); cpu->pc += 2; break; /*RST*/ case 0xf7: RST(6); break; case 0xf8: unimplemented(cpu, memory); cpu->pc += 1; break; case 0xf9: unimplemented(cpu, memory); cpu->pc += 1; break; /*JM*/ case 0xfa: if(getFlag(cpu, S)) cpu->pc = D16; break; /*EI*/ case 0xfb: setFlag(cpu, EI, 1); cpu->pc += 1; break; case 0xfc: unimplemented(cpu, memory); cpu->pc += 3; break; case 0xfd: unimplemented(cpu, memory); cpu->pc += 1; break; /*CPI*/ case 0xfe: setFlag(cpu, CY, cpu->A < b[1]); const uint8_t tmp = cpu->A - b[1]; fZ(tmp); fS(tmp); fP(tmp); cpu->pc += 2; break; /*RST*/ case 0xff: RST(7); break; } cpu->instr ++; #undef D16 }
C
#include <ctype.h> #include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <signal.h> #include <sys/wait.h> #include <termios.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include "tokenizer.h" /* Convenience macro to silence compiler warnings about unused function parameters. */ #define unused __attribute__((unused)) /* max size of path */ #define PATH_MAX 255 /* max size of arguments */ #define ARG_MAX 128 /* Whether the shell is connected to an actual terminal or not. */ bool shell_is_interactive; /* File descriptor for the shell input */ int shell_terminal; /* Terminal mode settings for the shell */ struct termios shell_tmodes; /* Process group id for the shell */ pid_t shell_pgid; // self define variables /* path */ char pwd[PATH_MAX]; extern char **environ; int cmd_exit(struct tokens *tokens); int cmd_help(struct tokens *tokens); int cmd_pwd(struct tokens *tokens); int cmd_cd(struct tokens *tokens); int pathcat(char *input, char *old, char *run_path); int eval(struct tokens *tokens); void tokenize_path(char* env_path, char** path); /* Built-in command functions take token array (see parse.h) and return int */ typedef int cmd_fun_t(struct tokens *tokens); /* Built-in command struct and lookup table */ typedef struct fun_desc { cmd_fun_t *fun; char *cmd; char *doc; } fun_desc_t; fun_desc_t cmd_table[] = { {cmd_help, "?", "show this help menu"}, {cmd_exit, "exit", "exit the command shell"}, {cmd_pwd, "pwd", "get current dirctory path"}, {cmd_cd, "cd", "change current dirctory path"}, }; char *env_paths[ARG_MAX]; /* Prints a helpful description for the given command */ int cmd_help(unused struct tokens *tokens) { for (unsigned int i = 0; i < sizeof(cmd_table) / sizeof(fun_desc_t); i++) printf("%s - %s\n", cmd_table[i].cmd, cmd_table[i].doc); return 1; } /* Exits this shell */ int cmd_exit(unused struct tokens *tokens) { exit(0); } /* Looks up the built-in command, if it exists. */ int lookup(char cmd[]) { for (unsigned int i = 0; i < sizeof(cmd_table) / sizeof(fun_desc_t); i++) if (cmd && (strcmp(cmd_table[i].cmd, cmd) == 0)) return i; return -1; } /* Intialization procedures for this shell */ void init_shell() { /* Our shell is connected to standard input. */ shell_terminal = STDIN_FILENO; /* Check if we are running interactively */ shell_is_interactive = isatty(shell_terminal); if (shell_is_interactive) { /* If the shell is not currently in the foreground, we must pause the shell until it becomes a * foreground process. We use SIGTTIN to pause the shell. When the shell gets moved to the * foreground, we'll receive a SIGCONT. */ while (tcgetpgrp(shell_terminal) != (shell_pgid = getpgrp())) kill(-shell_pgid, SIGTTIN); /* Saves the shell's process id */ shell_pgid = getpid(); /* Take control of the terminal */ tcsetpgrp(shell_terminal, shell_pgid); /* Save the current termios to a variable, so it can be restored later. */ tcgetattr(shell_terminal, &shell_tmodes); } /* initial env_path array*/ // for (int i = 0; environ[i]; i++) { // printf("envs %d : %s\n", i, environ[i]); // } tokenize_path(environ[9], env_paths); } int cmd_pwd(unused struct tokens *tokens) { if (getcwd(pwd, PATH_MAX) < 0) { fprintf(stderr, "can not get current dirctory\n"); return -1; } else { printf("%s\n", pwd); } return 1; } int cmd_cd(unused struct tokens *tokens) { // getcwd(pwd, PATH_MAX); char *curr_path = getcwd(pwd, PATH_MAX); char *input = tokens_get_token(tokens, 1); char run_path[PATH_MAX]; pathcat(input, curr_path, run_path); printf("cd path : %s\n", run_path); if (chdir(run_path) < 0) fprintf(stderr, "wrong path : %s\n", run_path); return 1; } /* if new paht star with '/', direct use it, else add input to current path*/ int pathcat(char *input, char *curr, char *run_path) { printf("Concatent %s & %s to ", input, curr); char *slash = "/"; // char *path = ""; char buff[255]; strcpy(buff, curr); if(input[0] != '/') { strcat(buff, slash); strcpy(run_path, strcat(buff, input)); } else { strcpy(run_path, input); } printf("%s \n", run_path); return 1; } int eval(unused struct tokens *tokens) { pid_t pid; int status, i = 0, redirect = 0; // 1 redirect in ; 2 redirect out char dir_file[PATH_MAX]; char *argv[ARG_MAX], *s; char *curr_path = getcwd(pwd, PATH_MAX); // get arguments fromm tokens while ((s = tokens_get_token(tokens, i))) { // printf("atgv %d: %s\n", i, s); if (strcmp(s, "<") == 0) { redirect = 1; break; } if (strcmp(s, ">") == 0) { redirect = 2; break; } argv[i] = s; i ++; } argv[i] = NULL; // now i is length of argv // get redirect file if (redirect) { char *tmp = tokens_get_token(tokens, i+1); pathcat(tmp, curr_path, dir_file); printf("Redirect file : %s \n", dir_file); char test[] = "Linux Programmer!\n"; int fd =open(dir_file, O_RDWR|O_CREAT); int size = write(fd, test, sizeof(test)); printf("write size : %d \n", size); close(fd); } char *inputLine = tokens_get_token(tokens, 0); env_paths[0] = getcwd(pwd, PATH_MAX); if ((pid = fork()) == 0) { for (i = 0; env_paths[i] != NULL; i++) { char run_path[PATH_MAX]; pathcat(inputLine, env_paths[i], run_path); printf("test path : %s \n", run_path); if (execve(run_path, argv, environ) > 0) // fprintf(stderr, "Can not find execute file.\n"); exit(0); } fprintf(stderr, "Can not find execute file.\n"); exit(0); } if (waitpid(pid, &status, 0) < 0) { fprintf(stderr, "waitpid error"); } return 1; } void tokenize_path(char* env_path, char** paths) { char *delim; int argc; env_path[strlen(env_path) - 1] = ' '; while (*env_path && (*env_path != '=')) { env_path ++; } env_path ++; // move after '=' argc = 1; paths[0] = getcwd(pwd, PATH_MAX); printf("\tPATH 0 : %s\n", paths[0]); while ((delim = strchr(env_path, ':'))) { paths[argc++] = env_path; *delim = '\0'; env_path = delim + 1; printf("\tPath %d : %s\n", argc, paths[argc-1]); } // if only segment of PATH no ':' if (delim == NULL) { paths[argc++] = env_path; printf("\tPath 0 : %s\n", paths[argc-1]); } paths[argc] = NULL; } int main(unused int argc, unused char *argv[]) { init_shell(); static char line[4096]; int line_num = 0; /* Please only print shell prompts when standard input is not a tty */ if (shell_is_interactive) fprintf(stdout, "%d: ", line_num); while (fgets(line, 4096, stdin)) { /* Split our line into words. */ struct tokens *tokens = tokenize(line); /* Find which built-in function to run. */ int fundex = lookup(tokens_get_token(tokens, 0)); if (fundex >= 0) { cmd_table[fundex].fun(tokens); } else { /* REPLACE this to run commands as programs. */ eval(tokens); } if (shell_is_interactive) /* Please only print shell prompts when standard input is not a tty */ fprintf(stdout, "%d: ", ++line_num); /* Clean up memory */ tokens_destroy(tokens); } return 0; }
C
/* ** EPITECH PROJECT, 2019 ** game loading functions ** File description: ** */ #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <curses.h> #include "my.h" #include "my_sokoban.h" box_t *box_load(map_t *map, int box_count) { box_t *box = malloc(sizeof(box_t) * box_count); int j = 0; int x = 0; int y = 0; for (int i = 0; map->draw_map[i] != '\0'; i++, x++) { if (map->draw_map[i] == '\n') { x = 0; y++; i++; } if (map->draw_map[i] == 'X') { map->draw_map[i] = ' '; box[j].status = 1; box[j].id = j; box[j].pos = vect_init(x, y); j++; } } return box; } vect_t *goal_load(map_t *map, int goal_count) { vect_t *vect = malloc(sizeof(vect_t) * goal_count); int j = 0; int x = 0; int y = 0; for (int i = 0; map->draw_map[i] != '\0'; i++, x++) { if (map->draw_map[i] == '\n') { x = 0; y++; i++; } if (map->draw_map[i] == 'O') { vect[j] = vect_init(x, y); j++; } } return vect; } vect_t player_pos_init(map_t *map) { int x = 0; int y = 0; for (int i = 0; map->draw_map[i] != '\0'; i++, x++) { if (map->draw_map[i] == '\n') { x = 0; y++; i++; } if (map->draw_map[i] == 'P') { map->draw_map[i] = ' '; return vect_init(x, y); } } return vect_init(0, 0); } game_t *game_load(char *filepath) { game_t *game = malloc(sizeof(game_t)); game->map_path = my_strdup(filepath); MAP = map_load(filepath); if (MAP == NULL) return NULL; if (!check_map_validity(game)) return NULL; game->box_count = get_occurences(MAP->draw_map, 'X'); BOX = box_load(MAP, game->box_count); game->goal_count = get_occurences(MAP->draw_map, 'O'); GOALS = goal_load(MAP, game->goal_count); P_POS = player_pos_init(MAP); getmaxyx(stdscr, MAXH, MAXW); return game; } void game_reload(game_t *game) { char *path = my_strdup(game->map_path); game_unload(game); game = game_load(path); free(path); return; }
C
#include "pathfinder.h" static int **copy_matrix(int **deixtra_matrix) { int size = 0; int **copy = NULL; for (;deixtra_matrix[0][size] != -2; size++); copy = (int **)malloc(sizeof(int *) * 3); for (int j = 0; j < 3; j++) { copy[j] = (int *)malloc(sizeof(int) * size + 1); for (int i = 0; i < size; i++) copy[j][i] = deixtra_matrix[j][i]; } copy[0][size] = -2; copy[1][size] = -1; copy[2][size] = 1; return copy; } static void recursion(int **deixtra_matrix, int **matrix, int min, mini_list **list) { int size = 0; int **copy = NULL; for (size = 0; deixtra_matrix[0][size] != -2; size++); for (int i = 0; deixtra_matrix[0][i] != -2; i++) { if (matrix[min][i] != -1 && ((deixtra_matrix[2][i] != 1 && deixtra_matrix[0][min] + matrix[min][i] == deixtra_matrix[0][i]) || (deixtra_matrix[0][i] == -1 && deixtra_matrix[2][i] != 1)) && deixtra_matrix[1][i] != min) { copy = copy_matrix(deixtra_matrix); copy[1][i] = min; mx_deixtra(copy, matrix, size, list); } } } static void algorithm(int **deixtra_matrix, int **matrix, int min) { int size = 0; for (size = 0; deixtra_matrix[0][size] != -2; size++); for (int i = 0; deixtra_matrix[0][i] != -2; i++) { if (matrix[min][i] != -1 && ((deixtra_matrix[2][i] != 1 && deixtra_matrix[0][min] + matrix[min][i] < deixtra_matrix[0][i]) || (deixtra_matrix[0][i] == -1 && deixtra_matrix[2][i] != 1))) { deixtra_matrix[0][i] = deixtra_matrix[0][min] + matrix[min][i]; deixtra_matrix[1][i] = min; } } } void mx_deixtra(int **deixtra_matrix, int **matrix, int size, mini_list **list) { while (!mx_is_done(deixtra_matrix[2], size)) { int min = mx_is_min(deixtra_matrix, size); if (min != -1) { deixtra_matrix[2][min] = 1; algorithm(deixtra_matrix, matrix, min); recursion(deixtra_matrix, matrix, min, list); } } mx_push_back_custom(list, deixtra_matrix[0], deixtra_matrix[1], size); mx_del_intarr(&deixtra_matrix, size); free(deixtra_matrix[2]); }
C
/* ************************************************************************** * more - display the contents of a file */ nomask int more_file(string path) { int line; object tp; CHECK_LEVEL(_BUILDER); tp = this_interactive(); if (!path || !strlen(path)) { tp->catch_tell("Usage: more [line] <filename>\n"); return -1; } sscanf(path, "%d %s", line, path); path = FPATH(tp->query_path(), path); if (!path || !strlen(path)) { tp->catch_tell("Bad file name format.\n"); return -1; } if (file_size(path) < 0) { tp->catch_tell("No such file: " + path + "\n"); return -1; } tp->catch_tell(" --- showing file " + path + "\n"); more(path, tp, 0, line); return 1; }
C
#ifdef APP_BETA_LABS #include "usr/beta_labs/cmd/cmd_inv.h" #include "sys/commands.h" #include "sys/defines.h" #include "usr/beta_labs/inverter.h" #include <stdint.h> #include <stdlib.h> #include <string.h> static command_entry_t cmd_entry; #define NUM_HELP_ENTRIES (2) static command_help_t cmd_help[NUM_HELP_ENTRIES] = { { "dtc <uDcomp> <mCurrLimit>", "Set deadtime compensation" }, { "Vdc <mVdc>", "Set Vdc" }, }; void cmd_inv_register(void) { // Populate the command entry block commands_cmd_init(&cmd_entry, "inv", "Inverter commands", cmd_help, NUM_HELP_ENTRIES, cmd_inv); // Register the command commands_cmd_register(&cmd_entry); } // // Handles the 'inv' command // and all sub-commands // int cmd_inv(int argc, char **argv) { // Handle 'dtc' sub-command if (strcmp("dtc", argv[1]) == 0) { // Check correct number of arguments if (argc != 4) return CMD_INVALID_ARGUMENTS; // Pull out uDcomp argument // and saturate to 0 .. 0.2 double uDcomp = (double) atoi(argv[2]); if (uDcomp > 200000.0) return CMD_INVALID_ARGUMENTS; if (uDcomp < 0.0) return CMD_INVALID_ARGUMENTS; // Pull out mCurrLimit argument // and saturate to 0 ... 4A double mCurrLimit = (double) atoi(argv[3]); if (mCurrLimit > 4000.0) return CMD_INVALID_ARGUMENTS; if (mCurrLimit < 0.0) return CMD_INVALID_ARGUMENTS; inverter_set_dtc(uDcomp / 1000000.0, mCurrLimit / 1000.0); return CMD_SUCCESS; } // Handle 'Vdc' sub-command if (strcmp("Vdc", argv[1]) == 0) { // Check correct number of arguments if (argc != 3) return CMD_INVALID_ARGUMENTS; // Pull out mVdc argument // and saturate to 0 .. 100V double mVdc = (double) atoi(argv[2]); if (mVdc > 100000.0) return CMD_INVALID_ARGUMENTS; if (mVdc < 0.0) return CMD_INVALID_ARGUMENTS; inverter_set_Vdc(mVdc / 1000.0); return CMD_SUCCESS; } return CMD_INVALID_ARGUMENTS; } #endif // APP_BETA_LABS
C
#include "csapp.h" #define NUM_THREADS 4 #define SBUF_SIZE 16 // an array queue // interestingly, using PV we don't have to manage the state of // empty or full, it will suspend and wait for insert or remove // but we can't insert and remove on the same thread, it may cause dead-lock. typedef struct { int *buf; //array buf int n; // max number of queue int front; //if queue isn't empty, buf[(front+1) % n] is first item int rear; //if queue isn't empty, buf[rear % n] is last item sem_t mutex; // mutex for buf sem_t slots; //number of avilable slots sem_t items; //number of avilable items } sbuf_t; void sbuf_init(sbuf_t *psbuf, int n) { psbuf->n = n; psbuf->buf = malloc(n * sizeof(int)); psbuf->front = 0; psbuf->rear = 0; Sem_init(&psbuf->mutex, 0, 1); Sem_init(&psbuf->slots, 0, n); Sem_init(&psbuf->items, 0, 0); } void sbuf_deinit(sbuf_t *psbuf) { Free(psbuf->buf); } void sbuf_insert(sbuf_t *psbuf, int value) { P(&psbuf->slots); P(&psbuf->mutex); psbuf->rear = (psbuf->rear + 1) % psbuf->n; (psbuf->buf)[psbuf->rear] = value; V(&psbuf->mutex); V(&psbuf->items); } int sbuf_remove(sbuf_t *psbuf) { P(&psbuf->items); P(&psbuf->mutex); int value = (psbuf->buf)[(psbuf->front + 1) % psbuf->n]; psbuf->front += 1; V(&psbuf->mutex); V(&psbuf->slots); return value; } sbuf_t sbuf; static int byte_count = 0; static sem_t mutex; void echo_count(int connfd) { int n; char buf[MAXLINE]; rio_t rio; Rio_readinitb(&rio, connfd); while ((n = Rio_readlineb(&rio, buf, MAXLINE)) != 0) { P(&mutex); byte_count += n; printf("server received: %d (%d total) bytes on fd %d\n", (int)n, byte_count, connfd); V(&mutex); Rio_writen(connfd, buf, n); } } void *thread_routine(void *parg) { Pthread_detach(pthread_self()); while (1) { int connfd = sbuf_remove(&sbuf); echo_count(connfd); Close(connfd); } } sbuf_t sbuf; int main(int argc, char const *argv[]) { sem_init(&mutex, 0, 1); int listenfd; int connfd; pthread_t pids[NUM_THREADS]; socklen_t clientlen = sizeof(struct sockaddr_storage); struct sockaddr_storage clientaddr; char client_hostname[MAXLINE]; char client_port[MAXLINE]; if (argc != 2) { fprintf(stderr, "usage: %s <port>\n", argv[0]); exit(0); } listenfd = open_listenfd(argv[1]); sbuf_init(&sbuf, SBUF_SIZE); for (int i = 0; i < NUM_THREADS; i++) { Pthread_create(&pids[i], NULL, thread_routine, NULL); } while (1) { connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen); Getnameinfo((SA *)&clientaddr, clientlen, client_hostname, MAXLINE, client_port, MAXLINE, 0); printf("Connected to (%s, %s)\n", client_hostname, client_port); //note we can't pass &connfd to get connfd in new thread, it will cause data race. //we just pass connfd then cast void* to int... sbuf_insert(&sbuf, connfd); } return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #define FILE_NAME "dict_spanish.txt" #define MAX_DIC_LEN 100000 typedef struct dicto { char **values; int length; } dicto; int buildDicto(char ** d) { FILE * infile; char line[121]; char ** info = NULL; int llen; int counter = 0; int backdown; infile = fopen(FILE_NAME, "r"); while (fgets(line, 120, infile)) { // Allocate memory for pointer to line just added // d= realloc(d,(counter+1) * sizeof(char *)); // And allocate memory for that line itself! llen = strlen(line); d[counter] = calloc(sizeof(char), llen + 1); line[llen - 1] = '\0'; // Copy the line just read into that memory strcpy(d[counter], line); //printf("%d characters in line %d \n",llen,counter); counter++; } //for (backdown = counter-1; backdown >= 0; backdown--) { // printf("%d: %s",backdown,info[backdown]); // } int length = counter; // printf("%d\n",length); return length; } //#include "Functions.h" /* int main(){ char * d[MAX_DIC_LEN ]; int n = buildDicto(d); printf("%d\n",n); int i; for (i = 0; i < n; i++) { printf("%d: %s",i,d[i]); } } */
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "lib.h" #include "funciones.h" /** \brief Inicializa el status en un array de programadores * * \param personArray[] ePerson el array en el cual inicializara * \param arrayLenght int la longitud del array * \return void * */ void inicializarProgramadores(eProgramador arrayProgramadores[],int arrayLength) { int i; for(i=0;i<arrayLength;i++) //en cada posicion del array { arrayProgramadores[i].status==0; } } /** \brief Inicializa el status en un array de categorias * * \param personArray[] ePerson el array en el cual inicializara * \param arrayLenght int la longitud del array * \return void * */ void setCategoriaStatus(eCategoria arrayCategorias[],int arrayLength) { int i; for(i=0;i<arrayLength;i++) //en cada posicion del array { arrayCategorias[i].status==0; } } /** \brief Inicializa el status en un array de proyectos * * \param personArray[] ePerson el array en el cual inicializara * \param arrayLenght int la longitud del array * \return void * */ void setProyectoStatus(eProyecto arrayProyectos[],int arrayLength) { int i; for(i=0;i<arrayLength;i++) //en cada posicion del array { arrayProyectos[i].status==0; } } int menu() { int opcion; system("cls"); printf("**Menu de opciones**\n\n"); printf("1- Alta Programador\n"); printf("2- Modificacion Programador\n"); printf("3- Baja Programador\n"); printf("4- Asignar Programador a Proyecto\n"); printf("5- Mostrar listado de Programadores\n"); printf("6- Mostrar listado de todos los Proyectos\n"); printf("7- Mostrar listado de Proyectos de Programador\n"); printf("8- Mostrar Proyecto con mas Programadores asingados\n"); printf("9-salir"); printf("\nIngrese opcion: "); scanf("%d", &opcion); return opcion; } /** \brief Busca la primer ocurrencia de una persona mediante su codigo * * \param programmerArray[] eProgramador es el array en el cual buscar * \param arrayLenght int La longitud del array * \param id int es el valor que se busca * \return int si no hay ocurrencia (-1) y si la hay la posicion en el array de la misma (i) * */ int findProgramadorById(eProgramador programmerArray[],int arrayLenght,int id) { int i; for(i=0;i<arrayLenght;i++) { if(programmerArray[i].idProgramador==id&&programmerArray[i].status==1) { return i; } } return -1; } int findCategoriaById(eCategoria CategoriesArray[],int arrayLenght,int id) { int i; for(i=0;i<arrayLenght;i++) { if(CategoriesArray[i].idCateg==id&&CategoriesArray[i].status==1) { return i; } } return -1; } int findProyectById(eProyecto proyectsArray[],int arrayLenght,int id) { int i; for(i=0;i<arrayLenght;i++) { if(proyectsArray[i].idProyecto==id&&proyectsArray[i].status==1) { return i; } } return -1; } void showListadoDeProgramadores (eProgramador arrayDeProgramadores[], int arrayProgLength, eCategoria arrayCategorias[], int arrayCatLength, eProyecto arraydeProyectos[], int arrayProyLength, eProgramador_Categoria arrayProg_Cat[], int arrayCYPLength, eProgramador_Proyecto arrayProg_Proy[], int arrayPYPLength) { int i;//,j,k,m,n; int auxIdProgramador; int auxIdCategory; int auxCategory[50]; /* char auxProyecto[51]; char NombreYApellido[200];//no olvidar concatenar*/ printf("\n |\tID\t|\t|\tNOMBRE Y APELLIDO\t|\t|\tCATEGORIA\t|\t"); for(i=0;i<arrayProgLength;i++) //busca en array de programadores { if(arrayDeProgramadores[i].status==1) { auxIdCategory=findCategoriaById(arrayCategorias,arrayCatLength,arrayDeProgramadores[i].idCategoria);//busca coincidencia entre id de categoria entre array de programadores y array de categorias if(auxIdCategory!=-1)//en el caso de coincidir { strcpy(auxCategory,arrayCategorias[auxIdCategory].descripcionCateg); } printf("|\t%d\t|\t%s\t%s\t|\t%s\t|",arrayDeProgramadores[i].idProgramador,arrayDeProgramadores[i].nombreProg,arrayDeProgramadores[i].apellidoProg,auxCategory); } } }
C
/* cٲ: : feof : ϵļ : int feof(FILE *stream); */ #include <stdio.h> int main(void) { FILE *stream; /* open a file for reading */ stream = fopen("file.txt", "r"); /* read a character from the file */ fgetc(stream); /* check for EOF */ if (feof(stream)) printf("We have reached end-of-file\n"); /* close the file */ fclose(stream); return 0; }
C
#include "stdio.h" int main() { int km; scanf("%d",&km); int tempo = (60 * km) / 30; printf("%d minutos\n",tempo); return 0; }
C
#include "TreeData.h" Data* createData(int n, char* label) { Data* data = malloc(sizeof(Data)); data->name = label; data->num = n; } int compareNodes(TYPE left, TYPE right) { Data* newLeft = (Data*)left; Data* newRight = (Data*)right; if (newLeft->num < newRight->num) { return -1; } else if (newLeft->num > newRight->num) { return 1; } return 0; }
C
#define _CRT_SECURE_NO_DEPRECATE #include "rwchead.h" int* bubblesort(int* inputArray, int length); void swap(int *i, int *j); int main(void) { char* inputFileName = "random.txt"; char* outpuFileName = "c bubble sort.txt"; int count = countElement(inputFileName); int* readfile = readTxtfile(inputFileName, count); int* sortedArray = bubblesort(readfile, count); writeTxtFile(sortedArray, outpuFileName, count); printf("!] Sucess! \n"); } int* bubblesort(int* inputArray, int length) { int i, j; for (i = 1; i < length; i++) { for (j = 0; j < length - 1; j++) { if (inputArray[j] > inputArray[j + 1]) { swap(&inputArray[j], &inputArray[j + 1]); } } } return inputArray; } void swap(int* i, int* j) { int temp = *i; *i = *j; *j = temp; }
C
Ҫ: Linuxled 1, ӦÿռõĿ 2, Զ豸ڵķ 3, ں˶Ӳʼķʽ 4, Ӧÿռں֮ݽ 5, linuxioctlʵֺgpio⺯ʹ --------------------------------------------------- 2, Զ豸ڵķ #define MINORBITS 20 #define MINORMASK ((1U << MINORBITS) - 1) #define MAJOR(dev) ((unsigned int) ((dev) >> MINORBITS)) #define MINOR(dev) ((unsigned int) ((dev) & MINORMASK)) #define MKDEV(ma,mi) (((ma) << MINORBITS) | (mi)) // 1---ǰģ--THIS_MODULE // 2---ַ,ʾ //ֵ--struct classָ class_create(owner, name); //һ豸ڵ // 1---class_createصָ // 2---豸Ǹ--һ㶼NULL //3--豸--豸majorʹ豸minor //4---˽ָ---һ㶼NULL //5---豸ڵ // /dev/led // ֵ--struct deviceָ struct device *device_create(struct class *cls, struct device *parent, dev_t devt, void *drvdata, const char *fmt, ...) // 3, ʼӲ //1---ַ //2--ӳij //ֵ--ӳַ֮ gpc0_conf = ioremap(0xE0200060, 8); 4, Ӧÿռں֮ݽ // ûռȡ, һ㶼д-- xxx_write // 1---Ŀַ---ںеĿռĵַ //2---ԭַ---ûռĵַ //3---ݸ //ֵ--ûпɹݸ, 0ʾɹ unsigned long copy_from_user(void * to,const void __user * from,unsigned long n) //ûռ, һ㶼ж-- xxx_read unsigned long copy_to_user(void __user * to,const void * from,unsigned long n) 5, linuxioctlʵֺgpio⺯ʹ Ҫûṩʹapi,һioctlӿ: ioctl()ڸָ: ij, ij, ȫ,ȫ Ӧÿռ: int ioctl(int fd, int cmd, .../unsigned long args); -------------------------------------------------------- : xxx_ioctl(struct file *filp, unsigned int cmd, unsigned long args) { //ֲͬ switch(cmd) { case 1: case 2: case 3: case 4: } } ζ: ɳԳ, һҪһ 1,ֱһ--пϵͳеѾڵͻ #define LED_ALL_ON 0x2222 #define LED_ALL_OFF 0x3333 2, ںṩӿһ _IO(type,nr) //1--ħ--ַ // 2--Ψһ _IOW(type,nr,size) _IOR(type,nr,size) _IOWR(type,nr,size) : #define LED_NUM_ON _IOW('L',0x3456, int) #define LED_NUM_OFF _IOW('L',0x3457, int) #define LED_ALL_ON _IO('L',0x3458) #define LED_ALL_OFF _IO('L',0x3459) gpio: 1, ֱӲgpioڶӦļĴַ(ԭͼ---ֲ---ַ--ioremap) *gpc0_conf &= ~(0xff<<12); *gpc0_conf |= (0x11<<12); 2, gpio⺯Ľӿ---ֻҪ֪gpioڵĺ뼴 gpio_request(unsigned gpio,const char * label) // ijgpioó,ֱߵ͵ƽ gpio_direction_output(unsigned gpio,int value) // ijgpioó빦 gpio_direction_input(unsigned gpio) // ijgpioóض s3c_gpio_cfgpin(unsigned int pin,unsigned int config) //ijgpioڲ s3c_gpio_setpull(unsigned int pin,s3c_gpio_pull_t pull) //ȡgpioֵ gpio_get_value //gpioֵ gpio_set_value //ͨgpioڻȡжϺ gpio_to_irq gpio_free(unsigned gpio)
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_listdelnode.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ntrancha <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/12/30 06:09:07 by ntrancha #+# #+# */ /* Updated: 2015/08/19 07:33:57 by ntrancha ### ########.fr */ /* */ /* ************************************************************************** */ #include "../../includes/list.h" #include "../../includes/mem.h" void ft_listdelnode(t_list *list, t_node *node, void (del)(void **)) { if (list && node && ft_listcontent(list, node)) { if (node->previous) node->previous->next = node->next; if (node->next) node->next->previous = node->previous; if (list->end == node) list->end = node->previous; if (list->start == node) list->start = node->next; if (node->content) del(&(node->content)); list->size--; ft_memdel((void**)&node); } }
C
#include <stdio.h> #include <stdlib.h> int main(int ac, char **av) { if (ac == 4) { int nb1 = atoi(av[1]), nb2 = atoi(av[3]), result = 0; char op = av[2][0]; if (op == '+') result = nb1 + nb2; if (op == '-') result = nb1 - nb2; if (op == '*') result = nb1 * nb2; if (op == '/') result = nb1 / nb2; if (op == '%') result = nb1 % nb2; printf("%d\n", result); } else printf("\n"); return (0); }
C
/******************************************************************************* * @File: main.c * @Author: Milandr, L. * @Project: Sample 2.1 * @Microcontroller: 1986VE92U * @Device: Evaluation Board For MCU 1986VE92U * @Date: 04.04.2017 * @Purpose: *******************************************************************************/ // #include "main.h" // int main(void) { // uint8_t current_state = RED; // LED_Init(); // BTN_Init(); // LED_ImplementState(current_state); // while (1) { // if ((MDR_PORTC->RXTX & (1 << 2)) == 0) { // current_state++; // if (current_state > BLUE) current_state = RED; // LED_ImplementState(current_state); } // (~100 ) DELAY(1000); } }
C
/* Bryson Goad * Parallel Quicksort * Implementation of a parallel quicksort using OpenMP * uses in place recursive quicksort algorithm * parallel sort reverts to sequential at cutoff partition size to eliminate unnecessary overhead and improve performance * optimal cutoff point may vary, in my testing around 440000 worked well * * randomly generates an array of ints for ease of testing with various sizes * runs sequential and parallel sorts with same data and calculates average time for each * * Program Arguments: <thread_count> <array_length> <cutoff> <test_count> */ #include <stdio.h> #include <time.h> #include <stdlib.h> #include <stdbool.h> #include <omp.h> #include <string.h> //#define DISPLAY_ARR // displays arrays when defined #define SEQ // runs sequential quicksort when defined #define PAR // runs parallel quicksort when defined void qSort(int[], int); int partition(int[], int); void qSortPar(int[], int); int thread_count; // number of threads used for parallel sections int cutoff; // array sizes less than the cutoff will revert to sequential sort int main(int argc, char* argv[]) { int length; // length of the array being sorted int *A1, *A2; // arrays to be sorted double time_start, time_end; // start and end time of the sort int test_count; // number of times to run the sort double seq_sum = 0; // sum of sequential run times, used for calculating average double par_sum = 0; // sum of parallel run times, used for calculating average // get program arguments thread_count = atoi(argv[1]); length = atoi(argv[2]); cutoff = atoi(argv[3]); test_count = atoi(argv[4]); printf("thread_count: %d\n", thread_count); printf("length: %d\n", length); printf("cutoff: %d\n", cutoff); printf("test_count: %d\n\n", test_count); // allocate arrays A1 = malloc(length * sizeof(int)); A2 = malloc(length * sizeof(int)); // seed random number generator srand(time(NULL)); for (int i = 0; i < test_count; i++) { // generate random data printf("generating data..."); #pragma omp parallel for num_threads(thread_count) for (int i = 0; i < length; i++) { A1[i] = rand(); } memcpy(A2, A1, length * sizeof(int)); printf("done generating\n"); #ifdef DISPLAY_ARR // display unsorted array for (int i = 0; i < length; ++i) { printf("%d, ", A1[i]); } printf("\n"); #endif /*--------- sequential sort --------------------------------------*/ #ifdef SEQ printf("\nsequential sort:\n"); time_start = omp_get_wtime(); // start timer qSort(A1, length); // sequential sort time_end = omp_get_wtime(); // end timer #ifdef DISPLAY_ARR // display sorted array for (int i = 0; i < length; ++i) { printf("%d, ", A1[i]); } printf("\n"); #endif // add elapsed time to sum seq_sum += (time_end - time_start); // display elapsed time printf("elapsed time: %f\n\n", time_end - time_start); #endif /*--------------------------------------------------------------*/ /*--------- parallel sort ---------------------------------------*/ #ifdef PAR printf("parallel sort:\n"); time_start = omp_get_wtime(); // start timer // parallel sort #pragma omp parallel num_threads(thread_count) { // start by creating a partition with a single thread #pragma omp single nowait qSortPar(A2, length); } time_end = omp_get_wtime(); // end timer #ifdef DISPLAY_ARR // display sorted array for (int i = 0; i < length; ++i) { printf("%d, ", A2[i]); } printf("\n"); #endif // add elapsed time to sum par_sum += (time_end - time_start); // display elapsed time printf("elapsed time: %f\n\n", time_end - time_start); #endif /*--------------------------------------------------------------*/ } printf("\n"); // calculate and display average times #ifdef SEQ printf("sequential average: %f\n", seq_sum/test_count); #endif #ifdef PAR printf("parallel average: %f\n", par_sum/test_count); #endif return 0; } // Sequential Quicksort // Parameters: // A : pointer to start of partition to sort // Length : length of partition void qSort(int A[], int length) { // a single element is already sorted if (length > 1) { int p = partition(A, length); // create partition qSort(A, p); // sort left side qSort(A + p, length - p); // sort right side } } // Creates partition for quicksort // Parameters: // A : pointer to start of partition to sort // Length : length of partition // Returns: // pivot point int partition(int A[], int length) { int pivot = A[length / 2]; // select pivot int i = 0; // left side index int j = length - 1; // right side index // find elements on the wrong side of pivot and swap them in place while (true) { while (A[i] < pivot) i++; while (A[j] > pivot) j--; if (i >= j) return i; int temp = A[i]; A[i] = A[j]; A[j] = temp; i++; j--; } } // Parallel Quicksort // must be started by a single thread // creates OpenMP tasks for each side of the partition when partition size is above cutoff // reverts to sequential quicksort when partition size is below cutoff // Parameters: // A : pointer to start of partition to sort // Length : length of partition void qSortPar(int A[], int length) { // a single element is already sorted if (length > 1) { int p = partition(A, length); // create partition // if below cutoff revert to sequential if (length < cutoff) { qSortPar(A, p); // sort left side qSortPar(A + p, length - p); // sort right side } else { // create a task to sort the left side #pragma omp task default(none) firstprivate(A, p) qSortPar(A, p); // create a task to sort the right side #pragma omp task default(none) firstprivate(A, p, length) qSortPar(A + p, length - p); } } }
C
#include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <unistd.h> #include <errno.h> #include <stdio.h> #include <arpa/inet.h> #include <strings.h> #include <string.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #include <signal.h> #include <pthread.h> #define KEYBOARD 0 #define SCREEN 1 #define DO_FOREVER 1 #define true 1 #define false 0 int CONNECTED = 0; extern int errno; /* Codul de eroare returnat de unele functii */ int port; /* Portul folosit pentru conectare */ int Comm_sock; // descriptorul de socket pentru comunicarea cu serverul char username[25]; void Connect_to_server(char IP[50],char PORT[10]) { if ( -1 == (Comm_sock = socket (AF_INET, SOCK_STREAM, 0)) ) { perror ("Error at creating the socket in Config_Socket!\n"); exit(errno); } struct sockaddr_in server; port = atoi (PORT); /* umplem structura folosita pentru realizarea conexiunii cu serverul */ /* familia socket-ului */ server.sin_family = AF_INET; /* adresa IP a serverului */ server.sin_addr.s_addr = inet_addr(IP); /* portul de conectare */ server.sin_port = htons (port); /* ne conectam la server */ if (connect (Comm_sock, (struct sockaddr *) &server,sizeof (struct sockaddr)) == -1) { perror ("Error at connecting in the server!\n"); exit(errno); } } void Requesting_registration() { char user_reg[121]; /* Reading peoples information */ memset(user_reg,32,121); int read_size; printf("[CLIENT-specifications]Completezi formularul de inregistrate!\n[CLIENT-specifications]Asigurate ca datele introduse sunt corecte!\n"); printf("#############################################################################\n"); printf("[CLIENT]Introduceti numele de utilizator: "); fflush(stdout); if( 0 >= (read_size = read(KEYBOARD,user_reg,25) )) { perror("Error at reading the username from the keyboard in Write_registration!\n"); exit(errno); } user_reg[read_size-1] = 32; printf("[CLIENT]Introduceti parola: "); fflush(stdout); if( 0 >= (read_size = read(KEYBOARD,user_reg+25,25) )) { perror("Error at reading the password from the keyboard in Write_registration!\n"); exit(errno); } user_reg[read_size+25-1] = 32; printf("[CLIENT]Introduceti-va prenumele: "); fflush(stdout); if( 0 >= (read_size = read(KEYBOARD,user_reg+50,20) )) { perror("Error at reading the name from the keyboard in Write_registration!\n"); exit(errno); } user_reg[read_size+50-1] = 32; printf("[CLIENT]Introduceti-va numele: "); fflush(stdout); if( 0 >= (read_size = read(KEYBOARD,user_reg+70,20) )) { perror("Error at reading the surname from the keyboard in Write_registration!\n"); exit(errno); } user_reg[read_size+70-1] = 32; printf("[CLIENT]Introduceti-va data de nastere(DD/MM/YYYY): "); fflush(stdout); if( 0 >= (read_size = read(KEYBOARD,user_reg+90,15) )) { perror("Error at reading the date of birth from the keyboard in Write_registration!\n"); exit(errno); } user_reg[read_size+90-1] = 32; printf("[CLIENT]Introduceti-va sexul(MALE/FEMALE): "); fflush(stdout); if( 0 >= (read_size = read(KEYBOARD,user_reg+105,10) )) { perror("Error at reading the sex from the keyboard in Write_registration!\n"); exit(errno); } user_reg[read_size+105-1] = 32; printf("#############################################################################\n");fflush(stdout); /* Sending to the server the information */ if( -1 == write(Comm_sock,user_reg,120)) { perror("Error at writing the registration in Write_registration!\n"); exit(errno); } } int Requesting_login() { char USER[25],PASS[25]; bzero(USER,25);bzero(PASS,25); int size; printf("[CLIENT-specification]Completati procedura de logare!\n"); fflush(stdout); printf("#############################################################################\n");fflush(stdout); printf("[CLIENT]Introduceti username-ul: "); fflush(stdout); if(-1 == (size = read(KEYBOARD,USER,25)))/* Reading the username and password for login from the keyboard */ { perror("Error at reading the username in the DO_LOGIN!\n"); exit(errno); } USER[size - 1] = 0; printf("[CLIENT]Introduceti parola: "); fflush(stdout); if(-1 == (size = read(KEYBOARD,PASS,25))) { perror("Error at reading the password in the DO_LOGIN!\n"); exit(errno); } PASS[size - 1] = 0; if(-1 == write(Comm_sock,USER,25)) /* Sending the username and password for login to the server */ { perror("Error at writing the username in the DO_LOGIN!\n"); exit(errno); } if(-1 == write(Comm_sock,PASS,25)) { perror("Error at writing the password in the DO_LOGIN!\n"); exit(errno); } char answer[300]; bzero(answer,300); if(-1 == (size = read(Comm_sock,answer,300))) { perror("Error at reading the password in the DO_LOGIN!\n"); exit(errno); } if( -1 == write(SCREEN,answer,size)) /* Scriem pe ecran mesajul primit */ { perror("Error at writing the message from server to SCREEN in ReceiveFromServer_thread!\n"); exit(errno); } if(strstr(answer,"succes") != NULL) return true; return false; } void Register_Login() { char command[50]; while(DO_FOREVER) { printf("[CLIENT]Insereaza comanda: "); fflush(stdout); int size_command; if( -1 == ( size_command = read(KEYBOARD,command,50)) )/* Citim ce dorim sa facem (register/login) */ { perror("Error at reading the command in the Register_Login!\n"); exit(errno); } command[size_command-1] = 0; if( strcmp(command,"login") == 0 ) { if(-1 == write(Comm_sock,command,10))/* Reading the username and password for login from the keyboard */ { perror("Error at reading the username in the DO_LOGIN!\n"); exit(errno); } if( true == Requesting_login()) { CONNECTED = true; break;} } else if( strcmp(command,"register") == 0) { if(-1 == write(Comm_sock,command,10))/* Reading the username and password for login from the keyboard */ { perror("Error at reading the username in the DO_LOGIN!\n"); exit(errno); } char response[300]; bzero(response,300); Requesting_registration(); if(-1 == read(Comm_sock,response,300)) { perror("Error at reading the asnwer from registration!\n"); exit(errno); } printf("%s",response); } else { printf("[CLIENT-help]Comanda introdusa nu este cunoscuta. Va rog sa incercati din nou.\n[CLIENT-help]Singurele comenzi disponibile sunt <login> si <register>!\n"); printf("#############################################################################\n");fflush(stdout); } } } static void * ReceiveFromServer_thread(void * arg) { char received[10000]; bzero(received,10000); int size = 0; while(DO_FOREVER) { if( -1 == (size = read(Comm_sock,received,10000)) ) /* Citim mesajul de la server */ { perror("Error at receiving a message from server in ReceiveFromServer_thread!\n"); exit(errno); } if(size == 0) {printf("[CLIENT]Conexiunea cu serverul s-a inchis..Inchidem aplicatia...\n"); exit(1);} if( -1 == write(SCREEN,received,size)) /* Scriem pe ecran mesajul primit */ { perror("Error at writing the message from server to SCREEN in ReceiveFromServer_thread!\n"); exit(errno); } if(strcmp("[SERVER]Te-ai delogat cu success!\n",received) == 0) { printf("[CLIENT]Clientul se va inchide...\n"); exit(EXIT_SUCCESS); } bzero(received,size); } } void SendToServer_mainthread() { char sent[10000]; bzero(sent,10000); int size = 0; pthread_t receive_thread,send_thread; while(DO_FOREVER) { bzero(sent,size + 1); if( -1 == (size = read(KEYBOARD,sent,10000)) ) /* Citim mesajul de la server */ { perror("Error at reading a message from KEYBOARD in SendToServer_mainthread!\n"); exit(errno); } if( -1 == write(Comm_sock,sent,size+1)) /* Scriem pe ecran mesajul primit */ { perror("Error at sending the message to the server in SendToServer_mainthread!\n"); exit(errno); } } } int main(int argc, char *argv[]) { if (argc != 3) /* Verificam daca am primit informatiile necesare pentru conectare */ { printf ("[CLIENT]Sintaxa pentru client este: <adresa_server> <port>\n"); exit(-1); } Connect_to_server(argv[1],argv[2]);/* Ne conectam la server */ Register_Login(); pthread_t receive_thread,send_thread; pthread_create(&receive_thread, NULL, &ReceiveFromServer_thread, NULL); SendToServer_mainthread(); return 0; }
C
/* Solve AX = b, where A is a lower triungular matrix */ #include <stdio.h> #include <stdlib.h> //X[i] = (b[i] - sum) / A[i][i] #define N 2 int main(void) { int **A, *b; float *X; int lin = N; int col = 1; int i, j; float sum; A = (int**) malloc(lin * sizeof(int*)); b = (int*) malloc(lin * sizeof(int)); X = (float*) malloc(lin * sizeof(float)); //read b for(i = 0; i < lin; i++) { printf("b[%d] = ", i); scanf("%d", &b[i]); } //construct the LT matrix for(i = 0; i < lin; i++) { A[i] = calloc(col, sizeof(int)); for(j = 0; j < col; j++) { printf("A[%d][%d] = ", i, j); scanf("%d", &A[i][j]); } col++; } for(i = 0; i < lin; i++) { sum = 0; for(j = 0; j < i; j++) { sum += A[i][j] * X[j]; } X[i] = (float) (b[i] - sum) / A[i][i]; printf("X[%d] = %.2f\n", i, X[i]); } for(i = 0; i < lin; i++) { free(A[i]); } free(A); free(X); free(b); return 0; }
C
#include <stdio.h> #include "minunit.h" #include "../src/nlk_array.h" int tests_run = 0; int tests_passed = 0; /** * Test writing an array to a text file and loading from it */ static char * test_array_text() { FILE *fp; size_t rows = 20; size_t cols = 31; /* create, init */ NLK_ARRAY *origin = nlk_array_create(rows, cols); nlk_array_init_uniform(origin, 1, 2); /* save */ fp = fopen("tmp/array.txt", "wb"); if(fp == NULL) { mu_assert("unable to open file for writting: array.txt", 0); } nlk_array_save_text(origin, fp); fclose(fp); /* load */ fp = fopen("tmp/array.txt", "rb"); if(fp == NULL) { mu_assert("unable to open file for reading: array.txt ", 0); } NLK_ARRAY *loaded = nlk_array_load_text(fp); fclose(fp); /* compare headers */ mu_assert("Array-Text Serialization: arrays rows do not match", loaded->rows == origin->rows); mu_assert("Array-Text Serialization: arrays columns do not match", loaded->cols == origin->cols); /* compare data */ for(size_t ri = 0; ri < rows; ri++) { for(size_t ci = 0; ci < cols; ci++) { nlk_real ld = loaded->data[ri * cols + ci]; nlk_real od = origin->data[ri * cols + ci]; if(ld != od) { printf("original = %f\n", od); printf("loaded = %f\n", ld); } mu_assert("Array-Text Serialization: error in data", ld == od); } } return 0; } /** * Test loading an array created with a different tool (text format) */ static char * test_array_load_text() { /* create, init */ size_t rows = 3; size_t cols = 3; nlk_real carr[9] = {0.503196, -0.482911, -0.538873, -1.135939, 0.318962, -0.591220, 0.551616, 0.001735, -0.919580}; NLK_ARRAY *origin = nlk_array_create(rows, cols); nlk_array_init_wity_carray(origin, carr); /* load */ FILE *fp = fopen("data/small.vector.txt", "rb"); if(fp == NULL) { mu_assert("unable to open file for reading: small.vector.txt", 0); } NLK_ARRAY *loaded = nlk_array_load_text(fp); fclose(fp); /* compare headers */ mu_assert("Array-Load-Text: arrays rows do not match", loaded->rows == origin->rows); mu_assert("Array-Load-Text: arrays columns do not match", loaded->cols == origin->cols); /* compare data */ for(size_t ri = 0; ri < rows; ri++) { for(size_t ci = 0; ci < cols; ci++) { nlk_real ld = loaded->data[ri * cols + ci]; nlk_real od = origin->data[ri * cols + ci]; if(ld != od) { printf("original = %f\n", od); printf("loaded = %f\n", ld); } mu_assert("Array-Load-Text: error in data", ld == od); } } return 0; } /** * Function that runs all tests */ static char * all_tests() { mu_run_test(test_array_text); mu_run_test(test_array_load_text); return 0; } int main() { printf("\n-------------------------------------------------------\n"); printf("Serialization Tests\n"); printf("---------------------------------------------------------\n"); char *result = all_tests(); if (result != 0) { printf("%s\n", result); } else { printf("ALL TESTS PASSED\n"); } printf("Tests Passed: %d/%d\n", tests_run, tests_passed); return result != 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_statistics.h> #include <gsl/gsl_permutation.h> int main(int argc, char* argv[]){ const gsl_rng_type *T; gsl_rng *r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); gsl_rng_set(r, 13); int i = 0; int j = 0; int N = 10; int* table = NULL; table = malloc( N * sizeof(int)); for(i=0; i<N; ++i){ table[i] = i; } for(i=0; i<1000; i++){ j=gsl_rng_uniform_int(r, N); printf("%d\n",table[j]); } free(table); }
C
#include <stdio.h> #include <stdlib.h> struct data{ int nim; char nama[20]; }; typedef struct data data; void swap (struct data *a,struct data *b){ data tmp; tmp = *a; *a = *b; *b = tmp; } void cetak(data mhs[100],int n){ for (int i = 0; i < n; ++i) { printf("%d ", mhs[i].nim); } printf("\r\n"); } void InsertionSort(struct data mhs[100], int n) { int i, key, j; for (i = 1; i < n; i++) { key = mhs[i].nim; j = i-1; while (j >= 0 && mhs[j].nim > key) { swap(&mhs[j+1],&mhs[j]); j = j-1; } cetak(mhs,n); mhs[j+1].nim = key; } } void BubbleSort(data mhs[100], int n){ int i, j; int swapped; for (i = 0; i < n-1; i++) { swapped = 0; for (j = 0; j < n-i-1; j++){ if(mhs[j].nim > mhs[j+1].nim){ swap(&mhs[j],&mhs[j+1]); swapped = 1; } cetak(mhs,n); } if (swapped == 0) break; } } int main(){ struct data mhs[100]; int n; char s[8]; scanf("%d", &n); for (int i = 0; i < n; ++i){ scanf("%s %s",s,mhs[i].nama); mhs[i].nim = atoi(s); } InsertionSort(mhs,n); printf("Hasil akhir :\r\n"); for (int i = 0; i < n; ++i) { printf("%d - %s\r\n", mhs[i].nim, mhs[i].nama); } return 0; }
C
/* Name 1: Duc Tran Name 2: Brandon Wong UTEID 1: dmt735 UTEID 2: blw868 */ #include <stdio.h> /* standard input/output library */ #include <stdlib.h> /* Standard C Library */ #include <string.h> /* String operations library */ #include <ctype.h> /* Library for useful character operations */ #include <limits.h> /* Library for definitions of common variable type characteristics */ #define MAX_LINE_LENGTH 255 #define MAX_LABEL_LEN 20 #define MAX_SYMBOLS 255 #define DEBUG_EN0 0 #define DEBUG_EN 1 #define DEBUG_EN1 0 #define ADD 4096 #define AND 20480 #define BRN 2048 #define BRP 512 #define BRNP 2560 #define BR 3584 #define BRZ 1024 #define BRNZ 3072 #define BRZP 1536 #define BRNZP 3584 #define JMP 49152 #define JSR 18432 #define JSRR 16384 #define LDB 8192 #define LDW 24576 #define LEA 57344 #define NOT 36927 #define RET 49600 #define RTI 32768 #define LSHF 53248 #define RSHFL 53264 #define RSHFA 53296 #define STB 12288 #define STW 28672 #define TRAP 61440 #define XOR 36864 #define HALT 61477 FILE* infile = NULL; FILE* outfile = NULL; typedef struct { int address; char label[MAX_LABEL_LEN +1]; }TableEntry; TableEntry symbolTable[MAX_SYMBOLS]; enum{ DONE, OK, EMPTY_LINE }; /***************list of opcode********************/ char* opcodeName[32] = { "add", "and", "brn", "brp", "brnp", "br", "brz", "brnz", "brzp", "brnzp", "jmp", "jsr", "jsrr", "ldb", "ldw", "lea", "not", "ret", "rti", "lshf", "rshfl", "rshfa", "stb", "stw", "trap", "xor", "halt", "nop", "nop", "nop", "nop", "nop" /**/ }; char *pseudoOpcode[3]= { ".orig", ".fill", ".end" }; /* **************isOpcode************* input: char pointer to string output: -1 : not valid opcode OK : valid opcode */ int isOpcode(char * inString){ int i; for(i=0; i < 31;i++){ if(strcmp(opcodeName[i],inString)==0){ if(DEBUG_EN0) printf("opcode found: %s %s \n", inString,opcodeName[i]); return(OK); } } if(DEBUG_EN0) printf("Not an opcode %s \n",inString); return(-1); } /*************End isOpcode************/ /* **************isPseudoOpcode************* input: char pointer to string output: -1 : not valid opcode OK : valid opcode */ int isPseudoOpcode(char * inString){ int i; for(i=0; i < 3;i++){ if(strcmp(pseudoOpcode[i],inString)==0){ if(DEBUG_EN0) printf("pseudo opcode found: %s %s \n", inString,pseudoOpcode[i]); return(OK); } } if(DEBUG_EN0) printf("Not an pseudo opcode %s \n",inString); return(-1); } /*************End isPseudoOpcode************/ /***************regToNum************/ int regToNum(char *reg, int argno){ if(strcasecmp(reg, "R0")==0) { switch(argno) { case 1: return 0; case 2: return 0; case 3: return 0; default: printf("**INVALID ARG**\n"); return 0; } } else if(strcasecmp(reg, "R1")==0) { switch(argno) { case 1: return 512; case 2: return 64; case 3: return 1; default: printf("**INVALID ARG**\n"); return 0; } } else if(strcasecmp(reg, "R2")==0) { switch(argno) { case 1: return 1024; case 2: return 128; case 3: return 2; default: printf("**INVALID ARG**\n"); return 0; } } else if(strcasecmp(reg, "R3")==0) { switch(argno) { case 1: return 1536; case 2: return 192; case 3: return 3; default: printf("**INVALID ARG**\n"); return 0; } } else if(strcasecmp(reg, "R4")==0) { switch(argno) { case 1: return 2048; case 2: return 256; case 3: return 4; default: printf("**INVALID ARG**\n"); return 0; } } else if(strcasecmp(reg, "R5")==0) { switch(argno) { case 1: return 2560; case 2: return 320; case 3: return 5; default: printf("**INVALID ARG**\n"); return 0; } } else if(strcasecmp(reg, "R6")==0) { switch(argno) { case 1: return 3072; case 2: return 384; case 3: return 6; default: printf("**INVALID ARG**\n"); return 0; } } else if(strcasecmp(reg, "R7")==0) { switch(argno) { case 1: return 3584; case 2: return 448; case 3: return 7; default: printf("**INVALID ARG**\n"); return 0; } } else { printf("**ERROR 4 INVALID REGISTER**\n"); exit(4); } } /*********toNum**************/ int toNum( char * pStr ) { char * t_ptr; char * orig_pStr; int t_length,k; int lNum, lNeg = 0; long int lNumLong; orig_pStr = pStr; if( *pStr == '#' ) /* decimal */ { pStr++; if( *pStr == '-' ) /* dec is negative */ { lNeg = 1; pStr++; } t_ptr = pStr; t_length = strlen(t_ptr); for(k=0;k < t_length;k++) { if (!isdigit(*t_ptr)) { printf("Error 4: invalid decimal operand, %s\n",orig_pStr); exit(4); } t_ptr++; } lNum = atoi(pStr); if (lNeg) lNum = -lNum; return lNum; } else if( *pStr == 'x' ) /* hex */ { pStr++; if( *pStr == '-' ) /* hex is negative */ { lNeg = 1; pStr++; } t_ptr = pStr; t_length = strlen(t_ptr); for(k=0;k < t_length;k++) { if (!isxdigit(*t_ptr)) { printf("Error 4: invalid hex operand, %s\n",orig_pStr); exit(4); } t_ptr++; } lNumLong = strtol(pStr, NULL, 16); /* convert hex string into integer */ lNum = (lNumLong > INT_MAX)? INT_MAX : lNumLong; if( lNeg ) lNum = -lNum; return lNum; } else { printf( "Error 4: invalid operand, %s\n", orig_pStr); exit(4); /* This has been changed from error code 3 to error code 4, see clarification 12 */ } } /***********END toNum******************/ /************convertBR*********/ /*Return offset value to be add to opecode*/ int convertBR(int labellen,int memaddr, char *arg1 , char *arg2, char*arg3){ int i; int offset=0; if(strcmp(arg2, "\0") !=0 || strcmp(arg3,"\0")!=0) { printf("ERROR 4: Unwanted Field!"); exit(4); } if(strcmp(arg1,"\0") == 0){ printf("ERROR 4: Missing Field"); exit(4);} else { if(arg1[0] == 'x' || arg1[0] == '#'){ printf("ERROR 4: not a valid label"); exit(4); } for (i=0;i<labellen;i++) { if(strcmp(symbolTable[i].label,arg1) ==0) { offset = (symbolTable[i].address-memaddr)/2; if(offset >= -256 && offset <= 255) { if(offset < 0) { offset = offset - 0xFFFFFE00; } return(offset); } else { printf("ERROR 3: OFFSET TOO LARGE\n"); exit(3); } } } printf("ERROR 1: Undefined label!!!"); exit(1); } } /*********EndConvertBR********/ /***********readAndParse*************/ int readAndParse( FILE * pInfile, char * pLine, char ** pLabel, char ** pOpcode, char ** pArg1, char ** pArg2, char ** pArg3, char ** pArg4 ) { char * lRet, * lPtr; int i; if( !fgets( pLine, MAX_LINE_LENGTH, pInfile ) ) return( DONE ); for( i = 0; i < strlen( pLine ); i++ ) pLine[i] = tolower( pLine[i] ); /* convert entire line to lowercase */ *pLabel = *pOpcode = *pArg1 = *pArg2 = *pArg3 = *pArg4 = pLine + strlen(pLine); /* ignore the comments */ lPtr = pLine; while( *lPtr != ';' && *lPtr != '\0' && *lPtr != '\n' ) lPtr++; *lPtr = '\0'; if( !(lPtr = strtok( pLine, "\t\n ," ) ) ) return( EMPTY_LINE ); if( isOpcode( lPtr ) == -1 && lPtr[0] != '.' ) /* found a label */ { if(isdigit(lPtr[0]) != 0 || tolower(lPtr[0]) == 'x' || isalnum(lPtr[0]) == 0) { printf("**ERROR 4 INVALID LABEL**\n"); exit(4); } *pLabel = lPtr; if( !( lPtr = strtok( NULL, "\t\n ," ) ) ) return( OK ); } *pOpcode = lPtr; if( !( lPtr = strtok( NULL, "\t\n ," ) ) ) return( OK ); *pArg1 = lPtr; if( !( lPtr = strtok( NULL, "\t\n ," ) ) ) return( OK ); *pArg2 = lPtr; if( !( lPtr = strtok( NULL, "\t\n ," ) ) ) return( OK ); *pArg3 = lPtr; if( !( lPtr = strtok( NULL, "\t\n ," ) ) ) return( OK ); *pArg4 = lPtr; return( OK ); } /**************End readAndParse*******/ /************assembleCommand*************/ /* input: int value of Lable table lenght output: DONE Error code: exit(n) 1- undefined label 2- invalid opcode 3- invalid constant 4- other error */ int assembleCommand(int symbolTableLen){ int lRet,i; int memAddr =0; int opcode, arg1, arg2, arg3; int retVal; int labelFlag; /*Line parsing init*/ char lLine[MAX_LINE_LENGTH + 1], *lLabel, *lOpcode, *lArg1, *lArg2, *lArg3, *lArg4; i =0; do { lRet = readAndParse( infile, lLine, &lLabel, &lOpcode, &lArg1, &lArg2, &lArg3, &lArg4 ); if( lRet != DONE && lRet != EMPTY_LINE ) { memAddr++; memAddr++; retVal = 0; /********For Debug*********/ if(DEBUG_EN1){ i++; printf("*****Line: %d ***** \n", i); printf("Label: %s \n",lLabel); printf("Opcode: %s \n",lOpcode); printf("Arg1: %s \n",lArg1); printf("Arg2: %s \n",lArg2); printf("Arg3: %s \n",lArg3); printf("Arg4: %s \n",lArg4); } /********EndDebugBlock*****/ /***Do computation here****/ if(isOpcode(lOpcode) == -1 && isPseudoOpcode(lOpcode) == -1) { printf("**ERROR 2 INVALID OPCODE**"); exit(2); /*Opcode not define in ISA*/ } if(strcmp(lOpcode,".orig")==0){ memAddr = toNum(lArg1); fprintf(outfile, "0x%0.4X\n", toNum(lArg1)); } else if(strcmp(lOpcode,".fill") == 0){ if(strcmp(lArg1,"\0")==0 || strcmp(lArg2,"\0") !=0){ printf("Error 4: Unwanted field or Missing field"); exit(4); } retVal = (toNum(lArg1)); if(retVal > 0xFFFF || retVal < -32768){ printf("ERROR 3: INVALID CONSTANT IN FILL"); exit(3); } if(retVal <=0) { retVal = retVal - 0xFFFF0000; } fprintf(outfile,"0x%0.4X\n",retVal); } else if(strcmp(lOpcode,".end") == 0){ if(strcmp(lArg1,"\0")!=0) { printf("ERROR 4: Unwanted Field \n"); exit(4); } lRet = DONE; } else if(strcmp(lOpcode,"nop") ==0){ if(strcmp(lArg1,"\0")!=0){ printf("Error!!! Unwanted Field \n"); exit(4); } fprintf(outfile,"0x%0.4X\n",0); /*NOP 0X0000*/ } else if(strcmp(lOpcode,"and" )==0){ if(strcmp(lArg1,"\0")==0){ printf("Error!!! Unwanted Field"); exit(4); } else { arg1 = regToNum(lArg1, 1); } if(strcmp(lArg2,"\0")==0){ printf("Error!!! Unwanted Field"); exit(4); } else { arg2 = regToNum(lArg2, 2); } if(strcmp(lArg3,"\0")==0){ printf("Error!!! Unwanted Field"); exit(4); } else { if(lArg3[0] == 'r') { arg3 = regToNum(lArg3, 3); } else if(lArg3[0] == '#' || lArg3[0] == 'x') { if(toNum(lArg3)>=-16 && toNum(lArg3)<=15) { retVal = toNum(lArg3); if(retVal <0) { retVal = retVal - 0xFFFFFFE0; } arg3 = toNum(lArg3) + 32; } else { printf("**ERROR 3 Invalid Constant**\n"); exit(3); } } else { printf("**ERROR 4 INVALID ARG**\n"); exit(4); } } fprintf(outfile,"0x%0.4x\n", AND + arg1 + arg2 + arg3); } else if(strcmp(lOpcode,"add" )==0){ if(strcmp(lArg1,"\0")==0){ printf("Error4!!! Unwanted Field"); exit(4); } else { arg1 = regToNum(lArg1, 1); } if(strcmp(lArg2,"\0")==0){ printf("Error4!!! Unwanted Field"); exit(4); } else { arg2 = regToNum(lArg2, 2); } if(strcmp(lArg3,"\0")==0){ printf("Error 4!!! Unwanted Field"); exit(4); } else { if(lArg3[0] == 'r') { arg3 = regToNum(lArg3, 3); } else if(lArg3[0] == '#' || lArg3[0] == 'x') { if(toNum(lArg3)>=-16 && toNum(lArg3)<=15) { retVal = toNum(lArg3); if(retVal <0) { retVal = retVal - 0xFFFFFFE0; } arg3 = retVal + 32; } else { printf("**ERROR 3 Invalid Constant**\n"); exit(3); } } else { printf("**ERROR 4 INVALID ARG*add*\n"); exit(4); } } fprintf(outfile,"0x%0.4x\n", ADD + arg1 + arg2 + arg3); } else if(strcmp(lOpcode,"brn" )==0){ retVal = convertBR(symbolTableLen, memAddr, lArg1 , lArg2, lArg3); fprintf(outfile,"0x%0.4X\n",BRN+retVal); } else if(strcmp(lOpcode,"brp" )==0){ retVal = convertBR(symbolTableLen,memAddr, lArg1 , lArg2, lArg3); fprintf(outfile,"0x%0.4X\n",BRP+retVal); } else if(strcmp(lOpcode,"br" )==0){ retVal = convertBR(symbolTableLen,memAddr, lArg1 , lArg2, lArg3); fprintf(outfile,"0x%0.4X\n",BR+retVal); } else if(strcmp(lOpcode,"brz" )==0){ retVal = convertBR(symbolTableLen,memAddr, lArg1 , lArg2, lArg3); fprintf(outfile,"0x%0.4X\n",BRZ+retVal); } else if(strcmp(lOpcode,"brnz" )==0){ retVal = convertBR(symbolTableLen,memAddr, lArg1 , lArg2, lArg3); fprintf(outfile,"0x%0.4X\n",BRNZ+retVal); } else if(strcmp(lOpcode,"brzp" )==0){ retVal = convertBR(symbolTableLen,memAddr, lArg1 , lArg2, lArg3); fprintf(outfile,"0x%0.4X\n",BRZP+retVal); } else if(strcmp(lOpcode,"brnzp" )==0){ retVal = convertBR(symbolTableLen,memAddr, lArg1 , lArg2, lArg3); fprintf(outfile,"0x%0.4X\n",BRNZP+retVal); } else if(strcmp(lOpcode,"brnp" )==0){ retVal = convertBR(symbolTableLen,memAddr, lArg1 , lArg2, lArg3); fprintf(outfile,"0x%0.4X\n",BRNP+retVal); } else if(strcmp(lOpcode,"jmp" )==0){ if(strcmp(lArg2,"\0")!=0 || strcmp(lArg1,"\0") == 0) { printf("ERROR 4: Unwanted Field or missing field"); exit(4); }else { retVal = regToNum(lArg1,2); fprintf(outfile,"0x%0.4X\n",JMP+retVal); } } else if(strcmp(lOpcode,"jsr" )==0){ labelFlag = 0; if(strcmp(lArg2,"\0")!=0 || strcmp(lArg1,"\0") == 0) { printf("ERROR 4: Unwanted Field or missing field"); exit(4); } if(lArg1[0] == 'x' || lArg1[0] == '#'){ printf("ERROR 4: not a valid label"); exit(4); } for(i =0;i<symbolTableLen;i++) { if(strcmp(symbolTable[i].label,lArg1)==0) { retVal = (symbolTable[i].address - memAddr)/2; if(retVal >= -1024 && retVal <= 1023) { if(retVal <0) { retVal = retVal - 0xFFFFF800; } fprintf(outfile,"0x%0.4X\n",JSR+retVal); labelFlag =1; break; } else { printf("ERROR 3: OFFSET OUT OF RANGE"); exit(3); } } } if(labelFlag == 0) { printf("ERROR 1: Undefined label!!!"); exit(1); } } else if(strcmp(lOpcode,"jsrr" )==0){ if(strcmp(lArg2,"\0")!=0 || strcmp(lArg1,"\0") == 0) { printf("ERROR 4: Unwanted Field or missing field"); exit(4); }else { retVal = regToNum(lArg1,2); fprintf(outfile,"0x%0.4X\n",JSRR + retVal); } } else if(strcmp(lOpcode,"ldb" )==0){ if(strcmp(lArg1,"\0")==0 || strcmp(lArg2,"\0")==0 || strcmp(lArg3,"\0")==0 ) { printf("Error 4: Missing Operand\n"); exit(4); } retVal = toNum(lArg3); if(retVal >= -32 && retVal <=31) { if(retVal < 0) { retVal = retVal - 0xFFFFFFC0; } retVal = retVal+ regToNum(lArg1,1) + regToNum(lArg2,2);/*Need to convert here**/ fprintf(outfile,"0x%0.4X\n",LDB+retVal); }else{ printf("ERROR 3: Invalid Constant\n"); exit(3); } } else if(strcmp(lOpcode,"ldw" )==0){ if(strcmp(lArg1,"\0")==0 || strcmp(lArg2,"\0")==0 || strcmp(lArg3,"\0")==0 ) { printf("Error 4: Missing Operand\n"); exit(4); } retVal = toNum(lArg3); if(retVal >= -32 && retVal <=31) { if(retVal < 0) { retVal = retVal - 0xFFFFFFC0; } retVal = retVal+ regToNum(lArg1,1) + regToNum(lArg2,2); fprintf(outfile,"0x%0.4X\n",LDW+retVal); }else{ printf("ERROR 3: Invalid Constant"); exit(3); } } else if(strcmp(lOpcode,"lea" )==0){ labelFlag =0; if(strcmp(lArg1,"\0")==0 || strcmp(lArg2,"\0")==0 || strcmp(lArg3,"\0") !=0) { printf("ERROR 4: Missing opperand or unwanted field"); exit(4); } if(lArg2[0] == 'x' || lArg2[0] == '#'){ printf("ERROR 4: not a valid label"); exit(4); } for(i = 0; i < symbolTableLen;i++) { if(strcmp(symbolTable[i].label, lArg2)==0) { retVal = (symbolTable[i].address - memAddr)/2;/****need to convert to 2's complement***/ if(retVal >= -256 && retVal <= 255) { if(retVal < 0) { retVal = retVal - 0xFFFFFE00; } printf("%x!!!!!!!\n", memAddr); retVal = retVal + regToNum(lArg1,1); fprintf(outfile,"0x%0.4X\n",LEA + retVal); labelFlag = 1; break; } } } if(labelFlag == 0) { printf("ERROR 1: UNDEFINED LABEL!!!"); exit(1); } } else if(strcmp(lOpcode,"not" )==0){ if(strcmp(lArg1,"\0") == 0 || strcmp(lArg2,"\0") == 0 || strcmp(lArg3,"\0") !=0) { printf("ERROR 4: Missing Operand or Unwanted field"); exit(4); } retVal = regToNum(lArg1,1) + regToNum(lArg2,2); fprintf(outfile,"0x%0.4X\n",NOT+retVal); } else if(strcmp(lOpcode,"ret" )==0){ if(strcmp(lArg1,"\0")!=0) { printf("ERROR 4: Unwanted Field"); exit(4); } fprintf(outfile,"0x%0.4X\n",RET); } else if(strcmp(lOpcode,"rti" )==0){ if(strcmp(lArg1,"\0")!=0) { printf("ERROR 4: Unwanted Field"); exit(4); } fprintf(outfile,"0x%0.4X\n",RTI); } else if(strcmp(lOpcode,"lshf" )==0){ if(strcmp(lArg1,"\0") == 0 || strcmp(lArg2,"\0") == 0||strcmp(lArg3,"\0") == 0) { printf("ERROR 4: Missing Operand"); exit(4); } retVal = toNum(lArg3); if(retVal >= 0 && retVal <= 15) { retVal = retVal + regToNum(lArg1,1) + regToNum(lArg2,2);/***NEED TO CONVERT TO 2'S complement before adding***/ fprintf(outfile,"0x%0.4X\n",LSHF+retVal); }else { printf("ERROR 3: INVALID CONSTANT"); exit(3); } } else if(strcmp(lOpcode,"rshfl" )==0){ if(strcmp(lArg1,"\0") == 0 || strcmp(lArg2,"\0") == 0||strcmp(lArg3,"\0") == 0) { printf("ERROR 4: Missing Operand"); exit(4); } retVal = toNum(lArg3); if(retVal >= 0 && retVal <= 15) { retVal = retVal + regToNum(lArg1,1) + regToNum(lArg2,2); fprintf(outfile,"0x%0.4X\n",RSHFL +retVal); }else { printf("ERROR 3: INVALID CONSTANT"); exit(3); } } else if(strcmp(lOpcode,"rshfa" )==0){ if(strcmp(lArg1,"\0") == 0 || strcmp(lArg2,"\0") == 0||strcmp(lArg3,"\0") == 0) { printf("ERROR 4: Missing Operand"); exit(4); } retVal = toNum(lArg3); if(retVal >= 0 && retVal <= 15) { retVal = retVal + regToNum(lArg1,1) + regToNum(lArg2,2);/***NEED TO CONVERT TO 2'S complement before adding***/ fprintf(outfile,"0x%0.4X\n",RSHFA+retVal); }else { printf("ERROR 3: INVALID CONSTANT"); exit(3); } } else if(strcmp(lOpcode,"stb" )==0){ if(strcmp(lArg1,"\0")==0 || strcmp(lArg2,"\0")==0 || strcmp(lArg3,"\0")==0 ) { printf("Error 4: Missing Operand"); exit(4); } retVal = toNum(lArg3); if(retVal >= -32 && retVal <=31) { if(retVal<0) retVal = retVal - 0xFFFFFFC0; retVal = retVal+ regToNum(lArg1,1) + regToNum(lArg2,2); fprintf(outfile,"0x%0.4X\n",STB+retVal); }else{ printf("ERROR 3: Invalid Constant"); exit(3); } } else if(strcmp(lOpcode,"stw" )==0){ if(strcmp(lArg1,"\0")==0 || strcmp(lArg2,"\0")==0 || strcmp(lArg3,"\0")==0 ) { printf("Error 4: Missing Operand"); exit(4); } retVal = toNum(lArg3); if(retVal >= -32 && retVal <=31) { if(retVal < 0) retVal = retVal - 0xFFFFFFC0; retVal = retVal+ regToNum(lArg1,1) + regToNum(lArg2,2); fprintf(outfile,"0x%0.4X\n",STW+retVal); }else{ printf("ERROR 3: Invalid Constant"); exit(3); } } else if(strcmp(lOpcode,"trap" )==0){ if(strcmp(lArg2,"\0" ) !=0) { printf("ERROR 4: Unwanted Field \n"); exit(4); } if(lArg1[0] == 'x') { retVal = toNum(lArg1); if(retVal >= 0 && retVal <=255) { fprintf(outfile,"0x%0.4X\n",TRAP+retVal); }else{ printf("ERROR 3: INVALID CONSTANT -OUT OF BOUND \n"); exit(3); } }else{ printf("ERROR 3: INVALID CONSTANT \n"); exit(3); } } else if(strcmp(lOpcode,"xor" )==0){ if(strcmp(lArg1,"\0")==0){ printf("Error 4!!! Unwanted Field"); exit(4); } else { arg1 = regToNum(lArg1, 1); } if(strcmp(lArg2,"\0")==0){ printf("Error 4!!! Unwanted Field"); exit(4); } else { arg2 = regToNum(lArg2, 2); } if(strcmp(lArg3,"\0")==0){ printf("Error 4!!! Unwanted Field"); exit(4); } else { if(lArg3[0] == 'r') { arg3 = regToNum(lArg3, 3); } else if(lArg3[0] == '#' || lArg3[0] == 'x') { if(toNum(lArg3)>=-16 && toNum(lArg3)<=15) { retVal = toNum(lArg3); if(retVal <0) { retVal = retVal - 0xFFFFFFE0; } arg3 = toNum(lArg3) + 32; } else { printf("**ERROR 3 Invalid Constant**\n"); exit(3); } } else { printf("**ERROR 4 INVALID ARG**\n"); exit(4); } } fprintf(outfile,"0x%0.4x\n", XOR + arg1 + arg2 + arg3); } else if(strcmp(lOpcode,"halt" )==0){ if(strcmp(lArg1,"\0") !=0 || strcmp(lArg2,"\0") !=0 || strcmp(lArg3,"\0") !=0 || strcmp(lArg4,"\0") !=0) { printf("Halt error"); exit(4); } fprintf(outfile,"0x%0.4X\n",HALT); } } }while(lRet !=DONE); if(strcmp(lOpcode,".end")!=0){ printf("ERROR 4: NO .END \n"); exit(4); } return (DONE); } /**********END assembleCommand**************/ /**************MAIN*******************/ int main(int argc, char* argv[]){ char *prgName = NULL; char *iFileName = NULL; char *oFileName = NULL; int lRet,i,j; int labelTableLen; int memaddr = 0; int firstOpcode =0; /*Line parsing init*/ char lLine[MAX_LINE_LENGTH + 1], *lLabel, *lOpcode, *lArg1, *lArg2, *lArg3, *lArg4; labelTableLen = 0; i=0; /*Use for debugging*/ prgName = argv[0]; iFileName = argv[1]; oFileName = argv[2]; printf("program name = '%s'\n", prgName); printf("input file name = '%s'\n", iFileName); printf("output file name = '%s'\n", oFileName); /*open in file*/ infile = fopen(argv[1],"r"); if(!infile){ printf("Cannot open %s file \n",argv[1]); exit(4); } do { lRet = readAndParse( infile, lLine, &lLabel, &lOpcode, &lArg1, &lArg2, &lArg3, &lArg4 ); if( lRet != DONE && lRet != EMPTY_LINE ) { memaddr++; memaddr++; j=0; if(firstOpcode == 0 && strcmp(lOpcode,".orig") !=0) { printf("ERROR 4: NOT A VALID PROGRAM"); exit(4); } /*if(strcmp(lOpcode,"\0") == 0){ printf("ERROR 4: NO OPCODE"); exit(4); }*/ /********For Debug*********/ if(DEBUG_EN){ i++; printf("*****Line: %d ***** \n", i); printf("Label: %s \n",lLabel); printf("Opcode: %s \n",lOpcode); printf("Arg1: %s \n",lArg1); printf("Arg2: %s \n",lArg2); printf("Arg3: %s \n",lArg3); printf("Arg4: %s \n",lArg4); printf("Addr: 0x%x\n\n", memaddr); } /********EndDebugBlock*****/ if(memaddr ==1 && strcmp(lOpcode,"\0") == 0) { printf("ERROR: No starting address"); exit(4); } if(isOpcode(lOpcode) == -1 && isPseudoOpcode(lOpcode) == -1) { printf("**ERROR 2 INVALID OPCODE**\n"); exit(2); /*Opcode not define in ISA*/ } else if(strcmp(lOpcode, ".orig") == 0) { firstOpcode = 1; printf ("set starting address \n"); /*if((lArg1[0]=='x') &&(lArg1[4]=='\0' || lArg1[5] !='\0')) { printf("ERROR 3: INVALID STARTING ADDRESS \n"); exit(3); }*/ if(toNum(lArg1) > 0xFFFF || toNum(lArg1) <0){ printf("ERROR 3: INVALID STARTING ADDRESS \n"); exit(3); } if(toNum(lArg1)%2 ==0 ) { memaddr = toNum(lArg1)-2; } else { printf("**ERROR 3 INVALID CONSTANT**\n"); exit(3); } } else if(strcmp(lOpcode,".end") == 0){ if(strcmp(lArg1,"\0")!=0) { printf("ERROR 4: Unwanted Field"); exit(4); } lRet = DONE; } /*Add label to constructor*/ else if(strcmp(lLabel, "\0")!=0 && strcmp(lLabel, "\t\n ,")!=0) { if(labelTableLen == 255) { printf("Lable Table is full\n"); exit(4); } else { if(strcmp(lLabel ,"r0") == 0 || strcmp(lLabel ,"r1") == 0 || strcmp(lLabel ,"r2") == 0 || strcmp(lLabel ,"r3") == 0 ||strcmp(lLabel ,"r4") == 0 ||strcmp(lLabel ,"r5") == 0 || strcmp(lLabel ,"r6") == 0 ||strcmp(lLabel ,"r7") == 0||strcmp(lLabel ,"in") == 0 ||strcmp(lLabel ,"out") == 0||strcmp(lLabel ,"getc") == 0 || strcmp(lLabel ,"puts") == 0) { printf("ERROR 4: Not a Valid label \n"); exit(4); } for(j=0; j<labelTableLen; j++) { if(strcmp(symbolTable[j].label, lLabel) == 0) { printf("Error 4 Label already exists\n"); exit(4); } } strcpy(symbolTable[labelTableLen].label, lLabel); /*Need to add address*/ symbolTable[labelTableLen].address = memaddr; labelTableLen++; } } } }while(lRet !=DONE); /********For Debug*********/ if(DEBUG_EN){ printf("Debug: \n"); for(i = 0;i < labelTableLen;i++){ printf("Label %d : %s Addr: 0x%x \n", i,symbolTable[i].label, symbolTable[i].address); } } /*****End Debug****/ fclose(infile); /*End First pass*/ printf("Done First pass \n"); infile = fopen(argv[1],"r"); outfile = fopen(argv[2],"w"); if(assembleCommand(labelTableLen) == DONE) printf("******FINISH!!! NO ERROR******* \n"); fclose(outfile); fclose(infile); exit(0); }
C
/*************************************************************************** * Copyright (c) Date: Mon Nov 24 16:25:59 CST 2008 Qualcomm Technologies INCORPORATED * All Rights Reserved * Modified by Qualcomm Technologies INCORPORATED on Mon Nov 24 16:25:59 CST 2008 ****************************************************************************/ /*! \file dsp_libs.h \brief Brief description of file */ typedef struct { Word32 result; /*!< Result value */ Word32 scale; /*!< Scale factor */ } us_result_scale_t; /*! Approximates inversion of a 32-bit positive number \param x number to be inverted \details \return 64-bit integer where the high 32-bit is shift factor and the low 32-bit is Q-shifted inverse \b Assembly \b Assumptions - None \b Cycle-Count - 6 \b Notes - Approximation done with a linearly interpolated lookup table. - Data format \par IF input is in Qn and output in Qm, then m = 30 - SF - n . \par For example, \par input is 0x0F000000 in Q26, i.e., 3.75 \par return values are result = 0x44730000, SF = -28 \par Thus, m = 30-(-28)-26 = 32, i.e., inversion is (0x44730000)/2^32 = 0.266464 */ Word64 us_dsplib_approx_invert(Word32 x); /*! Approximates inversion of a 32-bit positive number(fast version) \param x number to be inverted \details \return 64-bit integer where the high 32-bit is shift factor and the low 32-bit is Q-shifted inverse \b Assembly \b Assumptions - None \b Cycle-Count - 5 \b Notes - Modified version of dsplib_approx_invert - Data format (ref. to dsplib_approx_invert) */ us_result_scale_t us_dsplib_approx_invert_simple(Word32 x); /*! Approximate division \param numer numerator \param denom denominator \details \b Assembly \b Assumptions - None \b Cycle-Count - 7 \b Notes - Inversion is approximated by linear interpolation of LUT. - Data format \par IF inputs are in Q0, then output is in Q(-SF) \par For example, \par numer = 5297, denom = 13555 \par return values are result = 839214304, SF = -31 \par Thus, division value is 839214304/2^31 = 0.3907896 */ Word64 us_dsplib_approx_divide(Word32 numer,Word32 denom); /*! Inverts a 32-bit positive number using Newton's method \param x number to be inverted \details \b Assembly \b Assumptions - None \b Cycle-Count - 18 \b Notes - Data format \par IF input is in Q0, then output is in Q(45-SF) \par For example, \par input is 14767, \par return values are result = 18179, SF = 17 \par Thus, inversion value is 18179/2^(45-17) = 6.7722 x 10^-5 */ Word64 us_dsplib_newtons_invert(Word32 x); /*! Inversion of a 16-bit positive number \param x number to be inverted \details \return 64-bit integer where the high 32-bit is shift factor and the low 16-bit is Q-shifted inverse \b Assembly \b Assumptions - None \b Cycle-Count - 18 \b Notes - Inversion has 15-bit full precision. - Data format \par IF input is in Qn and output in Qm, then m = SF - n . \par For example, \par input is 0x0F00 in Q10, i.e., 3.75 \par return values are result = 17476, SF = 26 \par Thus, m = 26 - 10 = 16, i.e., inversion is 17476/2^16 = 0.2666626 */ us_result_scale_t us_dsplib_invert(Word16 x); /*! Approximates sqrt(x) \param x input number in Q0 \param rnd_fac rounding factor \details \return sqrt(x) in Q16 \b Assembly \b Assumptions - None \b Cycle-Count - 8 \b Notes - ref. to QDSP4000 library for implementation */ Word32 dsplib_sqrt_lut(Word32 x, Word32 rnd_fac); /*! Approximates 1/sqrt(x) \param x input number in Q0 \param rnd_fac rounding factor \details \return 1/sqrt(x) in Q30 \b Assembly \b Assumptions - None \b Cycle-Count - 8 \b Notes - ref. to QDSP4000 library for implementation */ Word32 dsplib_inv_sqrt_lut(Word32 x, Word32 rnd_fac); /*! Approximates 10*log10(x) \param x input \details \return 10log10(x) in unsigned Q23 \b Assembly \b Assumptions - None \b Cycle-Count - 7 \b Notes - ref. to QDSP4000 library for implementation */ Word32 dsplib_log10(Word32 x); /*! Approximates 10^x for x in [-1, 1] \param x input in Q26 \details \return 10^x in Q15 \b Assembly \b Assumptions - None \b Cycle-Count - 8 \b Notes - ref. to QDSP4000 library for implementation */ Word32 dsplib_exp10(Word32 x); /*! Approximates sin(2*PI*x) \param x input in Q24 \details \return sin(2*PI*x) in Q31 \b Assembly \b Assumptions - None \b Cycle-Count - 6 (x<0) - 5 (x >=0) \b Notes - Use 512-entry LUT with interpolation for approximation */ Word32 us_dsplib_sin(Word32 x); /*! Approximates cos(2*PI*x) \param x input in Q24 \details \return cos(2*PI*x) in Q31 \b Assembly \b Assumptions - None \b Cycle-Count - 6 (x<0) - 5 (x >=0) \b Notes - Use 512-entry LUT with interpolation for approximation */ Word32 us_dsplib_cos(Word32 x); /*! Approximates arctan(x)/PI for x in [-1,1) \param x input in Q15 \details \return arctan(x)/PI in Q31 \b Assembly \b Assumptions - None \b Cycle-Count - 4 \b Notes - Use polynomial approximation with MSE */ Word32 us_dsplib_atan(Word16 x); /*! Approximate unsigned-inverse using linear 8-entry lookup table. \param input unsigned number to be inverted \details \return A result/scale pair corresponding to 1/input. If input is 0, the output returned is result=0xFFFFFFFF, scale=0. Valid input range is 0-0xFFFFFFFF \b Assembly \b Assumptions - LUT aligned by 32-bytes \b Cycle-Count - The optimized assembly function is 5 cycles. \b Notes - Maximum absolute relative error is 1.8e-3. - Data format \par With the input in Qi, the output is Qo=32-Qi. Right-shifting the result by the scale, converts the result to Qo. \par For example, \par input: 3.5625 (57 in Q4) \par output: scale=4, result=0x47dd8000=1205698560 (Q30) \par Thus, shift right by 4 => 0x47dd800=75356160 (Q28=32-4)=0.280724 */ extern us_result_scale_t approx_uinv_linlut8(UWord32 input); /*! Approximate unsigned-inverse using cubic polynomial approximation. \param input unsigned number to be inverted \details \return A result/scale pair corresponding to 1/input. If input is 0, the output returned is result=0xFFFFFFFF, scale=0. Valid input range is 0-0xFFFFFFFF. \b Assembly \b Assumptions - LUT aligned by 64-bytes \b Cycle-Count - The optimized assembly function is 7 cycles. \b Notes - Maximum absolute relative error is 1.525879e-5. - Data format \par With the input in Qi, the output is Qo=32-Qi. Right-shifting the result by the scale, converts the result to Qo. \par For example, \par input: 3.5625 (57 in Q4) \par output: scale=4, result=0x47dc5800=1205622784 (Q30) \par Thus, shift right by 4 => 0x47dc580=75351424 (Q28=32-4)=0.280706 */ extern us_result_scale_t approx_uinv_cubelut8(UWord32 input); /*! Approximate unsigned-inverse using Newton-Raphson iterative method. \param input unsigned number to be inverted \param iter number of iterations to be used. The iteration count must be in [1,3]. \details \return A result/scale pair corresponding to 1/input. If input is 0, the output returned is result=0xFFFFFFFF, scale=0. \b Assembly \b Assumptions - None \b Cycle-Count - The optimized assembly function is 4+2*(iterations) cycles. \b Notes - Maximum absolute relative error : 7.3e-3(iter=1), 6e-5(iter=2) 5.5e-9(iter=3) - Quantization noise makes error worse at more than 3 iterations. - Data format \par With the input in Qi, the output is Qo=32-Qi. Right-shifting the result by the scale, converts the result to Qo. \par For example, \par input: 3.5625 (57 in Q4) \par output: scale=4, result=0x47dc11f8=1205604856 (Q30) \par Thus, shift right by 4 => 0x47dc120=75350304 (Q28=32-4)=0.280702 */ extern us_result_scale_t approx_uinv_newt(UWord32 input, UWord32 iter); /*! Approximate unsigned-inverse using Taylor's series expansion. \param input unsigned number to be inverted \param hi_pow the degree of the Taylor polynomial to be used (must be in [3,8]). \details \return A result/scale pair corresponding to 1/input. If input is 0, the output returned is result=0xFFFFFFFF, scale=0. \b Assembly \b Assumptions - None \b Cycle-Count - The optimized assembly function is 6+(hi_pow) cycles. \b Notes - Max absolute relative errors are: 1.6-4, 1.8e-5, 2.0e-6, 2.5e-7, 3.5e-8, 3.5e-9 for highest power = 3,...,8 respectively. - Competitive only for hi_pow=4 but 2 cycles more than newt_2iter and 3 more than cube8fit - Data format \par With the input in Qi, the output is Qo=32-Qi. Right-shifting the result by the scale, converts the result to Qo. \par For example, \par input: 3.5625 (57 in Q4) \par output: scale=5, result=0x8fb8235d=2411209565 (Q31) \par Thus, result shift right by 5 => 0x47dc11b=75350299 (Q28=32-4)=0.280702 (NOTE: The result is twice the magnitude, compared to other algorithms and so the scale is also 1 more) */ extern us_result_scale_t approx_uinv_tylr(UWord32 input, UWord32 hi_pow); /*! Approximate dB-to-linear conversion using linear 8-segment lookup table. \param input number in dB (in Q24) to be converted \details \return A result/scale pair corresponding to 10^(input/10). \b Assembly \b Assumptions - LUT aligned by 32-bytes. \b Cycle-Count - The optimized assembly function is 5 cycles. \b Notes - Maximum absolute relative error is 5.8121e-04 - Data format \par The scale_factor is signed and lies in the range [-32,31]. The scale_factor corresponds to the right shift amount in a 64-bit shift operation on the result & interpreting the resultant 64 bits as a Q32 number. For other output Q-factors, the scale_factor is to be adjusted appropriately (ensure no overflow/underflow). For e.g. Q16 result can be obtained w/o underflow for inputs in range -48.1647dB:127dB with right shift amount given by: right shift = scale_factor + 16. \par Considering only the positive input dB range upto 96.32dB, no shift is required if we treat the result as floating point. The Qo is given by: Qo = 32 + scale_factor..Qo is in the range [0,31] \par Valid input range is Q24 numbers corresponding to real values within +/-96.32 (dB range corresponding to linear 32-bit no. range). Inputs between 96.33dB:127dB or -128dB:-96.33dB can be used, but the right shift for the result in 64 bits, now interpreted as Q21, is given by: right shift =scale_factor + sign(scale_factor)*11 \par For example, \par input is -16.00dB =0xf0000000 in Q24 \par return (scale, result) = (5, 0xcddfb7c0) \par Thus, Qo = 32 + 5 = 37, and the value is (0xcddfb7c0)*2^-37 = 2.513109e-02 */ extern us_result_scale_t approx_dB_to_ulin_linlut8( Word32 input ); /*! Approximate dB-to-linear conversion using a single cubic polynomial fit. \param input number in dB to be converted \details \return A result/scale pair corresponding to 10^(input/10). \b Assembly \b Assumptions - None \b Cycle-Count - The optimized assembly function is 6 cycles. \b Notes - Maximum absolute relative error is 1.3463e-04 - Data format \par Please refer to approx_db_to_ulin_linlut8(). */ extern us_result_scale_t approx_dB_to_ulin_cubefit( Word32 input ); /*! Approximate dB-to-linear conversion using 2nd degree 8-segment lookup table. \param x number to be inverted \details \return A result/scale pair corresponding to 10^(input/10). \b Assembly \b Assumptions - LUT is aligned by 64-bytes \b Cycle-Count - The optimized assembly function is 7 cycles. \b Notes - Maximum absolute relative error is 4.4531e-06 - Data format \par Please refer to approx_db_to_ulin_linlut8(). */ extern us_result_scale_t approx_dB_to_ulin_quadlut8( Word32 input ); /*! Approximate linear range to dB conversion using linear 8-segment lookup table. \param input number to be converted into dB \param Qi Q-factor of the input number (Q-factor must be in [0,32]). \details \return A result corresponding to 10*log10(input). If input is 0, the output returned is 0x80000000=-256dB in Q24. \b Assembly \b Assumptions - LUT aligned by 32-bytes \b Cycle-Count - The optimized assembly function is 6 cycles. \b Notes - Maximum absolute error is less than 0.004012 dB - Data format \par The output Q-factor is fixed at Q24. Valid output is in the range +/-96.32dB. \par IF input is in Qn and output in Qm, then m = 30 - SF - n . \par For example, \par input: 0xffffffff..Q0 = 4.29e+09, output: 0x6054bd9b = 96.33102dB (Q24) \par input: 0xffffffff..Q32= 1.00e+00, output: 0x00005cfb = 0.00142dB (Q24) */ extern Word32 approx_ulin_to_dB_linlut8( UWord32 input, Word32 Qi); /*! Approximate linear range to dB conversion using cubic 32-segment lookup table. \param input number to be converted into dB \param Qi Q-factor of the input number (Q-factor must be in [0,32]). \details \return A result corresponding to 10*log10(input). If input is 0, the output returned is 0x80000000=-256dB in Q24. \b Assembly \b Assumptions - LUT aligned by 64-bytes \b Cycle-Count - The optimized assembly function is 7 cycles. \b Notes - Maximum absolute error is less than 0.0000483 dB - Data format \par The output Q-factor is fixed at Q24. Valid output is in the range +/-96.32dB. \par IF input is in Qn and output in Qm, then m = 30 - SF - n . \par For example, \par input: 0xffffffff..Q0 = 4.29e+09, output: 0x60546034 = 96.32959 dB (Q24) \par input: 0xffffffff..Q32= 1.00e+00, output: 0xffffff94 = -0.00001 dB (Q24) */ extern Word32 approx_ulin_to_dB_cubelut8( UWord32 input, Word32 Qi); /*! Approximate atan2(y,x)/pi using 7th degree polynomial approximation. \param x x-coordinate of the input point \param y y-coordinate of the input point \details \return A result corresponding to atan2(y,x)/pi. If the input pair is (0,0), the output returned is 0. \b Assembly \b Assumptions - None \b Cycle-Count - The optimized assembly function is 22 cycles. \b Notes - Maximum absolute relative error is 3.9419e-007. - Data format \par The output is in Q31. \par For example, \par input:y=-2147483648 x=-2147483648 \par output: -1610611935 = 0xA0000321 =-7.499996e-01..Q31 (pi * -.75) */ extern Word32 approx_atan2_poly7( Word32 y, Word32 x);
C
#include "types.h" #include "user.h" #include "syscall.h" #define NUM_ELEMENTS 100 int mutex; void producer(void *arg){ int *buffer = (int*) arg; int i; for(i=0; i < NUM_ELEMENTS; i++){ mtx_lock(mutex); buffer[i]= i*5; printf(1,"Producer put %d\n", buffer[i]); mtx_unlock(mutex); if(i==(NUM_ELEMENTS/2)){ sleep(100); } } exit(); } void consumer(void *arg){ int *buffer = (int*) arg; int i; mtx_lock(mutex); printf(1,"Consumer has:["); for(i=0 ; i<NUM_ELEMENTS; i++){ if(buffer[i]!=-1){ printf(1,"%d,", buffer[i]); buffer[i]=-1; } } printf(1,"]\n"); mtx_unlock(mutex); exit(); } int main(int argc,char *argv[]){ mutex = mtx_create(0); int *buffer= (int*) malloc(NUM_ELEMENTS * sizeof(int)); memset(buffer, -1, NUM_ELEMENTS * sizeof(int*)); uint *stack1= (uint *) malloc(1024); //uint *stack2=(uint *)malloc(1024); void *return_stack1; //void *return_stack2; thread_create(*producer,(void *)stack1,(void *)buffer); thread_join((void**)&return_stack1); thread_create(*consumer,(void *)stack1,(void *)buffer); thread_join((void**)&return_stack1); free(return_stack1); //free(return_stack2); free(buffer); exit(); return 0; }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> int main(){ int file_des[2]; int n; scanf("%d", &n); if(pipe(file_des) == -1){// handles file error perror("pipe()"); exit("EXIT_FAILURE"); } switch(fork()){ case -1: // jamd;es fprl errpr perror("fork()"); case 0: // child if(close(file_des[0] == -1)){ // close reading side of pipe perror("close()"); exit("EXIT_FAILURE"); } /* child writes to pipe */ FILE *fw; fw = fdopen(file_des[1], "w"); // IMPORTANT convert file descriptor to FILE handler fscanf(fr, "%d", &answer); } /*key_t key = 0x00304340; // create 4096 bytes of shared memory if (shmid < 0){ fprintf(stderr, "failed to create shm argument\n"); perror("shmget"); return -1; } printf("created %d\n", shmid); return 0;*/ }
C
#include <stdio.h> #define S(a,b,c) (a+b+c)/2 #define area(a,b,c) { double ss = S(a,b,c) ; double r = sqrt(ss*(ss-a)*(ss-b)*(ss-c)) ; printf("%.3f",r) ; } int main(){ int a,b,c; scanf("%d %d %d",&a,&b,&c); area(a,b,c); return 0; }
C
/* Copyright (C) 2017, 2018 Andrew Sveikauskas Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. */ #include <common/error.h> #include <common/logger.h> #include <string.h> #include <stdio.h> const char * error_get_string(error *err) { if (err->get_string) return err->get_string(err); return NULL; } static const char* unknown_get_string(error *err) { return err->context ? err->context : "<Generic error>"; } void error_set_unknown(error *err, const char *msg) { error_clear(err); err->source = ERROR_SRC_UNKNOWN; err->get_string = unknown_get_string; err->context = (char*)msg; } void error_set_nomem(error *err) { #if defined(_WINDOWS) error_set_win32(err, E_OUTOFMEMORY); #else error_set_errno(err, ENOMEM); #endif } void error_set_notimpl(error *err) { #if defined(_WINDOWS) error_set_win32(err, E_NOTIMPL); #else error_set_errno(err, ENOTSUP); #endif } void error_set_access(error *err) { #if defined(_WINDOWS) error_set_win32(err, ERROR_ACCESS_DENIED); #else error_set_errno(err, EACCES); #endif } void error_clear(error *err) { if (err) { if (err->free_fn) err->free_fn(err->context); memset(err, 0, sizeof(*err)); } } void error_log(error *err, const char *func, const char *file, int line_no) { const char *str = error_get_string(err); const char *source = NULL; char hexbuf[10]; switch (err->source) { case ERROR_SRC_ERRNO: source = "errno"; break; case ERROR_SRC_COM: source = "com"; break; case ERROR_SRC_OSSTATUS: source = "osstatus"; break; case ERROR_SRC_DARWIN: source = "kern_return_t"; break; case ERROR_SRC_UNKNOWN: source = "generic"; break; default: snprintf(hexbuf, sizeof(hexbuf), "%x", err->source); source = hexbuf; } log_printf( "%s (%s:%d): %s 0x%.8x%s%s", func, file, line_no, source, err->code, str ? ": " : "", str ? str : "" ); }
C
#include"pch.h" #include<stdio.h> #if(1) void pojie(int num[9][9]); int pojie_p(int num[9][9], int i, int j); int jiancha(int num[9][9]); int panduan(int num[9][9], int i, int j); int panduan_xie(int num[9][9], int i, int j); int panduan_hang(int num[9][9], int i, int j); int panduan_shu(int num[9][9], int i, int j); int panduan_fujin(int num[9][9], int i, int j); #endif int main() { int n, tmp, x, i = 0, j = 0; int num[9][9] = { 0 }; printf("ɵʽƽ\n"); printf("е,ûе0\n"); printf(":123456000\n"); // int num[9][9] = { {0,0,4,6,0,2,0,0,0 }, {6,0,0,0,3,0,0,0,4}, {0,2,0,4,0,0,0,9,0},{9,8,0,0,0,0,3,5,0},{1,0,3,0,0,0,0,4,0},{0,6,0,0,0,0,8,0,7},{0,3,0,0,2,0,0,7,0},{0,0,0,0,6,1,0,0,5},{0,0,9,3,0,0,4,0,0} }; for (i=0;i<9;i++) { printf("[%d][%d]:", i + 1, j + 1); scanf_s("%d", &n); x = 8; while (x>=0) { tmp = n % 10; n = n / 10; num[i][x] =tmp; x--; } } for (i = 0; i < 9; i++) { for (j = 0; j < 9; j++) { printf("%d", num[i][j]); } printf("\n"); } pojie(num); system("pause"); return 0; } void pojie(int num[9][9]) { int NUM; int i=0, j=0; NUM=jiancha(num);//ȼû if (NUM == 1) { printf("\n"); exit(1); } /*ǽⷨ˼·*/ for (i=0;i<9;i++) { for (j=0;j<9;j++) { if (num[i][j] == 0) goto ij; } }//õһ0λ ij: printf("\n\n"); pojie_p(num, i, j);//ƽ printf("ƽ\n"); printf("\n\n"); NUM =jiancha(num);//ټһ if (NUM == 1) { printf("\n"); exit(1); } return; } int pojie_p(int num[9][9], int i, int j) { int x,n=0; int a, b,tmp=1; int q, w; q = w = 0; int NUM=0;//1Ϊ0Ϊ for (x=1;x<10;x++) { num[i][j] = x;//ֵָ if (1) { if ((i == j) || ((i + j) == 8))//жб߽ { // NUM = panduan_xie(num, i, j); } if (NUM == 1) { NUM = 0; continue;//жб߽и } NUM = panduan_hang(num, i, j); if (NUM == 1) { NUM = 0; continue;//жи } NUM = panduan_shu(num, i, j); if (NUM == 1) { NUM = 0; continue;//жи } NUM = panduan_fujin(num, i, j); if (NUM == 1) { NUM = 0; continue;//жи } } /*жбǷ*/ if (1) { for (a = 0; a < 9; a++)//ǵõһ0λ { for (b = 0; b < 9; b++) { if (num[a][b] == 0) { goto aa; } if ((a == 8) && (b == 8))//[8][8]λã { for (q = 0; q < 9; q++) { for (w = 0; w < 9; w++) { printf("%d", num[q][w]); } printf("\n"); } printf("\n\n"); tmp = 1; return tmp; } } } } bb: if (0) { aa: tmp=pojie_p(num, a, b); if (tmp==1) { return tmp; } } } if (x == 10) { num[i][j] = 0;//ѭ1-9ûʺϵΪ0һ } return;//һ } #if(1) int jiancha(int num[9][9]) { int i = 0, j = 0, n = 0;//n=[i][j] int NUM=0;//1Ϊ0Ϊ for(i=0;i<9;i++) { for (j=0;j<9;j++) { n = num[i][j];//õnumֵ if (n==0) { continue;//n==0˴ѭ } NUM = panduan(num,i,j); if (NUM==1) { goto jiancha_over;// } } } jiancha_over: return NUM; } int panduan(int num[9][9], int i, int j) { /*жnum[i][j]бǷֵͬ */ /*ֵͬ1ֵͬ0 */ int n, tmp, NUM=0; if ((i==j)||((i+j)==8))//ҪжбǷֵͬ { // NUM=panduan_xie(num, i, j); if (NUM == 1) goto panduan_over; } NUM = panduan_hang(num, i, j); if (NUM == 1) goto panduan_over; NUM = panduan_shu(num, i, j); if (NUM == 1) goto panduan_over; NUM = panduan_fujin(num, i, j); if (NUM == 1) goto panduan_over; panduan_over: return NUM; } int panduan_xie(int num[9][9], int i, int j) { /*жnum[i][j]бǷֵͬ */ /*ֵͬ1ֵͬ0 */ int z,NUM=0; int x, y; if (i == j) { for (z = 0; z < 9; z++) { if (z == i) { continue; } if (num[i][i] == num[z][z]) { NUM = 1; break; } } } if (8==(i+j)) { for (x=0,y=8;;x++,y--) { if ((x==9)) { break;//ѭ } if (((i==x)&&(j==y))||(num[x][y]==0)) { continue; } if (num[i][j]==num[x][y]) { NUM = 1; break; } } } return NUM; } int panduan_hang(int num[9][9], int i, int j) { /*жnum[i][j]Ƿֵͬ */ /*ֵͬ1ֵͬ0 */ int z; int NUM=0; for (z=0;z<9;z++) { if (num[i][z]==0) { continue;//num[i][z]==0 } if (j==z) { continue; } if (num[i][j]==num[i][z]) { NUM = 1;//ͬ break; } } return NUM; } int panduan_shu(int num[9][9], int i, int j) { /*жnum[i][j]Ƿֵͬ */ /*ֵͬ1ֵͬ0 */ int z; int NUM = 0; for (z = 0; z < 9; z++) { if (num[z][j] == 0) { continue;//num[z][j]==0 } if (i == z) { continue; } if (num[i][j] == num[z][j]) { NUM = 1;//ͬ break; } } return NUM; } int panduan_fujin(int num[9][9], int i, int j) { /*жnum[i][j]Ƿֵͬ */ /*ֵͬ1ֵͬ0 */ int x, y, z,tmp,NUM=0; x = i / 3; y = j / 3; x = x * 3; y = y * 3; for(z=0;z<3;z++) { for (tmp=0;tmp<3;tmp++) { if (((i==x+z)&&(j==y+tmp))||(num[x+z][y+tmp]==0)) { continue; } if (num[i][j]==num[x+z][y+tmp]) { NUM = 1; goto fujin_over; } } } fujin_over: return NUM; } #endif//бǷֵͬ
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* utils_libft.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mel-oual <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/28 00:15:38 by mel-oual #+# #+# */ /* Updated: 2020/02/28 04:33:12 by mel-oual ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ls.h" void *ft_memset(void *b, int c, size_t len) { unsigned i; i = 0; while (i < len) { ((unsigned char*)b)[i++] = (unsigned char)c; } return (b); } int ft_strchr(char c, char *str) { int x; x = -1; while(str[++x]) if(str[x] == c) return(x); return(-1); } int ft_strlen(const char *str) { int len; len = 0; if(str == NULL || *str == '\0') return(0); while(str[len] != 0) len++; return(len); } char *ft_strnew(int len) { char *str_new; str_new = NULL; if(!(str_new = (char *)malloc(sizeof(char) * len))) return(NULL); return(str_new); } char *ft_strjoin(char *s1, char *s2) { char *tmp; int len_s1; int len_s2; tmp = NULL; len_s1 = 0; len_s2 = 0; if(s1 == NULL || s2 == NULL) return(NULL); len_s1 = ft_strlen(s1); len_s2 = ft_strlen(s2); if(!(tmp = (char *)malloc(sizeof(char) * len_s1 + len_s2 + 1))) return(NULL); while(s1 <= s1 + len_s1 && *s1) { *tmp = *s1; tmp++; s1++; } while(s2 <= s2 + len_s2 && *s2) { *tmp = *s2; tmp++; s2++; } *(tmp + 1) = '\0'; return(tmp - (len_s1 + len_s2)); } void ft_strdel(char *str) { if(str != NULL) free(str); str = NULL; } char *ft_strndup(char *str, int i) { int x; char *tmp; x = -1; tmp = NULL; if(!(tmp = (char *)malloc(sizeof(char) * i + 1))) return(0); while(++x < i && str[x]) tmp[x] = str[x]; tmp[x] = '\0'; return(tmp); } char *ft_strdup(char *str) { char *tmp; int x; x = -1; tmp = NULL; tmp = ft_strnew(ft_strlen(str) + 1); while(str[++x]) tmp[x] = str[x]; tmp[x] = '\0'; return(tmp); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> void getArr(int arr[], int n){ unsigned sr = time(NULL); srand(sr); for(int i = 0; i < n; i++){ arr[i] = 20 + rand()%10; } printf("随机生成的数组\n"); } void printArr(int arr[], int n){ for(int i = 0; i < n; i++){ printf("%d\t", arr[i]); } printf("\n"); } // 直接插入排序 void insertSort(int arr[], int n){ // 要进行 n - 1 趟插入 for(int i = 1; i < n; i++){ // 假设第0个已经在正确的位置,从第一个(arr[1])开始插入 // 第 i 趟插入需要在[ 0, i - 1]中找到i的合适位置 int temp = arr[i]; int j = i - 1; while((j >= 0)&&(arr[j] > temp)){ arr[j + 1] = arr[j]; // 元素后移 j--; } arr[j + 1] = temp; } } // 直排2 void insertSort2(int arr[], int n){ for(int i = 1; i < n; i++){ // 要进行 n - 1 趟插入 int j = 0; while((j < i)&&(arr[i] > arr[j])){ j++; } // 如果找到合适的位置 i 应该不等于j,如果i==j,说明i正好在正确的位置 if(i != j){ int temp = arr[i]; for(int k = i; k > j; k--){ arr[k] = arr[k - 1]; } arr[j] = temp; } } } int main(){ int arr[8]; int len = sizeof(arr)/sizeof(int); getArr(arr, len); printArr(arr, len); insertSort2(arr, len); printf("直接插入排序:\n"); printArr(arr, len); return 0; }
C
#include <stdio.h> int main() { int arr[10]; int i; int index; int max; int max_i; i = 1; while (i <= 9) { scanf("%d", &index); arr[i] = index; i++; } max = arr[1]; max_i = 1; i = 1; while (i <= 9) { if (arr[i] > max) { max = arr[i]; max_i = i; } i++; } printf("%d\n", max); printf("%d", max_i); }
C
/* * Copyright (c) 1983 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. */ #include <sys/param.h> #include <sys/dir.h> /* * seek to an entry in a directory. * Only values returned by "telldir" should be passed to seekdir. */ void seekdir(dirp, loc) register DIR *dirp; long loc; { long curloc, base, offset; struct direct *dp; extern long lseek(); curloc = telldir(dirp); if (loc == curloc) return; base = loc & ~(DIRBLKSIZ - 1); offset = loc & (DIRBLKSIZ - 1); (void) lseek(dirp->dd_fd, base, 0); dirp->dd_loc = 0; while (dirp->dd_loc < offset) { dp = readdir(dirp); if (dp == NULL) return; } }
C
/* STEPS Create a normal process (Parent process) Create a child process from within the above parent process The process hierarchy at this stage looks like : TERMINAL -> PARENT PROCESS -> CHILD PROCESS Terminate the the parent process. The child process now becomes orphan and is taken over by the init process. Call setsid() function to run the process in new session and have a new group. After the above step we can say that now this process becomes a daemon process without having a controlling terminal. Change the working directory of the daemon process to root and close stdin, stdout and stderr file descriptors. Let the main logic of daemon process run. About logs… Writing on a disk is a heavy operation. Well, not “heavy” as you think of it, but compared to memory manipulation, it takes a while to write to a file. That’s why most UNIX systems use file buffers : contents are loaded into the buffer, and your modifications happen in it as well. Regularly, the kernel will unload the buffer into the files in order to apply changes. This operation is called syncing, and even though it happens regularly on kernel orders, you can ask for it using the sync() function. If you don’t, and your daemon crashes, changes to the log file might not be visible, as the automatic syncing may not have happened yet. By the way, buffer contents are pushed into the real file upon the fclose call, no need for a final sync(). */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> int main(int argc, char* argv[]) { FILE *fp= NULL; pid_t process_id = 0; pid_t sid = 0; // Create child process process_id = fork(); // Indication of fork() failure if (process_id < 0) { printf("fork failed!\n"); // Return failure in exit status exit(1); } // PARENT PROCESS. Need to kill it. if (process_id > 0) { printf("process_id of child process %d \n", process_id); // return success in exit status exit(0); } //unmask the file mode umask(0); //set new session sid = setsid(); if(sid < 0) { // Return failure exit(1); } // Change the current working directory to root. chdir("/"); // Close stdin. stdout and stderr close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); // Open a log file in write mode. fp = fopen ("Log.txt", "w+"); while (1) { //Dont block context switches, let the process sleep for some time sleep(10); fprintf(fp, "Logging info...\n"); fflush(fp); // Implement and call some function that does core work for this daemon. } fclose(fp); return (0); } /* #include <stdio.h> #include <fcntl.h> #include <signal.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #define RUNNING_DIR "/tmp" #define LOCK_FILE "daemond.lock" #define LOG_FILE "daemond.log" void log_message(char *filename,char *message){ FILE *logfile; logfile = fopen(filename,"a"); if(!logfile) return; fprintf(logfile,"%s",message); fclose(logfile); } void signal_handler(int sig){ switch(sig){ case SIGHUP: log_message(LOG_FILE,"Hangup Signal Catched"); break; case SIGTERM: log_message(LOG_FILE,"Terminate Signal Catched"); exit(0); break; } } void daemonize() { int i,lfp; char str[10]; if(getppid() == 1) return; i = fork(); if(i < 0) exit(1); if(i > 0) exit(0); setsid(); for(i = getdtablesize(); i >= 0; --i) close(i); i = open("/dev/null",O_RDWR); dup(i); dup(i); umask(027); chdir(RUNNING_DIR); lfp = open(LOCK_FILE,O_RDWR|O_CREAT,0640); if(lfp < 0) exit(1); if(lockf(lfp,F_TLOCK,0) < 0) exit(1); sprintf(str,"%d\n",getpid()); write(lfp,str,strlen(str)); signal(SIGCHLD,SIG_IGN); signal(SIGTSTP,SIG_IGN); signal(SIGTTOU,SIG_IGN); signal(SIGTTIN,SIG_IGN); signal(SIGHUP,signal_handler); signal(SIGTERM,signal_handler); } int main(int argc,char **argv){ daemonize(); while(1) sleep(1); } */
C
#include <stdio.h> #include <stdlib.h> int maior(int x, int y){ if (x>y){ return x; } else { return y; } } int is_Triangulo(int x, int y, int z){ if (x+y<z) return 0; if (x+z<y) return 0; if (z+y<x) return 0; return 1; } void main() { printf("%d\n",maior(7,9)); printf("%d\n",is_Triangulo(90,45,46)); }
C
//Data Structure Program 20 // Various sorting techniques #include<stdio.h> #include<conio.h> #include<stdlib.h> int a[20],n; void create(); void display(); void bubblesort(); void insertionsort(); void quicksort(int number[20],int first,int last); void heapup(int n,int i); void heapsort(); void merge(int a[],int f1,int l1,int f2,int l2); void mergesort(int a[],int i,int j); void shellsort(int arr[], int num); void main() { int op; char ch; while(1) { system("cls"); printf("\n1-Enter Array"); printf("\n2-Bubble Sort"); printf("\n3-Insertion Sort"); printf("\n4-Quick Sort"); printf("\n5-Heap Sort"); printf("\n6-Merge Sort"); printf("\n7-Shell Sort"); printf("\n8-Exit"); printf("\nEnter Choice"); scanf("%d",&op); switch(op) { case 1: create(); break; case 2: bubblesort(); display(); getch(); break; case 3: insertionsort(); display(); getch(); break; case 4: quicksort(a,0,n-1); display(); getch(); break; case 5: heapsort(); display(); getch(); break; case 6: mergesort(a,0,n-1); display(); getch(); break; case 7: shellsort(a,n); display(); getch(); break; case 8: exit(0); break; default: printf("\nWrong Choice"); break; } } } void create() { printf("\nEnter Number of Elements:"); scanf("%d",&n); printf("\nEnter Elements of Array:\n"); for(int i=0; i<=n-1; i++) scanf("%d",&a[i]); printf("\nEntered Array is:"); for(int i=0; i<=n-1; i++) printf("%d ",a[i]); getch(); } void display() { printf("\nSorted Array is:"); for(int i=0; i<=n-1; i++) printf("%d ",a[i]); } void bubblesort() { int temp; for(int i=0; i<=n-2; i++) { for(int j=0; j<=n-2-i; j++) if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } void insertionsort() { int temp,j; for(int i=1; i<=n-1; i++) { j=i-1; temp=a[i]; while(j>=0 && temp<a[j]) { a[j+1]=a[j]; j--; } a[j+1]=temp; } } void quicksort(int number[25],int first,int last) { int i, j, pivot, temp; if(first<last) { pivot=first; i=first; j=last; while(i<j) { while(number[i]<=number[pivot]&&i<last) i++; while(number[j]>number[pivot]) j--; if(i<j) { temp=number[i]; number[i]=number[j]; number[j]=temp; } } temp=number[pivot]; number[pivot]=number[j]; number[j]=temp; quicksort(number,first,j-1); quicksort(number,j+1,last); } } void heapup(int n, int i) { int temp,largest = i; int l = 2*i + 1; int r = 2*i + 2; if (l < n && a[l] > a[largest]) largest = l; if (r < n && a[r] > a[largest]) largest = r; if (largest != i) { temp=a[i]; a[i]=a[largest]; a[largest]=temp; heapup( n, largest); } } void heapsort() { int temp; for (int i = n / 2 - 1; i >= 0; i--) heapup(n, i); for (int i=n-1; i>=0; i--) { temp=a[0]; a[0]=a[i]; a[i]=temp; heapup( i, 0); } } void mergesort(int a[],int i,int j) { int mid; if(i<j) { mid=(i+j)/2; mergesort(a,i,mid); mergesort(a,mid+1,j); merge(a,i,mid,mid+1,j); } } void merge(int a[],int f1,int l1,int f2,int l2) { int temp[50]; int i,j,k; i=f1; j=f2; k=0; while(i<=l1 && j<=l2) { if(a[i]<a[j]) temp[k++]=a[i++]; else temp[k++]=a[j++]; } while(i<=l1) temp[k++]=a[i++]; while(j<=l2) temp[k++]=a[j++]; for(i=f1,j=0; i<=l2; i++,j++) a[i]=temp[j]; } void shellsort(int arr[], int num) { int i, j, k, tmp; for (i = num / 2; i > 0; i = i / 2) { for (j = i; j < num; j++) { for(k = j - i; k >= 0; k = k - i) { if (arr[k+i] >= arr[k]) break; else { tmp = arr[k]; arr[k] = arr[k+i]; arr[k+i] = tmp; } } } } }
C
/** * @file circular_buff.h * @author Konrad Sikora * @date Jan 2021 */ #ifndef circular_buff_h #define circular_buff_h #include "MKL05Z4.h" #define CB_MAX_LEN 50 typedef struct circular_buff { uint8_t *head; uint8_t *tail; uint8_t *data; uint8_t *buffor; uint16_t new_len; } circular_buff; typedef enum { buffor_full, buffor_not_full, buffor_empty, buffor_not_empty } CB_state; uint8_t *CB_init(circular_buff *cbuff); void CB_free(circular_buff *cbuff); CB_state CB_buff_full(circular_buff *cbuff); CB_state CB_buff_empty(circular_buff *cbuff); uint8_t CB_read_data(circular_buff *cbuff); uint8_t CB_add_data(circular_buff *cbuff, uint8_t data); #endif
C
//Faça um programa que leia um número inteiro e o imprima #include <stdio.h> #include <stdlib.h> int q1 (){ int num; printf("Digite um número inteiro: "); scanf("%i", &num); printf("Número digitado: %i\n", num); return 0; }
C
//Program to print natural numbers from 1 to n using for loop #include<conio.h> #include<stdio.h> int main() { int n,i; Printf("Enter the Number till u wanna Print"); scanf("%d",&n); while(i<=n) { printf("%d\n",i); i++; } getch(); return 0; }
C
/* preencher um vetor de inteiros com dimenso 20 e depois mover todos os nmeros mpares do vetor para o final e os pares para o incio. */ #include <stdio.h> #include <stdlib.h> #include <time.h> int main(){ int v[20], i, j, aux; srand(time(NULL)); i = 0; while(i < 20){ v[i] = rand() / 100 + 1; i = i + 1; } printf("\nVetor original\n"); for(i = 0;i < 20;i = i + 1){ printf("%d ",v[i]); } for(i = 0;i < 19;i = i + 1){ for(j = 0;j < (19 - i);j = j + 1){ if(v[j] % 2 != 0){ aux = v[j + 1]; v[j + 1] = v[j]; v[j] = aux; } } } printf("\nVetor depois da troca\n"); for(i = 0;i < 20;i = i + 1){ printf("%d ",v[i]); } return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> typedef struct color { int r; int g; int b; } color; typedef struct point { float x; float y; } point; float pi = 3.14159265358079323846264338; color **blank(int widh) { color **pixels = malloc(widh * sizeof(color *)); for(int i=0; i<widh; i++) { color *col = malloc(widh * sizeof(color)); color white; white.r = 255; white.g = 255; white.b = 255; for(int j=0; j<widh; j++) { col[j] = white; } pixels[i] = col; } return pixels; } void circle(color **pix, int widh) { int rad = (widh - 1)/2; int x; int y; int x2; int y2; color black = {0, 0, 0}; for(int i=0; i<rad; i++) { x = i; //x2 = 101-i; y = (int) round(sqrt((rad * rad) - ((rad - x) * (rad - x)))) + rad; //y2 = 101 - y; color *col = pix[x]; col[y] = black; col[(widh - 1) - y] = black; col = pix[(widh - 1) - x]; col[y] = black; col[(widh - 1) - y] = black; //pix[x][y] = black; //pix[x][y2] = black; ///pix[x2][y] = black; //pix[x2][y2] = black; //printf("%d\t%d\n", x, y); } } /* int func(int a) { FILE *new = fopen("pic.ppm", "w"); if(new) { fprintf(new, "P3\n100 100\n255\n"); */ void print_pix(color **pix, int widh) { unsigned black = 0; for(int i=0; i<widh; i++) { color *col = pix[i]; for(int j=0; j<widh; j++) { color c = col[j]; printf("%d\t%d\t%d\n", c.r, c.g, c.b);//"%d\n", (100 * i) + j); if(c.r == 0) { ++black; } } } //printf("Black: %d\n", black); } void spiro(float orad, float irad, float poff, float revs, color **pix, int widh) { if(irad >= orad || poff > irad || widh < orad || orad < 0 || irad < 0 || poff < 0 || widh < 0) { return; } float pang = 0; float iang = 0; for(int i=0; i<(revs * 360); i++) { point icent; icent.x = ((orad - irad) * cos(iang)) + orad; icent.y = ((orad - irad) * sin(iang)) + orad; point pcent; pcent.x = poff * cos(pang); pcent.y = poff * sin(pang); point ret; ret.x = icent.x + pcent.x; ret.y = icent.y + pcent.y; color bb = {0, 0, 255}; int xx = (int) round(ret.x); int yy = (int) round(ret.y); color *col = pix[xx]; col[yy] = bb; pang += (2 * pi)/360.0; iang += ((((2 * pi) / 360.0) * irad) / ((2 * pi) * orad)) * (2 * pi); } } color next_color(color in) { color c = in; if(c.g == 255) { if(c.b == 255) { --c.g; } else { ++c.b; } } else { if(c.b == 255) { if(c.g == 0) { --c.b; } else { --c.g; } } else { if(c.b == 0) { ++c.g; } else { --c.b; } } } return c; } void put_in_ppm(color c, unsigned x, unsigned y, color **pix, unsigned rad) { if(x > (2 * rad) + 1) { x = (2 * rad) + 1; } if(y > (2 * rad) + 1) { y = (2 * rad) + 1; } color *col = pix[x]; col[y] = c; } float aeq(unsigned t, float curr, unsigned style) { float base = (2 * pi); if(style == 0) { return base * (float) ((float) t / 1000); } return base * (float) ((float) t / 1000); } float pat(float ang, float a, float b, float c, float d, float e) { return a * sin((b * (ang + c)) + d) + e; } float req(unsigned t, float acurr, float rcurr, unsigned style) { if(style == 0) { return 0.5;//sin(acurr); } if(style == 1) { return sin(acurr / 2); } if(style == 2) { return sin((acurr / 5.25) + (2 * pi) / 5.25); } if(style == 3) { return sin(acurr / 5.33333333333333); } if(style == 4) { return sin((acurr / 5.25) + ((2 * pi) / 4)); } if(style == 5) { return pat(acurr, 1, (1 / 5.25), 0, (2 * pi) / 4, 0); } if(style == 6) { return pat(acurr, 0.5, 0, (1.0 / 3.0), 1, 0.5); } if(style == 7) { return pat(acurr, 1, (1 / 5.25), (2 * pi) / 16.0, 0, 0); } if(style == 8) { return 0.5; } return 0.5; } void spiro2(unsigned rad, unsigned steps, unsigned astyle, unsigned rstyle, color **pix, color colo) { if(rstyle == 8) { float a = ((float) rand() / (float) RAND_MAX); float b = ((float) rand() / (float) RAND_MAX) * 10; float c = (2 * pi) * ((float) rand() / (float) RAND_MAX); float d = (2 * pi) * ((float) rand() / (float) RAND_MAX); float e = ((1 - a) * ((float) rand() / (float) RAND_MAX); printf("[|a|b|c|d|e|]: |%f| |%f| |%f| |%f| |%f|\n", a, b, c, d, e); } point pt; color c = {0, 0, 0}; if(colo.r == 255 && colo.g == 255 && colo.b == 255) { c = c; } else { c = colo; } float ang = 0; float r = 0.5; unsigned xx; unsigned yy; for(int t=0; t<steps; t++) { ang = aeq(t, ang, astyle); //printf("\tAng:%f\n", ang); if(rstyle == 8) { r = pat(ang, a, b, c, d, e); } else { r = req(t, ang, r, rstyle); } if(r < 0) { r = 0; } else { if(r > 1) { r = 1; } } //printf("\tR:%f\n", r); pt.x = ((rad * r) * cos(ang)) + rad; pt.y = ((rad * r) * sin(ang)) + rad; //printf("%f\t%f\n", pt.x, pt.y); xx = (unsigned) round(pt.x); yy = (unsigned) round(pt.y); //printf("%u\t%u\n", xx, yy); if(colo.r == 255 && colo.g == 255 && colo.b == 255) { c = next_color(c); } put_in_ppm(c, xx, yy, pix, rad); } } void make_ppm(color **pix, int widh) { FILE *new = fopen("pic.ppm", "w"); if(new) { fprintf(new, "P3\n%d\t%d\n255\n", widh, widh); for(int i=0; i<widh; i++) { for(int j=0; j<widh; j++) { color *col = pix[j]; color c = col[i]; fprintf(new, "%d\t%d\t%d\n", c.r, c.g, c.b); } } } fclose(new); } void random_pats(int num) { color c = {0, 0, 0}; for(int i=0; i<num; i++) { c.b = (unsigned) round(255.0 / num) * i; spiro( int main() { int rad = 500; int widh = (2 * rad) + 1; color **pix = blank(widh); circle(pix, widh); color c = {255, 255, 255}; spiro2(rad, 100000, 0, 7, pix, c); //spiro2(rad, 100000, 0, 4, pix); //spiro2(rad, 100000, 0, 1, pix); //spiro2(rad, 100000, 0, 3, pix); make_ppm(pix, widh); return 0; }
C
#include "hash_table.h" #include <stdlib.h> #include <string.h> int tests_run = 0; #define mu_assert(message,test) do{if(!(test)) return message;} while(0) #define mu_run_test(test) do {char * message = test();tests_run++;\ if(message) return message;}while(0) static char * test_insert() { ht_hash_table * ht = ht_new(); ht_insert(ht, "k", "v"); int count = 0; for (int i = 0; i < ht->size; ++i) { if (ht->items[i] != NULL) { count++; } } mu_assert("error,num items in ht !=1", count == 1); for (int i = 0; i < ht->size; ++i) { if (ht->items[i] != NULL) { ht_item * cur_item = ht->items[i]; mu_assert("error, key != k", strcmp(cur_item->key, "k") == 0); mu_assert("error, value != v", strcmp(cur_item->value, "v") == 0); } } ht_del_hash_table(ht); return 0; } int main() { //ht_hash_table * ht = ht_new(); //ht_del_hash_table(ht); test_insert(); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> char* readCommand(char* currentInput, char* lastInput){ char current[1000]; char past[1000]; char cmd[6]; char value[980]; int exitNum; char toReturn[1000]; strcpy(current, currentInput); strcpy(past, lastInput); strncpy(cmd, current, 5); if (strcmp(cmd,"!!\n") == 0){ if (past[0] != '\0'){ printf("%s", past); readCommand(past, past); } } else if (strcmp(cmd,"echo ") == 0){ memset(value, '\0', strlen(value)); strncpy(value, &current[5], strlen(current) - 6); printf("%s\n", value); } else if (strcmp(cmd,"exit ") == 0){ //variables char recentInput[1000]; char pastInput[1000] = ""; char val[980]; char readLine[1000]; strncpy(value, &current[5], strlen(current) - 6); exitNum = atoi(value); if (exitNum < 0){ exitNum = 0; } else if (exitNum > 255){ exitNum = 255; } printf("-bye-\n"); printf("exit code: %d\n", exitNum); exit(atoi(value)); } else if (strcmp(cmd,"\n")==0){ } else { printf("bad command\n"); } return cmd; } char* readFromFile(char* currentInput, char* lastInput){ char current[1000]; char past[1000]; char cmd[6]; char value[980]; int exitNum; strcpy(current, currentInput); strcpy(past, lastInput); strncpy(cmd, current, 5); if (strcmp(cmd,"echo ") == 0){ memset(value, '\0', strlen(value)); strncpy(value, &current[5], strlen(current) - 6); printf("%s\n", value); } else if (strcmp(cmd,"!!\n") == 0){ if (past[0] != '\0'){ readFromFile(past, past); } } else if (strcmp(cmd,"exit ") == 0){ strncpy(value, &current[5], strlen(current) - 6); exitNum = atoi(value); if (exitNum < 0){ exitNum = 0; } else if (exitNum > 255){ exitNum = 255; } exit(exitNum); } else if (strcmp(cmd,"\n")==0){ } else{ printf("bad command\n"); } return cmd; } int main(int argc, char *argv[]){ //variables char recentInput[1000]; char pastInput[1000] = ""; char val[980]; char readLine[1000]; if (argc > 1){ FILE* fileOpen = fopen(argv[1],"r"); if (fileOpen == NULL){ exit(-1); } while (fgets(readLine, 1000, fileOpen) > 0){ strcpy(recentInput, readLine); if (strcmp(readFromFile(recentInput, pastInput),"!!\n")!=0){ memset(pastInput, '\0', strlen(pastInput)); strcpy(pastInput, recentInput); } } fclose(fileOpen); } else{ printf("Starting IC shell\n"); while(1){ printf("icsh $ "); fgets(recentInput,100,stdin); if (strcmp(readCommand(recentInput, pastInput),"!!\n")!=0){ memset(pastInput, '\0', strlen(pastInput)); strcpy(pastInput, recentInput); } } } }
C
//EEPROM emulation library for STM32F1XX with HAL-Driver //V2.0 //define to prevent recursive inclusion #ifndef __EEPROM_H #define __EEPROM_H //includes #include "stm32f1xx_hal.h" //-------------------------------------------library configuration------------------------------------------- //number of variables (maximum variable name is EEPROM_VARIABLE_COUNT - 1) //keep in mind it is limited by page size //maximum is also determined by your variable sizes //space utilization ratio X = (2 + 4*COUNT_16BIT + 6*COUNT_32BIT + 10*COUNT_64BIT) / PAGE_SIZE //if X is high, variable changes more often require a page transfer --> lifetime of the flash can be reduced significantly //depending on your variable change rate, X should be at least <50% #define EEPROM_VARIABLE_COUNT (uint16_t) 4 //flash size of used STM32F1XX device in KByte #define EEPROM_FLASH_SIZE (uint16_t) 64 //-------------------------------------------------constants------------------------------------------------- //EEPROM emulation start address in flash: use last two pages of flash memory #define EEPROM_START_ADDRESS (uint32_t) (0x08000000 + 1024*EEPROM_FLASH_SIZE - 2*FLASH_PAGE_SIZE) //used flash pages for EEPROM emulation typedef enum { EEPROM_PAGE0 = EEPROM_START_ADDRESS, //Page0 EEPROM_PAGE1 = EEPROM_START_ADDRESS + FLASH_PAGE_SIZE, //Page1 EEPROM_PAGE_NONE = 0x00000000 //no page } EEPROM_Page; //page status typedef enum { EEPROM_ERASED = 0xFFFF, //Page is empty EEPROM_RECEIVING = 0xEEEE, //Page is marked to receive data EEPROM_VALID = 0x0000 //Page containing valid data } EEPROM_PageStatus; //results typedef enum { EEPROM_SUCCESS = 0x00, //Method successful / HAL_OK EEPROM_ERROR = 0x01, //Error: HAL_ERROR occurred EEPROM_BUSY = 0x02, //Error: HAL_BUSY occurred EEPROM_TIMEOUT = 0x03, //Error: HAL_TIMEOUT occurred EEPROM_NO_VALID_PAGE = 0x04, //Error: no valid page found EEPROM_NOT_ASSIGNED = 0x05, //Error: variable was never assigned EEPROM_INVALID_NAME = 0x06, //Error: variable name to high for variable count EEPROM_FULL = 0x07 //Error: EEPROM is full } EEPROM_Result; //sizes ( halfwords = 2 ^ (size-1) ) typedef enum { EEPROM_SIZE_DELETED = 0x00, //variable is deleted (no size) EEPROM_SIZE16 = 0x01, //variable size = 16 bit = 1 Halfword EEPROM_SIZE32 = 0x02, //variable size = 32 bit = 2 Halfwords EEPROM_SIZE64 = 0x03 //variable size = 64 bit = 4 Halfwords } EEPROM_Size; typedef union { int16_t Int16; int32_t Int32; int64_t Int64; uint16_t uInt16; uint32_t uInt32; uint64_t uInt64; float Float; double Double; } EEPROM_Value; //----------------------------------------------public functions--------------------------------------------- EEPROM_Result EEPROM_Init(); EEPROM_Result EEPROM_ReadVariable(uint16_t VariableName, EEPROM_Value* Value); EEPROM_Result EEPROM_WriteVariable(uint16_t VariableName, EEPROM_Value Value, EEPROM_Size Size); EEPROM_Result EEPROM_DeleteVariable(uint16_t VariableName); #endif
C
// This program sets up GPIO pin 24 as an input pin, and sets it to generate // an interrupt whenever a rising edge is detected. The pin is assumed to // be connected to a push button switch on a breadboard. When the button is // pushed, a 3.3V level will be applied to the pin. The pin should otherwise // be pulled low with a pull-down resistor of 10K Ohms. // Include files #include "uart.h" #include "sysreg.h" #include "gpio.h" #include "irq.h" #include "systimer.h" // Function prototypes void init_GPIO24_to_risingEdgeInterrupt(); void init_GPIO23_to_fallingEdgeInterrupt(); void init_GPIO17_to_output(); void set_GPIO17(); void clear_GPIO17(); void init_GPIO27_to_output(); void set_GPIO27(); void clear_GPIO27(); void init_GPIO22_to_output(); void set_GPIO22(); void clear_GPIO22(); // Declare a global shared variable unsigned int sharedValue; //////////////////////////////////////////////////////////////////////////////// // // Function: main // // Arguments: none // // Returns: void // // Description: This function first prints out the values of some system // registers for diagnostic purposes. It then initializes // GPIO pin 24 and 23 to be an input pin that generates an interrupt // (IRQ exception) whenever a rising edge occurs on pin 24 and when a falling edge occurs on pin 23. // The function then goes into an infinite loop, the program starts in state 1 where LED 1, LED2, then LED3 are lit in that order. The // shared global variable is continually checked. If the // interrupt service routine changes the shared variable, // then this is detected in the loop, and the current value // is printed out and the program transitions from state 1 to state 2, vice versa, or stays the in the same state. State 2 of the program is where LED3, LED2, LED1 are lit in that order. // //////////////////////////////////////////////////////////////////////////////// void main() { unsigned int r; sharedValue = 1; // Set up the UART serial port uart_init(); // Query the current exception level r = getCurrentEL(); // Print out the exception level uart_puts("Current exception level is: 0x"); uart_puthex(r); uart_puts("\n"); // Get the SPSel value r = getSPSel(); // Print out the SPSel value uart_puts("SPSel is: 0x"); uart_puthex(r); uart_puts("\n"); // Query the current DAIF flag values r = getDAIF(); // Print out the DAIF flag values uart_puts("Initial DAIF flags are: 0x"); uart_puthex(r); uart_puts("\n"); // Print out initial values of the Interrupt Enable Register 2 r = *IRQ_ENABLE_IRQS_2; uart_puts("Initial IRQ_ENABLE_IRQS_2 is: 0x"); uart_puthex(r); uart_puts("\n"); // Print out initial values the GPREN0 register (rising edge interrupt // enable register) r = *GPREN0; uart_puts("Initial GPREN0 is: 0x"); uart_puthex(r); uart_puts("\n"); // Set up GPIO pin #24 to input and so that it triggers // an interrupt when a rising edge is detected init_GPIO24_to_risingEdgeInterrupt(); // Set up GPIO pin #23 to input and so that it triggers // an interrupt when a falling edge is detected init_GPIO23_to_fallingEdgeInterrupt(); // Enable IRQ Exceptions enableIRQ(); // Query the DAIF flag values r = getDAIF(); // Print out the new DAIF flag values uart_puts("\nNew DAIF flags are: 0x"); uart_puthex(r); uart_puts("\n"); // Print out new value of the Interrupt Enable Register 2 r = *IRQ_ENABLE_IRQS_2; uart_puts("New IRQ_ENABLE_IRQS_2 is: 0x"); uart_puthex(r); uart_puts("\n"); // Print out new value of the GPREN0 register r = *GPREN0; uart_puts("New GPREN0 is: 0x"); uart_puthex(r); uart_puts("\n"); // Print out a message to the console uart_puts("\nRising Edge IRQ program starting.\n"); // Loop forever, waiting for interrupts to change the shared value while (1) { // Check to see if the shared value was changed by an interrupt if (sharedValue == 1) { // Print out the shared value uart_puts("\nsharedValue is: "); uart_puthex(sharedValue); uart_puts("\n"); // Set up GPIO pin #17 for output init_GPIO17_to_output(); // Set up GPIO pin #27 for output init_GPIO27_to_output(); // Set up GPIO Pin #22 for output init_GPIO22_to_output(); // Print out a message to the console uart_puts("State 1.\n"); // Loop forever, blinking the LED on and off // LED1 on, LED2 and LED3 off set_GPIO17(); clear_GPIO27(); clear_GPIO22(); // Print a message to the console uart_puts("LED1\n"); // Delay 0.5 second using the system timer microsecond_delay(500000); // LED2 on, LED1 and LED3 off clear_GPIO17(); set_GPIO27(); clear_GPIO22(); // Print a message to the console uart_puts("LED2\n"); // Delay 0.5 second using the system timer microsecond_delay(500000); // LED3 on, LED1 and LED2 off clear_GPIO17(); clear_GPIO27(); set_GPIO22(); // Print a message to the console uart_puts("LED3\n"); // Delay 0.5 second using the system timer microsecond_delay(500000); } if (sharedValue == 2) { // Print out the shared value uart_puts("\nsharedValue is: "); uart_puthex(sharedValue); uart_puts("\n"); // Set up GPIO pin #17 for output init_GPIO17_to_output(); // Set up GPIO pin #27 for output init_GPIO27_to_output(); // Set up GPIO Pin #22 for output init_GPIO22_to_output(); // Print out a message to the console uart_puts("State 2.\n"); // Loop forever, blinking the LED on and off // LED3 on, LED2 and LED1 off clear_GPIO17(); clear_GPIO27(); set_GPIO22(); // Print a message to the console uart_puts("LED3\n"); // Delay 0.25 second using the system timer microsecond_delay(250000); // LED2 on, LED1 and LED3 off clear_GPIO17(); set_GPIO27(); clear_GPIO22(); // Print a message to the console uart_puts("LED2\n"); // Delay 0.25 second using the system timer microsecond_delay(250000); // LED1 on, LED3 and LED2 off set_GPIO17(); clear_GPIO27(); clear_GPIO22(); // Print a message to the console uart_puts("LED1\n"); // Delay 0.25 second using the system timer microsecond_delay(250000); } } } //////////////////////////////////////////////////////////////////////////////// // // Function: init_GPIO24_to_risingEdgeInterrupt // // Arguments: none // // Returns: void // // Description: This function sets GPIO pin 24 to an input pin without // any internal pull-up or pull-down resistors. Note that // a pull-down (or pull-up) resistor must be used externally // on the bread board circuit connected to the pin. Be sure // that the pin high level is 3.3V (definitely NOT 5V). // GPIO pin 24 is also set to trigger an interrupt on a // rising edge, and GPIO interrupts are enabled on the // interrupt controller. // //////////////////////////////////////////////////////////////////////////////// void init_GPIO24_to_risingEdgeInterrupt() { register unsigned int r; // Get the current contents of the GPIO Function Select Register 2 r = *GPFSEL2; // Clear bits 12 - 14. This is the field FSEL17, which maps to GPIO pin 24. // We clear the bits by ANDing with a 000 bit pattern in the field. This // sets the pin to be an input pin r &= ~(0x7 << 12); // Write the modified bit pattern back to the // GPIO Function Select Register 2 *GPFSEL2 = r; // Disable the pull-up/pull-down control line for GPIO pin 24. We follow the // procedure outlined on page 101 of the BCM2837 ARM Peripherals manual. We // will pull down the pin using an external resistor connected to ground. // Disable internal pull-up/pull-down by setting bits 0:1 // to 00 in the GPIO Pull-Up/Down Register *GPPUD = 0x0; // Wait 150 cycles to provide the required set-up time // for the control signal r = 150; while (r--) { asm volatile("nop"); } // Write to the GPIO Pull-Up/Down Clock Register 0, using a 1 on bit 24 to // clock in the control signal for GPIO pin 24. Note that all other pins // will retain their previous state. *GPPUDCLK0 = (0x1 << 24); // Wait 150 cycles to provide the required hold time // for the control signal r = 150; while (r--) { asm volatile("nop"); } // Clear all bits in the GPIO Pull-Up/Down Clock Register 0 // in order to remove the clock *GPPUDCLK0 = 0; // Set pin 24 to so that it generates an interrupt on a rising edge. // We do so by setting bit 24 in the GPIO Rising Edge Detect Enable // Register 0 to a 1 value (p. 97 in the Broadcom manual). *GPREN0 = (0x1 << 24); // Enable the GPIO IRQS for ALL the GPIO pins by setting IRQ 52 // GPIO_int[3] in the Interrupt Enable Register 2 to a 1 value. // See p. 117 in the Broadcom Peripherals Manual. *IRQ_ENABLE_IRQS_2 = (0x1 << 20); } //////////////////////////////////////////////////////////////////////////////// // // Function: init_GPIO23_to_risingEdgeInterrupt // // Arguments: none // // Returns: void // // Description: This function sets GPIO pin 23 to an input pin without // any internal pull-up or pull-down resistors. Note that // a pull-down (or pull-up) resistor must be used externally // on the bread board circuit connected to the pin. Be sure // that the pin high level is 3.3V (definitely NOT 5V). // GPIO pin 23 is also set to trigger an interrupt on a // rising edge, and GPIO interrupts are enabled on the // interrupt controller. // //////////////////////////////////////////////////////////////////////////////// void init_GPIO23_to_fallingEdgeInterrupt() { register unsigned int r; // Get the current contents of the GPIO Function Select Register 2 r = *GPFSEL2; // Clear bits 9 - 11. This is the field FSEL17, which maps to GPIO pin 23. // We clear the bits by ANDing with a 000 bit pattern in the field. This // sets the pin to be an input pin r &= ~(0x7 << 9); // Write the modified bit pattern back to the // GPIO Function Select Register 2 *GPFSEL2 = r; // Disable the pull-up/pull-down control line for GPIO pin 23. We follow the // procedure outlined on page 101 of the BCM2837 ARM Peripherals manual. We // will pull down the pin using an external resistor connected to ground. // Disable internal pull-up/pull-down by setting bits 0:1 // to 00 in the GPIO Pull-Up/Down Register *GPPUD = 0x0; // Wait 150 cycles to provide the required set-up time // for the control signal r = 150; while (r--) { asm volatile("nop"); } // Write to the GPIO Pull-Up/Down Clock Register 0, using a 1 on bit 23 to // clock in the control signal for GPIO pin 23. Note that all other pins // will retain their previous state. *GPPUDCLK0 = (0x1 << 23); // Wait 150 cycles to provide the required hold time // for the control signal r = 150; while (r--) { asm volatile("nop"); } // Clear all bits in the GPIO Pull-Up/Down Clock Register 0 // in order to remove the clock *GPPUDCLK0 = 0; // Set pin 23 to so that it generates an interrupt on a rising edge. // We do so by setting bit 23 in the GPIO Rising Edge Detect Enable // Register 0 to a 1 value (p. 97 in the Broadcom manual). *GPFEN0 = (0x1 << 23); // Enable the GPIO IRQS for ALL the GPIO pins by setting IRQ 52 // GPIO_int[3] in the Interrupt Enable Register 2 to a 1 value. // See p. 117 in the Broadcom Peripherals Manual. *IRQ_ENABLE_IRQS_2 = (0x1 << 20); } //////////////////////////////////////////////////////////////////////////////// // // Function: init_GPIO17_to_output // // Arguments: none // // Returns: void // // Description: This function sets GPIO pin 17 to an output pin without // any pull-up or pull-down resistors. // //////////////////////////////////////////////////////////////////////////////// void init_GPIO17_to_output() { register unsigned int r; // Get the current contents of the GPIO Function Select Register 2 r = *GPFSEL1; // Clear bits 21-23. This is the field FSEL23, which maps to GPIO pin 17. // We clear the bits by ANDing with a 000 bit pattern in the field. r &= ~(0x7 << 21); // Set the field FSEL23 to 001, which sets pin 17 to an output pin. // We do so by ORing the bit pattern 001 into the field. r |= (0x1 << 21); // Write the modified bit pattern back to the // GPIO Function Select Register 2 *GPFSEL1 = r; // Disable the pull-up/pull-down control line for GPIO pin 17. We follow the // procedure outlined on page 101 of the BCM2837 ARM Peripherals manual. The // internal pull-up and pull-down resistor isn't needed for an output pin. // Disable pull-up/pull-down by setting bits 0:1 // to 00 in the GPIO Pull-Up/Down Register *GPPUD = 0x0; // Wait 150 cycles to provide the required set-up time // for the control signal r = 150; while (r--) { asm volatile("nop"); } // Write to the GPIO Pull-Up/Down Clock Register 0, using a 1 on bit 17 to // clock in the control signal for GPIO pin 17. Note that all other pins // will retain their previous state. *GPPUDCLK0 = (0x1 << 17); // Wait 150 cycles to provide the required hold time // for the control signal r = 150; while (r--) { asm volatile("nop"); } // Clear all bits in the GPIO Pull-Up/Down Clock Register 0 // in order to remove the clock *GPPUDCLK0 = 0; } //////////////////////////////////////////////////////////////////////////////// // // Function: init_GPIO27_to_output // // Arguments: none // // Returns: void // // Description: This function sets GPIO pin 27 to an output pin without // any pull-up or pull-down resistors. // //////////////////////////////////////////////////////////////////////////////// void init_GPIO27_to_output() { register unsigned int r; // Get the current contents of the GPIO Function Select Register 2 r = *GPFSEL2; // Clear bits 21-23. This is the field FSEL23, which maps to GPIO pin 27. // We clear the bits by ANDing with a 000 bit pattern in the field. r &= ~(0x7 << 21); // Set the field FSEL23 to 001, which sets pin 27 to an output pin. // We do so by ORing the bit pattern 001 into the field. r |= (0x1 << 21); // Write the modified bit pattern back to the // GPIO Function Select Register 2 *GPFSEL2 = r; // Disable the pull-up/pull-down control line for GPIO pin 27. We follow the // procedure outlined on page 101 of the BCM2837 ARM Peripherals manual. The // internal pull-up and pull-down resistor isn't needed for an output pin. // Disable pull-up/pull-down by setting bits 0:1 // to 00 in the GPIO Pull-Up/Down Register *GPPUD = 0x0; // Wait 150 cycles to provide the required set-up time // for the control signal r = 150; while (r--) { asm volatile("nop"); } // Write to the GPIO Pull-Up/Down Clock Register 0, using a 1 on bit 27 to // clock in the control signal for GPIO pin 27. Note that all other pins // will retain their previous state. *GPPUDCLK0 = (0x1 << 27); // Wait 150 cycles to provide the required hold time // for the control signal r = 150; while (r--) { asm volatile("nop"); } // Clear all bits in the GPIO Pull-Up/Down Clock Register 0 // in order to remove the clock *GPPUDCLK0 = 0; } //////////////////////////////////////////////////////////////////////////////// // // Function: init_GPIO22_to_output // // Arguments: none // // Returns: void // // Description: This function sets GPIO pin 22 to an output pin without // any pull-up or pull-down resistors. // //////////////////////////////////////////////////////////////////////////////// void init_GPIO22_to_output() { register unsigned int r; // Get the current contents of the GPIO Function Select Register 2 r = *GPFSEL2; // Clear bits 6-8. This is the field FSEL23, which maps to GPIO pin 22. // We clear the bits by ANDing with a 000 bit pattern in the field. r &= ~(0x7 << 6); // Set the field FSEL23 to 001, which sets pin 22 to an output pin. // We do so by ORing the bit pattern 001 into the field. r |= (0x1 << 6); // Write the modified bit pattern back to the // GPIO Function Select Register 2 *GPFSEL2 = r; // Disable the pull-up/pull-down control line for GPIO pin 22. We follow the // procedure outlined on page 101 of the BCM2837 ARM Peripherals manual. The // internal pull-up and pull-down resistor isn't needed for an output pin. // Disable pull-up/pull-down by setting bits 0:1 // to 00 in the GPIO Pull-Up/Down Register *GPPUD = 0x0; // Wait 150 cycles to provide the required set-up time // for the control signal r = 150; while (r--) { asm volatile("nop"); } // Write to the GPIO Pull-Up/Down Clock Register 0, using a 1 on bit 22 to // clock in the control signal for GPIO pin 22. Note that all other pins // will retain their previous state. *GPPUDCLK0 = (0x1 << 22); // Wait 150 cycles to provide the required hold time // for the control signal r = 150; while (r--) { asm volatile("nop"); } // Clear all bits in the GPIO Pull-Up/Down Clock Register 0 // in order to remove the clock *GPPUDCLK0 = 0; } //////////////////////////////////////////////////////////////////////////////// // // Function: set_GPIO17 // // Arguments: none // // Returns: void // // Description: This function sets the GPIO output pin 17 // to a 1 (high) level. // //////////////////////////////////////////////////////////////////////////////// void set_GPIO17() { register unsigned int r; // Put a 1 into the SET17 field of the GPIO Pin Output Set Register 0 r = (0x1 << 17); *GPSET0 = r; } //////////////////////////////////////////////////////////////////////////////// // // Function: set_GPIO27 // // Arguments: none // // Returns: void // // Description: This function sets the GPIO output pin 27 // to a 1 (high) level. // //////////////////////////////////////////////////////////////////////////////// void set_GPIO27() { register unsigned int r; // Put a 1 into the SET27 field of the GPIO Pin Output Set Register 0 r = (0x1 << 27); *GPSET0 = r; } //////////////////////////////////////////////////////////////////////////////// // // Function: set_GPIO22 // // Arguments: none // // Returns: void // // Description: This function sets the GPIO output pin 22 // to a 1 (high) level. // //////////////////////////////////////////////////////////////////////////////// void set_GPIO22() { register unsigned int r; // Put a 1 into the SET22 field of the GPIO Pin Output Set Register 0 r = (0x1 << 22); *GPSET0 = r; } //////////////////////////////////////////////////////////////////////////////// // // Function: clear_GPIO17 // // Arguments: none // // Returns: void // // Description: This function clears the GPIO output pin 17 // to a 0 (low) level. // //////////////////////////////////////////////////////////////////////////////// void clear_GPIO17() { register unsigned int r; // Put a 1 into the CLR17 field of the GPIO Pin Output Clear Register 0 r = (0x1 << 17); *GPCLR0 = r; } //////////////////////////////////////////////////////////////////////////////// // // Function: clear_GPIO27 // // Arguments: none // // Returns: void // // Description: This function clears the GPIO output pin 27 // to a 0 (low) level. // //////////////////////////////////////////////////////////////////////////////// void clear_GPIO27() { register unsigned int r; // Put a 1 into the CLR27 field of the GPIO Pin Output Clear Register 0 r = (0x1 << 27); *GPCLR0 = r; } //////////////////////////////////////////////////////////////////////////////// // // Function: clear_GPIO22 // // Arguments: none // // Returns: void // // Description: This function clears the GPIO output pin 22 // to a 0 (low) level. // //////////////////////////////////////////////////////////////////////////////// void clear_GPIO22() { register unsigned int r; // Put a 1 into the CLR22 field of the GPIO Pin Output Clear Register 0 r = (0x1 << 22); *GPCLR0 = r; }
C
#include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "arm_general.h" void setBit(word32* word, int index) { *word |= 1 << index; } // inclusive start_index, exclusive end_index, indices start from LSB to MSB word32 getBits(word32 word, int start_index, int end_index) { word32 mask = UINT32_MAX >> (WORD_SIZE - (end_index - start_index)); return (word >> start_index) & mask; } void safeStrCpy(char* dest, char* src, int n) { strncpy(dest, src, n); if (dest[n - 1] != '\0') { dest[n - 1] = '\0'; } } void safeSeek(FILE* file, word32 line) { if (fseek(file, line, SEEK_SET)) { perror("Error: Seek file line failed\n"); exit(EXIT_FAILURE); } }
C
#include "common.h" #include "config.h" #include "options.h" #include "flashlog.h" uint32_t FlashLogFreeAddress = 0; FLASHLOG_IBG_RECORD FlashLogIBGRecord; FLASHLOG_GPS_RECORD FlashLogGPSRecord; SemaphoreHandle_t FlashLogMutex = NULL; #define TAG "flashlog" void flashlog_erase(uint32_t untilAddress) { spiflash_globalUnprotect(); if (untilAddress == 0) untilAddress = FLASH_SIZE_BYTES; // manually force erase of entire chip uint32_t lastSectorAddress = untilAddress & 0xFFFFF000; // sector size = 4096 for (uint32_t sectorAddress = 0; sectorAddress <= lastSectorAddress; sectorAddress += 4096) { spiflash_sectorErase(sectorAddress); delayMs(50); } ESP_LOGI(TAG,"Erased"); FlashLogFreeAddress = 0; } int flashlog_init(void ) { uint16_t flashID = spiflash_readID(); if (flashID != 0xEF17) { ESP_LOGE(TAG, "Winbond W25Q128FVSG ID [expected EF17] = %04X", flashID); return -1; } spiflash_globalUnprotect(); FlashLogMutex = xSemaphoreCreateMutex(); if (FlashLogMutex == NULL) { ESP_LOGE(TAG, "Error creating FlashLogMutex"); return -2; } FlashLogFreeAddress = flashlog_getFreeAddress(); ESP_LOGI(TAG,"FlashLogFreeAddress = %08d", FlashLogFreeAddress); return 0; } int flashlog_isEmpty() { uint32_t dw; spiflash_readBuffer(0, (uint8_t*)&dw, sizeof(uint32_t)); return (dw == 0xFFFF) ? 1 : 0; } // if there is only an I record, size of record = IBGHDR + I // if there is a B record, size of record = IBGHDR + I + B // if there is a G record, size of record = IBGHDR + I + B + G even if B record is invalid int flashlog_getNumIBGRecords() { uint32_t addr = 0; uint32_t maxAddr = FLASH_SIZE_BYTES - sizeof(FLASHLOG_IBG_RECORD); int numRecords = 0; while (1) { if (addr >= maxAddr) break; // flash is full IBG_HDR hdr; hdr.magic = 0; spiflash_readBuffer(addr, (uint8_t*)&hdr, sizeof(IBG_HDR)); if (hdr.magic == 0xFFFF) break; // found free address addr += (sizeof(IBG_HDR) + sizeof(I_RECORD)); if (hdr.baroFlags || hdr.gpsFlags) addr += sizeof(B_RECORD); if (hdr.gpsFlags) addr += sizeof(G_RECORD); numRecords++; if ((numRecords % 100) == 0) delayMs(10); // yield for task watchdog } return numRecords; } uint32_t flashlog_getFreeAddress() { uint32_t loAddr = 0; uint32_t hiAddr = FLASH_SIZE_BYTES - 4; uint32_t midAddr = ((loAddr+hiAddr)/2)&0xFFFFFFFE; while (hiAddr > loAddr+4) { uint32_t dw; spiflash_readBuffer(midAddr, (uint8_t*)&dw, sizeof(uint32_t)); if (dw == 0xFFFFFFFF) { hiAddr = midAddr; } else { loAddr = midAddr; } midAddr = ((loAddr+hiAddr)/2)&0xFFFFFFFE; } ESP_LOGI(TAG,"Lo %d mid %d hi %d", loAddr, midAddr, hiAddr); return midAddr; } // ensure this function is called within a mutex take/give as there are multiple tasks // updating the log record int flashlog_writeIBGRecord(FLASHLOG_IBG_RECORD* pRecord) { if (FlashLogFreeAddress > (FLASHLOG_MAX_ADDR - sizeof(FLASHLOG_IBG_RECORD))) { return -1; } int numBytes = sizeof(IBG_HDR) + sizeof(I_RECORD); if (pRecord->hdr.baroFlags || pRecord->hdr.gpsFlags) numBytes += sizeof(B_RECORD); if (pRecord->hdr.gpsFlags) numBytes += sizeof(G_RECORD); spiflash_writeBuffer(FlashLogFreeAddress, (uint8_t*)pRecord, numBytes); FlashLogFreeAddress += numBytes; return 0; } int flashlog_readIBGRecord(uint32_t addr, FLASHLOG_IBG_RECORD* pRecord) { IBG_HDR hdr; spiflash_readBuffer(addr, (uint8_t*)&hdr, sizeof(IBG_HDR)); if (hdr.magic != FLASHLOG_IBG_MAGIC) { ESP_LOGE(TAG, "error flash log header does not have magic id"); return -1; } int numBytes = sizeof(IBG_HDR) + sizeof(I_RECORD); if (hdr.baroFlags || hdr.gpsFlags) numBytes += sizeof(B_RECORD); if (hdr.gpsFlags) numBytes += sizeof(G_RECORD); spiflash_readBuffer(addr, (uint8_t*)pRecord, numBytes); return 0; } // this function does not have to be called within a mutex take/give as // only gps_task updates and writes the log record int flashlog_writeGPSRecord(FLASHLOG_GPS_RECORD* pRecord) { if (FlashLogFreeAddress > (FLASHLOG_MAX_ADDR - sizeof(FLASHLOG_GPS_RECORD))) { return -1; } int numBytes = sizeof(FLASHLOG_GPS_RECORD); spiflash_writeBuffer(FlashLogFreeAddress, (uint8_t*)pRecord, numBytes); FlashLogFreeAddress += numBytes; return 0; }
C
/* * Honors project for CS241 by Ellis Hoag * * To compile on mac: * gcc main.c cl_fluid_sim.c sdl_window.c -framework OpenCL -framework OpenGL -framework SDL2 -ofluid */ #include <unistd.h> #include "sdl_window.h" #include "cl_fluid_sim.h" #define WINDOW_WIDTH 600 #define WINDOW_HEIGHT 600 #define MAX_FPS 30 extern char * optarg; window_t * my_window; FluidSim * my_fluid_sim; float x_prev = -1; float y_prev = -1; VEC_TYPE fluid_color = IS_A_DENSITY; void toggle_source_color() { fluid_color = (fluid_color == IS_A_DENSITY) ? IS_B_DENSITY : IS_A_DENSITY; } void on_clicked(float x, float y, int shift_held) { const float dens_strength = 2.f; const float dens_radius = 1.f; const float vel_strength = 10.f; const float vel_radius = 0.05f; if (x_prev != -1 && y_prev != -1) { float u = x - x_prev; float v = y - y_prev; float dist_sqrd = u * u + v * v; if (dist_sqrd > 0) { float mag = vel_strength / sqrtf(dist_sqrd); if (shift_held) { enqueue_event(my_fluid_sim, x, y, dens_strength, dens_radius, fluid_color); } else { enqueue_event(my_fluid_sim, x, y, mag * u, vel_radius, IS_U_VELOCITY); enqueue_event(my_fluid_sim, x, y, mag * v, vel_radius, IS_V_VELOCITY); } } } x_prev = x; y_prev = y; } void on_release() { x_prev = y_prev = -1; } void add_stream(FluidSim * fluid, float x, float y, float u, float v, float dens_strength, float vel_strength, VEC_TYPE source_type) { const float radius = 0.05f; float u_offset = ((rand() % 100) - 50) / 30.f; float v_offset = ((rand() % 100) - 50) / 30.f; u += u_offset; v += v_offset; float dist_sqrd = u * u + v * v; if (dist_sqrd > 0) { float mag = vel_strength / sqrtf(dist_sqrd); u = mag * u; v = mag * v; enqueue_event(fluid, x, y, dens_strength, radius, source_type); enqueue_event(fluid, x, y, u, radius, IS_U_VELOCITY); enqueue_event(fluid, x, y, v, radius, IS_V_VELOCITY); } } int main(int argc, char ** argv) { FLAGS flags = 0; float viscosity = 0.0001f; float diffusion_rate = 0.0001f; int num_r_steps = 20; size_t sim_size = 128; int has_chosen_type = 0; int ch; while ((ch = getopt(argc, argv, "bpv:d:n:t:r:")) != -1) { switch (ch) { case 'b': flags |= F_DEBUG; break; case 'p': flags |= F_PROFILE; break; case 'v': viscosity = (float)atof(optarg); break; case 'd': diffusion_rate = (float)atof(optarg); break; case 'n': sim_size = atoi(optarg); break; case 't': if (strcmp(optarg, "CPU") == 0) { flags |= F_USE_CPU; has_chosen_type = 1; } else if (strcmp(optarg, "GPU") == 0) { flags |= F_USE_GPU; has_chosen_type = 1; } else { fprintf(stderr, "Invalid device type.\n"); return 1; } break; case 'r': num_r_steps = atoi(optarg); break; default: break; } } if (!has_chosen_type) { //set defualt value flags |= F_USE_GPU; } my_window = create_window(WINDOW_WIDTH, WINDOW_HEIGHT, sim_size); if (!my_window) { fprintf(stderr, "Failed to create window!\n"); return 2; } my_fluid_sim = create_fluid_sim(my_window->window_texture, "fluid_kernel.cl", sim_size, diffusion_rate, viscosity, num_r_steps, flags); if (!my_fluid_sim) { fprintf(stderr, "Unable to create fluid_sim!\n"); return 3; } Uint32 prev_time = SDL_GetTicks(); while (my_window->is_running) { float dt = (SDL_GetTicks() - prev_time) / 1000.f; prev_time = SDL_GetTicks(); add_stream(my_fluid_sim, 0.5f, 0.75f, 0.f, -1.f, 1.f, 1.f, IS_B_DENSITY); add_stream(my_fluid_sim, 0.25f, 0.25f, 1.f, 1.f, 1.f, 1.f, IS_A_DENSITY); add_stream(my_fluid_sim, 0.75f, 0.25f, -1.f, 1.f, 1.f, 1.f, IS_A_DENSITY); //add_stream(my_fluid_sim, 0.5f, 0.5f, -1.f, 1.f, 1.f, 1.f, IS_A_DENSITY); //add_stream(my_fluid_sim, 0.5f, 0.25f, 0.f, -1.f, 1.f, 2.f, IS_B_DENSITY); simulate_next_frame(my_fluid_sim, dt); render_window(my_window, 1.f / dt); do { poll_events(my_window, on_clicked, toggle_source_color, on_release); } while (SDL_GetTicks() - prev_time < 1000.f / MAX_FPS); } destroy_fluid_sim(my_fluid_sim); destroy_window(my_window); return 0; }
C
/** * Rewrite the routines day_of_year and month_day with pointers instead of indexing */ #include <stdio.h> static char daytab[2][13] = { {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, // non-leap {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, // leap }; int day_of_year(int, int, int); void month_day(int, int, int *, int *); int main() { printf("%d\n", day_of_year(2018, 05, 24)); printf("%d\n", day_of_year(2018, 12, 31)); int m, d; month_day(2018, 144, &m, &d); printf("%d/%d\n", m, d); month_day(2018, 365, &m, &d); printf("%d/%d\n", m, d); } int day_of_year(int year, int month, int day) { int leap; char *p; leap = (year%4 == 0 && year%100 != 0) || year%400 == 0; p = *daytab+leap; // == &daytab[leap][0]; while (--month) day += *++p; return day; } void month_day(int year, int yearday, int *pmonth, int *pday) { int leap, i; char *p; leap = (year%4 == 0 && year%100 != 0) || year%400 == 0; p = *daytab + leap; for (i = 1; yearday > *++p; i++) yearday -= *p; *pmonth = i; *pday = yearday; }
C
#include "estudiantes.h" Alumno aprendiz; /** Guardar nombre **/ void guardarNombreCompleto(char *n, char *a){ aprendiz.nombre = (char *) malloc(strlen(n)*sizeof(char)); aprendiz.nombre = strcpy(aprendiz.nombre, n); aprendiz.apellidos = (char *) malloc(strlen(a)*sizeof(char)); aprendiz.apellidos = strcpy(aprendiz.apellidos, a); } /** Solicitar calficaciones **/ void solicitarCalificaciones(){ for(int i=0; i < TAM; i++){ printf("Ingresa calificacion %d : \n",(i+1)); scanf("%f",&aprendiz.calificaciones[i]); aprendiz.calificaciones[i] = aprendiz.calificaciones[i]; } } /** Mostrar informacion **/ void mostrarInformacion(){ float suma; printf("Nombre completo: %s",strcat(aprendiz.nombre, aprendiz.apellidos)); puts("Calificaciones:"); for(int i=0; i < TAM; i++){ printf("%f\n", aprendiz.calificaciones[i]); suma += aprendiz.calificaciones[i]; } printf("Promedio obtenido: %.2f\n", (suma/TAM)); }
C
/****************************************************************************** * Pwarp.c * * MEX file to do projective warp * Fast version for contiguous image based on first differences * Same functionality as Pwarp.m (but about 8 times faster for 640*320 warp) * * Copyright (c) 1998 Frank Dellaert * All rights reserved *****************************************************************************/ #include <math.h> #include "resampling.h" /****************************************************************************** * fully specified Pwarp, completely C. No mex stuff here... * However: all pointers use -1 trick to get base 1 integer access *****************************************************************************/ #define crop 0.5 void Pwarp(const double *original, int m, int n, const double *H, const double *mosaic, int blend, double *warped, double *goodpix, int nrRowsWarped, int nrColsWarped ) { /* get homography coefficients */ double a=H[1],b=H[4],c=H[7], d=H[2],e=H[5],f=H[8], g=H[3],h=H[6],i=H[9]; int ix,iy; /* integer coordinates in warped */ /* for each scanline */ for(iy=1;iy<=nrRowsWarped;iy++) { double U,V,W; /* homogeneous coordinates in original */ int indexInWarped = iy; /* integer index (base 1) in warped */ /* calculate the first preimage in the scanline */ { double x = 0.5, y = iy - 0.5; /* double coordinates in warped */ U = a*x + b*y + c; V = d*x + e*y + f; W = g*x + h*y + i; } for (ix=1;ix<=nrColsWarped;ix++) { /*calculate image coordinates in original */ double u = U/W, v = V/W; /* filter out pixels that land outside original */ int good = v>crop && v<m-crop && u>crop && u<n-crop; if (good) { double resampled = sampleBilinear(original,m,u,v); goodpix[indexInWarped] = 1; /* (primitive) blend or not */ if (blend) warped[indexInWarped]=(mosaic[indexInWarped]+resampled)/2; else warped[indexInWarped]=resampled; } else { goodpix[indexInWarped] = 0; if (mosaic) warped[indexInWarped]=mosaic[indexInWarped]; } /* update by first differencing */ U += a; V += d; W += g; indexInWarped += nrRowsWarped; } } } /****************************************************************************** * all MEX stuff below this line *****************************************************************************/ #include "mex.h" /****************************************************************************** * 4 argument version * all pointers use -1 trick to get base 1 integer access *****************************************************************************/ mxArray *goodpix; mxArray *Pwarp4(const mxArray *original, const mxArray *H, const mxArray *mosaic, int blend) { /* get image size */ int m = mxGetM(original); int n = mxGetN(original); /* create a warped image the same size as the mosaic */ int nrRowsWarped = mxGetM(mosaic); int nrColsWarped = mxGetN(mosaic); mxArray *warped = mxCreateDoubleMatrix(nrRowsWarped,nrColsWarped,mxREAL); /* get pointers to data */ double * HPr = mxGetPr(H) -1; double * warpedPr = mxGetPr(warped) -1; double * originalPr = mxGetPr(original)-1; double * mosaicPr = mxGetPr(mosaic) -1; double *goodPr; goodpix = mxCreateDoubleMatrix(nrRowsWarped,nrColsWarped,mxREAL); goodPr = mxGetPr(goodpix) -1; Pwarp(originalPr, m, n, HPr, mosaicPr, blend, warpedPr, goodPr, nrRowsWarped, nrColsWarped ); return warped; } /****************************************************************************** * three argument version *****************************************************************************/ mxArray *Pwarp3(const mxArray *original, const mxArray *H, const mxArray *mosaic) { return Pwarp4(original, H, mosaic, 0); } /****************************************************************************** * two argument version * all pointers use -1 trick to get base 1 integer access *****************************************************************************/ mxArray *Pwarp2(const mxArray *original, const mxArray *H) { /* get image size */ int m = mxGetM(original); int n = mxGetN(original); /* create a warped image the same size as the original */ int nrRowsWarped = m; int nrColsWarped = n; mxArray *warped = mxCreateDoubleMatrix(nrRowsWarped,nrColsWarped,mxREAL); /* get pointers to data */ double * HPr = mxGetPr(H) -1; double * warpedPr = mxGetPr(warped) -1; double * originalPr = mxGetPr(original)-1; double *goodPr; goodpix = mxCreateDoubleMatrix(nrRowsWarped,nrColsWarped,mxREAL); goodPr = mxGetPr(goodpix) -1; Pwarp(originalPr, m, n, HPr, NULL, 0, warpedPr, goodPr, nrRowsWarped, nrColsWarped ); return warped; } /****************************************************************************** * function warped = Pwarp(original,H,mosaic,blend) * hack: mere existence of input argument blend makes blend=1 *****************************************************************************/ void mexFunction(int nargout, mxArray *out[], int nargin, const mxArray *in[]) { mxArray *warped; if (nargout>2) goto usage; switch(nargin) { case 2: warped = Pwarp2(in[0],in[1]); break; case 3: warped = Pwarp3(in[0],in[1],in[2]); break; case 4: warped = Pwarp4(in[0],in[1],in[2],1); break; default: goto usage; } out[0] = warped; out[1] = goodpix; return; usage: mexErrMsgTxt("usage: [warped, goodpix] = Pwarp(original,H[,mosaic,blend])"); } /******************************************************************************/
C
#include "globals.h" char * getHomeDirectory() { size_t size=40000; char * tempdir=(char*)malloc(size); tempdir=getcwd(tempdir,size); return tempdir; } char* giveDirectory(char* home) { size_t size=40000; char * tempdir=(char*)malloc(size); tempdir=getcwd(tempdir,size); int i=0; char* currdir=(char*)malloc(size); while(i <= strlen(tempdir)&&i <= strlen(home)&&tempdir[i]==home[i]&&home[i]!='\0'&&tempdir[i]!='\0') ++i; if (i==strlen(home)) { currdir[0]='~'; for (int j = i; j <strlen(tempdir) ; ++j) { currdir[j-i+1]=tempdir[j]; } } else { currdir=tempdir; } return currdir; }
C
#include<stdio.h> int main(){ int i,j,count=0; i=1; j=7; while(i!=11){ printf("I=%d J=%d\n", i,j); j--; printf("I=%d J=%d\n", i,j); j--; printf("I=%d J=%d\n", i,j); j--; i += 2; j += 5; } return 0; }
C
/* FILE NAME: daifugo_client.c DESCRIPTION: クライアントの処理 */ #include "daifugo.h" int main(int argc, char *argv[]) { CARD_DATA field[MAX_PLAYER_CARD+1] = { EMPTY }; CARD_DATA select[MAX_PLAYER_CARD+1] = { EMPTY }; PLAYER_DATA all_player_data[PLAYER_NUM]; int turn; int select_card_num; int field_status; int player_number; char str[256]; int control_data; int fd; int max_point; int game_number = 1; // 引数チェック if (argc-1 != 1){ printf("Usage: %s SERVER_NAME\n", argv[0]); exit(1); } // ネットワークの初期化 network_init_client(&fd, argv); // 他のプレイヤーが揃うまで待機メッセージ do { printf("Waiting for other players ...\n"); recv(fd, str, sizeof(char)*1024, 0); } while(strcmp(str, "START") != 0); // player number[PLAYER-?]を決定 recv(fd, &player_number, sizeof(int), 0); printf("player number : %d\n", player_number); do{ // 誰からゲームを開始するかを表示 recv(fd, str, sizeof(char)*1024, 0); printf("%s\n", str); sleep(2); // メインループ while (1) { // 制御データを受信(network.hで定義) recv(fd, &control_data, sizeof(int), 0); // フィールド(手札も)表示 if (control_data == FIELD_DATA) { recv(fd, &select_card_num, sizeof(int), 0); recv(fd, &turn, sizeof(int), 0); recv(fd, &field_status, sizeof(int), 0); recv(fd, all_player_data, sizeof(PLAYER_DATA)*(PLAYER_NUM), 0); recv(fd, field, sizeof(CARD_DATA)*(MAX_FIELD_CARD+1), 0); printf(CLEAR_DISPLAY); printf("\n========== I'm PLAYER-%d GAME:%d ==========\n\n", player_number, game_number); disp_field(all_player_data, field, select_card_num, turn, field_status); disp_my_card(&all_player_data[player_number]); } /// カード選択 else if (control_data == SELECT_CARD) { recv(fd, &turn, sizeof(int), 0); if (turn == player_number) { init_card_data(select); select_card_num = select_card(&all_player_data[turn], select); /* 場に出すカードを選択させる */ send(fd, &select_card_num, sizeof(int), 0); send(fd, select, sizeof(CARD_DATA)*(MAX_FIELD_CARD+1), 0); } } /// パスメッセージ else if (control_data == PASS) { disp_pass_message(); } /// 全員パスメッセージ else if (control_data == ALL_PASS) { disp_all_pass_message(); } /// 8切りメッセージ else if(control_data == YAGIRI) { recv(fd, all_player_data, sizeof(PLAYER_DATA)*(PLAYER_NUM), 0); recv(fd, field, sizeof(CARD_DATA)*(MAX_FIELD_CARD+1), 0); recv(fd, &select_card_num, sizeof(int), 0); recv(fd, &turn, sizeof(int), 0); recv(fd, &field_status, sizeof(int), 0); printf(CLEAR_DISPLAY); /* 画面クリア */ printf("========== I'm PLAYER-%d GAME:%d ==========\n\n", player_number, game_number); disp_field(all_player_data, field, select_card_num, turn, field_status); disp_my_card(&all_player_data[player_number]); disp_yagiri_message(); /* メッセージの表示 */ } /// 革命メッセージ else if (control_data == KAKUMEI_MSG) { recv(fd, all_player_data, sizeof(PLAYER_DATA)*(PLAYER_NUM), 0); recv(fd, field, sizeof(CARD_DATA)*(MAX_FIELD_CARD+1), 0); recv(fd, &select_card_num, sizeof(int), 0); recv(fd, &turn, sizeof(int), 0); recv(fd, &field_status, sizeof(int), 0); printf(CLEAR_DISPLAY); /* 画面クリア */ printf("========== I'm PLAYER-%d GAME:%d ==========\n\n", player_number, game_number); disp_field(all_player_data, field, select_card_num, turn, field_status); disp_my_card(&all_player_data[player_number]); disp_kakumei_message(); } /// 結果表示 else if(control_data == RESULT) { recv(fd, all_player_data, sizeof(PLAYER_DATA)*(PLAYER_NUM), 0); printf(CLEAR_DISPLAY); /* 画面クリア */ disp_result(all_player_data); recv(fd, &max_point, sizeof(int), 0); break; } } game_number++; }while (max_point < POINT); // max_pointがPOINTに達したらゲーム終了 printf("誰かが%d点に達したのでゲームを終了します...\n", POINT); close(fd); return 0; }
C
#include "strlib.h" char * _strcpy(dst, src) char *dst; char *src; { int i; i = 0; while (src[i]) { dst[i] = src[i]; i += 1; } dst[i] = '\0'; return (dst); }
C
/** * \file * * \brief Empty user application template * */ #include <asf.h> #include "PID.h" #include "HMI.h" #include "matlabcomm.h" #include <math.h> #include "timer_delay.h" #include "my_adc.h" #include "lcd_shield.h" #include "global_variables.h" /* Define a variable of the type xSemaphoreHandle */ xSemaphoreHandle semafor_signal = 0; /* data type for button identification */ /* signal characteristics */ struct { uint16_t setpoint; double P; uint16_t I; uint16_t D; } reglering; static void dacc_setup(void) { pmc_enable_periph_clk(ID_DACC); dacc_reset(DACC); dacc_set_transfer_mode(DACC, 0); dacc_set_timing(DACC,1,1,0); //1 is shortest refresh period, 1 max. speed, 0 startup time dacc_set_channel_selection(DACC,0); //Channel DAC0 dacc_enable_channel(DACC, 0); //enable DAC0 } /* * Making some necessary initializations for hardware and interrupts. */ static void init_hardware(void) { /* Initiera SAM systemet */ sysclk_init(); board_init(); delay_init(0); /* timer 0: for delay() */ ioport_init(); adc_setup(); dacc_setup(); //adc_start(ADC); //config_timer_irq(1, 10); /* timer 1: for reading ADC, 10 times/second */ lcd_init(); } void display_program_text(void) { /* initial program text */ // lcd_put_cursor(0, 0); // lcd_write_str("*"); lcd_put_cursor(0, 1); lcd_write_str("B"); lcd_put_cursor(0, 5); lcd_write_str("Kp"); lcd_put_cursor(0, 10); lcd_write_str("Ti"); lcd_put_cursor(0, 14); lcd_write_str("Td"); /*lcd_put_cursor(1,8); lcd_write_str("0.0"); */ } void configure_console(void) { const usart_serial_options_t uart_serial_options = { .baudrate = CONF_UART_BAUDRATE, .paritytype = CONF_UART_PARITY }; sysclk_enable_peripheral_clock(CONSOLE_UART_ID); stdio_serial_init(CONF_UART, & uart_serial_options); //& betyder att man hmtar minnesplatsen fr det objektet! /* Stdout shall not be buffered */ #if defined(__GNUC__) setbuf(stdout, NULL); #else /* Redan i fallet IAR's Normal DLIB default konfiguration: * snder en tecken tgngen */ #endif } int main(void) { init_hardware(); //LCD_Shield display_program_text(); //Setpoint, P, I, D- text. while(1) { reglering.setpoint = SETPOINT_START_VALUE; reglering.P = P_START_VALUE; reglering.I = I_START_VALUE; reglering.D = D_START_VALUE; configure_console(); /* Print demo information */ /*printf("-- Freertos Exempel - Semaforer --\n\r"); printf("-- %s\n\r", BOARD_NAME); printf("-- Kompilerad: %s %s --\n\r", __DATE__, __TIME__);*/ /* a semaphore cannot be used wihtout calling vSemaphoreCreateBinary() */ vSemaphoreCreateBinary(semafor_signal); /* Create the task giving the semaphore */ if (xTaskCreate(pid_reg, (const signed char * const) "Task1", 1024, NULL, 3, NULL) != pdPASS) { } /* Create a task taking the semaphore and doing its stuff */ if (xTaskCreate(disp_buttons, (const signed char * const) "Task2", 1024, NULL, 2, NULL) != pdPASS) { } /* Create a task taking the semaphore and doing its stuff */ if (xTaskCreate(communication, (const signed char * const) "Task3", 1024, NULL, 1, NULL) != pdPASS) { } vTaskStartScheduler(); } }
C
#include<stdio.h> //vladimir drob 312964844 int main() { char a, b, c; int diff; printf("plese enter two chars with space between them\n"); scanf_s("%c", &a); scanf_s("%c", &b); scanf_s("%c", &c); if (b !=' ') { printf("error! type space between the chars\n"); return 1; } diff = a - c; if (diff < 0) { diff = -1 * diff; } printf(" the absolute number between two chars is %d", diff); return 0; } /*plese enter two chars with space between them A B the absolute number between two chars is 1*/ /*plese enter two chars with space between them @ 7 the absolute number between two chars is 9*/ /*plese enter two chars with space between them Q Q the absolute number between two chars is 0*/ /*plese enter two chars with space between them &^% error! type space between the chars */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* input_wordmove.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: amordret <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/11 12:01:12 by amordret #+# #+# */ /* Updated: 2019/10/11 12:05:09 by amordret ### ########.fr */ /* */ /* ************************************************************************** */ #include "sh.h" void input_is_prevword(t_read_input *s) { int i; i = s->cursorpos; while (i > 0 && s->buffer.buf && s->buffer.buf[i] != ' ') { input_is_left(&(s->cursorpos), s); i--; } if (i > 0) { input_is_left(&(s->cursorpos), s); } } void input_is_nextword(t_read_input *s) { int i; i = 0; while (s->buffer.buf && s->buffer.buf[i] && i < s->cursorpos) i++; while (s->buffer.buf && s->buffer.buf[i] && (s->buffer.buf[i] != ' ')) { input_is_right(&(s->cursorpos), s); i++; } if (s->buffer.buf && s->buffer.buf[i++]) { input_is_right(&(s->cursorpos), s); } } void input_is_nextorprevword(t_read_input *s) { char c; c = 0; read(0, &c, 1); read(0, &c, 1); c = 0; read(0, &c, 1); if (c == 'D' || c == 'd') return (input_is_prevword(s)); if (c == 'C' || c == 'c') return (input_is_nextword(s)); if (c == 'A' || c == 'a') return (input_is_upline(s)); if (c == 'B' || c == 'b') return (input_is_downline(s)); }
C
#include <stdio.h> #include <stdlib.h> int quit = 0; getstring(FILE *f, char *s, long len) { long i; for (i=0; i<len; i++) if ((s[i] = fgetc(f))==EOF) quit = 1; s[len] = '\0'; } char name[9]; char blockname[5]; char sizebuf[5]; main(int argc, char **argv) { FILE *fp; long blocksize; char *block; int i,j; if (argc !=2) { printf("whoops\n"); exit(1); } fp = fopen(argv[1],"r"); getstring(fp,name,8); printf("id: %s\n\n",name); while (1) { getstring(fp,blockname,4); if (quit) break; printf("Block: %s\n",blockname); getstring(fp,sizebuf,4); blocksize = (long)sizebuf[3] + (long)sizebuf[2]*256 + (long)sizebuf[1]*256*256 + (long)sizebuf[0]*256*256*256; printf("Size: %ld\n",blocksize); if (blocksize < 65536) { block = (char *)malloc(blocksize); getstring(fp,block,blocksize); } if (strcmp(blockname,"CMOD")==0) { printf("channel modes: "); for (i=0; i<blocksize/2; i++) printf("%d ",(int)block[i*2+1] + (int)block[i*2]); printf("\n\n"); } else if (strcmp(blockname,"SAMP")==0) { for (i=0; i<blocksize/32; i++) { printf("%20s ",&block[i*32]); for (j=20; j<32; j++) printf("%2x ",block[i*32+j]); printf("\n"); } printf("\n"); } else if (strcmp(blockname,"SPEE")==0) { printf("speed = %d\n\n",(int)block[1] + (int)block[0]*256); } else if (strcmp(blockname,"PLEN")==0) { printf("pattern length = %d\n\n",(int)block[1] + (int)block[0]*256); } else if (strcmp(blockname,"SLEN")==0) { printf("song length = %d\n\n",(int)block[1] + (int)block[0]*256); } else if (strcmp(blockname,"SBOD")==0) { } free(block); getchar(); } close(fp); }
C
#include<stdio.h> int length(char *str) { int l=0; while(*str != '\0') { l++; str++; } return l; } int compare(char *str1,char *str2) { int flag=1; if(length(str1)==length(str2)) return 0; while(*str1 != '\0') { if(*str1 != *str2) { str1++; str2++; flag=0; } else str1++; str2++; if(flag==0) return 0; else return 1; } } int main() { char str1[100]; char str2[100]; printf("Enter first string= "); gets(str1); printf("Enter second string= "); gets(str2); int l1=length(str1); int l2=length(str2); int flag=0; printf("%d,%d\n\n",l1,l2); if(flag==compare(str1,str2)) printf("Not equal"); else printf("Strings are equal"); return 0; }
C
#include <avr/io.h> #include <avr/interrupt.h> #include <avr/sleep.h> #include <util/delay.h> enum { DELAY_MS_DEBOUCE = 50, DELAY_MS_MOVE = 300, LED_MIN = 0, LED_MAX = 11, NUM_LEDS = 12, PLAYER_0 = 0, PLAYER_1 = 1, }; uint8_t direction[] = { 0b0011, 0b0011, 0b0101, 0b0101, 0b0110, 0b0110, 0b1001, 0b1001, 0b1010, 0b1010, 0b1100, 0b1100, }; uint8_t port[] = { 0b0001, 0b0010, 0b0001, 0b0100, 0b0010, 0b0100, 0b0001, 0b1000, 0b0010, 0b1000, 0b0100, 0b1000 }; volatile int button0_pressed = 0; volatile int button1_pressed = 0; void beep(void) { TCCR0A |= _BV(COM0B1); _delay_ms(50); TCCR0A &= ~_BV(COM0B1); } ISR(INT0_vect) { if (bit_is_clear(PIND, PD2)) { _delay_ms(DELAY_MS_DEBOUCE); if (bit_is_clear(PIND, PD2)) { ++button0_pressed; beep(); } } } ISR(INT1_vect) { if (bit_is_clear(PIND, PD3)) { _delay_ms(DELAY_MS_DEBOUCE); if (bit_is_clear(PIND, PD3)) { ++button1_pressed; beep(); } } } void flash(int n) { while (n-- > 0) { for (int i = 5, j = 6; i > 0; --i, ++j) { DDRB = direction[i]; PORTB = port[i]; _delay_ms(20); DDRB = direction[j]; PORTB = port[j]; _delay_ms(20); } } } void reset_buttons() { cli(); button0_pressed = 0; button1_pressed = 0; sei(); } int check_button(int i) { int pressed = 0; cli(); switch (i) { case 0: pressed = (button0_pressed != 0); button0_pressed = 0; break; case 1: pressed = (button1_pressed != 0); button1_pressed = 0; break; } sei(); return pressed; } void led(int i) { DDRB = direction[i]; PORTB = port[i]; } void setup(void) { DDRB = 0; PORTB = 0; DDRD = _BV(PD5); /* PD5 output (piezo) */ PORTD |= _BV(PD2); /* enable pull-up on PD2 - INT0 */ PORTD |= _BV(PD3); /* enable pull-up on PD3 - INT1 */ /* INT1 on falling edge */ MCUCR |= _BV(ISC11); MCUCR &= ~_BV(ISC10); /* INT0 on falling edge */ MCUCR |= _BV(ISC01); MCUCR &= ~_BV(ISC00); GIMSK |= (_BV(INT1) | _BV(INT0)); /* enable INT1, INT0 */ /* PWM */ TCCR0A |= (_BV(WGM01) | _BV(WGM00)); TCCR0B |= _BV(CS01); TCNT0 = 0; OCR0B = 50; sei(); } int mainloop(int start_player) { int i = 0; int inc = 1; int good = 1; int delay = 10; reset_buttons(); if (start_player == 0) { i = LED_MIN; inc = 1; } else { i = LED_MAX; inc = -1; } for (;;) { led(i); switch (delay) { case 10: _delay_ms(DELAY_MS_MOVE); break; case 9: _delay_ms(DELAY_MS_MOVE-20); break; case 8: _delay_ms(DELAY_MS_MOVE-40); break; case 7: _delay_ms(DELAY_MS_MOVE-60); break; case 6: _delay_ms(DELAY_MS_MOVE-80); break; case 5: _delay_ms(DELAY_MS_MOVE-100); break; case 4: _delay_ms(DELAY_MS_MOVE-120); break; case 3: _delay_ms(DELAY_MS_MOVE-140); break; case 2: _delay_ms(DELAY_MS_MOVE-160); break; case 1: _delay_ms(DELAY_MS_MOVE-180); break; default: _delay_ms(DELAY_MS_MOVE-200); } switch (i) { case LED_MIN: if ((good = (inc == 1 || check_button(1)))) { inc = 1; --delay; } break; case LED_MAX: if ((good = (inc == -1 || check_button(0)))) { inc = -1; --delay; } break; default: good = !(check_button(0) || check_button(1)); break; } if (!good) { /* who won? */ return inc == 1 ? PLAYER_0 : PLAYER_1; } i += inc; } } int main(void) { int start_player = 0; setup(); for (;;) { flash(3); start_player = mainloop(start_player); } return 0; }
C
//Ŀ //ʱ临ӶΪO(N) /** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ typedef struct TreeNode* STDataType; typedef struct Stack { STDataType* _a; int _top;//ջ int _capacity; }Stack; void StackInit(Stack* ps, int n) { assert(ps); ps->_a = (STDataType*)malloc(sizeof(STDataType)*n); ps->_top = 0; ps->_capacity = n; } void StackDestroy(Stack* ps) { assert(ps); free(ps->_a); ps->_a = NULL; ps->_top = ps->_capacity = 0; } void StackPush(Stack* ps, STDataType x)//ջ { assert(ps); if (ps->_top == ps->_capacity)// { ps->_a = (STDataType*)realloc(ps->_a, ps->_capacity * 2 * sizeof(STDataType)); ps->_capacity *= 2; } ps->_a[ps->_top] = x; ps->_top++; } void StackPop(Stack* ps)//ջ { assert(ps); if (ps->_top > 0) { ps->_top--; } } STDataType StackTop(Stack* ps)//ȡջ { assert(ps); return ps->_a[ps->_top - 1]; } int StackSize(Stack* ps)//ݸ { assert(ps); return ps->_top;//topʵеsize } int StackEmpty(Stack* ps) { assert(ps); if (ps->_top == 0) { return 0; } else { return 1; } } void Find(Stack* st, struct TreeNode* root, struct TreeNode* p) { if (root == NULL) return; struct TreeNode* cur = root; struct TreeNode* prev; while (cur != NULL || StackEmpty(st) != 0) { while (cur)//·ڵ { if (cur->val == p->val)//pcurֱӷغ { StackPush(st, cur); return; } else//·ڵ㣬p { StackPush(st, cur); cur = cur->left; } } //·ڵ struct TreeNode* top = StackTop(st); if (top->right == NULL || top->right == prev) { prev = top; StackPop(st); //cur= NULL; } else cur = top->right; } } struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) { Stack st_p; Stack st_q; StackInit(&st_p, 10); StackInit(&st_q, 10); if (root == NULL) return NULL; //p· Find(&st_p, root, p); //q· Find(&st_q, root, q); int sz1 = StackSize(&st_p); int sz2 = StackSize(&st_q); int gap = abs(sz1 - sz2); if (sz1<sz2) { while (gap--) { StackPop(&st_q); } } else { while (gap--) { StackPop(&st_p); } } //ͬʱpop if (sz1 == 0) return root; struct TreeNode* top; while (StackEmpty(&st_p) != 0 && StackEmpty(&st_q) != 0) { struct TreeNode* top1 = StackTop(&st_p); struct TreeNode* top2 = StackTop(&st_q); if (top1->val != top2->val) { StackPop(&st_p); StackPop(&st_q); } else { top = top1; break; } } return top; } //ʱ临ӶΪO(N2) /** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ bool FindNode(struct TreeNode* root, struct TreeNode* node) { if (root == NULL) return false; if (root == node) return true; return FindNode(root->left, node) || FindNode(root->right, node); } struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) { if (root == NULL) return NULL; if (root == p || root == q) return root; //ȷpqλ bool pLeft, pRight, qLeft, qRight; if (FindNode(root->left, p)) { pLeft = true; pRight = false; } else { pLeft = false; pRight = true; } if (FindNode(root->left, q)) { qLeft = true; qRight = false; } else { qLeft = false; qRight = true; } //pq if (pLeft&&qLeft) { return lowestCommonAncestor(root->left, p, q); } else if (pRight&&qRight) //pq { return lowestCommonAncestor(root->right, p, q); } else//pq { return root; } }
C
#include<stdio.h> int log(int n); int main(void){ int i,vezes; int n,x; scanf("%d", &vezes); for(i=0;i<vezes;i++) { scanf("%d",&n); printf("%d\n",log(n)); } return 0; } int log(int n){ static int i=0; int aux; if(n == 1) { aux = i; i = 0; return aux; } else i++; n = log(n/2); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "db.h" typedef struct treenode { char *key; char *value; struct treenode *left; struct treenode *right; } *TreeNode; void printIntro(void){ puts("Welcome to"); puts(" ____ ____ "); puts("/\\ _`\\ /\\ _`\\ "); puts("\\ \\ \\/\\ \\ \\ \\L\\ \\ "); puts(" \\ \\ \\ \\ \\ \\ _ <\\ "); puts(" \\ \\ \\_\\ \\ \\ \\L\\ \\ "); puts(" \\ \\____/\\ \\____/ "); puts(" \\/___/ \\/___/ "); puts(""); } void printOption(void){ puts("PLEASE CHOOSE AN OPERATION"); puts("1. Query a key"); puts("2. Update an entry"); puts("3. New entry"); puts("4. Remove entry"); puts("5. Print database"); puts("0. Exit database"); printf("? "); } void readline(char *dest, int n, FILE *source){ fgets(dest, n, source); int len = strlen(dest); if(dest[len-1] == '\n') dest[len-1] = '\0'; } void readFile(char *filename, TreeNode *pp_tree){ printf("Loading database \"%s\"...\n\n", filename); FILE *database = fopen(filename, "r"); char buffer[128]; char buffer2[128]; int found = -1; while(!feof(database)){ readline(buffer, 128, database); readline(buffer2, 128, database); insert(pp_tree, buffer, buffer2, &found); } fclose(database); } void insertValue(TreeNode *pp_tree){ char buffer[128]; char buffer2[128]; int found = -1; printf("Enter key: "); readline(buffer, 128, stdin); printf("Enter value: "); readline(buffer2, 128, stdin); puts("Searching database for duplicate keys..."); insert(pp_tree, buffer, buffer2,&found); if(found != 0){ puts("Entry inserted successfully:"); printf("key: %s\nvalue: %s\n", buffer, buffer2); } else { printf("key \"%s\" already exists!\n", buffer); } } void insert(TreeNode *pp_tree, char *insert_key, char *insert_value, int *p_found){ if (*pp_tree == NULL){ TreeNode p_temp = NULL; p_temp = malloc(sizeof(struct treenode)); p_temp->key = malloc(strlen(insert_key)+1); strcpy(p_temp->key, insert_key); p_temp->value = malloc(strlen(insert_value)+1); strcpy(p_temp->value, insert_value); p_temp->left = NULL; p_temp->right = NULL; *pp_tree = p_temp; return; } else if(strcmp(insert_key,(*pp_tree)->key) > 0){ // Right insert(&(*pp_tree)->right, insert_key, insert_value,p_found); } else if(strcmp(insert_key,(*pp_tree)->key) < 0) { // Left insert(&(*pp_tree)->left, insert_key, insert_value,p_found); } else if(strcmp(insert_key,(*pp_tree)->key) == 0) { *p_found = 0; } } TreeNode returnPre(TreeNode p_tree, char oldKey[]){ TreeNode temp = NULL; if(p_tree == NULL){ return NULL; } if(strcmp((p_tree)->key, oldKey) == 0){ return p_tree; } if(strcmp(oldKey,(p_tree)->key) < 0 && p_tree->left != NULL){ //left temp = (p_tree)->left; if(strcmp((temp)->key, oldKey) == 0){; return p_tree; } else return returnPre(temp, oldKey); } if(strcmp(oldKey,(p_tree)->key) > 0 && p_tree->right != NULL){ //right temp = (p_tree)->right; if(strcmp((temp)->key, oldKey) == 0){ return p_tree; } else return returnPre(temp, oldKey); } else return NULL; } TreeNode findRightNode(TreeNode p_tree){ while(p_tree->right != NULL){ p_tree = p_tree->right; } return p_tree; } TreeNode findNode(TreeNode p_tree, char buffer[],int *found){ while(strcmp(buffer, p_tree->key) != 0){ if (strcmp(buffer, (p_tree)->key) < 0 && p_tree->left != NULL){ //left p_tree = p_tree->left; } else if (strcmp(buffer, (p_tree)->key) > 0 && p_tree->right != NULL){ //right p_tree = p_tree->right; } else{ *found = 0; return NULL; } } return p_tree; } void hQuery(TreeNode *pp_tree){ char buffer[128]; int found = -1; printf("Enter key: "); readline(buffer, 128,stdin); char *newValue = query(pp_tree, buffer); if(strcmp(newValue,"NULL") != 0){ puts("Matching entry found:"); printf("key: %s\nvalue: %s\n\n", buffer, newValue); } else { printf("Sorry, could not find a matching key\n\n"); } free(newValue); } char *query(TreeNode *pp_tree, char buffer[]){ int found = -1; TreeNode temp = findNode(*pp_tree, buffer, &found); if(found != 0){ return temp->value; } else return "NULL"; } void hUpdate(TreeNode *pp_tree){ char buffer[128]; char buffer2[128]; printf("Enter key: "); readline(buffer, 128, stdin); printf("Enter new desired value: "); readline(buffer2, 128, stdin); printf("Searching for node...\n\n"); char *newValue = update(*pp_tree,buffer,buffer2); if(strcmp(newValue,"NULL") != 0){ printf("Found matching key\n"); printf("New value (%s) is inserted\n",newValue); } else { printf("Sorry, could not find a matching key\n\n"); } } char *update(TreeNode p_tree, char *buffer, char *buffer2){ int found = -1; TreeNode temp = findNode(p_tree, buffer, &found); if(found != 0){ free(temp->value); temp->value = malloc(strlen(buffer2)+1); strcpy(temp->value,buffer2); return temp->value; } else return "NULL"; } void printTree(TreeNode p_tree){ if(p_tree == NULL){ puts("\nThe tree is empty\n"); return; } printf("%s\n%s\n", p_tree->key, p_tree->value); if(p_tree->left != NULL) { printTree(p_tree->left);} if(p_tree->right != NULL) { printTree(p_tree->right);} return; } void hDelete(TreeNode *pp_tree){ char buffer[128]; printf("Please enter key: "); readline(buffer,128,stdin); printf("\nSearching for node...\n\n"); char *deletedKey = delete(pp_tree, buffer); if(strcmp(deletedKey,buffer) == 0){ printf("Successfully deleted key: %s\n", deletedKey); } else { puts("Sorry, could not find a matching key\n\n"); } free(deletedKey); } char *delete(TreeNode *pp_tree, char buffer[]){ int found = -1; TreeNode deletedNode = findNode(*pp_tree, buffer, &found); char *tempKey = malloc(128); if(deletedNode == NULL){ return "NULL"; } //Om rootnoden ska deletas if(strcmp(deletedNode->key,(*pp_tree)->key) == 0){ //Om det endast finns en nod i trdet if(deletedNode->left == NULL && deletedNode->right == NULL){ *pp_tree = NULL; strcpy(tempKey, deletedNode->key); free(deletedNode); return tempKey; } else if(deletedNode->left != NULL && deletedNode->right != NULL){ TreeNode rNode = deletedNode->right; TreeNode lNode = deletedNode->left; TreeNode temp = findRightNode(lNode); temp->right = rNode; *pp_tree = lNode; strcpy(tempKey, deletedNode->key); free(deletedNode); return tempKey; } //Om det endast finns en vnsternod till roten else if(deletedNode->left != NULL){ *pp_tree = deletedNode->left; strcpy(tempKey, deletedNode->key); free(deletedNode); return tempKey; } //Om det endast finns en hgernod till roten else if(deletedNode->right != NULL){ *pp_tree = deletedNode->right; strcpy(tempKey, deletedNode->key); free(deletedNode); return tempKey; } //Om det finns 2 noder till roten } //ej rotnod else { //Om noden som ska deletas inte har ngra barn if(deletedNode->left == NULL && deletedNode->right == NULL){ TreeNode preNode = returnPre(*pp_tree,buffer); if(strcmp(buffer,preNode->key) < 0){ //left preNode->left = NULL; strcpy(tempKey, deletedNode->key); free(deletedNode); return tempKey; } else{// right preNode->right = NULL; strcpy(tempKey, deletedNode->key); free(deletedNode); return tempKey; } } //Om noden som ska deletas har tv barn if(deletedNode->left != NULL && deletedNode->right !=NULL){ TreeNode rNode = deletedNode->right; TreeNode lNode = deletedNode->left; TreeNode preNode = returnPre(*pp_tree,buffer); TreeNode temp = findRightNode(lNode); if(strcmp(lNode->key,preNode->key) < 0){ //Left side temp->right = rNode; preNode->left = lNode; } else{ //Right side temp->right = rNode; preNode->right = lNode; } strcpy(tempKey, deletedNode->key); free(deletedNode); return tempKey; } //Om noden som ska deletas bara har ett vnsterbarn if(deletedNode->left != NULL){ TreeNode lNode = deletedNode->left; TreeNode preNode = returnPre(*pp_tree,buffer); preNode->left = lNode; strcpy(tempKey, deletedNode->key); free(deletedNode); return tempKey; } //Om noden som ska deletas bara har ett hgerbarn else if(deletedNode->right != NULL){ TreeNode rNode = deletedNode->right; TreeNode preNode = returnPre(*pp_tree,buffer); preNode->right = rNode; strcpy(tempKey, deletedNode->key); free(deletedNode); return tempKey; } } }