language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define HASHSIZE 3 struct nlist { struct nlist *next; char *name; char *defn; }; static struct nlist *hashtable[HASHSIZE]; unsigned hash(char *s); struct nlist *lookup(char *s); struct nlist *install(char *name, char *defn); void undef(char *name); void freex(struct nlist *np); /* * Write a function undef that will remove a name and definition from * the table maintained by lookup and install . */ int main(void) { install("Z", "z"); install("B", "b"); install("F", "f"); install("D", "d"); install("U", "u"); undef("F"); int i; struct nlist *cur; for (i = 0; i < HASHSIZE; i++) { cur = hashtable[i]; while (cur) { printf("name: %s, defn: %s\n", cur->name, cur->defn); cur = cur->next; } } return 0; } unsigned hash(char *s) { unsigned hashval; for (hashval = 0; *s != '\0'; s++) { hashval = *s + 31 * hashval; } return hashval % HASHSIZE; } struct nlist* lookup(char *s) { struct nlist *np; for (np = hashtable[hash(s)]; np != NULL; np = np->next) { if (strcmp(s, np->name) == 0) { return np; } } return NULL; } struct nlist *install(char *name, char *defn) { struct nlist *np; unsigned hashval; if ((np = lookup(name)) == NULL) { np = (struct nlist *)malloc(sizeof(*np)); np->name = (char *)malloc(sizeof(char) * strlen(name)); strcpy(np->name, name); hashval = hash(name); np->next = hashtable[hashval]; hashtable[hashval] = np; } else { free((void*)np->defn); } np->defn = (char *)malloc(sizeof(char) * strlen(defn)); strcpy(np->defn, defn); return np; } void undef(char *name) { struct nlist *np, *pre, *cur; unsigned hashval; if ((np = lookup(name))) { hashval = hash(name); cur = hashtable[hashval]; if (cur == np) { hashtable[hashval] = cur->next; freex(cur); return; } else { pre = cur; cur = cur->next; while (cur) { if (cur == np) { pre->next = cur->next; freex(cur); return; } pre = cur; cur = cur->next; } } } } void freex(struct nlist *np) { free((void *)np->name); free((void *)np->defn); free((void *)np); }
C
#include<stdio.h> #define ABC DEF #define GHI JKL #define MAIN(content) int main() { content } MAIN( /* a */ FILE*f=fopen("./Grace_kid.c", "w+"); char*a="#include<stdio.h>%c#define ABC DEF%c#define GHI JKL%c#define MAIN(content) int main() { content }%cMAIN(%c/*%c a%c*/%cFILE*f=fopen(%c./Grace_kid.c%c, %cw+%c);%cchar*a=%c%s%c;%cfprintf(f,a,10,10,10,10,10,10,10,10,34,34,34,34,10,34,a,34,10,10);)%c"; fprintf(f,a,10,10,10,10,10,10,10,10,34,34,34,34,10,34,a,34,10,10);)
C
// gdt.c // Written by Harry Rigg // Installs the GDT #include <kernel/init/gdt.h> // Installs a GDT entry void install_gdt(int32_t index, size_t base, size_t limit, uint8_t access, uint8_t gran) { gdt[index].base_low = (base & 0xFFFF); gdt[index].base_middle = (base >> 16) & 0xFF; gdt[index].base_high = (base >> 24) & 0xFF; gdt[index].limit_low = (limit & 0xFFFF); gdt[index].granularity = ((limit >> 16) & 0x0F); gdt[index].granularity |= (gran & 0xF0); gdt[index].access = access; } extern void place_gdt(); // Installs the GDT void gdt_init() { g_pointer.limit = (sizeof(struct gdt_entry) * 3) -1; g_pointer.base = &gdt; install_gdt(0,0,0,0,0); install_gdt(1, 0, 0xFFFFFFFF, 0x9A, 0xCF); install_gdt(2, 0, 0xFFFFFFFF, 0x92, 0xCF); place_gdt(); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include "my_library.h" #include "song_library.h" #define print_section(section) do{printf("\n\n================ " section " ================\n");}while(0) int main(void) { struct my_library* library = library_create(); int i; for(i = 0; i < MUSIC_LIBRARY_SIZE; ++i) { const char* artist = MUSIC_LIBRARY[i].artist; const char* title = MUSIC_LIBRARY[i].title; library_add(library, song_create(artist, title)); } print_section("Library"); printf("Print Out Entire Library:\n"); library_print(library); print_section("J Section Manipulation"); printf("\nPrint Out J Category:\n"); category_print(library_get_category(library, 'J')); printf("\n\nRemoving Songs With Artist \"Juice WRLD\"...\n"); library_remove(library, "Juice WRLD", NULL); printf("\nPrint Out J Category:\n"); category_print(library_get_category(library, 'J')); print_section("Kendrick Lamar"); printf("\nPrinting Songs with Artist \"Kendrick Lamar\":\n"); library_print_match(library, "Kendrick Lamar", NULL); printf("\nRemoving Songs With Title \"Alright\"...\n"); library_remove(library, NULL, "Alright"); printf("Removing Songs With Title \"DNA.\"...\n"); library_remove(library, NULL, "DNA."); printf("Removing Songs With Title \"King Kunta\"...\n"); library_remove(library, NULL, "King Kunta"); printf("\nPrinting Songs with Artist \"Kendrick Lamar\":\n"); library_print_match(library, "Kendrick Lamar", NULL); print_section("Random Songs"); srand(time(0)); printf("Printing 10 Random Songs:\n"); for(i = 0; i < 10; ++i) { printf("\t%d) ", i); song_print(library_get_song_rand(library)); printf("\n"); } print_section("Random T Section"); printf("Printing 10 Random Songs from T Section:\n"); for(i = 0; i < 10; ++i) { printf("\t%d) ", i); song_print(category_get_rand(library_get_category(library, 'T'))); printf("\n"); } print_section("Random Ski Mask The Slump God Songs"); printf("Printing 10 Random Songs with Artist \"Ski Mask The Slump God\":\n"); for(i = 0; i < 10; ++i) { printf("\t%d) ", i); song_print(library_get_song_rand_match(library, "Ski Mask The Slump God", NULL)); printf("\n"); } print_section("We are done here"); printf("Clearing Library...\n\n"); library_clear(library); printf("Print Out Entire Library:\n"); library_print(library); printf("\nFreeing Library...\n"); library_free(library); }
C
#include <stdlib.h> #include "parser/stmt.h" #include "test.h" void test_new_stmt() { expr_t expr; stmt_t *subject = new_stmt(&expr); assert(subject->data == &expr); assert(subject->type == EXPR); } void test_new_stmt_list() { stmt_t *stmt = new_stmt(NULL); stmt_list_t *subject = new_stmt_list(stmt); assert(subject != NULL); assert(subject->capacity > 0); assert(subject->size = 1); assert(subject->stmt_array != NULL); stmt_t *stmt2 = new_stmt(NULL); stmt_list_t* list2 = append_stmt_list(subject, stmt2); assert(list2 == subject); assert(subject->size = 2); assert(subject->capacity >= subject->size); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/wait.h> int n; void collatz(int n) { while(n != 1){ printf("%d ", n); if(n % 2 == 1) n = 3 * n + 1; else n = n / 2; } printf("%d\n", 1); } int main() { int i; printf("How many numbers do you want to process?"); scanf("%d", &n); int *v = malloc(sizeof(int) * n); for(i = 0; i < n; ++i) { scanf("%d", &v[i]); } printf("Starting Parent %d\n", getpid()); for(i = 0; i < n; ++i){ pid_t pid = fork(); if(pid < 0) perror("error"); if(pid == 0){ collatz(v[i]); printf("Done Parent %d Me %d\n", getppid(), getpid()); exit(0); } } for(i = 0; i < n; i++) wait(NULL); printf("Done Parent %d Me %d\n", getppid(), getpid()); return 0; }
C
/* * File: main.c * Author: Felipe Costa */ /*Cap4, ex15, proposto*/ #include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { int menu; float vlrInv, rend, vlrFinal; printf("\n\t TIPO DESCRIÇÃO RENDIMENTO MENSAL"); printf("\n\t 1 Poupança 3%%"); printf("\n\t 2 Fundos de renda fixa 4%%\n"); printf("\nQual tipo de investimento pretende fazer: "); scanf("%d*c", &menu); printf("\nQual o valor que sera investido: R$"); scanf("%d*c", &vlrInv); if (menu == 1) { rend = 0.03; } else if (menu == 2) { rend = 0.04; } else { printf("\n\t*Opção Invalida*"); } vlrFinal = vlrInv + (vlrInv * rend); printf("\n\tApos 1 mes tera a quantia de R$%.2f", vlrFinal); return (EXIT_SUCCESS); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define A 3 int main() { /* sAlumno miAlumno = {4545,"Gigliotti",3} ; printf("%d %s %0.2f",miAlumno.legajo,miAlumno.nombre,miAlumno.promedio) ; return 0; ------------ Asi para mostrar yo el dato que introduzco ------------- */ /* sAlumno miAlumno ; printf("Ingrese legajo: ") ; fflush(stdin) ; scanf("%d", &miAlumno.legajo) ; printf("Ingrese el nombre alumno: ") ; fflush(stdin) ; gets(miAlumno.nombre) ; printf("Ingrese edad") ; fflush(stdin) ; scanf("%d",&miAlumno.edad) ; printf("Ingrese promedio: ") ; fflush(stdin) ; scanf("%f", &miAlumno.promedio) ; system("cls") ; printf("Legajo Nombre Edad Promedio\n") ; mostrarUnalumno(miAlumno) ; asi muestra con funcion mi alumno */ /* sAlumno listadoMain[A] ; for(int i=0; i<A; i++) { printf("Ingrese legajo: "); scanf("%d",&listadoMain[i].legajo) ; printf("Ingrese el nombre alumno: ") ; fflush(stdin) ; gets(listadoMain[i].nombre) ; printf("Ingrese edad") ; fflush(stdin) ; scanf("%d",&listadoMain[i].edad) ; printf("Ingrese promedio: ") ; fflush(stdin) ; scanf("%f", &listadoMain[i].promedio) ; } printf("Legajo Nombre Edad Promedio\n") ; for(int i=0; i<A; i++) { mostrarUnalumno(listadoMain[i]); acceder a elemento del arrays para ir mostrando varios alumnos */ }
C
#include <stdio.h> int numZeroes(int input); int main(void){ int num_tests,N; scanf("%d",&num_tests); for(int i=0;i<num_tests;i++){ scanf("%d",&N); printf("%d\n",numZeroes(N)); } return 0; } int numZeroes(int input){ int zeroes = 0; while(input){ zeroes+= input/5; input/=5; } return zeroes; }
C
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> int main() { char gender; int f, l; int out; int temp1,temp2,temp3,temp4; int c1,c2,c3,c4; scanf("%c %d %d", &gender, &f, &l); //남녀 / f 와 l> //////////////////////////////////////// if(gender == 'M'){ temp1 = (2 - f); if(temp1 < 0) temp1 = -(temp1); c1 = (0 - l); if(c1 < 0) c1 = -(c1); temp1 = c1 + temp1; temp2 = (4 - f); if(temp2 < 0) temp2 = -(temp2); c2 = (0 - l); if(c2 < 0) c2 = -(c2); temp2 = c2 + temp2; temp3 = (1 - f); if(temp3 < 0) temp3 = -(temp3); c3 = (6 - l); if(c3 < 0) c3 = -(c3); temp3 = c3 + temp3; temp4 = (3 - f); if(temp4 < 0) temp4 = -(temp4); c4 = (6 - l); if(c4 < 0) c4 = -(c4); temp4 = c4 + temp4; } else if(gender == 'W'){ temp1 = (1 - f); if(temp1 < 0) temp1 = -(temp1); c1 = (0 - l); if(c1 < 0) c1 = -(c1); temp1 = c1 + temp1; temp2 = (3 - f); if(temp2 < 0) temp2 = -(temp2); c2 = (0 - l); if(c2 < 0) c2 = -(c2); temp2 = c2 + temp2; temp3 = (2 - f); if(temp3 < 0) temp3 = -(temp3); c3 = (6 - l); if(c3 < 0) c3 = -(c3); temp3 = c3 + temp3; temp4 = (4 - f); if(temp4 < 0) temp4 = -(temp4); c4 = (6 - l); if(c4 < 0) c4 = -(c4); temp4 = c4 + temp4; } if(temp1 <= temp2){ if(temp1 <= temp3){ if(temp1 <= temp4){ out = temp1; } else{ out = temp4; } } else if(temp3 <= temp4){ out = temp3; } else{ out = temp4; } } else if(temp2 <= temp3){ if(temp2 <= temp4){ out = temp2; } else{ out = temp4; } } else if (temp3 <= temp4){ out = temp3; } else{ out = temp4; } //////////////////////////////////////// printf("%d\n", out); return 0; }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<stdio_ext.h> #define max_length 30 #define max_base 20 typedef struct sudents { char *surname, *name, *patronymic; union { struct { char *father, *mother, *brother; } family1; struct { char *father, *mother, *brother, *sister; } family2; struct { char *mother, *brother, *sister; } family3; } choicefamily; } student_t; void check_help(int, char**); int init_array(int, char **, student_t *); void init_additional(int , char **, student_t *); void stud_output(int, student_t*, char **); char* check_string(char*); int atoi_change(); int main(int argc, char **argv) { int array_size, arg1; student_t *stud; check_help(argc, argv); if(!strcmp(argv[1], "1") || !strcmp(argv[1], "2")) { stud = (student_t*)malloc(max_base*sizeof(student_t)); if(!strcmp(argv[1], "1")) { arg1 = 0; } else { arg1 = 1; if(!(!strcmp(argv[2], "1") || !strcmp(argv[2], "2") || !strcmp(argv[2], "3"))) { puts("Input command-line data is wrong. Re-run program according to next rules:\n \''-h\'' (means help), \''1\'' or \''2\'' - for first argument\n \''1\'', \''2\'' or \''3\'' - for second argument\n"); return 0; } } array_size = init_array(arg1, argv, stud); stud_output(array_size, stud, argv); free(stud); } else puts("Input command-line data is wrong. Re-run program according to next rules:\n \''-h\'' (means help), \''1\'' or \''2\'' - for first argument\n \''1\'', \''2\'' or \''3\'' - for second argument\n"); return 0; } int init_array(int arg1, char **argv, student_t* stud_array) { int n=0, identifier; do { stud_array[n].surname = check_string("Enter a student's surname: "); stud_array[n].name = check_string("Enter a student's name: "); stud_array[n].patronymic = check_string("Enter a student's patronymic: "); if(arg1) { init_additional(n, argv, stud_array); } n++; identifier = 0; puts("Want to continue?"); identifier = atoi_change(); if(!identifier) return n; } while(n<max_base); return n; } void init_additional(int n, char **argv, student_t* stud_array) { if(!strcmp(argv[2], "1")) { stud_array[n].choicefamily.family1.brother = check_string("Enter brother's name: "); stud_array[n].choicefamily.family1.father = check_string("Enter father's name: "); stud_array[n].choicefamily.family1.mother = check_string("Enter mother's name: "); } else if(!strcmp(argv[2], "2")) { stud_array[n].choicefamily.family2.brother = check_string("Enter brother's name: "); stud_array[n].choicefamily.family2.sister = check_string("Enter sister's name: "); stud_array[n].choicefamily.family2.father = check_string("Enter father's name: "); stud_array[n].choicefamily.family2.mother = check_string("Enter mother's name: "); } else { stud_array[n].choicefamily.family3.brother = check_string("Enter brother's name: "); stud_array[n].choicefamily.family3.sister = check_string("Enter sister's name: "); stud_array[n].choicefamily.family3.mother = check_string("Enter mother's name: "); } } void stud_output(int array_size, student_t* stud_array, char **argv) { int n; puts("There is the list of students, according to input data:\n"); do { if(!strcmp(argv[1], "2")) { if(!strcmp(argv[2], "1")) { printf("#%d - %s %s %s. Father - %s. Mother - %s. Brother - %s\n", n, stud_array[n].surname, stud_array[n].name, stud_array[n].patronymic, stud_array[n].choicefamily.family1.father, stud_array[n].choicefamily.family1.mother, stud_array[n].choicefamily.family1.brother); } else if(!strcmp(argv[2], "2")) { printf("#%d - %s %s %s. Father - %s. Mother - %s. Brother - %s. Sister - %s\n", n, stud_array[n].surname, stud_array[n].name, stud_array[n].patronymic, stud_array[n].choicefamily.family2.father, stud_array[n].choicefamily.family2.mother, stud_array[n].choicefamily.family2.brother, stud_array[n].choicefamily.family2.sister); } else { printf("#%d - %s %s %s. Mother - %s. Brother - %s. Sister - %s\n", n, stud_array[n].surname, stud_array[n].name, stud_array[n].patronymic, stud_array[n].choicefamily.family3.mother, stud_array[n].choicefamily.family3.brother, stud_array[n].choicefamily.family3.sister); } } else printf("#%d - %s %s %s\n", n, stud_array[n].surname, stud_array[n].name, stud_array[n].patronymic); n++; } while (n< array_size); } void check_help(int argc, char** argv) { if(!strcmp(argv[1], "-h")) { puts("\n=============================================\n" "Manual\n\n" "1) Send the way of data output by command line\n" "2) A: Enter an information about students:\n" "- surname\n" "- name\n" "- patronymic\n" "B: Whether how it's asked to output the family members, the next data needs to be entered:\n" "- father\n" "- mother\n" "- brother\n" "- sister\n" "3) Output data in an interested way\n\n" "=================================================\n"); exit(0); } } int atoi_change() { int identifier; char string[128]; while(1) { printf("(yes - 1/no - 0) "); fgets(string, 128, stdin); identifier = atoi(string); if(identifier == 1 || identifier == 0) { break; } puts("It's not correct. Please, input data again."); } return identifier; } char* check_string(char* comment) { char *text; text = (char*)malloc(max_length*sizeof(char)); do { printf("%s", comment); __fpurge(stdin); gets(text); if(text[0] == '\n') { continue; } } while (0); return text; }
C
/** ****************************************************************************** * ļ: bsp_rtc.c * : * : V1.0 * д: 2017-03-30 * : RTCʵʱʱ ****************************************************************************** */ /* ͷļ ----------------------------------------------------------------*/ #include "rtc/bsp_rtc.h" #include "usart/bsp_debug_usart.h" /* ˽Ͷ --------------------------------------------------------------*/ /* ˽к궨 ----------------------------------------------------------------*/ /* ˽б ------------------------------------------------------------------*/ //ʱ RTC_HandleTypeDef hrtc; /* չ ------------------------------------------------------------------*/ /* ˽кԭ --------------------------------------------------------------*/ /* --------------------------------------------------------------------*/ /** * : ASCIIתΪ,ַתʮ * : value ûڳնֵ * ֵ: ַASCIIӦֵ * ˵ רRTCȡʱ */ int StringToArray(char *str, unsigned char *out) { char *p = str; char high = 0, low = 0; int tmplen = strlen(p); int cnt = 0; tmplen = strlen(p); if(tmplen % 2 != 0) return -1; while(cnt < tmplen / 2) { high = ((*p > '9') && ((*p <= 'F') || (*p <= 'f'))) ? *p - 48 - 7 : *p - 48; low = (*(++ p) > '9' && ((*p <= 'F') || (*p <= 'f'))) ? *(p) - 48 - 7 : *(p) - 48; out[cnt] = ((high & 0x0f) << 4 | (low & 0x0f)); p++; cnt ++; } return tmplen / 2; } /** * : õǰʱ * : * ֵ: * ˵ : */ void RTC_CalendarConfig(char *time) { RTC_TimeTypeDef sTime; RTC_DateTypeDef DateToUpdate; int outlen = 0; unsigned char out[10] = {0}; outlen = StringToArray(time, out); Show_Data(out,7); if(outlen != 7) { printf("RTC_CalendarConfig:ʱ,ֶΪ%dطʱ\n",outlen); HAL_UART_Transmit(&husart_debug,"+",1,1000); return; } /* */ /* ڣ20181128 ڶ*/ if(out[0] < 0x18 || out[0] > 0x40) { printf("RTC_CalendarConfig:ݴ%02xط\n",out[0]); HAL_UART_Transmit(&husart_debug,"+",1,1000); return; } if(out[1] > 0x12) { printf("RTC_CalendarConfig:·ݴ%02xط\n",out[1]); HAL_UART_Transmit(&husart_debug,"+",1,1000); return; } if(out[2] > 0x31) { printf("RTC_CalendarConfig:ڴ%02xط\n",out[2]); HAL_UART_Transmit(&husart_debug,"+",1,1000); return; } if(out[3] > 0x07) { printf("RTC_CalendarConfig:ڴ%02xط\n",out[3]); HAL_UART_Transmit(&husart_debug,"+",1,1000); return; } if(out[4] > 0x24) { printf("RTC_CalendarConfig:Сʱ%02xط\n",out[4]); HAL_UART_Transmit(&husart_debug,"+",1,1000); return; } if(out[5] > 0x60) { printf("RTC_CalendarConfig:÷Ӵ%02xط\n",out[5]); HAL_UART_Transmit(&husart_debug,"+",1,1000); return; } if(out[6] > 0x60) { printf("RTC_CalendarConfig:%02xط\n",out[6]); HAL_UART_Transmit(&husart_debug,"+",1,1000); return; } /* ʱ */ /* ʱʱ䣺10:15:46 */ sTime.Hours = out[4]; sTime.Minutes = out[5]; sTime.Seconds = out[6]; DateToUpdate.Year = out[0]; DateToUpdate.Month = out[1]; DateToUpdate.Date = out[2]; DateToUpdate.WeekDay = out[3]; HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BCD); HAL_RTC_SetDate(&hrtc,&DateToUpdate,RTC_FORMAT_BCD); /* дһֵ0x32F1RTCݼĴ1 */ HAL_RTCEx_BKUPWrite(&hrtc, RTC_BKP_DR1, 0x32F1); } /** * : RTCʵʱʱӳʼ * : * ֵ: * ˵ : */ void MX_RTC_Init(void) { /* ʼRTCʵʱʱӲʱ */ hrtc.Instance = RTC; hrtc.Init.HourFormat = RTC_HOURFORMAT_24; //24Сʱ hrtc.Init.AsynchPrediv = 127; //첽 hrtc.Init.SynchPrediv = 255; //ͬ hrtc.Init.OutPut = RTC_OUTPUT_DISABLE; //ʹRTC_ALARMı־ hrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH; //RTC_ALARMΪ hrtc.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN; //RTC_ALARMΪ© HAL_RTC_Init(&hrtc); //char *strCom = "18121704121700"; /* Ƿ񱣴RTCݼĴ1ѾͲҪںʱ */ /* ȡݼĴ1 */ if (HAL_RTCEx_BKUPRead(&hrtc, RTC_BKP_DR1) != 0x32F1) { /* RTCʱ */ // RTC_CalendarConfig(strCom); } else { /* ϵ縴λ־λǷΪSET */ if (__HAL_RCC_GET_FLAG(RCC_FLAG_PORRST) != RESET) { printf("ϵ縴λ\n"); } /* Ÿλ־λǷΪSET */ if (__HAL_RCC_GET_FLAG(RCC_FLAG_PINRST) != RESET) { printf("ⲿŸλ\n"); } /* λԴ־λ */ __HAL_RCC_CLEAR_RESET_FLAGS(); } } /** * : RTCʵʱʱӳʼ * : hrtcRTCָ * ֵ: * ˵ : úHALڲ */ void HAL_RTC_MspInit(RTC_HandleTypeDef* hrtc) { RCC_OscInitTypeDef RCC_OscInitStruct; RCC_PeriphCLKInitTypeDef PeriphClkInitStruct; if(hrtc->Instance==RTC) { /* To change the source clock of the RTC feature (LSE, LSI), You have to: - Enable the power clock using __HAL_RCC_PWR_CLK_ENABLE() - Enable write access using HAL_PWR_EnableBkUpAccess() function before to configure the RTC clock source (to be done once after reset). - Reset the Back up Domain using __HAL_RCC_BACKUPRESET_FORCE() and __HAL_RCC_BACKUPRESET_RELEASE(). - Configure the needed RTc clock source */ HAL_PWR_EnableBkUpAccess(); /* ʹܱʱӣݼĴ */ // __HAL_RCC_BKP_CLK_ENABLE(); /* ⲿʱΪRTCʱԴ */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; RCC_OscInitStruct.LSEState = RCC_LSE_ON; //RTCʹLSE HAL_RCC_OscConfig(&RCC_OscInitStruct); PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC; //ΪRTC PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSE; //RTCʱԴΪLSE HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct); /* ʹRTCʱ */ __HAL_RCC_RTC_ENABLE(); } } /** * : RTCʵʱʱӷʼ * : hrtcRTCָ * ֵ: * ˵ : úHALڲ */ void HAL_RTC_MspDeInit(RTC_HandleTypeDef* hrtc) { if(hrtc->Instance==RTC) { /* RTCʱ */ __HAL_RCC_RTC_DISABLE(); /* PWRʱӺͶȡ */ HAL_PWR_DisableBkUpAccess(); __HAL_RCC_PWR_CLK_DISABLE(); /* ñʱӣݼĴ */ //__HAL_RCC_BKP_CLK_DISABLE(); } }
C
#include "../../../test_common.h" #include <semaphore.h> #include <fcntl.h> void runSuccess() { char buf[] = "name"; //@ assert \valid(buf+(0..\block_length(buf)-1)); //@ assert \exists integer x; buf[x] == '\0'; sem_open(buf, O_CREAT); } void runSuccess1() { char buf[] = "name"; //@ assert \valid(buf+(0..\block_length(buf)-1)); //@ assert \exists integer x; buf[x] == '\0'; sem_open(buf, O_EXCL); } void runSuccess2() { char buf[] = "name"; //@ assert \valid(buf+(0..\block_length(buf)-1)); //@ assert \exists integer x; buf[x] == '\0'; sem_open(buf, O_EXCL | O_CREAT); } void runFailure() { sem_open(NULL, O_EXCL | O_CREAT); } int f; void testValues() { f = 2; sem_t* result; char buf[] = "name"; //@ assert \valid(buf+(0..\block_length(buf)-1)); //@ assert \exists integer x; buf[x] == '\0'; result = sem_open(buf, O_EXCL | O_CREAT); //@ assert result == SEM_FAILED || \valid(result); //@ assert f == 2; //@ assert vacuous: \false; }
C
/* HELLO.C -- Hello, world */ #include "stdio.h" #include "stdlib.h" #include "conio.h" #define MAXSIZE 10 typedef struct {int data[MAXSIZE]; int top; }SeqStack; SeqStack *Init_SeqStack() /*ÿջ*/ { SeqStack *s; s=malloc(sizeof(SeqStack)); s->top=0; return s; } int Empty_SeqStack(SeqStack *s) /*пջ*/ { if (s->top==0) return 1; else return 0; } int Push_SeqStack (SeqStack *s, int x) /* ջ*/ { if (s->top==MAXSIZE) return 0; /*ջջ*/ s->data[s->top]=x; s->top++; return 1; } int Pop_SeqStack(SeqStack *s, int *x) { if (Empty_SeqStack ( s ) ) return 0; /*ջղܳջ */ else { s->top--; *x=s->data[s->top-1]; return 1; } /*ջԪش*x*/ } int Top_SeqStack(SeqStack *s) { if ( Empty_SeqStack ( s )) return 0; /*ջ*/ else return (s->data[s->top]); } main() { SeqStack *ss; int select,i; int y,*z; ss=Init_SeqStack(); printf("\n(1)Input a stack data"); printf("\n(2)Onput a stack data"); printf("\n(3)Exit"); printf("\nPlease select one=>"); scanf("%d",&select); do { switch(select) { case 1:printf("\nPlease input the data=>"); scanf("%d",&y); Push_SeqStack(ss,y); printf("\nthe content:"); for(i=0;i<ss->top;i++) printf("%d ",ss->data[i]); break; case 2:Pop_SeqStack(ss,z); printf("the elements are:\n "); for(i=0;i<ss->top;i++) printf("%d ",ss->data[i]); break; } printf("\n(1)Input a stack data"); printf("\n(2)Onput a stack data"); printf("\n(3)Exit"); printf("\nPlease select one=>"); scanf("%d",&select); printf("\n"); } while(select!=3); }
C
#include <stdio.h> int recur(int n){ if(n>0){ // printf("%d\n", n); return n+recur(n-1); }else{ return 0; } } int hi(int n){ if (n<=0) { printf("BYE\n"); return 0; } else{ printf("HI!!!\n"); return hi(n-1); } } int main(){ //Number example int s=recur(5); printf("%d\n", s); // hi(5); return 0; }
C
#include <stdio.h> int NextPrime(int x); int main () { int Input; int Prime; int Remainder; scanf("%d", &Input); printf("%d=",Input); for (Prime=2;Input!=1;) { if ( Input%Prime==0) { Input = Input / Prime ; if (Input !=1) printf("%dx",Prime); else printf("%d",Prime); } else { Prime=NextPrime(Prime) ; } } return 0; } int NextPrime(int x) { int count=1; int i; int exit=0; for(x=x+1;count==1;x++) { int isPrime=1; for (i=2; i<x; i++) { if(x%i == 0) { isPrime = 0; break; } } if(isPrime ==1) { count++; break; } } return x; }
C
#include <stdio.h> int main(void) { char str[32]; printf("Enter a text to the field ---> "); gets(str); printf("Your text is ---> %s \n", str); return 0; }
C
#include <stdio.h> #include<math.h> #include "calculator_operations.h" #define INT_MAX __INT_MAX__ const double PI=3.141592; error_t add(arithmatic* data) { data->output=data->operand1+data->operand2; return SUCCESS; } error_t subtract(arithmatic* data) { data->output=data->operand1-data->operand2; return SUCCESS; } error_t multiply(arithmatic* data) { data->output=data->operand1*data->operand2; return SUCCESS; } error_t divide(arithmatic* data) { if(0 == data->operand2){ data->output=0; return ERROR_DIVISION_BY_ZERO; } else{ data->output=data->operand1/data->operand2; return SUCCESS; } } error_t sine(trignometric* data){ data->output=sin(data->operand*(PI/180)); return SUCCESS; } error_t Cos(trignometric* data){ data->output=cos(data->operand*(PI/180)); return SUCCESS; } error_t Tan(trignometric* data){ if(((int)(data->operand)/90)%2==1){ data->output=INT_MAX*1.0; return UNDEFINED; }else{ data->output=tan(data->operand*(PI/180)); return SUCCESS; } } error_t Cot(trignometric* data){ if(tan(data->operand*(PI/180))==0){ data->output=INT_MAX*1.0; return UNDEFINED; } else if(((int)(data->operand)/90)%2==1){ data->output=0; return SUCCESS; }else{ data->output=1/(tan(data->operand*(PI/180))); return SUCCESS; } } error_t Sec(trignometric* data){ if(cos(data->operand*(PI/180))==0){ data->output=INT_MAX*1.0; return UNDEFINED; } else{ data->output=1/(cos(data->operand*(PI/180))); return SUCCESS; } } error_t Cosec(trignometric* data){ if(sin(data->operand*(PI/180))==0){ data->output=INT_MAX*1.0; return UNDEFINED; } else{ data->output=1/(sin(data->operand*(PI/180))); return SUCCESS; } } error_t Exponent(single_double_inputs* data){ data->output=exp(data->operand); return SUCCESS; } error_t Natural_log(single_double_inputs* data){ if(data->operand<0){ data->output=0; return UNDEFINED; }else{ data->output=log(data->operand); return SUCCESS; } } error_t base_10_log(single_double_inputs* data){ if(data->operand<0){ data->output=0; return UNDEFINED; }else{ data->output=log10(data->operand); return SUCCESS; } } error_t square_root(single_double_inputs* data){ if(data->operand<0){ data->output=0; return UNDEFINED; }else{ data->output=sqrt(data->operand); return SUCCESS; } } error_t nth_root(arithmatic* data){ if((int)(data->operand2)%2==0 && data->operand1<0){ data->output=0; return UNDEFINED; } data->output=pow(data->operand1,(1/data->operand2)) ; return SUCCESS; } error_t square(single_double_inputs* data){ data->output=pow(data->operand,2.0); return SUCCESS; } error_t nth_power(arithmatic* data){ data->output=pow(data->operand1,data->operand2); return SUCCESS; } error_t xth_power_of_10(single_double_inputs* data){ data->output=pow(10,data->operand); return SUCCESS; } error_t factorial(single_int_inputs* data){ if(data->operand<0){ data->output=0; return UNDEFINED; }else{ data->output=1; unsigned int temp_var=data->operand; while(temp_var>0){ data->output=data->output*temp_var; temp_var--; } return SUCCESS; } }
C
#include <stdio.h> #include <stdlib.h> #include "cmd_line.h" #include "geometry.h" #include "postscript.h" #include "matrix.h" #include "xpm.h" //Compile and run with: //gcc *.c -o CG_hw1 -lm && ./CG_hw1 //PS file cmd line arg extern char * ps_file; extern float scale; extern int rotation_cc; extern int trans_x; extern int trans_y; extern int lower_bound_x; extern int lower_bound_y; extern int upper_bound_x; extern int upper_bound_y; int main(int argc, char** argv) { //Parse commandline into globals do_cmd_line_parse(argc,argv); //Parse the PS file into line structs int num_lines = 0; struct Line * lines = ps_parse_to_lines(ps_file,&num_lines); //Do transforms on these line structs //Objects of your scene are scaled, then rotated //and finally translated in the world coordinates. lines = transform_lines(lines, num_lines, scale, rotation_cc, trans_x, trans_y); //Clip lines to window lines = clip_lines_to_window(lines, &num_lines, lower_bound_x, lower_bound_y,upper_bound_x,upper_bound_y); //Convert lines into list of points int num_points = 0; struct Point * points = lines_to_points(lines, num_lines, &num_points); //Allocate a blank 2d matrix to serve as the pixel map //Pixel map is sizes according to view window //Columns = X size, Rows = Y size struct Matrix2D pixel_map = new_matrix( upper_bound_x-lower_bound_x+1, upper_bound_y-lower_bound_y+1); //Write list of pixels in world coords into this pixel map //Deals with origin location pixel_map = write_points_to_pixel_map(points, num_points, pixel_map, lower_bound_x, upper_bound_y); //Pass pixel map in xpm write do_xpm_write(pixel_map); //Done return 0; }
C
//Created by Shamit Mani //Created on 16/04/2017 #include <stdio.h> void get_bounding_box(int height, int width, int pixels[height][width], int *start_row, int *start_column, int *box_height, int *box_width) { int i, j; int box_width_count[width], box_height_count[height]; *box_height = 0; *box_width = 0; for(i = 0; i < height; i++) { for(j = 0; j < width; j++) { if(pixels[i][j] == 1) { box_height_count[i] = 1; } } } for(j = 0; j < width; j++) { for(i = 0; i < height; i++) { if(pixels[i][j] == 1) { box_width_count[j] = 1; } } } for(i = 0; i < height; i++) { if(box_height_count[i] == 1) { *box_height = *box_height + box_height_count[i]; } } for(j = 0; j < width; j++) { if(box_width_count[j] == 1) { *box_width = *box_width + box_width_count[j]; } } for(i = 0; i < height; i++) { for(j = 0; j < width; j++) { if(pixels[i][j] == 1){ break; } } if(pixels[i][j] == 1){ break; } } *start_row = i; for(j = 0; j < width; j++) { for(i = 0; i < height; i++) { if(pixels[i][j] == 1){ break; } } if(pixels[i][j] == 1){ break; } } *start_column = j; }
C
/* * Copyright 2022 NXP * * SPDX-License-Identifier: Apache-2.0 */ #include <zephyr/device.h> #include <zephyr/drivers/disk.h> #include <zephyr/sd/mmc.h> #include <zephyr/kernel.h> #include <zephyr/ztest.h> #define SECTOR_COUNT 32 #define SECTOR_SIZE 512 /* subsystem should set all cards to 512 byte blocks */ #define BUF_SIZE (SECTOR_SIZE * SECTOR_COUNT) static const struct device *const sdhc_dev = DEVICE_DT_GET(DT_ALIAS(sdhc0)); static struct sd_card card; static uint8_t buf[BUF_SIZE] __aligned(CONFIG_SDHC_BUFFER_ALIGNMENT); static uint8_t check_buf[BUF_SIZE] __aligned(CONFIG_SDHC_BUFFER_ALIGNMENT); static uint32_t sector_size; static uint32_t sector_count; #define MMC_UNALIGN_OFFSET 1 /* * Verify that SD stack can initialize an MMC card * This test must run first, to ensure the card is initialized. */ ZTEST(sd_stack, test_0_init) { int ret; zassert_true(device_is_ready(sdhc_dev), "SDHC device is not ready"); ret = sd_init(sdhc_dev, &card); zassert_equal(ret, 0, "Card initialization failed"); } /* Verify that MMC stack returns valid IOCTL values */ ZTEST(sd_stack, test_ioctl) { int ret; ret = mmc_ioctl(&card, DISK_IOCTL_GET_SECTOR_COUNT, &sector_count); zassert_equal(ret, 0, "IOCTL sector count read failed"); TC_PRINT("SD card reports sector count of %d\n", sector_count); ret = mmc_ioctl(&card, DISK_IOCTL_GET_SECTOR_SIZE, &sector_size); zassert_equal(ret, 0, "IOCTL sector size read failed"); TC_PRINT("SD card reports sector size of %d\n", sector_size); } /* Verify that SD stack can read from an SD card */ ZTEST(sd_stack, test_read) { int ret; int block_addr = 0; /* Try simple reads from start of SD card */ ret = mmc_read_blocks(&card, buf, block_addr, 1); zassert_equal(ret, 0, "Single block card read failed"); ret = mmc_read_blocks(&card, buf, block_addr, SECTOR_COUNT / 2); zassert_equal(ret, 0, "Multiple block card read failed"); /* Try a series of reads from the same block */ block_addr = sector_count / 2; for (int i = 0; i < 10; i++) { ret = mmc_read_blocks(&card, buf, block_addr, SECTOR_COUNT); zassert_equal(ret, 0, "Multiple reads from same addr failed"); } /* Verify that out of bounds read fails */ block_addr = sector_count; ret = mmc_read_blocks(&card, buf, block_addr, 1); zassert_not_equal(ret, 0, "Out of bounds read should fail"); block_addr = sector_count - 2; ret = mmc_read_blocks(&card, buf, block_addr, 2); zassert_equal(ret, 0, "Read from end of card failed"); /* Verify that unaligned reads work */ block_addr = 3; ret = mmc_read_blocks(&card, buf + MMC_UNALIGN_OFFSET, block_addr, SECTOR_COUNT - 1); zassert_equal(ret, 0, "Unaligned read failed"); } /* Verify that SD stack can write to an SD card */ ZTEST(sd_stack, test_write) { int ret; int block_addr = 0; /* Try simple writes from start of SD card */ ret = mmc_write_blocks(&card, buf, block_addr, 1); zassert_equal(ret, 0, "Single block card write failed"); ret = mmc_write_blocks(&card, buf, block_addr, SECTOR_COUNT / 2); zassert_equal(ret, 0, "Multiple block card write failed"); /* Try a series of reads from the same block */ block_addr = sector_count / 2; for (int i = 0; i < 10; i++) { ret = mmc_write_blocks(&card, buf, block_addr, SECTOR_COUNT); zassert_equal(ret, 0, "Multiple writes to same addr failed"); } /* Verify that out of bounds write fails */ block_addr = sector_count; ret = mmc_write_blocks(&card, buf, block_addr, 1); zassert_not_equal(ret, 0, "Out of bounds write should fail"); block_addr = sector_count - 2; ret = mmc_write_blocks(&card, buf, block_addr, 2); zassert_equal(ret, 0, "Write to end of card failed"); /* Verify that unaligned writes work */ block_addr = 3; ret = mmc_write_blocks(&card, buf + MMC_UNALIGN_OFFSET, block_addr, SECTOR_COUNT - 1); zassert_equal(ret, 0, "Unaligned write failed"); } /* Test reads and writes interleaved, to verify data is making it on disk */ ZTEST(sd_stack, test_rw) { int ret; int block_addr = 0; /* Zero the write buffer */ memset(buf, 0, BUF_SIZE); memset(check_buf, 0, BUF_SIZE); ret = mmc_write_blocks(&card, buf, block_addr, SECTOR_COUNT / 2); zassert_equal(ret, 0, "Write to card failed"); /* Verify that a read from this area is empty */ ret = mmc_read_blocks(&card, buf, block_addr, SECTOR_COUNT / 2); zassert_equal(ret, 0, "Read from card failed"); zassert_mem_equal(buf, check_buf, BUF_SIZE, "Read of erased area was not zero"); /* Now write nonzero data block */ for (int i = 0; i < sizeof(buf); i++) { check_buf[i] = buf[i] = (uint8_t)i; } ret = mmc_write_blocks(&card, buf, block_addr, SECTOR_COUNT); zassert_equal(ret, 0, "Write to card failed"); /* Clear the read buffer, then write to it again */ memset(buf, 0, BUF_SIZE); ret = mmc_read_blocks(&card, buf, block_addr, SECTOR_COUNT); zassert_equal(ret, 0, "Read from card failed"); zassert_mem_equal(buf, check_buf, BUF_SIZE, "Read of written area was not correct"); block_addr = (sector_count / 3); for (int i = 0; i < 10; i++) { /* Verify that unaligned writes work */ ret = mmc_write_blocks(&card, buf + MMC_UNALIGN_OFFSET, block_addr, SECTOR_COUNT - 1); zassert_equal(ret, 0, "Write to card failed"); /* Zero check buffer and read into it */ memset(check_buf + MMC_UNALIGN_OFFSET, 0, (SECTOR_COUNT - 1) * sector_size); ret = mmc_read_blocks(&card, check_buf + MMC_UNALIGN_OFFSET, block_addr, (SECTOR_COUNT - 1)); zassert_equal(ret, 0, "Read from card failed"); zassert_mem_equal(buf + MMC_UNALIGN_OFFSET, check_buf + MMC_UNALIGN_OFFSET, (SECTOR_COUNT - 1) * sector_size, "Unaligned read of written area was not correct"); } } /* Simply dump the card configuration. */ ZTEST(sd_stack, test_card_config) { switch (card.card_voltage) { case SD_VOL_1_2_V: TC_PRINT("Card voltage: 1.2V\n"); break; case SD_VOL_1_8_V: TC_PRINT("Card voltage: 1.8V\n"); break; case SD_VOL_3_0_V: TC_PRINT("Card voltage: 3.0V\n"); break; case SD_VOL_3_3_V: TC_PRINT("Card voltage: 3.3V\n"); break; default: zassert_unreachable("Card voltage is not known value"); } zassert_equal(card.status, CARD_INITIALIZED, "Card status is not OK"); switch (card.card_speed) { case MMC_LEGACY_TIMING: TC_PRINT("Card timing: Legacy MMC\n"); break; case MMC_HS_TIMING: TC_PRINT("Card timing: High Speed MMC\n"); break; case MMC_HS200_TIMING: TC_PRINT("Card timing: MMC HS200\n"); break; case MMC_HS400_TIMING: TC_PRINT("Card timing: MMC HS400\n"); break; default: zassert_unreachable("Card timing is not known value"); } switch (card.type) { case CARD_SDIO: TC_PRINT("Card type: SDIO\n"); break; case CARD_SDMMC: TC_PRINT("Card type: SDMMC\n"); break; case CARD_COMBO: TC_PRINT("Card type: combo card\n"); break; case CARD_MMC: TC_PRINT("Card type: MMC\n"); break; default: zassert_unreachable("Card type is not known value"); } } ZTEST_SUITE(sd_stack, NULL, NULL, NULL, NULL, NULL);
C
/* * Exercise 3-6. Write a version of itoa that accepts three arguments instead * of two. The third argument is a minimum field width; the converted number * must be padded with blanks on the left if necessary to make it wide enough. */ #include <stdio.h> #include <string.h> int reverse(char* s) { int len; int i; char c; len = strlen(s); for (i = 0; i < len/2; i++) { c = s[i]; s[i] = s[len - i - 1]; s[len - i - 1] = c; } } /* itoa: convert n to characters in s */ void my_itoa(int n, char s[], int mw) { int i, sign; if ((sign = n) < 0) /* record sign */ n = -n; /* make n positive */ i = 0; do { /* generate digits in reverse order */ s[i++]=((n%10 < 0)?(-1*(n%10)):(n%10)) + '0'; /*getnextdigit*/ } while ((n /= 10) != 0); if (sign < 0) s[i++] = '-'; while( i < mw) { s[i++] = ' '; } s[i] = '\0'; reverse(s); } int main() { int x = 0x80000000; char s[100]; my_itoa(x,s,22); printf ("s = %s\n", s); return 0; }
C
//-----------------------------------------------declaration------------------------------------------------------------------// // functions for creating interface void createInterfaceDinosaur(int firstColor); // functions for printing and deleting objects void printGameOver(); void printGround(char ground[3][121], int y0); void printObstacle(int type, int x, int y0, int color); void deleteObstacle(int type, int x, int y0); void printDinosaur(int height, int leg, int y0); void deleteDinosaur(int jump, int height, int y0); // functions for running game int random(int max); void initialize(char ground[3][121]); void makeGround(char ground[3][121]); int checkCollision(int height, int obstacle, int obstaclePos, int y0); // room.Dinosaur main void roomDinosaur(int firstColor, int secondColor); //----------------------------------------------------------------------------------------------------------------------------// // make random number in range [1, max] int random(int max){ return 1 + rand() % (max - 1); } // create interface for room.Dinosaur void createInterfaceDinosaur(int firstColor){ // print title textColor(firstColor); system("cls"); goToXY(0, 0); printf("Press Esc to back"); goToXY(22, 2); printf(" _ ___"); goToXY(22, 3); printf(" ______ _____ ___ (_)__ ___ _ ___/ (_)__ ___ ___ ___ ___ ______"); goToXY(22, 4); printf(" / __/ // / _ \\/ _ \\/ / _ \\/ _ `/ / _ / / _ \\/ _ \\(_-</ _ `/ // / __/"); goToXY(22, 5); printf("/_/ \\_,_/_//_/_//_/_/_//_/\\_, / \\_,_/_/_//_/\\___/___/\\_,_/\\_,_/_/"); goToXY(22, 6); printf(" /___/"); goToXY(119, 29); } void printGameOver(){ goToXY(55, 10); printf("GAME OVER"); goToXY(119, 29); } // set random seed; make ground void initialize(char ground[3][121]){ srand(time(NULL)); int i, t; for (i = 0; i <= 120; i++){ t = random(15); ground[0][i] = '_'; switch (t){ case 1: ground[1][i] = '.'; ground[2][i] = ' '; break; case 2: ground[1][i] = '-'; ground[2][i] = ' '; break; case 3: ground[1][i] = 248; ground[2][i] = ' '; break; case 4: ground[1][i] = '`'; ground[2][i] = ' '; break; case 5: ground[2][i] = '.'; ground[1][i] = ' '; break; case 6: ground[2][i] = '-'; ground[1][i] = ' '; break; case 7: ground[2][i] = '`'; ground[1][i] = ' '; break; default: ground[1][i] = ' '; ground[2][i] = ' '; break; } } ground[0][120] = '\0'; ground[1][120] = '\0'; ground[2][120] = '\0'; } // make next element for ground void makeGround(char ground[3][121]){ int t = random(15); switch (t){ case 1: ground[1][119] = '.'; ground[2][119] = ' '; break; case 2: ground[1][119] = '-'; ground[2][119] = ' '; break; case 3: ground[1][119] = 248; ground[2][119] = ' '; break; case 4: ground[1][119] = '`'; ground[2][119] = ' '; break; case 5: ground[2][119] = '.'; ground[1][119] = ' '; break; case 6: ground[2][119] = '-'; ground[1][119] = ' '; break; case 7: ground[2][119] = '`'; ground[1][119] = ' '; break; default: ground[1][119] = ' '; ground[2][119] = ' '; break; } } void printGround(char ground[3][121], int y0){ goToXY(0, y0); puts(&ground[0][0]); puts(&ground[1][0]); puts(&ground[2][0]); } void printObstacle(int type, int x, int y0, int color){ textColor(color); switch (type){ case 1: // 1 large (height = 5) goToXY(x - 1, y0 - 4) ; printf(" %c%c", 186, 186); goToXY(x - 1, y0 - 3) ; printf("%c%c%c", 186, 186, 186); goToXY(x - 1, y0 - 2) ; printf("%c%c%c", 186, 204, 188); goToXY(x - 1, y0 - 1); printf("%c%c", 200, 185); goToXY(x, y0); printf("%c", 186); break; case 2: // 3 smalls (height = 2) goToXY(x - 1, y0 - 1); printf("%c%c%c%c%c%c%c%c%c", 200, 206, 188, 200, 206, 188, 200, 206, 188); goToXY(x, y0); printf("%c__%c__%c", 186, 186, 186); break; case 3: // 2 mediums (height = 3) goToXY(x - 1, y0 - 2) ; printf("%c%c%c%c%c%c", 186, 186, 186, 186, 186, 186); goToXY(x - 1, y0 - 1); printf("%c%c%c%c%c%c", 200, 206, 188, 200, 206, 188); goToXY(x, y0); printf("%c__%c", 186, 186); break; case 4: // small - large goToXY(x - 1, y0 - 4) ; printf(" %c%c", 186, 186); goToXY(x - 1, y0 - 3) ; printf(" %c%c%c", 186, 186, 186); goToXY(x - 1, y0 - 2) ; printf(" %c%c%c", 186, 204, 188); goToXY(x - 1, y0 - 1); printf("%c%c%c%c%c", 200, 206, 188, 200, 185); goToXY(x, y0); printf("%c__%c", 186, 186); break; case 5: // large - large - medium goToXY(x - 1, y0 - 4) ; printf(" %c%c %c%c", 186, 186, 186, 186); goToXY(x - 1, y0 - 3) ; printf("%c%c%c%c%c%c", 186, 186, 186, 186, 186, 186); goToXY(x - 1, y0 - 2) ; printf("%c%c%c%c%c%c%c%c%c", 186, 204, 188, 186, 204, 188, 186, 186, 186); goToXY(x - 1, y0 - 1); printf("%c%c %c%c %c%c%c", 200, 185, 200, 185, 200, 206, 188); goToXY(x, y0); printf("%c__%c__%c", 186, 186, 186); break; case 6: // small - large - large - medium goToXY(x - 1, y0 - 4) ; printf(" %c%c %c%c", 186, 186, 186, 186); goToXY(x - 1, y0 - 3) ; printf(" %c%c%c%c%c%c", 186, 186, 186, 186, 186, 186); goToXY(x - 1, y0 - 2) ; printf(" %c%c%c%c%c%c%c%c%c", 186, 204, 188, 186, 204, 188, 186, 186, 186); goToXY(x - 1, y0 - 1); printf("%c%c%c%c%c %c%c %c%c%c", 200, 206, 188, 200, 185, 200, 185, 200, 206, 188); goToXY(x, y0); printf("%c__%c__%c__%c", 186, 186, 186, 186); break; case 7: // large - large - medium - large goToXY(x - 1, y0 - 4) ; printf(" %c%c %c%c %c%c", 186, 186, 186, 186, 186, 186); goToXY(x - 1, y0 - 3) ; printf("%c%c%c%c%c%c%c%c %c%c%c", 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, 186); goToXY(x - 1, y0 - 2) ; printf("%c%c%c%c%c%c%c%c%c%c%c%c", 186, 204, 188, 186, 204, 188, 186, 186, 186, 186, 204, 188); goToXY(x - 1, y0 - 1); printf("%c%c %c%c %c%c%c%c%c ", 200, 185, 200, 185, 200, 206, 188, 200, 185); goToXY(x, y0); printf("%c__%c__%c__%c", 186, 186, 186, 186); break; default: break; } } void deleteObstacle(int type, int x, int y0){ switch (type){ case 1: // 1 large (height = 5) goToXY(x + 1, y0 - 4) ; printf(" "); goToXY(x + 1, y0 - 3) ; printf(" "); goToXY(x + 1, y0 - 2) ; printf(" "); goToXY(x, y0 - 1); printf(" "); goToXY(x, y0); printf(" "); break; case 2: // 3 smalls (height = 2) goToXY(x + 7, y0 - 1); printf(" "); goToXY(x + 6, y0); printf(" "); break; case 3: // 2 mediums (height = 3) goToXY(x + 4, y0 - 2) ; printf(" "); goToXY(x + 4, y0 - 1); printf(" "); goToXY(x + 3, y0); printf(" "); break; case 4: // small - large goToXY(x + 4, y0 - 4) ; printf(" "); goToXY(x + 4, y0 - 3) ; printf(" "); goToXY(x + 4, y0 - 2) ; printf(" "); goToXY(x + 3, y0 - 1); printf(" "); goToXY(x + 3, y0); printf(" "); break; case 5: // large - large - medium goToXY(x + 4, y0 - 4) ; printf(" "); goToXY(x + 4, y0 - 3) ; printf(" "); goToXY(x + 7, y0 - 2) ; printf(" "); goToXY(x + 7, y0 - 1); printf(" "); goToXY(x + 6, y0); printf(" "); break; case 6: // small - large - large - medium goToXY(x + 7, y0 - 4) ; printf(" "); goToXY(x + 7, y0 - 3) ; printf(" "); goToXY(x + 10, y0 - 2) ; printf(" "); goToXY(x + 10, y0 - 1); printf(" "); goToXY(x + 9, y0); printf(" "); break; case 7: // large - large - medium - large goToXY(x + 10, y0 - 4) ; printf(" "); goToXY(x + 10, y0 - 3) ; printf(" "); goToXY(x + 10, y0 - 2) ; printf(" "); goToXY(x + 9, y0 - 1); printf(" "); goToXY(x + 9, y0); printf(" "); break; default: break; } } void printDinosaur(int height, int leg, int y0){ goToXY(25, y0 - 5 - height); printf(" e-e"); goToXY(25, y0 - 4 - height); printf(" /(\\_/)"); goToXY(25, y0 - 3 - height); printf(".___.--' /`-'"); goToXY(25, y0 - 2 - height); printf(" `-._. )/`"); goToXY(25, y0 - 1 - height); printf(" //"); goToXY(29, y0 - height); if ((height > 0) || (leg == 3)){ printf("^^"); return; } if (leg == 1) printf("^_"); if (leg == 2) printf("_^"); } void deleteDinosaur(int jump, int height, int y0){ if (jump){ if (jump < 25){ goToXY(38, y0 - 4 - height); printf(" "); goToXY(35, y0 - 3 - height); printf(" "); goToXY(32, y0 - 2 - height); printf(" "); goToXY(29, y0 - height); printf(" "); } else{ goToXY(35, y0 - 5 - height); printf(" "); goToXY(38, y0 - 4 - height); printf(" "); } } } int checkCollision(int height, int obstacle, int obstaclePos, int y0){ int i, j, xy[100][21]; for (i = 1; i <= 99; i++) for (j = 1; j <= 20; j++) xy[i][j] = 0; xy[38][y0 - 4 - height] = 1; xy[25][y0 - 3 - height] = 1; xy[35][y0 - 3 - height] = 1; xy[36][y0 - 3 - height] = 1; xy[37][y0 - 3 - height] = 1; xy[26][y0 - 2 - height] = 1; xy[27][y0 - 2 - height] = 1; xy[28][y0 - 2 - height] = 1; xy[31][y0 - 2 - height] = 1; xy[32][y0 - 2 - height] = 1; xy[33][y0 - 2 - height] = 1; xy[34][y0 - 2 - height] = 1; xy[29][y0 - 1 - height] = 1; xy[30][y0 - 1 - height] = 1; xy[29][y0 - height] = 1; xy[30][y0 - height] = 1; switch (obstacle){ case 1: // 1 large if (xy[obstaclePos][y0 - 4]) return 1; if (xy[obstaclePos + 1][y0 - 4]) return 1; if (xy[obstaclePos - 1][y0 - 3]) return 1; if (xy[obstaclePos - 1][y0 - 2]) return 1; if (xy[obstaclePos - 1][y0 - 1]) return 1; break; case 2: // 3 smalls if (xy[obstaclePos - 1][y0 - 1]) return 1; if (xy[obstaclePos][y0 - 1]) return 1; if (xy[obstaclePos + 1][y0 - 1]) return 1; if (xy[obstaclePos + 2][y0 - 1]) return 1; if (xy[obstaclePos + 3][y0 - 1]) return 1; if (xy[obstaclePos + 4][y0 - 1]) return 1; if (xy[obstaclePos + 5][y0 - 1]) return 1; if (xy[obstaclePos + 6][y0 - 1]) return 1; if (xy[obstaclePos + 7][y0 - 1]) return 1; break; case 3: // 2 mediums if (xy[obstaclePos - 1][y0 - 2]) return 1; if (xy[obstaclePos][y0 - 2]) return 1; if (xy[obstaclePos + 1][y0 - 2]) return 1; if (xy[obstaclePos + 2][y0 - 2]) return 1; if (xy[obstaclePos + 3][y0 - 2]) return 1; if (xy[obstaclePos + 4][y0 - 2]) return 1; if (xy[obstaclePos - 1][y0 - 1]) return 1; break; case 4: // small - large if (xy[obstaclePos + 3][y0 - 4]) return 1; if (xy[obstaclePos + 4][y0 - 4]) return 1; if (xy[obstaclePos + 2][y0 - 3]) return 1; if (xy[obstaclePos + 2][y0 - 2]) return 1; if (xy[obstaclePos - 1][y0 - 1]) return 1; if (xy[obstaclePos][y0 - 1]) return 1; if (xy[obstaclePos + 1][y0 - 1]) return 1; break; case 5: // large - large - medium if (xy[obstaclePos][y0 - 4]) return 1; if (xy[obstaclePos + 1][y0 - 4]) return 1; if (xy[obstaclePos + 3][y0 - 4]) return 1; if (xy[obstaclePos + 4][y0 - 4]) return 1; if (xy[obstaclePos - 1][y0 - 3]) return 1; if (xy[obstaclePos - 1][y0 - 2]) return 1; if (xy[obstaclePos + 5][y0 - 2]) return 1; if (xy[obstaclePos + 6][y0 - 2]) return 1; if (xy[obstaclePos + 7][y0 - 2]) return 1; if (xy[obstaclePos - 1][y0 - 1]) return 1; break; case 6: // small - large - large - medium if (xy[obstaclePos + 3][y0 - 4]) return 1; if (xy[obstaclePos + 4][y0 - 4]) return 1; if (xy[obstaclePos + 6][y0 - 4]) return 1; if (xy[obstaclePos + 7][y0 - 4]) return 1; if (xy[obstaclePos + 2][y0 - 3]) return 1; if (xy[obstaclePos + 2][y0 - 2]) return 1; if (xy[obstaclePos + 8][y0 - 2]) return 1; if (xy[obstaclePos + 9][y0 - 2]) return 1; if (xy[obstaclePos + 10][y0 - 2]) return 1; if (xy[obstaclePos - 1][y0 - 1]) return 1; if (xy[obstaclePos][y0 - 1]) return 1; if (xy[obstaclePos + 1][y0 - 1]) return 1; break; case 7: // large - large - medium - large if (xy[obstaclePos][y0 - 4]) return 1; if (xy[obstaclePos + 1][y0 - 4]) return 1; if (xy[obstaclePos + 3][y0 - 4]) return 1; if (xy[obstaclePos + 4][y0 - 4]) return 1; if (xy[obstaclePos + 9][y0 - 4]) return 1; if (xy[obstaclePos + 10][y0 - 4]) return 1; if (xy[obstaclePos - 1][y0 - 3]) return 1; if (xy[obstaclePos - 1][y0 - 2]) return 1; if (xy[obstaclePos - 1][y0 - 1]) return 1; break; default: break; } return 0; } // room.Dinosaur main void roomDinosaur(int firstColor, int secondColor){ // declare vars int y0 = 20; int frameCount, frameTime, highscore; int height, jump; int obstaclePos, obstacle; int i, t; char ground[3][121], ch; initialize(ground); // get highscore int tmp; FILE *memory = fopen("memory.txt", "r"); fscanf(memory, "%d %d %d %d", &tmp, &tmp, &tmp, &highscore); fclose(memory); // create interface createInterfaceDinosaur(firstColor); printGround(ground, y0); printDinosaur(0, 3, y0); goToXY(119, 29); // GAME while (1){ gameStart: // initialize frameCount = 0; frameTime = 10; jump = 0; obstacle = 0; // press enter to start do{ ch = getch(); if (ch == 27) return; // esc } while (ch != 13); // print stuffs system("cls"); goToXY(0, 0); printf("Press Esc to back"); goToXY(94, 1); printf("Highs: %d", highscore); goToXY(94, 2); printf("Score:"); // game while (1){ // delete deleteObstacle(obstacle, obstaclePos, y0); deleteDinosaur(jump, height, y0); textColor(firstColor); // make ground makeGround(ground); for (i = 0; i <= 118; i++){ ground[1][i] = ground[1][i + 1]; ground[2][i] = ground[2][i + 1]; } // make obstacle if (obstacle == 0){ t = random(100); if (t <= 7){ obstacle = t; obstaclePos = 108; } } else obstaclePos--; if (obstaclePos == 1){ printObstacle(obstacle, 1, y0, 0); obstacle = 0; textColor(firstColor); } // dinosaur jump height = (50 - jump) * jump / 60; // it's physic mate. it's physiccccc if ((jump < 50) && (jump != 0)) jump++; else jump = 0; // print printGround(ground, y0); printObstacle(obstacle, obstaclePos, y0, firstColor); printDinosaur(height, 1 + frameCount % 2, y0); goToXY(101, 2); printf("%d", frameCount); goToXY(119, 29); // check collision if (obstaclePos <= 39) if (checkCollision(height, obstacle, obstaclePos, y0)){ goToXY(35, y0 - 5 - height); printf("x-x"); printGameOver(); if (highscore < frameCount){ // set new highscore highscore = frameCount; // save new highscore to memory file int tmp, size; FILE *memory = fopen("memory.txt", "r"); fscanf(memory, "%d %d %d %d", &tmp, &tmp, &size, &tmp); fclose(memory); memory = fopen("memory.txt", "w"); fprintf(memory, "%d\n%d\n%d\n%d", firstColor, secondColor, size, highscore); fclose(memory); } goto gameStart; } // if keypressed if (kbhit()){ ch = getch(); // esc if (ch == 27) return; // spacebar if ((ch == ' ') && (jump == 0)) jump = 1; } // wait wait(frameTime); frameCount++; if ((frameCount % 600 == 0) && (frameTime > 2)) frameTime--; } } }
C
#include "ft_ls.h" char *get_file_name(char *path) { char *file_name; file_name = ft_strrchr(path, '/'); if (file_name == NULL) return (path); return (file_name + 1); }
C
//linear search #include<stdio.h> int Linear_Search(int a[],int x,int item) { int i,flag=0; //printf("data for search %d\n",item); for(i=0;i<x;i++) { if(a[i] == item) flag = 1; } if(flag == 1) return 1; } void main() { int a[10],n,i,data,s; printf("Enter Number of Element : "); scanf("%d",&n); printf("Enter Element : \n"); for(i=0;i<n;i++) { printf("[%d] - > ",i); scanf("%d",&a[i]); } printf("Enter Data For Search : "); scanf("%d",&data); s = Linear_Search(a,n,data); // printf("Return Value %d\n",s); if(s == 1) printf("Data is Found \n"); else printf("Data is Not Found\n"); }
C
#include <stdio.h> // getchar(), putchar() int main() { /* 1. Introduce getchar(), putchar() 2. Use while loop to process character sequence 3. Filter a specific character 4. Convert numbers to asterisks 5. Lower characters to Upper characters */ char ch; //ch = (char)getchar();// buffer //putchar(ch); //while (ch != '\n')// Use '\n' to find the end of a sentence while ((ch = (char)getchar()) != '\n') { if (ch >= '0' && ch <='9') ch = '*'; if (ch >= 'a' && ch <= 'z') ch -= 'a' - 'A'; else if (ch >= 'A' && ch <= 'Z') ch += 'a' - 'A'; //if (ch == 'f' || ch == 'F') //{ // ch = 'X'; //} /*else if (ch == 'F') { ch = 'X'; }*/ putchar(ch); } putchar(ch); return 0; }
C
#include<stdio.h> #include<stdlib.h> int main(){ pid_t pid; int i; pid=fork(); if(pid<0){ printf("fork() error\n"); exit(1); } else if(pid==0){ printf("this is child :pid= %d parent pid=%d\n",getpid(),getppid()); } else{ printf("this is parent:pid=%d, parent pid=%d\n",getpid(),getppid()); } i=0; for(;i<4;i++){ printf("thus is %d,i=%d\n",getpid(),i); sleep(3); } }
C
#include <stdio.h> #include <stdlib.h> /** * _strdup? (- create array)? * * @s: input int array size * Return: z */ char *_strdup(char *s) { char *z; unsigned int i, j; if (s == NULL) return (NULL); for (j = 0; s[j] != '\0'; j++) ; z = malloc(sizeof(char) * j + 1); if (z == NULL) return (NULL); for (i = 0; i <= j; i++) { if (i != j) z[i] = s[i]; else z[j] = '\0'; } return (z); }
C
#include "util.h" void Util_Increase( uint16_t * const psrc, uint8_t delta, uint16_t max ) { if ( ( *psrc ) + delta < max ) { ( *psrc ) += delta; } else { ( *psrc ) = max; } } void Util_Decrease( uint16_t * const psrc, uint8_t delta, uint16_t min ) { if ( ( *psrc ) > min + delta ) { ( *psrc ) -= delta; } else { ( *psrc ) = min; } }
C
#include <stdlib.h> void func2(char *); void func1() { func2(NULL); //DEFECT } void func2(char *var) { *var = 2; }
C
#include <stdio.h> #include<string.h> int main() { char s1[9],s2[9]; scanf("%s",s1); strcpy(s2,s1); strrev(s2); if(strcmp(s2,s1)==0) printf("the given sting is palindrome"); else printf("no"); return 0; }
C
/** I N C L U D E S **********************************************************/ #include <p18f4550.h> // PIC Controller header file #include <adc.h> // ADC library functions #include <xlcd.h> // LCD library functions #include <delays.h> // Delay library functions #include <stdio.h> // Standard IO functions #include <stdlib.h> // Standard library functions /** V A R I A B L E S ********************************************************/ #pragma idata int stepMotor1 = 4; // Array index for motor 1. int stepMotor2 = 4; // Array index for motor 2. int stepMotor3 = 4; char motor[8] = {0b10101010, // An array of characters which contains the output sequence for the motors 0b10001000, 0b10011001, 0b00010001, 0b01010101, 0b01000100, 0b01100110, 0b00100010}; // Array index for motor 2. /** P R I V A T E P R O T O T Y P E S ***************************************/ void rotateCW(int motorNum); // Function for rotating a motor one step in the clockwise direction void rotateCCW(int motorNum); // Function for rotating a motor one step in the counterclockwise direction int readFrontSensor(void); // Function to read the front sensor int readLeftSensor(void); // Function to read the left sensor int readRightSensor(void); // Function to read the right sensor void followLeftWall( int sensor, int tol); // Function to follow the wall on the left void followRightWall(int sensor, int tol); // Function to follow the wall on the right void followLeftWallIt(int dist, int tol); // Function to follow the wall on the left a given distance void followRightWallIt(int dist, int tol); // Function to follow the wall on the right a given distance void goForward(void); // Function to go forward by 1 step void goForwardx(int stepNum); // Function to go forward by a given number of steps void goBackward(); // Function to go backward by 1 step void goBackwardx(int stepNum); // Function to go backward by a given number of steps void turnRight(int stepNum); // Function to turn right void turnLeft(int stepNum); // Function to turn Left void goForwardR(void); void goForwardL(void); void goForwardF(void); void followRightWallF(int sensor, int tol); void followLeftWallF(int sensor, int tol); void goForwardFastF(void); void followRightWallR(int sensor, int tol); /**V E C T O R R E M A P P I N G*********************************************/ extern void _startup (void); #pragma code _RESET_INTERRUPT_VECTOR = 0x000800 void _reset (void){ _asm goto _startup _endasm } #pragma code _HIGH_INTERRUPT_VECTOR = 0x000808 void _high_ISR (void){ ; } #pragma code _LOW_INTERRUPT_VECTOR = 0x000818 void _low_ISR (void){ ; } #pragma code /** D E C L A R A T I O N S **************************************************/ /** U S E R A P I ***********************************************************/ /****************************************************************************** * Function: main * * PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: main entry point * Note: None *****************************************************************************/ void main(void) { int leftSensor = 0; int frontSensor = 0; // Variable to store front sensor value int rightSensor = 0; rightSensor = readRightSensor(); frontSensor = readFrontSensor(); leftSensor = readLeftSensor(); OpenADC(ADC_FOSC_32 & ADC_RIGHT_JUST & ADC_12_TAD, ADC_CH0 & ADC_INT_OFF & ADC_VREFPLUS_VDD & ADC_VREFMINUS_VSS, 12); OpenADC(ADC_FOSC_32 & ADC_RIGHT_JUST & ADC_12_TAD, ADC_CH1 & ADC_INT_OFF & ADC_VREFPLUS_VDD & ADC_VREFMINUS_VSS, 12); OpenADC(ADC_FOSC_32 & ADC_RIGHT_JUST & ADC_12_TAD, ADC_CH2 & ADC_INT_OFF & ADC_VREFPLUS_VDD & ADC_VREFMINUS_VSS, 12); while(1) { rightSensor = readRightSensor(); frontSensor = readFrontSensor(); leftSensor = readLeftSensor(); turnRight(235); goForwardL(); goForwardx(200); followRightWall(120,350); goForwardx(300); turnLeft(235); //enters box goForwardx(500); followRightWallF(120,350); turnLeft(245); followRightWallR(120,350); turnRight(210); //enters opponents zone goForwardFastF(); turnRight(235); turnRight(235); goForwardFastF(); turnRight(235); followLeftWallF(120,350); turnLeft(245); turnLeft(245); goForwardF(); turnRight(235); //exits box followLeftWall(120,350); goForwardF(); turnRight(240); followLeftWallF(120,350); turnRight(235); goForwardx(1000); turnRight(235); turnRight(235); followRightWallF(120,350); turnLeft(245); followRightWallF(120,350); turnLeft(235); followRightWallIt(22,350); turnLeft(235); turnLeft(235); followLeftWall(120,350); goForwardF(); while(1){} } } /****************************************************************************** * Function: followLeftWall * * PreCondition: None * * Input: sensor: the left sensor value required to exit the function. * tol: the minimum left sensor value for which the robot would move forward in a straight line. * * Output: follow the wall on the left * * Side Effects: None * * Overview: follows the left wall until the front sensor reads a certain value * * Note: None *****************************************************************************/ void followLeftWall( int sensor, int tol){ int frontSensor; int leftSensor; int rightSensor; leftSensor = readLeftSensor(); rightSensor = readRightSensor(); frontSensor = readFrontSensor(); while(1) { if(leftSensor > tol+65)//65 { turnRight(12); goForwardx(35); } else if(leftSensor < tol) { turnLeft(12); goForwardx(35); } else { goForwardx(20); } frontSensor = readFrontSensor(); rightSensor= readRightSensor(); leftSensor = readLeftSensor(); if (leftSensor < 200 || rightSensor < 200) { break; } if(frontSensor > 450){ turnLeft(235); turnLeft(235); break; } } return; } /****************************************************************************** * Function: followLeftWallIt * * PreCondition: None * * Input: dist the distance, or number of times the robot executes the loop. * tol: the minimum left sensor value for which the robot would move forward in a straight line. * * Output: follows the wall on the left a given distance * * Side Effects: None * * Overview: follows the left wall a given distance * * Note: None *****************************************************************************/ void followLeftWallIt (int dist, int tol){ int i=0; int leftSensor ; int rightSensor ; while (i < dist) { leftSensor = readLeftSensor(); if(leftSensor > tol+100) { turnRight(30); goForwardx(50); } if(leftSensor < tol) { turnLeft(30); goForwardx(50); } else { goForwardx(50); } rightSensor = readRightSensor(); i++; } return; } /****************************************************************************** * Function: followRightWall * * PreCondition: None * * Input: sensor: the front sensor value required to exit the function. * tol: the minimum right sensor value for which the robot would move forward in a straight line. * * Output: follow the wall on the right * * Side Effects: None * * Overview: follows the right wall until the front sensor reads a certain value * * Note: None *****************************************************************************/ void followRightWall(int sensor, int tol){ int frontSensor = readFrontSensor(); int rightSensor = readRightSensor() ; int leftSensor = readLeftSensor(); while(1) { rightSensor = readRightSensor(); if(rightSensor > tol+65)//65 { turnLeft(15); goForwardx(35); } else if(rightSensor < tol) { turnRight(15); goForwardx(35); } else { goForwardx(20); //20 } frontSensor = readFrontSensor(); rightSensor= readRightSensor(); leftSensor = readLeftSensor(); if (leftSensor < 200 || rightSensor < 200) { break;} if(frontSensor>450){ turnRight(235); turnRight(235); break; } } return; } /****************************************************************************** * Function: followRightWallIt * * PreCondition: None * * Input: dist the distance, or number of times the robot executes the loop. * tol: the minimum right sensor value for which the robot would move forward in a straight line. * * Output: follows the wall on the right a given distance * * Side Effects: None * * Overview: follows the right wall a given distance * * Note: None *****************************************************************************/ void followRightWallIt (int dist, int tol){ int i=0; int leftSensor ; int rightSensor ; while (i<dist) { rightSensor = readRightSensor(); if(rightSensor > tol+100) { turnLeft(30); goForwardx(20); } if(rightSensor < tol) { turnRight(30); goForwardx(20); } else { goForwardx(50); } rightSensor = readRightSensor(); i++; } return; } /****************************************************************************** * Function: readFrontSensor * * PreCondition: None * * Input: None * * Output: value read from front sensor, 10 bits * * Side Effects: None * * Overview: This function reads the front sensor which is hooked up with * channel 0 of the ADC of the PIC * * Note: None *****************************************************************************/ int readFrontSensor(void){ SetChanADC(ADC_CH0); // Set the analog input to A0 ConvertADC(); // Start the conversion while(BusyADC()); // Wait until the conversion is finished return ReadADC(); // Store the value from the conversion } /****************************************************************************** * Function: readLeftSensor * * PreCondition: None * * Input: None * * Output: value read from left sensor, 10 bits * * Side Effects: None * * Overview: This function reads the left sensor which is hooked up with * channel 1 of the ADC of the PIC * * Note: None *****************************************************************************/ int readLeftSensor(void){ SetChanADC(ADC_CH1); // Set the analog input to A1 ConvertADC(); // Start the conversion while(BusyADC()); // Wait until the conversion is finished return ReadADC(); // Store the value from the conversion } /****************************************************************************** * Function: readRightSensor * * PreCondition: None * * Input: None * * Output: value read from front sensor, 10 bits * * Side Effects: None * * Overview: This function reads the right sensor which is hooked up with * channel 2 of the ADC of the PIC * * Note: None *****************************************************************************/ int readRightSensor(void){ SetChanADC(ADC_CH2); // Set the analog input to A2 ConvertADC(); // Start the conversion while(BusyADC()); // Wait until the conversion is finished return ReadADC(); // Store the value from the conversion } /****************************************************************************** * Function: goForward * * PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: This function moves the robot 1 step forward * * Note: None *****************************************************************************/ void goForward(void){ rotateCCW(2); // Rotate motor two step rotateCW(1); // Rotate motor one step Delay1KTCYx(40); // Changing the argument in the delay function will change the speed at which the motor rotates. Delay equals 1000 x 50 x 1/12 = 4.167 ms LATD = 0x00; // Set all port D to 0 } /****************************************************************************** * Function: goForwardx * * PreCondition: None * * Input: the number of steps to be moved forward. * * Output: none * * Side Effects: None * * Overview: moves the robot forward a given number of steps * * Note: None *****************************************************************************/ void goForwardx( int stepNum){ int i=0; while( i < stepNum){ goForward(); i++; } return; } /****************************************************************************** * Function: turnRight * * PreCondition: None * * Input: stepNum: Number of steps to make for turning right * * Output: None * * Side Effects: None * * Overview: This function make the robot to turn right by making certain * number of steps which is indicated by the input * * Note: None *****************************************************************************/ void turnRight(int stepNum){ int i = 0; while(i<stepNum){ rotateCW(2); // Rotate motor two step rotateCW(1); // Rotate motor one step Delay1KTCYx(50); // Changing the argument in the delay function will change the speed at which the motor rotates. Delay equals 1000 x 50 x 1/12 = 4.167 ms i++; LATD = 0x00; // Set all port D to 0 LATB = 0x00; } return; } /****************************************************************************** * Function: turnLeft * * PreCondition: None * * Input: stepNum: Number of steps to make for turning left * * Output: None * * Side Effects: None * * Overview: This function make the robot to turn left by making certain * number of steps which is indicated by the input * * Note: None *****************************************************************************/ void turnLeft(int stepNum){ int i = 0; while(i<stepNum){ rotateCCW(2); // Rotate motor two step rotateCCW(1); // Rotate motor one step Delay1KTCYx(50); // Changing the argument in the delay function will change the speed at which the motor rotates. Delay equals 1000 x 50 x 1/12 = 4.167 ms i++; LATD = 0x00; // Set all port D to 0 LATB = 0x00; } return; } /****************************************************************************** * Function: rotateCW * * PreCondition: None * * Input: motorNum - determines which motor, * motor[] - an array which contains output sequence for the motors * * Output: sequence for correct motor operation * * Side Effects: None * * Overview: This function rotates the motor one step * * Note: NOT REQUIRED TO KNOW THE INNER WORKINGS OF THIS FUNCTION *****************************************************************************/ void rotateCW(int motorNum){ if(motorNum==1){ stepMotor1 = ++stepMotor1; // Increment the array index for motor 1 if(stepMotor1>7) // If the array index is out of range the reset it to 0 stepMotor1=0; TRISD &= 0x0f; // Set the upper 4 bits of port D as outputs LATD |= ((motor[stepMotor1]<<4)&0xf0); // Output the motor step sequence to the upper 4 bits of port D }else{ stepMotor2 = ++stepMotor2; // Increment the array index for motor 2 if(stepMotor2>7) // If the array index is out of range the reset it to 0 stepMotor2=0; TRISD &= 0xf0; // Set the lower 4 bits of port D as outputs LATD |= ((motor[stepMotor2]>>4)&0x0f); // Output the motor step sequence to the lower 4 bits of port D } } /****************************************************************************** * Function: rotateCCW * * PreCondition: None * * Input: motorNum - determines which motor, * motor[] - an array which contains output sequence for the motors * * Output: sequence for correct motor operation * * Side Effects: None * * Overview: This function rotates the motor one step * * Note: NOT REQUIRED TO KNOW THE INNER WORKINGS OF THIS FUNCTION *****************************************************************************/ void rotateCCW(int motorNum){ if(motorNum==1){ stepMotor1--; // Decrement the array index for motor 1 if(stepMotor1<0) // If the array index is out of range the reset it to 7 stepMotor1=7; TRISD &= 0x0f; // Set the upper 4 bits of port D as outputs LATD |= ((motor[stepMotor1]<<4)&0xf0); // Output the motor step sequence to the upper 4 bits of port D }else{ stepMotor2--; // Decrement the array index for motor 2 if(stepMotor2<0) // If the array index is out of range the reset it to 7 stepMotor2=7; TRISD &= 0xf0; // Set the lower 4 bits of port D as outputs LATD |= ((motor[stepMotor2]>>4)&0x0f); // Output the motor step sequence to the lower 4 bits of port D } } /****************************************************************************** * Function: goForwardR * * PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: This function moves the robot 1 step forward * * Note: None *****************************************************************************/ void goForwardR(void){ int rightSensor; rightSensor = readRightSensor(); while(rightSensor < 200){ goForward(); rightSensor = readRightSensor(); } goForwardx(100); return; } /****************************************************************************** * Function: goForwardL * * PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: This function moves the robot 1 step forward * * Note: None *****************************************************************************/ void goForwardL(void){ int leftSensor; leftSensor = readLeftSensor(); while(leftSensor < 200){ goForward(); leftSensor = readLeftSensor(); } goForwardx(100); return; } /****************************************************************************** * Function: goForwardF * * PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: This function moves the robot 1 step forward * * Note: None *****************************************************************************/ void goForwardF(void){ int frontSensor; frontSensor = readFrontSensor(); while(frontSensor < 450){ goForward(); frontSensor = readFrontSensor(); } return; } /****************************************************************************** * Function: goForwardFastF * * PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: This function moves the robot 1 step forward * * Note: None *****************************************************************************/ void goForwardFastF(void){ int frontSensor; frontSensor = readFrontSensor(); while(frontSensor < 450){ rotateCCW(2); // Rotate motor two step rotateCW(1); // Rotate motor one step Delay1KTCYx(35); // Changing the argument in the delay function will change the speed at which the motor rotates. Delay equals 1000 x 50 x 1/12 = 4.167 ms LATD = 0x00; // Set all port D to 0 frontSensor = readFrontSensor(); } return; } /****************************************************************************** * Function: followRightWall * * PreCondition: None * * Input: sensor: the front sensor value required to exit the function. * tol: the minimum right sensor value for which the robot would move forward in a straight line. * * Output: follow the wall on the right * * Side Effects: None * * Overview: follows the right wall until the front sensor reads a certain value * * Note: None *****************************************************************************/ void followRightWallF(int sensor, int tol){ int frontSensor = readFrontSensor(); int rightSensor = readRightSensor() ; int leftSensor = readLeftSensor(); while(1) { rightSensor = readRightSensor(); if(rightSensor > tol+65)//65 { turnLeft(10); goForwardx(35); } else if(rightSensor < tol) { turnRight(10); goForwardx(35); } else { goForwardx(20); //20 } frontSensor = readFrontSensor(); rightSensor= readRightSensor(); leftSensor = readLeftSensor(); if(frontSensor > 400){ break; } } return; } void followLeftWallF(int sensor, int tol){ int frontSensor = readFrontSensor(); int rightSensor = readRightSensor() ; int leftSensor = readLeftSensor(); while(1) { leftSensor = readLeftSensor(); if(leftSensor > tol+65)//65 { turnRight(10); goForwardx(35); } else if(leftSensor < tol) { turnLeft(10); goForwardx(35); } else { goForwardx(20); //20 } frontSensor = readFrontSensor(); rightSensor= readRightSensor(); leftSensor = readLeftSensor(); if(frontSensor>400){ break; } } return; } void followRightWallR(int sensor, int tol){ int frontSensor = readFrontSensor(); int rightSensor = readRightSensor() ; int leftSensor = readLeftSensor(); while(1) { rightSensor = readRightSensor(); if(rightSensor > tol+100)//65 { turnLeft(30); goForwardx(20); } else if(rightSensor < tol) { turnRight(30); goForwardx(20); } else { goForwardx(20); //20 } frontSensor = readFrontSensor(); rightSensor= readRightSensor(); leftSensor = readLeftSensor(); if (rightSensor < 200) { goForwardx(250); break; } } return; }
C
#include <stdlib.h> #include <stdio.h> #include "rpc_channel.h" #include "map.h" #include "mp_channel.h" #include "precondition.h" #include "condition.h" #include "amoeba.h" #include "thread.h" #include "assert.h" #define MODULE_NAME "RPC_CHANNEL" #define STACKSIZE 32000 static int me; static int group_size; static int proc_debug; static int initialized=0; static map_p rpc_channel_map; static map_p rpc_handlers_map; typedef struct trailer_s trailer_t, *trailer_p; struct rpc_channel_s { int ch_number; int ticket; /* Tickets used to make sure messages are not processed more than once. */ int server_ticket; int client_ticket; message_p request_message; message_p reply_message; condition_p channel_free; po_time_t timeout; /* Timeout value in milliseconds. */ set_p processors; /* Members connected by the channel. */ mp_channel_p mpch; /* Message passing channel used to connect members. */ message_p message; /* Used by server thread to process incoming messages. */ condition_p new_request; }; struct trailer_s { int rch_id; int to; int from; int ticket; int handler; }; static void __rpc_server_handler(message_p); static void rpc_server_thread(char *c, int size); static void rpc_server_handler(message_p); static void rpc_client_handler(message_p); /*==============================================================*/ /* Initializes the module. */ /*==============================================================*/ int init_rpc_channel(int moi, int gsize, int pdebug) { int r; if ((r=init_module())<=0) return r; init_mp_channel(me, group_size, proc_debug); init_message(me, group_size, proc_debug); init_map(me, group_size, proc_debug); init_condition(me, group_size, proc_debug); rpc_channel_map=new_map(); message_register_handler(rpc_server_handler); message_register_handler(rpc_client_handler); rpc_handlers_map=new_map(); return 0; } /*==============================================================*/ /* Ends the module. */ /*==============================================================*/ int finish_rpc_channel() { if (--initialized) return 0; free_map(rpc_handlers_map); free_map(rpc_channel_map); finish_condition(); finish_map(); finish_message(); finish_mp_channel(); return 0; } /*==============================================================*/ /* Creates a new channel between a set of processors. */ /*==============================================================*/ rpc_channel_p new_rpc_channel(set_p processors) { rpc_channel_p rch; int r; precondition(initialized); rch=(rpc_channel_p )malloc(sizeof(rpc_channel_t)); assert(rch!=NULL); if (processors==NULL) { rch->processors=new_set(group_size); full_set(rch->processors); } else rch->processors=duplicate_set(processors); assert(rch->processors!=NULL); rch->ticket=0; rch->server_ticket=1; rch->client_ticket=1; rch->request_message=new_message(0,0); rch->reply_message=new_message(0,0); rch->channel_free=new_condition(); rch->mpch=new_mp_channel(rch->processors); assert(rch->mpch!=NULL); rch->timeout=1000000; /* Default timeout is 1000000 microseconds. */ rch->message=new_message(0,0); rch->new_request=new_condition(); await_condition(rch->new_request); rch->ch_number=insert_item(rpc_channel_map, rch); assert(rch->ch_number>=0); r=thread_newthread(rpc_server_thread,STACKSIZE, (char *)rch, sizeof(rpc_channel_p)); assert(r>=0); return rch; } /*==============================================================*/ /* Frees an rpc channel. */ /*==============================================================*/ int free_rpc_channel(rpc_channel_p rch) { precondition(initialized); precondition(rch!=NULL); remove_item(rpc_channel_map,rch->ch_number); free_set(rch->processors); free_message(rch->request_message); free_message(rch->reply_message); free_condition(rch->channel_free); free_mp_channel(rch->mpch); free_message(rch->message); signal_condition(rch->new_request); return 0; } /*==============================================================*/ /* Sets the timeout for the next rpc issued by this processor. */ /*==============================================================*/ int set_timeout(rpc_channel_p rch, po_time_t time, unit_t unit) { precondition(initialized); precondition(rch!=NULL); switch (unit) { case PO_MICROSEC: rch->timeout=time; break; case PO_MILLISEC: rch->timeout=time*1000.0; break; case PO_SEC: rch->timeout=time*1000000.0; break; default: return -1; } return 0; } /*==============================================================*/ /* Sends a message to a processor and returns a ticket. Upon arrival at the server's side, the message is processed using the handler specified in the header of the message. This handler must be registered and set before calling rpc_request. The server must reply to the message using an rpc_reply call. */ /*==============================================================*/ int rpc_request(rpc_channel_p rch, int to, message_p message) { trailer_t trailer; precondition(initialized); precondition(rch!=NULL); precondition((to>=0) && (to<group_size)); precondition(message!=NULL); await_condition(rch->channel_free); /* Set rpc specific information in a trailer and replace handler by rpc_server_hanlder pointer. */ rch->ticket++; trailer.rch_id=rch->ch_number; trailer.ticket=rch->ticket; trailer.from=me; trailer.to=to; trailer.handler=item_index(rpc_handlers_map, (item_p )message_get_handler(message)); assert(trailer.handler>=0); message_append_data(message,&trailer,sizeof(trailer_t)); message_set_handler(message,rpc_server_handler); /* Save request message. */ if (message_get_header_size(rch->request_message)!= message_get_header_size(message)) { free_message(rch->request_message); rch->request_message=new_message(message_get_header_size(message), message_get_data_size(message)); } message_set_header(rch->request_message,message_get_header(message), message_get_header_size(message)); message_set_data(rch->request_message,message_get_data(message), message_get_data_size(message)); message_set_handler(rch->request_message, rpc_server_handler); /* Send message. */ mp_channel_unicast(rch->mpch,to,message); message_set_handler(message, get_item(rpc_handlers_map,trailer.handler)); return rch->ticket; } /*==============================================================*/ /* Replies to an rpc request. The server must provide the message sent by the client in smessage. The rmessage is the reply message and will be processed at the client's side by the handler specified in the message. The handler must be set before calling rpc_reply. */ /*==============================================================*/ int rpc_reply(rpc_channel_p rch, message_p smessage, message_p rmessage) { trailer_p strailer; trailer_t trailer; /* Set trailer in the message. */ strailer=(trailer_p )(message_get_data(smessage)+ message_get_data_size(smessage)- sizeof(trailer_t)); trailer.from=me; trailer.to=strailer->from; trailer.rch_id=strailer->rch_id; trailer.ticket=strailer->ticket; trailer.handler=item_index(rpc_handlers_map, (item_p)message_get_handler(rmessage)); assert(trailer.handler>=0); message_append_data(rmessage,&trailer,sizeof(trailer_t)); message_set_handler(rmessage,rpc_client_handler); /* Save reply message. */ if (message_get_header_size(rch->reply_message)!= message_get_header_size(rmessage)) { free_message(rch->reply_message); rch->reply_message=new_message(message_get_header_size(rmessage), message_get_data_size(rmessage)); } message_set_header(rch->reply_message,message_get_header(rmessage), message_get_header_size(rmessage)); message_set_data(rch->reply_message,message_get_data(rmessage), message_get_data_size(rmessage)); message_set_handler(rch->reply_message, rpc_client_handler); /* Send message. */ mp_channel_unicast(rch->mpch,trailer.to,rmessage); return 0; } /*==============================================================*/ /* Waits for a reply. If the reply does not arrive within 'timeout' time, sends the request again. Does the timeout twice only. */ /*==============================================================*/ int rpc_wait_reply(rpc_channel_p rch) { trailer_p trailer; /* Timeout reply. If it does not arrive within the required time, resend the request again. */ if (tawait_condition(rch->channel_free,rch->timeout,PO_MICROSEC)<0) { trailer=(trailer_p )(message_get_data(rch->request_message)+ message_get_data_size(rch->request_message)- sizeof(trailer_t)); mp_channel_unicast(rch->mpch,trailer->to,rch->request_message); /* Timeout this rpc again. */ if (tawait_condition(rch->channel_free,rch->timeout,PO_MICROSEC)<0) return -1; } signal_condition(rch->channel_free); return 0; } /*==============================================================*/ /* Registers a handler. */ /*==============================================================*/ int rpc_register_handler(message_handler_p handler) { precondition(initialized); precondition(handler!=NULL); return insert_item(rpc_handlers_map, (item_p)handler); } /*==============================================================*/ /* Unregisters a handler. */ /*==============================================================*/ int rpc_unregister_handler(message_handler_p handler) { precondition(initialized); precondition(handler!=NULL); return remove_item_p(rpc_handlers_map, (item_p)handler); } /*************************************************************************/ /*********************** Static functions ********************************/ /*************************************************************************/ void rpc_server_handler(message_p message) { trailer_p trailer; rpc_channel_p rch; trailer=(trailer_p )(message_get_data(message)+ message_get_data_size(message)- sizeof(trailer_t)); rch=get_item(rpc_channel_map,trailer->rch_id); assert(rch!=NULL); /* Wake up server thread. */ if (message_get_header_size(message)!= message_get_header_size(rch->message)) { free_message(rch->message); rch->message=new_message(message_get_header_size(message), message_get_data_size(message)); } message_set_header(rch->message,message_get_header(message), message_get_header_size(message)); message_set_data(rch->message,message_get_data(message), message_get_data_size(message)); message_set_handler(rch->message, rpc_server_handler); signal_condition(rch->new_request); return; } void rpc_server_thread(char *c, int size) { rpc_channel_p rch; rch=(rpc_channel_p)c; for (;;) { await_condition(rch->new_request); if (rch->message==NULL) { free_condition(rch->new_request); free(rch); thread_exit(); } __rpc_server_handler(rch->message); } } void __rpc_server_handler(message_p message) { trailer_p trailer; rpc_channel_p rch; message_handler_p handler; /* Make sure request has not yet been processed. */ trailer=(trailer_p )(message_get_data(message)+ message_get_data_size(message)- sizeof(trailer_t)); rch=get_item(rpc_channel_map,trailer->rch_id); assert(rch!=NULL); /* If already processed, send reply again without calling user server handler. */ if (trailer->ticket<rch->server_ticket) { trailer=(trailer_p )(message_get_data(rch->reply_message)+ message_get_data_size(rch->reply_message)- sizeof(trailer_t)); mp_channel_unicast(rch->mpch, trailer->to, rch->reply_message); return; } /* If not already processed, call the user server handler. */ /* assert(rch->server_ticket==trailer->ticket); */ rch->server_ticket++; handler=get_item(rpc_handlers_map,trailer->handler); (*handler)(message); return; } void rpc_client_handler(message_p message) { trailer_p trailer; rpc_channel_p rch; message_handler_p handler; /* Make sure reply has not yet been processed. */ trailer=(trailer_p )(message_get_data(message)+ message_get_data_size(message)- sizeof(trailer_t)); rch=get_item(rpc_channel_map,trailer->rch_id); assert(rch!=NULL); /* If already processed, do not call user client handler. */ if (trailer->ticket<rch->client_ticket) return; /* If not already processed, call the user client handler. */ assert(rch->client_ticket==trailer->ticket); rch->client_ticket++; handler=get_item(rpc_handlers_map,trailer->handler); (*handler)(message); /* Signal the end of RPC. */ signal_condition(rch->channel_free); return; }
C
/*T requires: veccuda T*/ #include <petscvec.h> static char help[] = "Tests vecScatter Sequential to Sequential for (CUDA) vectors\n\ -m # : the size of the vectors\n \ -n # : the numer of indices (with n<=m)\n \ -toFirst # : the starting index of the output vector for strided scatters\n \ -toStep # : the step size into the output vector for strided scatters\n \ -fromFirst # : the starting index of the input vector for strided scatters\n\ -fromStep # : the step size into the input vector for strided scatters\n\n"; int main(int argc, char * argv[]) { Vec X,Y; PetscInt m,n,i,n1,n2; PetscInt toFirst,toStep,fromFirst,fromStep; PetscInt *idx,*idy; PetscBool flg; IS toISStrided,fromISStrided,toISGeneral,fromISGeneral; VecScatter vscatSStoSS,vscatSStoSG,vscatSGtoSS,vscatSGtoSG; ScatterMode mode; InsertMode addv; PetscErrorCode ierr; ierr = PetscInitialize(&argc,&argv,0,help);CHKERRQ(ierr); ierr = PetscOptionsGetInt(NULL,NULL,"-m",&m,&flg);CHKERRQ(ierr); if (!flg) m = 100; ierr = PetscOptionsGetInt(NULL,NULL,"-n",&n,&flg);CHKERRQ(ierr); if (!flg) n = 30; ierr = PetscOptionsGetInt(NULL,NULL,"-toFirst",&toFirst,&flg);CHKERRQ(ierr); if (!flg) toFirst = 3; ierr = PetscOptionsGetInt(NULL,NULL,"-toStep",&toStep,&flg);CHKERRQ(ierr); if (!flg) toStep = 3; ierr = PetscOptionsGetInt(NULL,NULL,"-fromFirst",&fromFirst,&flg);CHKERRQ(ierr); if (!flg) fromFirst = 2; ierr = PetscOptionsGetInt(NULL,NULL,"-fromStep",&fromStep,&flg);CHKERRQ(ierr); if (!flg) fromStep = 2; if (n>m) { PetscPrintf(PETSC_COMM_WORLD,"The vector sizes are %d. The number of elements being scattered is %d\n",m,n);CHKERRQ(ierr); PetscPrintf(PETSC_COMM_WORLD,"Adjust the parameters such that m>=n\n");CHKERRQ(ierr); } else if (toFirst+(n-1)*toStep >=m) { PetscPrintf(PETSC_COMM_WORLD,"The vector sizes are %d. The number of elements being scattered is %d\n",m,n);CHKERRQ(ierr); PetscPrintf(PETSC_COMM_WORLD,"For the Strided Scatter, toFirst=%d and toStep=%d.\n",toFirst,toStep);CHKERRQ(ierr); PetscPrintf(PETSC_COMM_WORLD,"This produces an index (toFirst+(n-1)*toStep)>=m\n");CHKERRQ(ierr); PetscPrintf(PETSC_COMM_WORLD,"Adjust the parameterrs accordingly with -m, -n, -toFirst, or -toStep\n");CHKERRQ(ierr); } else if (fromFirst+(n-1)*fromStep>=m) { PetscPrintf(PETSC_COMM_WORLD,"The vector sizes are %d. The number of elements being scattered is %d\n",m,n);CHKERRQ(ierr); PetscPrintf(PETSC_COMM_WORLD,"For the Strided Scatter, fromFirst=%d and fromStep=%d.\n",fromFirst,toStep);CHKERRQ(ierr); PetscPrintf(PETSC_COMM_WORLD,"This produces an index (fromFirst+(n-1)*fromStep)>=m\n");CHKERRQ(ierr); PetscPrintf(PETSC_COMM_WORLD,"Adjust the parameterrs accordingly with -m, -n, -fromFirst, or -fromStep\n");CHKERRQ(ierr); } else { PetscPrintf(PETSC_COMM_WORLD,"m=%d\tn=%d\tfromFirst=%d\tfromStep=%d\ttoFirst=%d\ttoStep=%d\n",m,n,fromFirst,fromStep,toFirst,toStep);CHKERRQ(ierr); PetscPrintf(PETSC_COMM_WORLD,"fromFirst+(n-1)*fromStep=%d\ttoFirst+(n-1)*toStep=%d\n",fromFirst+(n-1)*fromStep,toFirst+(n-1)*toStep);CHKERRQ(ierr); /* Build the vectors */ ierr = VecCreate(PETSC_COMM_WORLD,&Y);CHKERRQ(ierr); ierr = VecSetSizes(Y,m,PETSC_DECIDE);CHKERRQ(ierr); ierr = VecCreate(PETSC_COMM_WORLD,&X);CHKERRQ(ierr); ierr = VecSetSizes(X,m,PETSC_DECIDE);CHKERRQ(ierr); ierr = VecSetFromOptions(Y);CHKERRQ(ierr); ierr = VecSetFromOptions(X);CHKERRQ(ierr); ierr = VecSet(X,2.0);CHKERRQ(ierr); ierr = VecSet(Y,1.0);CHKERRQ(ierr); /* Build the strided index sets */ ierr = ISCreate(PETSC_COMM_WORLD,&toISStrided);CHKERRQ(ierr); ierr = ISCreate(PETSC_COMM_WORLD,&fromISStrided);CHKERRQ(ierr); ierr = ISSetType(toISStrided, ISSTRIDE);CHKERRQ(ierr); ierr = ISSetType(fromISStrided, ISSTRIDE);CHKERRQ(ierr); ierr = ISStrideSetStride(fromISStrided,n,fromFirst,fromStep);CHKERRQ(ierr); ierr = ISStrideSetStride(toISStrided,n,toFirst,toStep);CHKERRQ(ierr); /* Build the general index sets */ ierr = PetscMalloc1(n,&idx);CHKERRQ(ierr); ierr = PetscMalloc1(n,&idy);CHKERRQ(ierr); for (i=0; i<n; i++) { idx[i] = i % m; idy[i] = (i+m) % m; } n1 = n; n2 = n; ierr = PetscSortRemoveDupsInt(&n1,idx);CHKERRQ(ierr); ierr = PetscSortRemoveDupsInt(&n2,idy);CHKERRQ(ierr); ierr = ISCreateGeneral(PETSC_COMM_WORLD,n1,idx,PETSC_COPY_VALUES,&toISGeneral);CHKERRQ(ierr); ierr = ISCreateGeneral(PETSC_COMM_WORLD,n2,idy,PETSC_COPY_VALUES,&fromISGeneral);CHKERRQ(ierr); /* set the mode and the insert/add parameter */ mode = SCATTER_FORWARD; addv = ADD_VALUES; /* VecScatter : Seq Strided to Seq Strided */ ierr = VecScatterCreate(X,fromISStrided,Y,toISStrided,&vscatSStoSS);CHKERRQ(ierr); ierr = VecScatterBegin(vscatSStoSS,X,Y,addv,mode);CHKERRQ(ierr); ierr = VecScatterEnd(vscatSStoSS,X,Y,addv,mode);CHKERRQ(ierr); ierr = VecScatterDestroy(&vscatSStoSS);CHKERRQ(ierr); /* VecScatter : Seq General to Seq Strided */ ierr = VecScatterCreate(Y,fromISGeneral,X,toISStrided,&vscatSGtoSS);CHKERRQ(ierr); ierr = VecScatterBegin(vscatSGtoSS,Y,X,addv,mode);CHKERRQ(ierr); ierr = VecScatterEnd(vscatSGtoSS,Y,X,addv,mode);CHKERRQ(ierr); ierr = VecScatterDestroy(&vscatSGtoSS);CHKERRQ(ierr); /* VecScatter : Seq General to Seq General */ ierr = VecScatterCreate(X,fromISGeneral,Y,toISGeneral,&vscatSGtoSG);CHKERRQ(ierr); ierr = VecScatterBegin(vscatSGtoSG,X,Y,addv,mode);CHKERRQ(ierr); ierr = VecScatterEnd(vscatSGtoSG,X,Y,addv,mode);CHKERRQ(ierr); ierr = VecScatterDestroy(&vscatSGtoSG);CHKERRQ(ierr); /* VecScatter : Seq Strided to Seq General */ ierr = VecScatterCreate(Y,fromISStrided,X,toISGeneral,&vscatSStoSG);CHKERRQ(ierr); ierr = VecScatterBegin(vscatSStoSG,Y,X,addv,mode);CHKERRQ(ierr); ierr = VecScatterEnd(vscatSStoSG,Y,X,addv,mode);CHKERRQ(ierr); ierr = VecScatterDestroy(&vscatSStoSG);CHKERRQ(ierr); /* view the results */ ierr = VecView(Y,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); /* Cleanup */ ierr = VecDestroy(&X);CHKERRQ(ierr); ierr = VecDestroy(&Y);CHKERRQ(ierr); ierr = ISDestroy(&toISStrided);CHKERRQ(ierr); ierr = ISDestroy(&fromISStrided);CHKERRQ(ierr); ierr = ISDestroy(&toISGeneral);CHKERRQ(ierr); ierr = ISDestroy(&fromISGeneral);CHKERRQ(ierr); ierr = PetscFree(idx);CHKERRQ(ierr); ierr = PetscFree(idy);CHKERRQ(ierr); } ierr = PetscFinalize(); return ierr; } /*TEST test: suffix: cuda args: -vec_type cuda requires: veccuda TEST*/
C
/* Octubre 14 de 2021 Aaron Sarmiento Programa en C que evalua cual es el mayor entre dos numeros o indica si los numeros son iguales */ #include<stdio.h> int main(){ //declaración inicial de las variables int numero1, numero2; //se pide introducir los números que desea evaluar printf("**************************************************\n"); printf("********************BIENVENIDO******************** \n"); printf("Por favor ingrese el primer numero\n"); scanf("%d", &numero1); printf("Por favor ingrese el segundo numero\n"); scanf("%d", &numero2); /*se realizan los calculos Se hace uso de la estructura condicional if la cual evalua si el número 1 es mayor al número 2 se repite la estructura condicional para evaluar si el número 2 es mayor al número 1 en caso de que ninguna de las dos condiciones se cumplan entrará al else y esto significa que los números son iguales */ if(numero1>numero2){ printf("El numero %d es mayor que el numero %d \n", numero1, numero2); } else if(numero2>numero1){ printf("El numero %d es mayor que el numero %d \n", numero2, numero1); } else{ printf("Los numeros son iguales\n"); } return 0; }
C
#include <stdio.h> int main() { int a,b; float c,d; long e,f; unsigned int u,v; char c1,c2; scanf("%d,%d",&a,&b); scanf("%f,%f",&c,&d); scanf("%d,%d",&e,&f); scanf("%o,%o",&u,&v); getchar(); scanf("%c,%C",&c1,&c2); printf("\n"); printf("a=%7d,b=%7d\n",a,b); printf("c=%10.2f,b=%10.2f\n",c,d); printf("e=%17ld,f=%17ld\n",e,f); printf("u=%v,v=%u\r\n",u,v); printf("c1=%c,c2=%c\n",c1,c2); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gderenzi <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/04/06 18:08:59 by gderenzi #+# #+# */ /* Updated: 2017/04/27 13:21:20 by gderenzi ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" int main(int argc, char **argv) { t_win *screen; t_map *map; if (argc == 2) { if (!(screen = (t_win *)malloc(sizeof(t_win)))) fdf_malloc_error(); printf("Memory allocated. Parsing map...\n"); map = ft_parse_map(argv[1], 0); if (map->len == 0 || map->lines[0]->len == 0) fdf_map_error(); printf("Map created. Choosing color...\n"); screen->map = map; get_center(screen); screen->color = choose_color(); screen->cnum = 0; printf("Color chosen. Displaying window...\n"); draw_win("42 FDF", WIN_W, WIN_H, screen); printf("Window displayed. Adapting map...\n"); adapt_map(screen); printf("Map adapted. If it fails after this, youre screwed...\n"); mlx_expose_hook(screen->win, draw_reload, screen); printf("Running draw_reload...\n"); mlx_hook(screen->win, 2, 3, key_hook, screen); printf("Running key_hook...\n"); mlx_loop(screen->mlx); } else fdf_arg_error(); return (0); }
C
#ifndef _T_SYSLOG_H_ #define _T_SYSLOG_H_ #include <stdarg.h> #include <stdio.h> #define LOG_ERROR 1 #define LOG_WARNING 1 #define LOG_NOTICE 1 static inline void syslog(int flag, const char* fmt, ...) { va_list arg_ptr; static char format[1024]; sprintf(format, "%s\n", fmt); va_start(arg_ptr, fmt); vprintf(format, arg_ptr); va_end(arg_ptr); return; } #endif
C
// // Created by Pedro on 01-06-2019. // #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> ///////////////////////////// PARTE A ///////////////////////////////////////////////////////////////////// // Questao 1 void strrev (char s[]) { int i, j; char guarda; for (i = 0; s[i]; i++) ; i--; for (j = 0; j < i; j++, i--) { guarda = s[j]; s[j] = s[i]; s[i] = guarda; } } // Questao 2 int remRep (char texto []) { int i, j; for (i = 0; texto[i]; i++) if (texto[i] == texto[i+1]) { for (j = i+1; texto[j]; j++) texto[j] = texto[j+1]; i--; } return i; } // Questao 3 void merge (int r [], int a[], int b[], int na, int nb){ int i, j, k; i = j = k = 0; while (i < na && j < nb) if (a[i] > b[j]) r[k++] = b[j++]; else r[k++] = a[i++]; while (j < nb) r[k++] = b[j++]; while (i < na) r[k++] = a[i++]; } // Questao 4 int menor (ABin a, int x) { int res = 1; if (a) res = a->valor > x && menor (a->esq, x) && menor (a->dir, x); return res; } int maior (ABin a, int x) { int res = 1; if (a) res = a->valor < x && maior (a->esq, x) && maior (a->dir, x); return res; } int deProcura (ABin a) { int res = 1; if (a) res = maior (a->esq, a->valor) && menor (a->dir, a->valor) && deProcura (a->esq) && deProcura (a->dir); return res; } // QUESTAO 5 int pruneAB (ABin *a, int l) { int r = 0; if (*a) { r += pruneAB(&(*a)->esq, l-1) + pruneAB(&(*a)->dir, l-1); if (l <= 0) { r++; free(*a); *a = NULL; } } return r; } ///////////////////////////// PARTE B ///////////////////////////////////////////////////////////////////// typedef struct digito { unsigned char val; struct digito *prox; }*Num; // Pergunta 1 a Num fromInt (unsigned int i) { int valor, decresce = i, conta = 0; Num nova = NULL, aux = NULL; if (i) { while (decresce) { decresce/=10; conta++; } decresce = pow(10, conta-1); while (i) { valor = i; while (valor > 9) valor/=10; nova = malloc(sizeof(struct digito)); nova->val = valor; nova->prox = aux; aux = nova; i -= valor * decresce; decresce /= 10; if (i < decresce) { nova = malloc(sizeof(struct digito)); nova->val = 0; nova->prox = aux; aux = nova; decresce /=10; } } } return nova; } // Pergunta 1 b unsigned int toInt(Num n) { int multiplica = 1, soma = 0; while (n) { soma += multiplica * n->val; n = n->prox; multiplica *= 10; } return soma; } // Pergunta 2 Num addNum (Num a, Num b) { Num nova = NULL, aux; int carry = 0, soma = 0; while (a && b) { if (!nova) nova = aux = malloc(sizeof(struct digito)); else aux = aux->prox = malloc(sizeof(struct digito)); soma = a->val + b->val + carry; carry = 0; if (soma > 9) { carry = 1; soma-=10; } aux->val = soma; aux->prox = NULL; a = a->prox; b = b->prox; } while (a) { if (!nova) nova = aux = malloc(sizeof(struct digito)); else aux = aux->prox = malloc(sizeof(struct digito)); aux->val = a->val + carry; aux->prox = NULL; carry = 0; a = a->prox; } while (b) { if (!nova) nova = aux = malloc(sizeof(struct digito)); else aux = aux->prox = malloc(sizeof(struct digito)); aux->val = b->val + carry; carry = 0; aux->prox = NULL; b = b->prox; } if (carry) { if (!nova) nova = aux = malloc(sizeof(struct digito)); else aux = aux->prox = malloc(sizeof(struct digito)); aux->val = 1; aux->prox = NULL; } return nova; } // Pergunta 3 Num mulDig (unsigned char dig, Num a) { Num nova = fromInt (dig * toInt(a)); return nova; } // Pergunta 4 Num mulNum (Num a, Num b) { Num nova = fromInt ( toInt(a) * toInt(b)); return nova; }
C
#include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <errno.h> int main(void) { pid_t child; int status,retval; child = fork(); if(child<0){ perror("fork"); exit(EXIT_FAILURE); } else if(child == 0){ printf("i am child process\n"); sleep(1000); exit(EXIT_SUCCESS); } else{ printf("i am parent process\n"); if((waitpid(child,&status,WNOHANG))==0){ printf("i am parent process 1 \n"); retval = kill(child,SIGKILL); if(retval){ puts("kill failed\n"); perror("kill"); waitpid(child,&status,0); }else{ printf("%d killed\n",child); } } } exit(EXIT_SUCCESS); }
C
#include<stdio.h> #include<math.h> int main(void) { int n, i1, j1; printf("Please input n:"); scanf("%d", &n); for (i1 = 0; i1 < 2 * n - 1; i1++) { for (j1 = 0; j1 < 2 * n - 1; j1++) { if (j1 == i1) { printf("@"); } else if (j1 + i1 - 2 * (n - 1) == 0) { printf("@"); } else { printf(" "); } } printf("\n"); } return 0; }
C
#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node *left; struct Node *right; }; struct Node *CreateNode(int data) { struct Node *n; //creating the node pointer n = (struct Node *)malloc(sizeof(struct Node)); //Allocating the memory in the heap n->data = data; //Setting the data n->left = NULL; //Setting the left and right children to NULL n->right = NULL; //Setting the left and right children to NULL return n; //Finally returning hte created node } struct Node *searchIter(struct Node *root, int key) { while (root != NULL) { if (key == root->data) { return root; } else if (key < root->data) { root = root->left; } else { root = root->right; } } return NULL; } void insert(struct Node *root, int key) { struct Node *prev = NULL; while (root != NULL) { prev = root; if (key == root->data) { printf("Cannot insert %d, already in BST", key); return; } else if (key < root->data) { root = root->left; } else { root = root->right; } } struct Node *new = CreateNode(key); if (key < prev->data) { prev->left = new; } else { prev->right = new; } } int main() { //Constructing the root node - Using function(recommended) struct Node *p = CreateNode(5); struct Node *p1 = CreateNode(3); struct Node *p2 = CreateNode(6); struct Node *p3 = CreateNode(1); struct Node *p4 = CreateNode(4); //linking the root node with left and right children p->left = p1; p->right = p2; p1->left = p3; p1->right = p4; insert(p, 20); printf("%d", p->right->right->data); return 0; }
C
#include<stdio.h> #define bool int bool ispower(int n)] { if(n==0) return 0; while(n!=1) { if(n%2==0) { return 0; n=n/2; } return 1; } int main() { ispower(31)?printf("yes\n"):printf("no\n"); ispower(64)?printf("yes\n"):printf("no\n"); return 0; }
C
# include <stdio.h> # include <stdlib.h> # include <stdbool.h> # include <argp.h> bool is_valid_url(char *url) { return false; } bool is_url_in_db(char *url) { return false; } int add_url(char *url){ return EXIT_FAILURE; } // Notice that there is no visible call to this function. // This is because `parse_opt` is a __callback function__. // Instead `Argp` is calling this function on our behalf when it processes // the `argc` and `argv` that we pass to `argp_parse`. // `Argp` repeatedly calls this function for eveyr option and argument // on the command line. // // The signature for the callback is defined it accepts is defined by `Argp` // Function Arguments: // key: An option's unique key, which can be the short option. // We can also use non-character keys. // arg: The option argument's value, as a string. // state: This keeps Argp's state as we iterate the callback function static int parse_opt (int key, char *arg, struct argp_state *state) { switch (key) { case 'a': { if (!is_valid_url(arg)){ argp_failure(state, 1, 0, "invalid URL"); } if (is_url_in_db(arg)) { argp_failure(state, 1, 0, "URL already added"); } // TODO: If it already exists, don't add it again printf("selected %s", arg); break; } } return EXIT_SUCCESS; // EXIT_FAILURE will stop Argp and return FAILURE } int main(int argc, char **argv) { struct argp_option options[] = { // Field options: // 1st -> long // 2nd -> short // 3rd -> name of the argument to this option // 4th -> A set of flags that change how our option works // 5th -> "Description of the option to be shown on help" { "add", 'a', "URL", 0, "Add an URL that you have downloaded from" }, { "check", 'c', "URL", 0 , "check if you have aleardy downloaded from this URL" }, { 0 } }; // This is the most important struct here // options: All of our cli options // parse_opt: A pointer to a function that Argp will call to assist in // parsing our options // // We can just use the name of the function to assign the // pointer to where the function is in memory. This is similar // to how the name of an array is a pointer to the array's first // element. struct argp argp = {options, parse_opt}; return argp_parse(&argp, argc, argv, 0, 0, 0); /* return EXIT_SUCCESS; */ }
C
/* * File: color.c * Brief: Print colorful message to console * Created on 18.11.2019 * (c) MIPT 2019 */ #include <Windows.h> #include <stdio.h> #include "color.h" /* This structure is not in header file, because it won't be shared */ typedef struct _CONSOLE_COLOR { HANDLE hConsole; WORD saved_attributes; } CONSOLE_COLOR; CONSOLE_COLOR g_console; void init_color() { g_console.hConsole = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO info; GetConsoleScreenBufferInfo(g_console.hConsole, &info); g_console.saved_attributes = info.wAttributes; } void deinit_color() { CloseHandle(g_console.hConsole); } void print_color(COLOR color, char *message) { switch (color) { case COLOR_GREEN: color = FOREGROUND_GREEN; break; case COLOR_RED: color = FOREGROUND_RED; break; default: color = FOREGROUND_BLUE; break; } SetConsoleTextAttribute(g_console.hConsole, color); printf(message); SetConsoleTextAttribute(g_console.hConsole, g_console.saved_attributes); }
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 */ /* Type definitions */ typedef int ULONG ; typedef int PVOID ; typedef int PBYTE ; /* Variables and functions */ int MEM_COMMIT ; int MEM_RESERVE ; int /*<<< orphan*/ PAGE_NOACCESS ; int /*<<< orphan*/ PAGE_READWRITE ; int PAGE_SIZE ; int VirtualAlloc (int /*<<< orphan*/ *,int,int,int /*<<< orphan*/ ) ; int /*<<< orphan*/ VirtualProtect (int,int,int /*<<< orphan*/ ,int*) ; PVOID AllocBufferOnPageBoundary(ULONG Size) { ULONG GuardBufSize; ULONG ProtBits; PBYTE GuardBuf; // Round size requested up to the next multiple of PAGE_SIZE GuardBufSize = (Size + (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1); // Add one page to be the guard page GuardBufSize = GuardBufSize + PAGE_SIZE; // Map this anonymous memory GuardBuf = VirtualAlloc(NULL, GuardBufSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); // Make the final page NOACCESS VirtualProtect(GuardBuf + GuardBufSize - PAGE_SIZE, PAGE_SIZE, PAGE_NOACCESS, &ProtBits); // Calculate where pointer should be, so that touching Buffer[Size] AVs. return GuardBuf + GuardBufSize - PAGE_SIZE - Size; }
C
/** * @file piano.h * @author Phi Luu * @date April 22, 2016 * * @brief UTAustinX: UT.6.03x Embedded Systems - Shape the World * Lab 13: Digital-Analog Conversion * * @section DESCRIPTION * * Takes inputs from switches and decides what note to output to the buzzer. * Port E, bits 3-0 have 4 piano keys. */ /** * Global variable which is accessable from other functions * store the index of the corresponding input */ extern unsigned short freq_index; /** * Initializes piano key inputs. */ void InitPiano(void); /** * Reads the input from PE3-PE0. * * @notes Returns to freq_index with values from 0 to 4 depending on key pressed * 0 if key 0 = note C = PE0 is pressed * 0 if key 0 = note C = PE0 is pressed * 1 if key 1 = note D = PE1 is pressed * 2 if key 2 = note E = PE2 is pressed * 3 if key 3 = note G = PE3 is pressed */ void PianoIn(void);
C
#include "Quantizer.h" #include <stdio.h> #define MAXCOLOR 256 #define RED 2 #define GREEN 1 #define BLUE 0 struct box { int r0; /* min value, exclusive */ int r1; /* max value, inclusive */ int g0; int g1; int b0; int b1; int vol; }; /* Histogram is in elements 1..HISTSIZE along each axis, * element 0 is for base or marginal value * NB: these must start out 0! */ float m2[33][33][33]; long int wt[33][33][33], mr[33][33][33], mg[33][33][33], mb[33][33][33]; unsigned char *Ir, *Ig, *Ib; int size; /*image size*/ int K; /*color look-up table size*/ unsigned short int *Qadd; void Hist3d(vwt, vmr, vmg, vmb, m2) /* build 3-D color histogram of counts, r/g/b, c^2 */ long int *vwt, *vmr, *vmg, *vmb; float *m2; { register int ind, r, g, b; int inr, ing, inb, table[256]; register long int i; for (i = 0; i<256; ++i) table[i] = i*i; Qadd = (unsigned short int *)malloc(sizeof(short int)*size); if (Qadd == NULL) { printf("Not enough space\n"); exit(1); } for (i = 0; i<size; ++i) { r = Ir[i]; g = Ig[i]; b = Ib[i]; inr = (r >> 3) + 1; ing = (g >> 3) + 1; inb = (b >> 3) + 1; Qadd[i] = ind = (inr << 10) + (inr << 6) + inr + (ing << 5) + ing + inb; /*[inr][ing][inb]*/ ++vwt[ind]; vmr[ind] += r; vmg[ind] += g; vmb[ind] += b; m2[ind] += (float)(table[r] + table[g] + table[b]); } } /* At conclusion of the histogram step, we can interpret * wt[r][g][b] = sum over voxel of P(c) * mr[r][g][b] = sum over voxel of r*P(c) , similarly for mg, mb * m2[r][g][b] = sum over voxel of c^2*P(c) * Actually each of these should be divided by 'size' to give the usual * interpretation of P() as ranging from 0 to 1, but we needn't do that here. */ /* We now convert histogram into moments so that we can rapidly calculate * the sums of the above quantities over any desired box. */ void M3d(vwt, vmr, vmg, vmb, m2) /* compute cumulative moments. */ long int *vwt, *vmr, *vmg, *vmb; float *m2; { register unsigned short int ind1, ind2; register unsigned char i, r, g, b; long int line, line_r, line_g, line_b, area[33], area_r[33], area_g[33], area_b[33]; float line2, area2[33]; for (r = 1; r <= 32; ++r) { for (i = 0; i <= 32; ++i) area2[i] = area[i] = area_r[i] = area_g[i] = area_b[i] = 0; for (g = 1; g <= 32; ++g) { line2 = line = line_r = line_g = line_b = 0; for (b = 1; b <= 32; ++b) { ind1 = (r << 10) + (r << 6) + r + (g << 5) + g + b; /* [r][g][b] */ line += vwt[ind1]; line_r += vmr[ind1]; line_g += vmg[ind1]; line_b += vmb[ind1]; line2 += m2[ind1]; area[b] += line; area_r[b] += line_r; area_g[b] += line_g; area_b[b] += line_b; area2[b] += line2; ind2 = ind1 - 1089; /* [r-1][g][b] */ vwt[ind1] = vwt[ind2] + area[b]; vmr[ind1] = vmr[ind2] + area_r[b]; vmg[ind1] = vmg[ind2] + area_g[b]; vmb[ind1] = vmb[ind2] + area_b[b]; m2[ind1] = m2[ind2] + area2[b]; } } } } long int Vol(cube, mmt) /* Compute sum over a box of any given statistic */ struct box *cube; long int mmt[33][33][33]; { return(mmt[cube->r1][cube->g1][cube->b1] - mmt[cube->r1][cube->g1][cube->b0] - mmt[cube->r1][cube->g0][cube->b1] + mmt[cube->r1][cube->g0][cube->b0] - mmt[cube->r0][cube->g1][cube->b1] + mmt[cube->r0][cube->g1][cube->b0] + mmt[cube->r0][cube->g0][cube->b1] - mmt[cube->r0][cube->g0][cube->b0]); } /* The next two routines allow a slightly more efficient calculation * of Vol() for a proposed subbox of a given box. The sum of Top() * and Bottom() is the Vol() of a subbox split in the given direction * and with the specified new upper bound. */ long int Bottom(cube, dir, mmt) /* Compute part of Vol(cube, mmt) that doesn't depend on r1, g1, or b1 */ /* (depending on dir) */ struct box *cube; unsigned char dir; long int mmt[33][33][33]; { switch (dir) { case RED: return(-mmt[cube->r0][cube->g1][cube->b1] + mmt[cube->r0][cube->g1][cube->b0] + mmt[cube->r0][cube->g0][cube->b1] - mmt[cube->r0][cube->g0][cube->b0]); break; case GREEN: return(-mmt[cube->r1][cube->g0][cube->b1] + mmt[cube->r1][cube->g0][cube->b0] + mmt[cube->r0][cube->g0][cube->b1] - mmt[cube->r0][cube->g0][cube->b0]); break; case BLUE: return(-mmt[cube->r1][cube->g1][cube->b0] + mmt[cube->r1][cube->g0][cube->b0] + mmt[cube->r0][cube->g1][cube->b0] - mmt[cube->r0][cube->g0][cube->b0]); break; } } long int Top(cube, dir, pos, mmt) /* Compute remainder of Vol(cube, mmt), substituting pos for */ /* r1, g1, or b1 (depending on dir) */ struct box *cube; unsigned char dir; int pos; long int mmt[33][33][33]; { switch (dir) { case RED: return(mmt[pos][cube->g1][cube->b1] - mmt[pos][cube->g1][cube->b0] - mmt[pos][cube->g0][cube->b1] + mmt[pos][cube->g0][cube->b0]); break; case GREEN: return(mmt[cube->r1][pos][cube->b1] - mmt[cube->r1][pos][cube->b0] - mmt[cube->r0][pos][cube->b1] + mmt[cube->r0][pos][cube->b0]); break; case BLUE: return(mmt[cube->r1][cube->g1][pos] - mmt[cube->r1][cube->g0][pos] - mmt[cube->r0][cube->g1][pos] + mmt[cube->r0][cube->g0][pos]); break; } } float Var(cube) /* Compute the weighted variance of a box */ /* NB: as with the raw statistics, this is really the variance * size */ struct box *cube; { float dr, dg, db, xx; dr = Vol(cube, mr); dg = Vol(cube, mg); db = Vol(cube, mb); xx = m2[cube->r1][cube->g1][cube->b1] - m2[cube->r1][cube->g1][cube->b0] - m2[cube->r1][cube->g0][cube->b1] + m2[cube->r1][cube->g0][cube->b0] - m2[cube->r0][cube->g1][cube->b1] + m2[cube->r0][cube->g1][cube->b0] + m2[cube->r0][cube->g0][cube->b1] - m2[cube->r0][cube->g0][cube->b0]; return(xx - (dr*dr + dg*dg + db*db) / (float)Vol(cube, wt)); } /* We want to minimize the sum of the variances of two subboxes. * The sum(c^2) terms can be ignored since their sum over both subboxes * is the same (the sum for the whole box) no matter where we split. * The remaining terms have a minus sign in the variance formula, * so we drop the minus sign and MAXIMIZE the sum of the two terms. */ float Maximize(cube, dir, first, last, cut, whole_r, whole_g, whole_b, whole_w) struct box *cube; unsigned char dir; int first, last, *cut; long int whole_r, whole_g, whole_b, whole_w; { register long int half_r, half_g, half_b, half_w; long int base_r, base_g, base_b, base_w; register int i; register float temp, max; base_r = Bottom(cube, dir, mr); base_g = Bottom(cube, dir, mg); base_b = Bottom(cube, dir, mb); base_w = Bottom(cube, dir, wt); max = 0.0; *cut = -1; for (i = first; i<last; ++i) { half_r = base_r + Top(cube, dir, i, mr); half_g = base_g + Top(cube, dir, i, mg); half_b = base_b + Top(cube, dir, i, mb); half_w = base_w + Top(cube, dir, i, wt); /* now half_x is sum over lower half of box, if split at i */ if (half_w == 0) { /* subbox could be empty of pixels! */ continue; /* never split into an empty box */ } else temp = ((float)half_r*half_r + (float)half_g*half_g + (float)half_b*half_b) / half_w; half_r = whole_r - half_r; half_g = whole_g - half_g; half_b = whole_b - half_b; half_w = whole_w - half_w; if (half_w == 0) { /* subbox could be empty of pixels! */ continue; /* never split into an empty box */ } else temp += ((float)half_r*half_r + (float)half_g*half_g + (float)half_b*half_b) / half_w; if (temp > max) { max = temp; *cut = i; } } return(max); } int Cut(set1, set2) struct box *set1, *set2; { unsigned char dir; int cutr, cutg, cutb; float maxr, maxg, maxb; long int whole_r, whole_g, whole_b, whole_w; whole_r = Vol(set1, mr); whole_g = Vol(set1, mg); whole_b = Vol(set1, mb); whole_w = Vol(set1, wt); maxr = Maximize(set1, RED, set1->r0 + 1, set1->r1, &cutr, whole_r, whole_g, whole_b, whole_w); maxg = Maximize(set1, GREEN, set1->g0 + 1, set1->g1, &cutg, whole_r, whole_g, whole_b, whole_w); maxb = Maximize(set1, BLUE, set1->b0 + 1, set1->b1, &cutb, whole_r, whole_g, whole_b, whole_w); if ((maxr >= maxg) && (maxr >= maxb)) { dir = RED; if (cutr < 0) return 0; /* can't split the box */ } else if ((maxg >= maxr) && (maxg >= maxb)) dir = GREEN; else dir = BLUE; set2->r1 = set1->r1; set2->g1 = set1->g1; set2->b1 = set1->b1; switch (dir) { case RED: set2->r0 = set1->r1 = cutr; set2->g0 = set1->g0; set2->b0 = set1->b0; break; case GREEN: set2->g0 = set1->g1 = cutg; set2->r0 = set1->r0; set2->b0 = set1->b0; break; case BLUE: set2->b0 = set1->b1 = cutb; set2->r0 = set1->r0; set2->g0 = set1->g0; break; } set1->vol = (set1->r1 - set1->r0)*(set1->g1 - set1->g0)*(set1->b1 - set1->b0); set2->vol = (set2->r1 - set2->r0)*(set2->g1 - set2->g0)*(set2->b1 - set2->b0); return 1; } void Mark(cube, label, tag) struct box *cube; int label; unsigned char *tag; { register int r, g, b; for (r = cube->r0 + 1; r <= cube->r1; ++r) for (g = cube->g0 + 1; g <= cube->g1; ++g) for (b = cube->b0 + 1; b <= cube->b1; ++b) tag[(r << 10) + (r << 6) + r + (g << 5) + g + b] = label; } main() { struct box cube[MAXCOLOR]; unsigned char *tag; unsigned char lut_r[MAXCOLOR], lut_g[MAXCOLOR], lut_b[MAXCOLOR]; int next; register long int i, weight; register int k; float vv[MAXCOLOR], temp; /* input R,G,B components into Ir, Ig, Ib; set size to width*height */ printf("no. of colors:\n"); scanf("%d", &K); Hist3d(wt, mr, mg, mb, m2); printf("Histogram done\n"); free(Ig); free(Ib); free(Ir); M3d(wt, mr, mg, mb, m2); printf("Moments done\n"); cube[0].r0 = cube[0].g0 = cube[0].b0 = 0; cube[0].r1 = cube[0].g1 = cube[0].b1 = 32; next = 0; for (i = 1; i<K; ++i) { if (Cut(&cube[next], &cube[i])) { /* volume test ensures we won't try to cut one-cell box */ vv[next] = (cube[next].vol>1) ? Var(&cube[next]) : 0.0; vv[i] = (cube[i].vol>1) ? Var(&cube[i]) : 0.0; } else { vv[next] = 0.0; /* don't try to split this box again */ i--; /* didn't create box i */ } next = 0; temp = vv[0]; for (k = 1; k <= i; ++k) if (vv[k] > temp) { temp = vv[k]; next = k; } if (temp <= 0.0) { K = i + 1; fprintf(stderr, "Only got %d boxes\n", K); break; } } printf("Partition done\n"); /* the space for array m2 can be freed now */ tag = (unsigned char *)malloc(33 * 33 * 33); if (tag == NULL) { printf("Not enough space\n"); exit(1); } for (k = 0; k<K; ++k) { Mark(&cube[k], k, tag); weight = Vol(&cube[k], wt); if (weight) { lut_r[k] = Vol(&cube[k], mr) / weight; lut_g[k] = Vol(&cube[k], mg) / weight; lut_b[k] = Vol(&cube[k], mb) / weight; } else { fprintf(stderr, "bogus box %d\n", k); lut_r[k] = lut_g[k] = lut_b[k] = 0; } } for (i = 0; i<size; ++i) Qadd[i] = tag[Qadd[i]]; /* output lut_r, lut_g, lut_b as color look-up table contents, Qadd as the quantized image (array of table addresses). */ }
C
#include <stdio.h> int main(){ long double a, koma; long long int integer; scanf("%llf", &a); integer=(int)a; koma=a-integer; printf("%lld %.5llf\n", integer, a); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/wait.h> #include <fcntl.h> #include <sys/types.h> int main() { int data_processed; int file_pipes[2]; int status; int fd; const char some_data[]="123"; char buffer[BUFSIZ+1]; pid_t fork_result; memset(buffer,'\0',sizeof(buffer)); fd =open("./test.txt",O_RDONLY,0666); if(pipe(file_pipes)==0) { fork_result=fork(); if(fork_result==-1) { fprintf(stderr,"Fork failure"); exit(EXIT_FAILURE); } if(fork_result==0) { data_processed=read(fd,buffer,10); buffer[data_processed]='\0'; printf("Child : %s\n",buffer); sprintf(buffer,"%d",file_pipes[0]); execl("pipe4","pipe4",buffer,(char*)0); exit(EXIT_FAILURE); } else { data_processed=read(fd,buffer,10); buffer[data_processed]='\0'; printf("Parents : %s\n",buffer); data_processed=write(file_pipes[1],some_data,strlen(some_data)); printf("%d - wrote %d bytes\n",getpid(),data_processed); } } wait(&status); close(file_pipes[0]); close(file_pipes[1]); exit(EXIT_SUCCESS); }
C
/* ** send.c for send in /home/tekm/tek2/PSU_2016_myirc ** ** Made by leroy_0 ** Login <maxime.leroy@epitech.eu> ** ** Started on Wed May 24 16:21:47 2017 leroy_0 ** Last update Fri Jun 9 16:11:35 2017 yan */ #include <string.h> #include "myirc.h" bool send_cmd(char **cmd, t_connect *client) { int x; x = 0; while (cmd && cmd[x]) { if ((send(client->fd, cmd[x], strlen(cmd[x]), 0)) == -1 || (send(client->fd , " ", 1, 0)) == -1) return (false); x++; } if (send(client->fd, "\r\n", 2, 0) == -1) return (false); return (true); }
C
#include<stdio.h> #include<stdlib.h> int main() { int **p=NULL; int r,c,i,j; printf("输入行和列"); scanf("%d%d",&r,&c); p=(int**)malloc(r*sizeof(int*)); if(NULL==p) { printf("p:malloc error"); exit(0); } for(i=0;i<r;i++) { *(p+i)=(int*)malloc(c*sizeof(int)); if(NULL==*(p+i)) { printf("p+i:malloc error"); exit(0); } } for(i=0;i<r;i++) { for(j=0;j<c;j++) { scanf("%d",*(p+i)+j); **p=**p<*(*(p+i)+j)?**p:*(*(p+i)+j); } } **p=9999999999; for(i=0;i<r;i++) { for(j=0;j<c;j++) { **p=**p<*(*(p+i)+j)?**p:*(*(p+i)+j); } } printf("第二小的数为:%d", **p); return 0; }
C
/* * ship.h - Space ship implementation * * Authors: Rafael Roquetto * Nicoli Gavassa */ #ifndef SHIP_H #define SHIP_H #include "beam.h" #include "list.h" #include "vector2d.h" enum { RED, GREEN, BLUE, RGB }; struct ship { int x; int y; int beam_count; int can_pulse; int lives; float angle; float speed; float accel; float radius; float color[RGB]; struct vector2d dir; struct list *beam_list; struct list *pulse_list; }; /* returns a new ship * at position (x, y) */ struct ship *ship_new(int x, int y); /* destroy the ship and releases * any resources to it associated */ void ship_destroy(struct ship *s); /* initializes the ship pointed by s * at the position x, y */ void ship_init(struct ship *s, int x, int y); /* sets texture blend color */ void ship_set_color(struct ship *s, float r, float g, float b); /* draws the ship to the screen buffer */ void ship_draw(const struct ship *s); /* moves the ship one (as long as accel > 0) * step forward */ void ship_move_forward(struct ship *s); /* rotates the ship clockwise */ void ship_rotate_cw(struct ship *s); /* rotates the ship counterclockwise */ void ship_rotate_countercw(struct ship *s); /* update the ship state */ void ship_update(struct ship *s); /* fires the ship front beam */ void ship_fire_front(struct ship *s); /* accelerates the ship */ void ship_throttle(struct ship *s); /* breaks and reverses the ship */ void ship_break_and_reverse(struct ship *s); /* emit a pulse */ void ship_pulse(struct ship *s); /* respawn the ship at a random * position */ void ship_respawn(struct ship *s); /* update ships 'a' supposing it is colliding * with ship 'b' */ void ship_collide(struct ship *a, struct ship *b); /* set a new direction angle for the ship */ void ship_set_direction(struct ship *a, float direction); /* returns 1 if ship is able to emit a pulse * returns 0 otherwise */ int ship_can_pulse(const struct ship *s); /* returns a list of beams originated * from the ship pointed by s */ struct list * ship_get_beam_list(const struct ship *s); /* * returns ship lives */ int ship_get_lives(const struct ship *s); /* ship size */ #define SHIP_WIDTH 25.f #define SHIP_HEIGHT 10.f #endif /* SHIP_H */
C
/********************************************************************************* * Copyright 2019 Huawei Technologies Co.,Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of the * License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. ********************************************************************************** */ #include "securec.h" #include "securecutil.h" /******************************************************************************* * <NAME> * wmemcpy_s * * <SYNOPSIS> * errno_t wmemcpy_s(wchar_t* dest, size_t destMax, const wchar_t* src, size_t count); * * <FUNCTION DESCRIPTION> * wmemcpy_s copies count wide character(two bytes) from src to dest. * * <INPUT PARAMETERS> * dest new buffer. * destMax Size of the destination buffer. * src Buffer to copy from. * count Number of characters to copy. * * <OUTPUT PARAMETERS> * dest buffer is uptdated. * * <RETURN VALUE> * 0 Success * EINVAL dest == NULL or src == NULL * ERANGE count > destMax or destMax > SECUREC_WCHAR_MEM_MAX_LEN * or destMax == 0 * EOVERLAP_AND_RESET dest buffer and source buffer are overlapped * * if an error occured, dest will be filled with 0. * If the source and destination overlap, the behavior of wmemcpy_s is undefined. * Use wmemmove_s to handle overlapping regions. ******************************************************************************* */ errno_t wmemcpy_s(wchar_t* dest, size_t destMax, const wchar_t* src, size_t count) { if (destMax == 0 || destMax > SECUREC_WCHAR_MEM_MAX_LEN ) { SECUREC_ERROR_INVALID_PARAMTER("wmemcpy_s"); return ERANGE; } if (count > destMax) { SECUREC_ERROR_INVALID_PARAMTER("wmemcpy_s"); if (dest != NULL) { (void)memset(dest, 0, destMax * WCHAR_SIZE); return ERANGE_AND_RESET; } return ERANGE; } return memcpy_s(dest, destMax * WCHAR_SIZE, src, count * WCHAR_SIZE); }
C
// // compile.c // // Created on 2/4/18. // #include "javaclass.h" #include "bytecode.h" #include "global.h" // Functions associated with Non-terminals void stmt(void); void opt_stmt(void); void expr(void); void term(void); void factor(void); void match(int); // Utility functions void add_ret(int); // adds loc of goto ins to the ret_goto_arr array void backpatch_ret(void); // backpatch the goto's for return labels void emit_init(void); // emit initial code void emit_end(void); // emit code after backpatching return labels // Class file globals struct ClassFile cf; int index1, index2, index3; int label1, label2; // Parse related globals int lookahead; int *ret_goto_arr; // array to store goto ins of return int ret_goto_cap = 8; // inital size of array int num_ret_goto = 0; // index of ret_goto_arr /******************************************************************************* MAIN *******************************************************************************/ int main(void) { init(); // initialize symbol table emit_init(); // emit initial code ret_goto_arr = (int *)malloc(sizeof(int) * ret_goto_cap); if (ret_goto_arr == NULL) { printf("ret_goto_arr: malloc failed\n"); exit(1); } lookahead = lexan(); stmt(); // parse backpatch_ret(); // backpatch all returns emit_end(); // emit final code // pre-save operations cf.methods[0].code_length = pc; cf.methods[0].code = copy_code(); save_classFile(&cf); free(ret_goto_arr); return 0; } /*******************************************************************************/ // Definitions of Non Terminal Functions void stmt() { if (lookahead == '{') { match('{'); opt_stmt(); match('}'); } else if (lookahead == ID) { int locvar = tokenval; match(ID); match('='); expr(); emit2(istore, locvar); match(';'); } else if (lookahead == IF) { int out, el; match(IF); match('('); expr(); match(')'); emit(iconst_0); el = pc; // label for branching to else emit3(if_icmpeq, PAD); // will be backpatched stmt(); out = pc; // label for branching past else emit3(goto_, PAD); // will be backpatched match(ELSE); backpatch(el, pc - el); // one past 'goto' is the location of else stmt(); backpatch(out, pc - out); // location past if else } else if (lookahead == WHILE) { int cond, out; match(WHILE); match('('); cond = pc; // location for conditional expr expr(); match(')'); emit(iconst_0); out = pc; // label for branching out of while emit3(if_icmpeq, PAD); // will be backpached stmt(); emit3(goto_, cond - pc); // goto condition expr backpatch(out, pc - out); // location past while } else if (lookahead == RETURN) { match(RETURN); expr(); emit(istore_2); add_ret(pc); emit3(goto_, PAD); // goto end of code match(';'); } else { error("syntax error"); } } void opt_stmt() { // keep calling statement if the lookahead is in FIRST(stmt) while (lookahead == '{' || lookahead == ID || lookahead == IF || lookahead == WHILE || lookahead == RETURN) { stmt(); } } void expr() { term(); // procedure moreterms "inlined" while (1) { if (lookahead == '+') { match('+'); term(); emit(iadd); } else if (lookahead == '-') { match('-'); term(); emit(isub); } else { break; } } } void term() { factor(); // procedure morefactors inlined while (1) { if (lookahead == '*') { match('*'); factor(); emit(imul); } else if (lookahead == '/') { match('/'); factor(); emit(idiv); } else if (lookahead == '%') { match('%'); factor(); emit(irem); } else { break; } } } void factor() { if (lookahead == '(') { match('('); expr(); match(')'); } else if (lookahead == '-') { match('-'); factor(); emit(ineg); } else if (lookahead == INT8) { emit2(bipush, tokenval); match(INT8); } else if (lookahead == INT16) { emit3(sipush, tokenval); match(INT16); } else if (lookahead == INT32) { int tv = tokenval; match(INT32); emit2(ldc, constant_pool_add_Integer(&cf, tv)); } else if (lookahead == ID) { emit2(iload, tokenval); match(ID); } else if (lookahead == ARG) { int num; match(ARG); match('['); num = tokenval; match(INT8); match(']'); emit(aload_1); emit2(bipush, num); emit(iaload); } else { error("syntax error"); } } void match(int t) { if (lookahead == t) { lookahead = lexan(); } else { error("syntax error"); } } /*******************************************************************************/ // Utility function definitions void add_ret(int loc) { if (num_ret_goto == ret_goto_cap) { ret_goto_cap *= 2; ret_goto_arr = realloc(ret_goto_arr, sizeof(int) * ret_goto_cap); if (ret_goto_arr == NULL) { printf("ret_goto_arr: realloc failed\n"); exit(1); } } ret_goto_arr[num_ret_goto++] = loc; } void backpatch_ret() { if (num_ret_goto != 0) { int rg, i; for (i = 0; i < num_ret_goto; ++i) { rg = ret_goto_arr[i]; backpatch(rg, pc - rg); } } } void emit_init() { init_ClassFile(&cf); // new class file structure cf.access = ACC_PUBLIC; // class access type cf.name = "Code"; // class name to be cf.field_count = 0; // num fields cf.method_count = 1; // num methods // allocate array for num methods cf.methods = (struct MethodInfo*)malloc(cf.method_count * sizeof(struct MethodInfo)); cf.methods[0].access = ACC_PUBLIC | ACC_STATIC; // method access type cf.methods[0].name = "main"; // method name // method descriptor "void main(String[] arg)" cf.methods[0].descriptor = "([Ljava/lang/String;)V"; cf.methods[0].max_stack = 127; // max size of operand stack cf.methods[0].max_locals = 127; // max local vars init_code(); emit(aload_0); emit(arraylength); emit2(newarray, T_INT); emit(astore_1); emit(iconst_0); emit(istore_2); label1 = pc; emit(iload_2); emit(aload_0); emit(arraylength); label2 = pc; emit3(if_icmpge, PAD); emit(aload_1); emit(iload_2); emit(aload_0); emit(iload_2); emit(aaload); index1 = constant_pool_add_Methodref(&cf, "java/lang/Integer", "parseInt", "(Ljava/lang/String;)I"); emit3(invokestatic, index1); emit(iastore); emit32(iinc, 2, 1); emit3(goto_, label1 - pc); backpatch(label2, pc - label2); } void emit_end() { index2 = constant_pool_add_Fieldref(&cf, "java/lang/System", "out", "Ljava/io/PrintStream;"); emit3(getstatic, index2); emit(iload_2); index3 = constant_pool_add_Methodref(&cf, "java/io/PrintStream", "println", "(I)V"); emit3(invokevirtual, index3); emit(return_); }
C
/* Aranea * Copyright (c) 2011-2012, Quoc-Viet Nguyen * See LICENSE file for copyright and license details. */ #ifndef ARANEA_CLIENT_H_ #define ARANEA_CLIENT_H_ #include <aranea/types.h> /** Allocate memory for a client. */ struct client_t *client_new(); /** Reset status of the client object to reuse it for another connection. */ void client_init(struct client_t *self); /** Reset client but keep current connection status (remote socket). */ void client_reset(struct client_t *self); /** Add this client to the list. */ void client_add(struct client_t *self, struct client_t **list); /** Remove current client from the list which it belongs to. */ void client_detach(struct client_t *self); /** Close connection from the client. */ void client_close(struct client_t *self); /** Process received data. */ void client_process(struct client_t *self); #endif /* ARANEA_CLIENT_H_ */ /* vim: set ts=4 sw=4 expandtab: */
C
#include<stdio.h> int heights[10000001], previous[10000001]; int main(){ int n, target, confort_level, cnt = 0; scanf("%d %d", &n, &target); int ans[n+1]; for(int i=1; i<=n; i++) { scanf("%d", &heights[i]); confort_level=0; for(int j=i-1; j>=1; j--) { if(heights[j] < heights[i]) { confort_level++; }else break; } if(confort_level == target) ans[cnt++] = i; } if(cnt>0) { //print answer printf("%d", ans[0]); for(int i=1; i<cnt; i++) printf(" %d", ans[i]); }else printf("ouo"); printf("\n"); return 0; }
C
#include <stdio.h> int isPalindrome(int num) { int temp = num; int reversed = 0; while (temp) { reversed *= 10; reversed += temp % 10; // integer division temp /= 10; // integer division } return num == reversed; } int main() { int max = 0; for (int a = 100; a <= 999; a++) { for (int b = 100; b <= a; b++) { int product = a * b; if (product > max && isPalindrome(product)) max = product; } } printf("%d\n", max); return 0; }
C
// // main.c // Challenge 9.3 // // Created by Wei on 7/6/15. // Copyright (c) 2015 OO. All rights reserved. // // An unsigned short only hold non-negative numbers. What is the largest number that an unsigned short can store? #include <stdio.h> #include <limits.h> // for MAX function int main(int argc, const char * argv[]) { //same question but unsigned short instead unsigned short m; for (m = 0; m < 1; m--) { continue; } printf("largest unsigned short is %d\n\n", m); printf("Maximum value of a unsigned short is %d\n", USHRT_MAX); //Way Two return 0; }
C
/************************************************************* CS530 - SPRING 2013 Name: Linh Ngoc Nguyen username: masc0755 Project: CSNNNN Assignment 2 Partner: Tuan Truong username :masc0710 *************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "a2.h" /*create file .list*/ void createList(struct IntermediateArray *arr,int Index) { int i,k,l; FILE *fp; fp=fopen("sic.list","w"); /*check if is NULL or not*/ if(fp==NULL) { printf("ERROR: Cannot open sic.list\n"); exit(1); } /*set header */ fprintf(fp, "%-4s\t%-10s%-10s%-10s\t%s\n","LOC","LABEL","OPERATOR","OPERAND","OBJECT CODE"); for(i=0;i<Index;i++)/*store into file*/ { if(!strcmp(arr[i].OperatorCol,"START") || !strcmp(arr[i].OperatorCol,"RESW") || !strcmp(arr[i].OperatorCol,"RESB") || !strcmp(arr[i].OperatorCol,"END")) fprintf(fp, "%04X\t%-10s%-10s%-10s\n",arr[i].Loc,arr[i].LabelField,arr[i].OperatorCol,arr[i].OperandCol); else fprintf(fp, "%04X\t%-10s%-10s%-10s\t%X\n",arr[i].Loc,arr[i].LabelField,arr[i].OperatorCol,arr[i].OperandCol,arr[i].ObjectCode); } fclose(fp); }
C
/*! Attribution.c Authors: Gabriela Marques and Leonardo Mizoguti Updated: 2015-10-28 */ #include "Attribution.h" /*! @const ATTR_NEXT_STATE @abstract Table indicating to which state the automaton must go given a current state and the value of the input token. @discussion The lines in this table represent the current state, and the columns represent the value of the input token. An error transition goes to a state represented by -1. */ const SubAutomatonState ATTR_NEXT_STATE[ATTR_COUNT_OF_STATES][ATTR_COUNT_OF_SYMBOLS] = { // "(" ")" "[" "]" "=" "." id int string other { -1, -1, -1 , -1 , -1 , -1 , 1 , -1 , -1 , -1 }, // State 0 { 5, -1, 2 , -1 , 4 , 3 , -1 , -1 , -1 , -1 }, // State 1 { -1, -1, -1 , -1 , -1 , -1 , -1 , 6 , -1 , -1 }, // State 2 { -1, -1, -1 , -1 , -1 , -1 , 8 , -1 , -1 , -1 }, // State 3 { 9, 9, 10 , 9 , 9 , 9 , 9 , 9 , 9 , 9 }, // State 4 { 7, 7, 7 , 7 , 7 , 7 , 7 , 7 , 7 , 7 }, // State 5 { -1, -1, -1 , 8 , -1 , -1 , -1 , -1 , -1 , -1 }, // State 6 { -1, 9, -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 }, // State 7 { -1, -1, 2 , -1 , 4 , 3 , -1 , -1 , -1 , -1 }, // State 8 { 9, 9, 9 , 9 , 9 , 9 , 9 , 9 , 9 , 9 }, // State 9 { 11, 11, 11 , 11 , 11 , 11 , 11 , 11 , 11 , 11 }, // State 10 { -1, -1, -1 , 9 , -1 , -1 , -1 , -1 , -1 , -1 } // State 11 }; /*! @const ATTR_SUB_AUTOMATON_CALL @abstract Table indicating if a sub automaton should be called given the current state and the input token. @discussion The lines in this table represent the current state, and the columns represent the value of the input token. If no sub automaton is to be token, this is expressed by the value "saiNONE". If the sub automaton reaches its end, this is represented by the value "saiFSTE". */ const SubAutomatonIdentifier ATTR_SUB_AUTOMATON_CALL[ATTR_COUNT_OF_STATES][ATTR_COUNT_OF_SYMBOLS] = { // "(" ")" "[" "]" "=" "." id int string other { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 0 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 1 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 2 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 3 { saiEXPR, saiEXPR, saiNONE, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiNONE, saiEXPR }, // State 4 { saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS }, // State 5 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 6 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 7 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 8 { saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE }, // State 9 { saiARYL, saiARYL, saiARYL, saiARYL, saiARYL, saiARYL, saiARYL, saiARYL, saiARYL, saiARYL }, // State 10 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE } // State 11 }; int GET_ATTR_TRANSITION(SubAutomatonState currentState, Token* token, SubAutomatonState* nextState, SubAutomatonIdentifier* subAutomatonCall) { AttributionTerminal terminalIndex = attrOther; switch (token->type) { case tokenTypeSpecialSymbol: switch (token->value.charValue) { case '(': terminalIndex = attrOpenParenthesis; break; case ')': terminalIndex = attrCloseParenthesis; break; case '[': terminalIndex = attrOpenBrackets; break; case ']': terminalIndex = attrCloseBrackets; break; case '=': terminalIndex = attrEqualSign; break; case '.': terminalIndex = attrDot; break; default: break; } break; case tokenTypeIdentifier: terminalIndex = attrIdentifier; break; case tokenTypeNumberInteger: terminalIndex = attrInteger; break; case tokenTypeString: terminalIndex = attrString; break; default:break; } *nextState = ATTR_NEXT_STATE[currentState][terminalIndex]; *subAutomatonCall = ATTR_SUB_AUTOMATON_CALL[currentState][terminalIndex]; return terminalIndex; }
C
#include <stdio.h> int power(int m, int n); /* power */ main() { int i; for (i = 0; i < 10; ++i) printf("%d %d %d\n", i, power(2,i), power(-3,i)); return 0; } /* power: base n ; n >= 0 */ int power(int base, int n) { int i, p; p = 1; for (i = 1; i <= n; ++i) p = p * base; return p; } /* ҳ˵"׼ṩһ pow(x,y)ڼ x^y"£*/ /* #include<stdio.h> main() { int c; c = pow(2,10); printf("%d", c); } */
C
#include "utils.h" int ***malloc3Dmatrix(int bands, int rows, int cols, double nodata){ int ***m = (int ***) malloc(sizeof(int **) * bands); for(int a = 0; a < bands; a++){ m[a] = (int **) malloc(sizeof(int *) * rows); for(int r = 0; r < rows; r++) m[a][r] = (int *) malloc(sizeof(int) * cols); } for(int a = 0; a < bands; a++) for(int r = 0; r < rows; r++) for(int c = 0; c < cols; c++) m[a][r][c] = nodata; return m; } DATA readRaster(char *input){ DATA in; /* Opening the file */ GDALAllRegister(); // Register all known drivers in.hDataset = GDALOpen(input, GA_ReadOnly); if(in.hDataset == NULL){ CPLGetLastErrorMsg(); exit(-1); } /* Getting Dataset Information */ in.hDriver = GDALGetDatasetDriver(in.hDataset); if(GDALGetProjectionRef(in.hDataset) != NULL) if(GDALGetGeoTransform(in.hDataset, in.adfGeoTransform) == CE_None){ if(in.adfGeoTransform[1] != - in.adfGeoTransform[5]){ printf("w-e and n-s pixel size are not equal.\n"); exit(-1); } } /* Fetching a Raster Band */ in.nbands = GDALGetRasterCount(in.hDataset); // number of bands if(in.nbands != 1){ printf("DEM files have only one band.\n"); exit(-1); } in.hBand = (GDALRasterBandH *) malloc(sizeof(GDALRasterBandH) * in.nbands); in.noData = (double *) malloc(sizeof(double) * in.nbands); in.adfMinMax = (double **) malloc(sizeof(double *) * in.nbands); for(int b = 0; b < in.nbands; b++) in.adfMinMax[b] = (double *) malloc(sizeof(double) * 2); for(int b = 0; b < in.nbands; b++){ in.hBand[b] = GDALGetRasterBand(in.hDataset, b+1); in.ncols = GDALGetRasterBandXSize(in.hBand[b]); in.nrows = GDALGetRasterBandYSize(in.hBand[b]); int bGotNoValue; in.noData[b] = GDALGetRasterNoDataValue(in.hBand[b], &bGotNoValue); if(!bGotNoValue) in.noData[b] = -32767; int bGotMin, bGotMax; in.adfMinMax[b][0] = GDALGetRasterMinimum(in.hBand[b], &bGotMin); in.adfMinMax[b][1] = GDALGetRasterMaximum(in.hBand[b], &bGotMax); if(!(bGotMin && bGotMax)) GDALComputeRasterMinMax(in.hBand[b],TRUE, in.adfMinMax[b]); //printf("Min=%.3f, Max=%.3f\n", in.adfMinMax[b][0], in.adfMinMax[b][1]); } in.buffer = (float ***) malloc(sizeof(float **) * in.nbands); for(int b = 0; b < in.nbands; b++){ in.buffer[b] = (float **) malloc(sizeof(float *) * in.nrows); for(int r = 0; r < in.nrows; r++) in.buffer[b][r] = (float *) malloc(sizeof(float) * in.ncols); } for(int b = 0; b < in.nbands; b++){ for(int r = 0; r < in.nrows; r++){ CPLErr e = GDALRasterIO(in.hBand[b], GF_Read, 0, r, in.ncols, 1, in.buffer[b][r], in.ncols, 1, GDT_Float32, 0, 0); } } return in; } void writeOutput(GDALDriverH driver, char *out, int **buffer, int nrows, int ncols, int noData, int type, double *adfGeo, const char *proj){ GDALDatasetH hDstDS; char **papszOptions = NULL; hDstDS = GDALCreate(driver, out, ncols, nrows, 1, type, papszOptions); GDALRasterBandH hBandOut = GDALGetRasterBand(hDstDS, 1); for(int r = 0; r < nrows; r++){ CPLErr e = GDALRasterIO(hBandOut, GF_Write, 0, r, ncols, 1, buffer[r], ncols, 1, type, 0, 0); } GDALSetGeoTransform(hDstDS, adfGeo); GDALSetProjection(hDstDS, proj); GDALSetRasterNoDataValue(hBandOut, noData); if(hDstDS != NULL) GDALClose(hDstDS); }
C
#include <stdio.h> #include <string.h> // 8. Any integer is input from the keyboard. Write a function to reverse an integer and print // using C language. For example if user enters 12323 then output should be 32321 int main(void) { char digits[80]; char reversed[80]; printf("Enter any nonnegative integer: "); scanf("%s", digits); puts(digits); int length = strlen(digits); printf("length = %d\n", length); for (int i = (length - 1); i >= 0; i--) { reversed[(length - 1) - i] = digits[i]; } // next digit reversed[length] = '\0'; printf("reversed: %s\n", reversed); } // main()
C
#include<stdio.h> int main(){ int num; printf("enter the no of element of your array\n"); scanf("%d",&num); int arr[num]; for(int i=0;i<num;i++){ printf("Enter element %d of array: \n",i+1); scanf("%d",&arr[i]); } int min=arr[0],max=arr[0]; for(int i=0;i<num;i++){ if(min>arr[i]){ min=arr[i]; } if(max<arr[i]){ max=arr[i]; } } printf("minimum number is %d\n",min); printf("maximum number is %d\n",max); return 0; }
C
/* * synt_anal.h * Autor: Tomas Zencak * Predmet: Formalni jazyky a prekladace * Projekt: Implementace interpretu jazyka IFJ15 * Varianta zadani: a/2/II * Datum: 1. 10. 2015 * Prelozeno: gcc 4.8 * Tomas Zencak xzenca00 * Ondrej Vales xvales03 * Nikola Valesova xvales02 * Radek Vit xvitra00 */ #ifndef SYNT_ANAL_H_ #define SYNT_ANAL_H_ #include <stdio.h> #include "synt_anal_types.h" #include "vector_rule.h" #include "vector_token.h" typedef struct{ Vector_Rule rules; Vector_Token values; }ParseTree; /** * @brief Analyzes the syntax of the program contained in progfile * @param progfile The stream from which the program will be read. * @param output The output of the parser. Expects both vectors to be initialized. * If it runs successfully, output will contain a sequence of rules used for parsing the program. * The rules are ordered as a leftmost derivation for everything except expressions, * which are ordered as a reversed rightmost derivation. * The values are ordered the same as the rules which produced the terminals carrying those values. * @return RET_EOK if the program is OK, an error otherwise */ int analyze_program_syntax(FILE *progfile, ParseTree *output); #endif
C
#include "timer.h" #define MICROSSECONDS_IN_SECONDS 1000000 /** Local function that returns the ticks * (number of microsseconds) since the Epoch. */ static suseconds_t get_ticks() { struct timeval tmp; gettimeofday(&(tmp), NULL); return (tmp.tv_usec) + (tmp.tv_sec * MICROSSECONDS_IN_SECONDS); } void timer_start(timer_t* t) { t->start_mark = get_ticks(); t->pause_mark = 0; t->running = true; t->paused = false; } void timer_pause(timer_t* t) { if (!(t->running) || (t->paused)) return; t->pause_mark = get_ticks() - (t->start_mark); t->running = false; t->paused = true; } void timer_unpause(timer_t* t) { if (t->running || !(t->paused)) return; t->start_mark = get_ticks() - (t->pause_mark); t->running = true; t->paused = false; } suseconds_t timer_delta_us (timer_t* t) { if (t->running) return get_ticks() - (t->start_mark); if (t->paused) return t->pause_mark; // Will never actually get here return (t->pause_mark) - (t->start_mark); } long timer_delta_ms(timer_t* t) { return (timer_delta_us(t) / 1000); } long timer_delta_s(timer_t* t) { return (timer_delta_us(t) / 1000000); } long timer_delta_m(timer_t* t) { return (timer_delta_s(t) / 60); } long timer_delta_h(timer_t* t) { return (timer_delta_m(t) / 60); }
C
#include <stdio.h> #include <stdlib.h> int main() { printf("Comments are fun"); } /*L'ordinateur ne lit pas les commentaires, ils sont un peu pour nous, pour nous retrouves dans notre code ou juste un effet personnel, bref l'ordi ne lit pas les commentaires.*/
C
/* * Copyright (c) 2019-2020 vanaur. * * This file is part of RCL * (see https://github.com/vanaur/The-Runtime-Core-Library). * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <stdio.h> #include <Tools\Utils\Utils.h> #include <Tools\console-color\console-color.h> #include <VM\Core\State\State.h> struct StateKind make_error(enum Origin origin, const String msg) { return (struct StateKind){.kind = Error, .u = {.error = {.msg = msg}}}; } struct StateKind make_warning(enum Origin origin, const String msg) { return (struct StateKind){.kind = Warning, .u = {.warning = {.msg = msg}}}; } struct StateKind make_info(enum Origin origin, const String msg) { return (struct StateKind){.kind = Info, .u = {.info = {.msg = msg}}}; } void state_init(struct State *state) { state->hasError = false; InitVector(state, 1, struct StateKind); } void state_put(struct State *state, struct StateKind statekind) { if (statekind.kind == Error) state->hasError = true; PushToVector(state, struct StateKind, statekind); } size_t count_errors(const struct State state) { size_t result = 0; for (Iterator i = 0; i < state.used; i++) if (state.array[i].kind == Error) result++; return result; } size_t count_warnigns(const struct State state) { size_t result = 0; for (Iterator i = 0; i < state.used; i++) if (state.array[i].kind == Warning) result++; return result; } size_t count_infos(const struct State state) { size_t result = 0; for (Iterator i = 0; i < state.used; i++) if (state.array[i].kind == Info) result++; return result; } void prettyPrint_state(struct State state) { const int errs = (int)count_errors(state); const int warns = (int)count_warnigns(state); const int infos = (int)count_infos(state); if (errs + warns + infos == 0) return; printf("\n"); for (Iterator i = 0; i < state.used; i++) { if (i >= 25 && i > 25) { i = state.used; cc_fprintf( CC_FG_MAGENTA, stdout, "\n... %d errors in all (+ %d warnings and %d information)\n", errs, warns, infos); return; } switch (state.array[i].kind) { case Error: cc_fprintf(CC_FG_DARK_RED, stdout, "Error: "); cc_fprintf(CC_FG_RED, stdout, "%s\n", state.array[i].u.error.msg); free(state.array[i].u.error.msg); break; case Warning: cc_fprintf(CC_FG_YELLOW, stdout, "Warning: "); cc_fprintf(CC_FG_DARK_YELLOW, stdout, "%s\n", state.array[i].u.warning.msg); free(state.array[i].u.warning.msg); break; case Info: cc_fprintf(CC_FG_CYAN, stdout, "Info: "); cc_fprintf(CC_FG_DARK_CYAN, stdout, "%s\n", state.array[i].u.info.msg); //free(state.array[i].u.info.msg); break; } } }
C
#include "header.h" s_argument agv(const char *arg, s_argument result) { int index; char c; index = 1; c = '\0'; if (arg[0] != '-' || strlen(arg) == 1) erreur_fichier(); while (arg[index]) { c = arg[index]; if (c != 'l' && c != 'R' && c!= 'a' && c != 'r' && c != 't') erreur_arg(c); if (c == 'l') result.arg_l = TRUE; else if (c == 'R') result.arg_R = TRUE; else if (c == 'a') result.arg_a = TRUE; else if (c == 'r') result.arg_r = TRUE; else if (c == 't') result.arg_t = TRUE; index++; } return(result); }
C
#include<stdio.h> #include<string.h> int main(int argc, char *argv[]) { char inbuf[4096]; unsigned char data[32768], *dst; unsigned char testbuf[32768]; int i, j, k, len, hit; //printf("hamming distance: %d\n", hamming_distance("this is a test", "wokka wokka!!!", 14)); while(fgets(inbuf, sizeof(inbuf), stdin)) { len = hexdecode(inbuf, data); hit = 0; for(i = 0; i <= len - 16; i+= 16) { for(j = i+16; j <= len - 16; j += 16) { for(k = 0; k < 16; k++) { if(data[i+k] != data[j+k]) { break; } } if(k >= 16) { /* hexencode(data+i, testbuf, 16); printf("Same ciphertext at pos %d and pos %d, %.32s\n", i, j, testbuf); hexencode(data+j, testbuf, 16); printf("Same ciphertext at pos %d and pos %d, %.32s\n", i, j, testbuf); */ hit = 1; } } } if(hit) { printf("%s\n", inbuf); } } return 0; }
C
#include "holberton.h" /** *_print_X - print an integer in hexadecimal (uppercase) (helper function) *@n: the integer to print *@count: a pointer to a counter for the number of bytes printed */ void _print_X(unsigned int n, int *count) { int lastRetVal; if (n > 0xf) _print_X(n >> 4, count); if (*count < 0) return; if ((n & 0xf) < 0xa) lastRetVal = _putchar('0' + (n & 0xf)); else lastRetVal = _putchar('A' + (n & 0xf) % 0xa); if (lastRetVal < 0) *count = (-1); else *count += lastRetVal; } /** * print_X - print an integer in hexadecimal (uppercase) * @args: the va_list with the integer to print as it's next element * * Return: the number of bytes printed */ int print_X(va_list args) { int count = 0; _print_X(va_arg(args, int), &count); return (count); }
C
#include<stdio.h> int main(){ char a[100]; int i; printf("Enter the string: "); gets(a); for ( ; a[i] != '\0';i++){ if(a[i]>='A'&&a[i]<='Z') a[i]=a[i]+32; } printf("Lower Case : %s",a); return 0; }
C
// // strchr.c // break-away-coding-interviews // // Created by Vaibhav Chauhan on 3/5/16. // Copyright © 2016 Vaibhav Chauhan. All rights reserved. // #include <stdio.h> char * my_strchr( char * str, int c) { if (str == NULL) return NULL; while (*str != '\0') { if (*str == c){ return str; } str++; } return NULL; } int main() { char * found = my_strchr("Hello World", 'o'); printf("%c\n", *found); }
C
#include <stdio.h> #include <stdlib.h> #include "linkqueue.h" ElementType Dequeue(linkqueue Q) { List tempNode; ElementType item; if(!Q->front) { printf("Queue is empty!\n"); return ERROR; } tempNode = Q->front; if(Q->front ==Q->rear) Q->front = Q->rear = NULL; else Q->front = tempNode->Next; item = tempNode->Data; free(tempNode); return item; } void Enqueue(linkqueue Q, ElementType item) { List S = (List)malloc(sizeof(struct Node)); S->Data = item; S->Next = NULL; Q->rear->Next = S; Q->rear = S; }
C
#include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <stdio.h> int main (void) { int fd; char buf[] = "mensaje 1..."; mkfifo("/tmp/mi_fifo", 0666); // 0666 = permisos de lectura y escritura fd = open("/tmp/mi_fifo", O_WRONLY); printf("Escribiendo mensaje..."); write(fd, buf, sizeof(buf)); close(fd); return 0; }
C
#include <stdio.h> int main(void) { int num, grade, i; int sum = 0; double doubSum; scanf("%d", &num); for (i=0; i<num; i++){ scanf("%d", &grade); sum = sum + grade; } doubSum = (double) sum; printf("%.2lf", doubSum/num); return 0; }
C
#include <stdio.h> #include <string.h> void displayDataSet(int dataSet[], int length) { int i =0; for(i=0;i<length;i++) { printf("%d ", dataSet[i]); } printf("\n"); } void insertionSort(int dataSet[], int len) { int i =0; int j= 0; int value = 0; for(i=1;i<len;i++) { displayDataSet(dataSet, len); ] if(dataSet[i-1] > dataSet[i]) { value = dataSet[i]; for(j=0;j<i; j++) { if(dataSet[j] > value) { /* * memmove(void* des, void* src, size_t size) */ memmove(&dataSet[j+1], &dataSet[j], sizeof(dataSet[0]) * (i-j)); dataSet[j] = value; break; } } } } } int main() { int dataSet[] = {5,1,6,4,2,3}; int length = sizeof dataSet / sizeof dataSet[0]; insertionSort(dataSet, length); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS #include"SList.h" //ӡ void SListPrint(SLTNode** pphead) { SLTNode* cur = *pphead; while (cur != NULL) { printf("%d->", cur->data); cur = cur->next; } printf("NULL\n"); } //һ½ڵ SLTNode* BuySListNode(SLTDataType x) { SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode)); newnode->data = x; newnode->next = NULL; return newnode; } //β void SListPushBack(SLTNode** pphead, SLTDataType x) { SLTNode* newnode = BuySListNode(x); //һʼΪգôֱӾ¿ٵĽڵ if (*pphead == NULL) { *pphead = newnode; } else { SLTNode* tail = *pphead; //ҵβָ while (tail->next != NULL) { tail = tail->next; } //ԭβӴӵĵַ tail->next = newnode; } } void SListPushBack1(SLTNode* pphead, SLTDataType x) { SLTNode* newnode = BuySListNode(x); //һʼΪգôֱӾ¿ٵĽڵ if (pphead == NULL) { pphead = newnode; } else { SLTNode* tail = pphead; //ҵβָ while (tail->next != NULL) { tail = tail->next; } //ԭβӴӵĵַ tail->next = newnode; } } void fun(int* x) { *x = 10; } int main() { SLTNode* plist = NULL; SListPushBack(&plist, 1); SListPushBack1(plist, 2); SListPushBack1(plist, 3); SListPrint(&plist); return 0; }
C
/* ** env.c for minishell in /home/raphael.goulmot/rendu/PSU_2016_minishell2 ** ** Made by Raphaël Goulmot ** Login <raphael.goulmot@epitech.net> ** ** Started on Sat Apr 1 04:51:24 2017 Raphaël Goulmot ** Last update Sun Apr 9 17:11:51 2017 Raphaël Goulmot */ #include "utils.h" #include <stdlib.h> char my_is_alphanumeric(char *str) { while (*str) { if (!(my_char_isalpha(*str) || (*str >= '0' && *str <= '9') || *str == '_')) return (0); str++; } return (1); } int my_env(char ***env, char **useless) { char **clone; clone = *env; while (clone && *clone) { my_putstr(*clone++); my_putchar('\n'); } return (0); } void add_env(char ***env, int i, char *str) { char **new; int index; char **clone; index = 0; if (i >= my_strstrlen(*env)) { new = malloc(sizeof(char *) * (my_strstrlen(*env) + 1) + sizeof(char) * (my_strlen(str) + 1)); clone = *env; while (clone && *clone++) new[index++] = *(clone - 1); new[index++] = str; new[index] = 0; *env = new; } else (*env)[i] = str; } int my_setenv(char ***env, char **args) { int size; char **line; char *value; int i; size = env ? my_strstrlen(args) : 0; if (!(i = 0) && size == 1) return (my_env(env, args)); else if (size >= 2 && size <= 3 && my_is_alphanumeric(args[1]) && !(value=0)) { while (!value && *env && (*env)[i] && (line = split((*env)[i], '='))) { if (line && my_strstrlen(line) && my_strcmp(line[0], args[1])) value = (*env)[i]; i += !value ? 1 : 0; free_wordtab(line); } value = my_strcpy(args[1], "="); add_env(env, i, my_strcpy(value, (size > 2 ? args[2] : ""))); free(value); } else my_putstr_err(size > 3 ? "setenv: Too many arguments.\n" : "setenv: Variable name must contain alphanumeric characters.\n"); return (size > 3 ? 1 : 0); } int my_unsetenv(char ***env, char **args) { int size; char **clone; char find; char **line; size = my_strstrlen(args); if (size == 1) my_putstr_err("unsetenv: Too few arguments.\n"); else { while (args && *(++args) && !(find = 0) && (clone = *env)) { while (clone && *clone && (line=split(*clone++, '='))) { if (line && my_strstrlen(line) && my_strcmp(line[0], *args)) find = 1; else *(clone - 1 - find) = *(clone - 1); if (line) free_wordtab(line); } *(clone - find) = 0; } } return (size == 1 ? 1 : 0); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <time.h> #include <sys/time.h> #include <unistd.h> #include <errno.h> #include <sys/msg.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> //#include "../include/alarm.h" // arm-linux-gcc -o msgrcv msgrcv.c typedef struct _alarm_info_t { short alarm_code; char chassis; char slot; char entity; char is_with_value; short alarm_value; unsigned short alarm_reason; time_t alarm_time; //void(*value2message)(short,char *); } alarm_info_t; typedef struct _alarm_msg_t { long msg_type; //alarm_info_t alarm_info; char alarm_info[sizeof(alarm_info_t)]; //void(*value2message)(short,char *); } alarm_msg_t; void main() { long int msgtype = 1; //注意1 int buf_size=sizeof(alarm_info_t); alarm_msg_t data; //建立消息队列 int almmsgid = msgget((key_t)1234, 0666 | IPC_CREAT); if(almmsgid == -1) { fprintf(stderr, "msgget failed with error: %d\n", errno); exit(EXIT_FAILURE); } //从队列中获取消息,直到遇到end消息为止 int count=0; while(1) { if(msgrcv(almmsgid, (void*)&data, buf_size, msgtype,0) != -1) { printf("msgrcv count=%d\n",++count); } } }
C
char line[100],male; int len; void hand(); int main() { cin>>line; len=strlen(line); male=line[0]; hand(); return 0; } void hand() { int i,j; for(i=0;i<len;i++) { if(line[i]!=male && line[i]!='\0') { for(j=i-1;j>=0;j--) { if(line[j]==male) { cout<<j<<' '<<i<<endl; line[i]='\0'; line[j]='\0'; break; } } } } }
C
#ifndef AN_BUF_H_ #define AN_BUF_H_ #include <unistd.h> #include <stdbool.h> /* * An abstract buffer API. * * The backend specific headers (an_buf_<backend>.h) contain the * functions required to create an an_[rw]buf object. Consumers should * include the backend specific header they need instead of this one. */ struct an_rbuf; struct an_wbuf; /* * We use transparent unions so that any function that can act on both * read and write buffers can be called with a pointer to either type * of buffer without needing to cast. * * You can think of a function having an an_buf_ptr_t parameter as a * function that accepts either a struct an_rbuf * or a struct an_wbuf *. * Similarly, an an_buf_const_ptr_t parameter is equivalent to a function * accepting either a const struct an_rbuf * or a const struct an_wbuf *. */ typedef union { struct an_rbuf *rbuf; struct an_wbuf *wbuf; } an_buf_ptr_t __attribute__((__transparent_union__)); typedef union { struct an_rbuf *rbuf; struct an_wbuf *wbuf; const struct an_rbuf *const_rbuf; const struct an_wbuf *const_wbuf; } an_buf_const_ptr_t __attribute__((__transparent_union__)); typedef void (an_buf_cleanup_t)(an_buf_ptr_t, void *); /* API for both read and write buffers. */ /* * Returns true if the underlying buffer is "owned" or false. * * When the underlying buffer is owned, it is destroyed when the parent * an_buf object is destroyed using an_buf_destroy(). If it isn't owned, * it will persist and remain usable after an_buf_destroy() is called. */ bool an_buf_owned(an_buf_const_ptr_t); /* Mark the underlying buffer as owned. */ void an_buf_own(an_buf_ptr_t); /* Mark the underlying buffer as *not* owned. */ void an_buf_disown(an_buf_ptr_t); /* Destroy an an_buf object (and the underlying buffer if owned). */ void an_buf_destroy(an_buf_ptr_t); /* Return the total length of the buffer. */ size_t an_buf_length(an_buf_const_ptr_t); /* Add a cleanup function to be called at destruction time. */ void an_buf_add_cleanup(an_buf_ptr_t, an_buf_cleanup_t *, void *); /* API for write buffers. */ /* Append data to a buffer. */ void an_buf_add(struct an_wbuf *, const void *, size_t); /* Append a printf() formatted string to the buffer. */ void an_buf_add_printf(struct an_wbuf *, const char *, ...) __attribute__((format(printf, 2, 3))); /* Empty the buffer. */ void an_buf_reset(struct an_wbuf *); /* * Mark this buffer as frozen. Any subsequent writes to this buffer * will cause an asertion failure. Mostly useful for debugging. */ void an_buf_freeze(struct an_wbuf *); /* Allow writes on this buffer again. */ void an_buf_thaw(struct an_wbuf *); /* API for read buffers. */ /* * Linearize the entire buffer chain in memory. * * This is a destructive operation: if the buffer hasn't been modified * since the last call, subsequent calls will be mostly free. The zone * of memory we return a pointer to is owned by the an_buf object. */ const void *an_buf_linearize(struct an_rbuf *); #endif /* AN_BUF_H_ */
C
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "USAGE: %s <num_elems>\n", argv[0]); exit(1); } int num = atoi(argv[1]); printf("num = %d\n", num); // create a dynamic array on the heap int *a = malloc(num * sizeof(int)); if (a == NULL) { fprintf(stderr, "Memory allocation failed.\n"); exit(1); } for (int i = 0; i < num; ++i) { a[i] = i; } for (int i = 0; i < num; ++i) { printf("a[%d] = %d\n", i, a[i]); } // double the size of the array // THIS IS THE BAD WAY!!! // 1) We lose access to the original a - so we can't copy the old data // 2) We lose access to the original a - so we can't free the memory // a = malloc(2 * num * sizeof(int)); // if (a == NULL) { // fprintf(stderr, "Memory allocation failed.\n"); // exit(1); // } int *p = malloc(2 * num * sizeof(int)); if (p == NULL) { fprintf(stderr, "Memory allocation failed.\n"); exit(1); } for (int i = 0; i< num; i++) p[i] = a[i]; free(a); a = p; for (int i = 0; i < 2*num; ++i) { printf("a[%d] = %d\n", i, a[i]); } free(a); return 0; }
C
#include <stdio.h> int main() { // 1.算术运算 printf("----1.算术运算----\n"); int a = 21; int b = 10; int c; printf("a = %d, b = %d\n", a, b); c = a + b; printf("a + b = %d\n", c); c = a - b; printf("a - b = %d\n", c); c = a * b; printf("a * b = %d\n", c); c = a / b; printf("a / b = %d\n", c); c = a % b; printf("a % b = %d\n", c); c = a++; printf("c = a++ 等于 %d\n", c); c = a--; printf("c = a-- 等于 %d\n--------\n", c); // ++a与a++ int d = 10; printf("d = %d, 先赋值后运算\n", d); int e = d ++; printf("e = d++ 等于 %d\n", e); printf("d = %d\n--------\n", d); d = 10; printf("d = %d\n", d); e = d --; printf("e = d-- 等于 %d\n", e); printf("d = %d\n--------\n", d); d = 10; printf("d = %d, 先运算后赋值\n", d); e = ++d; printf("e = ++d 等于 %d\n", e); printf("d = %d\n--------\n", d); d = 10; printf("d = %d\n", d); e = --d; printf("e = --d 等于 %d\n", e); printf("d = %d\n--------\n", d); // 2.关系运算 printf("----2.关系运算----\n"); a = 21; b = 10; printf("a = %d, b = %d\n", a, b); if (a == b) { printf("a 等于 b\n"); } else { printf("a 不等于 b\n"); } if (a < b) { printf("a 小于 b\n"); } else { printf("a 不小于 b\n"); } if (a > b) { printf("a 大于 b\n"); } else { printf("a 不大于 b\n"); } a = 5; b = 20; printf("a = %d, b = %d\n", a, b); if (a <= b) { printf("a 小于等于 b\n"); } if (b >= a) { printf("b 大于等于 a\n"); } // 3.逻辑运算 a = 5; b = 20; printf("a = %d, b = %d\n", a, b); if (a && b) { printf("a && b为真\n"); } if (a || b) { printf("a || b为真\n"); } a = 0; b = 10; printf("a = %d, b = %d\n", a, b); if (a && b) { printf("a && b为真\n"); } else { printf("a && b为假\n"); } if (!(a && b)) { printf("!(a && b)为真\n"); } // 3.位运算 printf("----3.位运算----\n"); unsigned int a1 = 60; unsigned int b1 = 13; printf("a = %d, b = %d\n", a1, b1); c = a1 & b1; printf("a & b 为 %d\n", c); c = a1 | b1; printf("a | b 为 %d\n", c); c = a1 ^ b1; printf("a ^ b为 %d\n", c); c = ~a1; printf("~a 为 %d\n", c); c = a1 << 2; printf("a << 2 为 %d\n", c); c = a1 >> 2; printf("a >> 2 为 %d\n", c); // 4.赋值运算 printf("----4.赋值运算----\n"); a = 21; printf("a = %d\n", a); c = a; printf("c = a 为 %d\n", c); c += a; printf("c += a 为 %d\n", c); c -= a; printf("c -= a 为 %d\n", c); c *= a; printf("c *= a 为 %d\n", c); c /= a; printf("c /= a 为 %d\n", c); c = 200; printf("c = %d\n", c); c %= a; printf("c %= a 为 %d\n", c); c <<= 2; printf("c <<= 2 为 %d\n", c); c >>= 2; printf("c >>= 2 为 %d\n", c); c &= 2; printf("c &= 2 为 %d\n", c); c ^= 2; printf("c ^= 2 为 %d\n", c); c |= 2; printf("c |= 2 为 %d\n", c); // 5.杂项运算 printf("----5.杂项运算----\n"); a = 4; short b2; double c2; int * ptr; printf("int 占用的字节数为 %lu\n", sizeof(a)); printf("short 占用的字节数为 %lu\n", sizeof(b2)); printf("double 占用的字节数为 %lu\n", sizeof(c2)); ptr = &a; printf("a = %d\n", a); printf("*ptr的值为 %d\n", *ptr); // 三目运算符 a = 10; b = (a == 1) ? 20 : 30; printf("b = (a == 1) ? 20 : 30 的值是 %d\n", b); b = (a == 10) ? 20 : 30; printf("b = (a == 10) ? 20 : 30 的值是 %d\n", b); // 6.运算符优先级 printf("----6.运算符优先级----\n"); a = 20; b = 10; c = 15; d = 5; printf("a = %d, b = %d, c = %d, d = %d\n", a, b, c, d); int result = (a + b) * c / d; printf("(a + b) * c / d 的值为 %d\n", result); result = ((a + b) * c) / d; printf("((a + b) * c) / d 的值为 %d\n", result); result = (a + b) * (c / d); printf("(a + b) * (c / d) 的值为 %d\n", result); result = a + (b * c) / d; printf("a + (b * c) / d 的值为 %d\n", result); return 0; }
C
/* Assignment 1 Name: Bilal Ayyache Student Number: 0988616 UofG Email: bayyache@uoguelph.ca */ #define MAX_ELEMENTS 256 long elements; int ds_create(char *filename, long size ); int ds_init(char *filename); long ds_malloc(long amount); void ds_free(long start); long ds_write(long start, void *ptr, long bytes); void *ds_read(void *ptr, long start, long bytes); int ds_finish(); int ds_create_array(); int ds_init_array(); int ds_replace(int value, long index ); int ds_insert( int value, long index ); int ds_delete( long index ); int ds_swap( long index1, long index2 ); long ds_find( int target ); int ds_read_elements( char *filename ); int ds_finish_array();
C
/* =================================================================================== Departamento Eng. Informatica - FCTUC Computacao Grafica - 2015/16 ................................................... PMartins/JArrais Trabalho 1 - George Nelson's Asterisk Clock (codigo incompleto) Completar as zonas assinaladas com comentarios TODO ======================================================================================= */ //.................................................... Bibliotecas necessarias #include <stdlib.h> #include <time.h> #ifdef __APPLE__ #include <OpenGL/OpenGL.h> #include <GLUT/glut.h> #else #include <GL/glut.h> #endif //.................................................... Variaveis GLint msecDelay=20; //definicao do timer (frequencia de actualizacao em milissegundos) struct tm *current_time; //tempo actual GLint hour, minute, second; //horas, minutos e segundos actuais //----------------------------------------------------------------------------------- // Init (definicoes iniciais: cor de fundo/cor para apagar, limites do mundo, // tipo de interpolacao de cor, etc ) //----------------------------------------------------------------------------------- void init(void) { glClearColor(1.0, 1.0, 1.0, 1.0); //.... Cor para apagar (branco) gluOrtho2D(-400, 400, -400, 400); //.... Definicao sistema coordenadas/ area de desenho glShadeModel(GL_FLAT); //.... Interpolacao de cor com base na cor dos vertices } //----------------------------------------------------------------------------------- // drawRectangle (desenha um rectangulo preenchido a preto) //----------------------------------------------------------------------------------- void drawRectangle() { glBegin(GL_POLYGON); //Neste caso, poderia ser GL_QUADS em vez de GL_POLYGON glVertex2f(-30,300); glVertex2f(30,300); glVertex2f(30,-300); glVertex2f(-30,-300); glEnd(); } //----------------------------------------------------------------------------------- // drawAsterisk (desenha a base do relogio (asterisco) a partir do drawRectangle) //----------------------------------------------------------------------------------- void drawAsterisk() { //TODO: desenhar o asterisco a partir da funcao drawRectangle glPushMatrix(); for(int i = 0; i < 6; i++){ drawRectangle(); glRotatef(30,0,0,1); } glPopMatrix(); } //----------------------------------------------------------------------------------- // drawHoursHand (desenha o ponteiro das horas a marcar 12 horas ) //----------------------------------------------------------------------------------- void drawHoursHand() { //TODO: definir (0.96,0.96,0.96) como a cor de preenchimento do poligono glColor3f(0.96,0.96,0.96); glBegin(GL_POLYGON); //Neste caso, poderia ser GL_QUADS em vez de GL_POLYGON glVertex2f(-13, -20); glVertex2f(13, -20 ); glVertex2f(4, 130); glVertex2f(-4, 130); glEnd(); } //----------------------------------------------------------------------------------- // drawMinsHand (desenha o ponteiro dos minutos a marcar 0 minutos ) //----------------------------------------------------------------------------------- void drawMinsHand() { //TODO: definir (0.96,0.96,0.96) como a cor de preenchimento dos poligonos glColor3f(0.96,0.96,0.96); glBegin(GL_POLYGON); //Neste caso, poderia ser GL_QUADS em vez de GL_POLYGON glVertex2f(-13, -20); glVertex2f(13, -20 ); glVertex2f(4, 140); glVertex2f(-4, 140); glEnd(); glBegin(GL_POLYGON); //Neste caso, poderia ser GL_TRIANGLES em vez de GL_POLYGON glVertex2f(-50, 140); glVertex2f(50, 140); glVertex2f(0, 190 ); glEnd(); } //------------------------------------------------------------------------------------ // drawSecsHand (desenha o ponteiro dos segundos a marcar 0 segundos ) //----------------------------------------------------------------------------------- void drawSecsHand() { //TODO: definir vermelho como a cor de preenchimento do poligono glColor3f(1.0,0,0); glBegin(GL_POLYGON); //Neste caso, poderia ser GL_QUADS em vez de GL_POLYGON glVertex2f(-12, -20); glVertex2f(12, -20 ); glVertex2f(3, 140); glVertex2f(-3, 140); glEnd(); } //---------------------------------------------------------------------------------------- // getTime (permite obter os horas, minutos e segundos, a partir do relógio do sistema) //--------------------------------------------------------------------------------------- void getTime() { time_t timer = time(0); current_time = localtime(&timer); hour = current_time->tm_hour; minute = current_time->tm_min; second = current_time->tm_sec; } void keyboard(unsigned char key, int x, int y) { switch (key){ case 27: //tecla ESCAPE exit(0); break; } } //---------------------------------------------------------------------------------------- // draw (funcao callback de desenho (principal)/desenho da cena) //---------------------------------------------------------------------------------------- void draw(void) { //TODO: desenhar os ponteiros das horas, minutos e segundos // NOTA: a cada instante que a cena e' desenhada, os // ponteiros devem indicar o tempo dado // pelo relogio do sistema glClear(GL_COLOR_BUFFER_BIT); //.... Apaga ecra glPushMatrix(); getTime(); //horas minutos e segundos actuais - para definir o angulo dos ponteiros glColor3f(1-second*0.1,1-(second+minute)*0.1,1-(second+hour)*0.1); drawAsterisk(); glRotatef(-0.5*(60*hour+minute) ,0,0,1); drawHoursHand(); glPopMatrix(); glPushMatrix(); glRotatef(-6*minute,0,0,1); drawMinsHand(); glPopMatrix(); glPushMatrix(); glRotatef(-second*6,0,0,1); drawSecsHand(); glPopMatrix(); glutSwapBuffers(); //.. actualiza ecra } //---------------------------------------------------------------------------------------- //timer (temporizador/funcao de callback) // de quanto em quanto tempo a função draw é chamada - para manter o relógio em tempo real // desenhar a cena de msec em msec (milissegundos) - inferior a 1 segundo, para vermos o relógio a funcionar //só chamamos a função (na main) para fazer registo dela //---------------------------------------------------------------------------------------- void timer(int value) { glutPostRedisplay(); //redesenhar glutTimerFunc(msecDelay,timer, 1); } //----------------------------------------------------------------------------------- //MAIN //----------------------------------------------------------------------------------- int main(int argc, char** argv) { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ glutInit(&argc, argv); //===1:Inicia janela glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); //Double mode (duplo buffer), modelo RBG glutInitWindowSize(600,500); //dimensoes (pixeis) glutInitWindowPosition(200,100); //localizacao da janela glutCreateWindow("George Nelson's Asterisk Clock");//criacao da janela //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ init(); //===2:Inicia estado/parametros //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //===3:Registo de callbacks glutDisplayFunc(draw); //desenho glutKeyboardFunc(keyboard); //eventos teclado glutTimerFunc(msecDelay,timer, 1); //temporizador //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ glutMainLoop(); //===4:Inicia processamento return 0; }
C
/* FILE: msss.c UNIT: CNCO3002 PURPOSE: Listening for client connections and serving them. REFERENCE: [1] Curtin University.(AU). Worksheet 05(tcpserv01.c): Threads. In Advanced Computer Communications (Semester 2 2018 Sri Lanka Inst Info Tech - INT[1]). Retrieved from https://lms.curtin.edu.au [2] Curtin University.(AU). Module 05: Threads. In Advanced Computer Communications (Semester 2 2018 Sri Lanka Inst Info Tech - INT[1]). Retrieved from https://lms.curtin.edu.au [3] Stevens, W. Richard, Bill Fenner, and Andrew M Rudoff. 2012. UNIX Network Programming(Chapter 30) : serv07. 1st ed. Boston [etc.]: Addison-Wesley. [4] "Terminating A Thread In C". 2018. Stack Overflow. https://stackoverflow.com/questions/6836894/terminating-a-thread-in-c. */ #include "acc.h" //Creating thread structure to store thread id of each thread typedef struct{ //To store the thread ID pthread_t thread_tid; }Thread; //Creating array of thread structures that was previously defined Thread *tptr; //Shared variables between created threads int listenfd, noOfCons, count, client_id; socklen_t addrlen; FILE *cli_list; pthread_mutex_t mlock = PTHREAD_MUTEX_INITIALIZER; //Function that initiates the threadpool void initThreadPool(int); //Function that is handled by the each thread void *thread_accept(void *); //Function to terminate threads void sig_int(int); //Function that is given to the new threads made when threadpool is busy static void * doit(void *); int main(int argc, char **argv) { int i, x, connfd; socklen_t naddrlen, nlen; pthread_t tid; struct sockaddr *ncliaddr; struct sockaddr_in servaddr; cli_details cli_info; if (argc == 3) { //noOfCons variable is Needed to store the number of threds that need to be in the thread pool noOfCons = atoi(argv[1]); count = 0; client_id = -1; //Checks if the user entered a invalid argument for the number of threads if(noOfCons == 0) { printf("MSS-S > "); err_quit("Invalid argument for number of threads"); } //Creating IPV4(AF_INET), TCP(SOCK_STREAM) socket listenfd = Socket(AF_INET,SOCK_STREAM,0); //Replacing every byte of server's socket address structure with zero bzero(&servaddr, sizeof(servaddr)); //Family of the server's socket address structure = AF_INET(IPV4) servaddr.sin_family = AF_INET; //Address of the server = INADDR_ANY(assuming that the server is multihoming device) servaddr.sin_addr.s_addr = htonl(INADDR_ANY); //Port address the server should listen at servaddr.sin_port = htons(atoi(argv[2])); //Binding the server details to the socket address structure Bind(listenfd, (SA *)&servaddr, sizeof(servaddr)); //Creating Main directory that contains all mailboxes mkdir("./mailboxes", 0777); //Creating file to store client list cli_list = Fopen("./mailboxes/clientlist.txt", "a+"); //Switching socket from closed state to listening state. Listen(listenfd,LISTENQ); //Allocating dynamic memory for the thread strcuture tptr = calloc( noOfCons,sizeof(Thread) ); //Used create the threadpool for(i=0; i<noOfCons; i++) { //Everytime this function is called a new thread will be created initThreadPool(i); } } else { //If number of argument are less or greater than the number of arguments requested by the program err_quit("usage: ./mssc.out <number of threads> <port number>"); } //Signal to caught when the user press ctrl+c/ when eof charachtor recieved Signal(SIGINT, sig_int); naddrlen = sizeof(ncliaddr); ncliaddr = (struct sockaddr *) Malloc(naddrlen); for ( ;; ) { //Creating new threads to handle new clients when whole thread pool is busy if(count == noOfCons) { nlen = naddrlen; //Mutex lock makes sure only one thread will call accept at the time and update the connfd Pthread_mutex_lock(&mlock); if(( connfd = Accept(listenfd, ncliaddr, &nlen)) > 3) { client_id++; } cli_info.connfd = connfd; cli_info.cli_id = client_id; cli_info.listen_fd = listenfd; Pthread_mutex_unlock(&mlock); Pthread_create(&tid, NULL, &doit, (void *) &cli_info); } } } void initThreadPool(int i) { Pthread_create(&tptr[i].thread_tid, NULL, &thread_accept, (void*)i); return; } void *thread_accept(void *arg) { //Will lead threads in thread pool to run independently of parent thread Pthread_detach(pthread_self()); int nconnfd; socklen_t clilen; //Array of socket structre to store client's adress struct sockaddr *cliaddr; //Dynamic memory allocation for sockets structure cliaddr = malloc(addrlen); printf("MES-S > Starting up thread %d \n",(int)arg); for( ;; ) { clilen = addrlen; //Mutex lock is used bacause to allow only one thread from pool to call accept() at a time Pthread_mutex_lock(&mlock); if( (nconnfd = Accept(listenfd, cliaddr, &clilen)) > 3) { client_id++; } //Count is to check if all threads in the thread pool are busy, so that parent thread can accept new connections count++; Pthread_mutex_unlock(&mlock); //User commands are handled by this function serv_client(nconnfd,listenfd,client_id,cli_list); //Mutex lock is used to avoid threads acessing connfd & count variables simultaneously Pthread_mutex_lock(&mlock); Close(nconnfd); count--; Pthread_mutex_unlock(&mlock); } } void sig_int(int signo) { int i=0; printf("\n"); for(i; i<noOfCons; i++) { //Terminating threads and checking if they are successfully terminated if (pthread_cancel(tptr[i].thread_tid) == 0) { printf("MES-S > Thread %d is terminated \n", i); } } fclose(cli_list); //Removing main folder created to store all the mailbox folders system("rm -rf ./mailboxes"); //Terminating the main thread exit(0); } static void * doit(void *arg) { //For new thread to run independently of parent thread Pthread_detach(pthread_self()); int connfd, clientid, listenfd; cli_details *new_info = (cli_details*) arg; connfd = (*new_info).connfd; clientid = (*new_info).cli_id; listenfd = (*new_info).listen_fd; //User commands are handled by this function serv_client(connfd, listenfd, clientid, cli_list); Close(connfd); return(NULL); }
C
#include <stdio.h> static inline long sum_recursion(int n, int before_is); int main(void) { int num_food = 0, before = 0; char *set = NULL; long sum = 0; scanf("%d", &num_food); set = calloc(sizeof(char)*num_food); printf("%ld\n", ret); return 0; } /* static inline long sum_recursion(int n, int before_is) { long sum = 0, sum1 = 0, sum2 = 0; if (n == 1) { if (before_is == 1) sum = 1; else sum = 2; } else { if (before_is == 1) sum = sum_recursion(n-1, 0); else { sum1 = sum_recursion(n-1, 1); sum2 = sum_recursion(n-1, 0); sum = sum1+sum2; } } return sum; } */
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <sys/shm.h> #include <sys/types.h> #include <sys/wait.h> #include "account.h" int main(){ //在共享内存中创建银行账户 int shmid; if((shmid = shmget(IPC_PRIVATE, sizeof(Account), IPC_CREAT | IPC_EXCL | 0777)) < 0){ perror("shmget error"); exit(1); } //进行共享内存映射 Account* a = (Account*)shmat(shmid, 0, 0); if(a == (Account*)-1){ perror("shmat error"); exit(1); } //初始化银行账户 a->code = 100001; a->balance = 10000; //创建信号量集并初始化(1个信号量集/信号灯,初始值为 1) a->semid = I(1, 1); if(a->semid < 0){ perror("I(1, 1) init error"); exit(1); } printf("balance: %f\n", a->balance); pid_t pid; if((pid = fork()) < 0){ perror("fork error"); exit(1); } else if(pid > 0){ //parent process执行取款操作 double amt = withdraw(a, 10000); printf("pid %d withdraw %f from code %d\n", getpid(), amt, a->code); wait(0); //对共享内存的操作要在解除映射之前 printf("balance: %f\n", a->balance); //销毁信号量 集 D(a->semid); //解除共享内存的映射 shmdt(a); //释放共享内存 shmctl(shmid, IPC_RMID, NULL); } else{ //子进程也执行取款操作 double amt = withdraw(a, 10000); printf("pid %d withdraw %f from code %d\n", getpid(), amt, a->code); //解除共享内存映射 shmdt(a); } return 0; }
C
/* ************************************************************************** */ /* Nome: Hélio Hideki Assakura Moreira */ /* Numero USP: 8941064 */ /* EP3: Indice Remissivo */ /* ************************************************************************** */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <ctype.h> /* STRUCTS */ typedef char * string; /*Estrutura feita para a montagem da Lista com as linhas que ocorreram cada palavra*/ struct cel{ int info; struct cel * prox; }; typedef struct cel celula; typedef celula * linha; /*Estrutura feita para os elementos*/ struct celElemento{ string palavra; int NroVezes; linha ProxLinha; }; typedef struct celElemento celula2; typedef celula2 * elemento; /*Estrutura feita para a montagem da Tabela De Simbolos*/ struct celT{ elemento info; struct celT * prox; }; typedef struct celT celula3; typedef celula3 *TdS; /*Estrutura feita para a montagem da arvore*/ typedef struct cel4 { elemento info; struct cel4 * esq; struct cel4 * dir; } no; typedef no * apontador; /* ---------------------------- */ /* Lista de Ocorrencias */ linha CriaLinha (int x){ linha novo; novo = malloc (sizeof (celula)); novo->prox = NULL; novo->info = x; return (novo); } /* Função para cópia de string, já alocando a memória para a cópia*/ string CopiaString (string s) { string str; str = malloc (strlen (s) + 1); if (str == NULL) exit( EXIT_FAILURE); strcpy (str, s); return str; } linha InsereNoFimLinha (linha inicio, int x) { linha novo, p; novo = CriaLinha (x); if (novo == NULL) printf ("ERRO \n"); if (inicio == NULL) return novo; p = inicio; while (p->prox != NULL) p = p->prox; p->prox = novo; return inicio; } void ImprimeLista (linha inicio){ linha p; for (p = inicio; p != NULL; p = p->prox) printf ("%d ", p->info); } /* --------------------- */ /*Elemento */ elemento CriaElemento (string str, int vezes, linha p){ elemento novo; novo = malloc (sizeof (celula2)); novo->palavra = CopiaString (str); novo->NroVezes = vezes; novo->ProxLinha = p; return novo; } void ImprimeElemento (elemento e){ printf ("%s ", e->palavra); printf ("%d ", e->NroVezes); printf ("["); ImprimeLista (e->ProxLinha); printf ("] \n\n"); } /* -------------------------------- */ /* Tabela de Simbolos */ TdS CriaTabela (elemento e){ TdS t; t = malloc (sizeof (celula3)); t->prox = NULL; t->info = e; return t; } void ImprimeTabela (TdS inicio){ TdS p; for (p = inicio; p != NULL; p = p->prox) ImprimeElemento (p->info); } /* Recebe o inicio da Lista (Tabela) e um elemento x, e insere esse elemento no final da lista*/ TdS InsereNoFimTabela (TdS inicio, elemento x) { TdS novo, p; novo = CriaTabela (x); if (novo == NULL) printf ("ERRO \n"); if (inicio == NULL) return novo; p = inicio; while (p->prox != NULL) p = p->prox; p->prox = novo; return inicio; } /* ---------------------------------- */ /* Arvore de Busca Binaria */ apontador CriaNo (elemento x){ apontador novo; novo = malloc (sizeof (no)); novo->info = x; novo->esq = NULL; novo->dir = NULL; return novo; } /* A função recebe a raiz e um elemento x e insere x na posição correta*/ apontador InsereArvore (apontador raiz, elemento x){ apontador p, pai, novo; novo = CriaNo (x); p = raiz, pai = NULL; while (p != NULL){ pai = p; if (strcmp (p->info->palavra, x->palavra) == -1) p = p->dir; else p = p->esq; } if (pai == NULL) return (novo); if (strcmp (pai->info->palavra, x->palavra) == -1) pai->dir = novo; else pai->esq = novo; return raiz; } /* Funções para impressão em Pré, In e Pós Ordem*/ void ImprimeArvorePre (apontador raiz){ if (raiz != NULL){ ImprimeElemento (raiz->info); ImprimeArvorePre (raiz->esq); ImprimeArvorePre (raiz->dir); } } void ImprimeArvoreIn (apontador raiz){ if (raiz != NULL){ ImprimeArvoreIn (raiz->esq); ImprimeElemento (raiz->info); ImprimeArvoreIn (raiz->dir); } } void ImprimeArvorePos (apontador raiz){ if (raiz != NULL){ ImprimeArvorePos (raiz->esq); ImprimeArvorePos (raiz->dir); ImprimeElemento (raiz->info); } } /* ---------------------------- */ /* A função Imprime recebe a linha lin, a palavra PProcurar (palavra a ser procurada), um texto e uma tabela e devolve um elemento e, com o numero de ocorrencias (ocorreu) da palavra PProcurar, uma lista p com as linhas (nlinhas) que PProcurar ocorreu e a palavra pesquisada*/ elemento Imprime (string lin, string PProcurar, FILE * texto, TdS t){ /* Aparentemente correto */ string a, token; linha p = NULL; elemento e; int ocorreu = 0, nlinhas = 1, i; a = malloc (2000 * sizeof(char)); token = malloc (20 * sizeof (char)); while (fgets (lin, 2000, texto) != NULL){ for (i = 0; lin[i] != '\0'; i++) lin[i] = tolower ( lin[i]); while (strstr (lin, PProcurar)){ a = strstr (lin, PProcurar); token = strtok (a, "\n,.;!?): "); if (!strcmp (PProcurar, token) && !isalpha(token[-1])){ p = InsereNoFimLinha (p, nlinhas); ocorreu++; } strcpy (lin,a + strlen (token) + 1); } nlinhas++; } e = CriaElemento (PProcurar, ocorreu, p); return e; } void ImprimeCabecalho (){ printf ("\n |-----------------------------------------| \n"); printf ("\n Escolha o tipo de Tabela a ser utilizada: \n"); printf (" 0 - Sair \n"); printf (" 1 - Lista Desordenada \n"); printf (" 2 - Lista Ordenada (lexicografica) \n"); printf (" 3 - Arvore de Busca Binaria (Saida Pre-Ordem) \n"); printf (" 4 - Arvore de Busca Binaria (Saida In-Ordem) \n"); printf (" 5 - Arvore de Busca Binaria (Saida Pos-Ordem) \n"); printf ("\n |-----------------------------------------| \n"); } int main(){ string caminhotexto, PProcurar, lin, *VetorDePalavras, temp, caminhopalavras; TdS t = NULL; apontador a = NULL; FILE * texto; FILE * palavras; elemento e; int i = 0, escolha = 0, QtdePalavras = 0, j; caminhotexto = malloc (200 * sizeof(char)); caminhopalavras = malloc (200 * sizeof(char)); PProcurar = malloc (20 * sizeof(char)); temp = malloc (20 * sizeof(char)); lin = malloc (2000 * sizeof(char)); printf ("Caminho Texto: "); scanf ("%s", caminhotexto); printf ("Caminho Palavras: "); scanf ("%s", caminhopalavras); ImprimeCabecalho (); scanf ("%d", &escolha); while (escolha != 0){ t = NULL; a = NULL; e = NULL; palavras = fopen (caminhopalavras, "r"); if (palavras == NULL){ printf ("ERRO \n"); exit (EXIT_FAILURE); } if (escolha == 1){ /* Após receber o arquivo com as palavras a serem pesquisadas, elas serão ser separadas em "tokens", pela função strtok(). Assim, para cada palavra, será criado um elemento com as informações necessárias (Palavra, Ocorrencias e Linhas das ocorrencias), e esse elemento será inserido na tabela t*/ while (fgets (PProcurar, 20, palavras) != NULL){ for (i = 0; PProcurar[i] != '\0'; i++) PProcurar[i] = tolower( PProcurar[i]); strtok (PProcurar, "\n"); texto = fopen (caminhotexto, "r"); if (texto == NULL){ printf ("ERRO \n"); exit (EXIT_FAILURE); } e = Imprime (lin, PProcurar, texto, t); t = InsereNoFimTabela (t, e); fclose (texto); } ImprimeTabela (t); free (e); free (t); } else if (escolha == 2){ /* Para a Lista Ordenada, as palavras também são separadas em tokens, mas antes são guardadas num vetor, e colocadas em ordem (lexicograficamente) crescente. Como as palavras não terão acento, essas palavras estarao em ordem alfabetica*/ VetorDePalavras = malloc (20000 * sizeof (char)); while (fgets (PProcurar, 20, palavras) != NULL){ for (i = 0; PProcurar[i] != '\0'; i++) PProcurar[i] = tolower( PProcurar[i]); strtok (PProcurar, "\n"); VetorDePalavras[QtdePalavras] = malloc (strlen (PProcurar) * sizeof (char)); strcpy (VetorDePalavras[QtdePalavras], PProcurar); QtdePalavras++; } for(i = 1; i < QtdePalavras; i++) for (j = 0; j < QtdePalavras -1 ; j++) if(strcmp (VetorDePalavras[j],VetorDePalavras[j+1]) > 0) { strcpy (temp,VetorDePalavras[j]); strcpy (VetorDePalavras[j],VetorDePalavras[j+1]); strcpy (VetorDePalavras[j+1],temp); } for (i = 0; i < QtdePalavras; i++){ strcpy (PProcurar, VetorDePalavras[i]); texto = fopen (caminhotexto, "r"); if (texto == NULL){ printf ("ERRO \n"); exit (EXIT_FAILURE); } e = Imprime (lin, PProcurar, texto, t); t = InsereNoFimTabela (t, e); fclose (texto); } ImprimeTabela (t); for (i = 0; i < QtdePalavras; i++) free (VetorDePalavras[i]); free(VetorDePalavras); free (e); free (t); } else{ /*Implementaçao da arvore binaria. A saida poderá ser escolhida: Pré, In ou Pós Ordem*/ while (fgets (PProcurar, 20, palavras) != NULL){ for (i = 0; PProcurar[i] != '\0'; i++) PProcurar[i] = tolower( PProcurar[i]); strtok (PProcurar, "\n"); texto = fopen (caminhotexto, "r"); if (texto == NULL){ printf ("ERRO \n"); exit (EXIT_FAILURE); } e = Imprime (lin, PProcurar, texto, t); a = InsereArvore (a, e); fclose (texto); } if (escolha == 3) ImprimeArvorePre (a); else if (escolha == 4) ImprimeArvoreIn (a); else ImprimeArvorePos (a); free (e); free (t); free (a); } fclose (palavras); i = 0, QtdePalavras = 0; ImprimeCabecalho (); scanf ("%d", &escolha); } free(caminhotexto); free(caminhopalavras); free(PProcurar); free(temp); free(lin); return 0; }
C
#include<stdio.h> int main() { int t,n,x,a[100],i,cst,w,flag; scanf("%d",&t); while(t--) { cst = 0; flag = 0; scanf("%d %d",&n,&x); for(i=0;i<n;i++) { scanf("%d",&a[i]); cst += a[i]; } w = cst % x; for(i=0;i<n;i++) { if(w >= a[i]) { printf("-1\n"); flag = 1; break; } } if(flag == 0) printf("%d\n",cst/x); } }
C
#include <stdio.h> void swap(int *px, int *py) { int temp = *px; *px = *py; *py = temp; } int main(void) { int na, nb; puts("enter two integers:"); printf("A:"); scanf("%d", &na); printf("B:"); scanf("%d", &nb); swap(&na, &nb); puts("swapped the two integers"); printf("integer A:%d\n",na); printf("integer B:%d\n",nb); return 0; }
C
#include<stdio.h> #include<locale.h> main() { int n1, n2, quociente, resto; setlocale(LC_ALL, "Portuguese"); do{ if(n1<0) printf("Valor invlido..."); printf("Digite um nmero natural: \n"); scanf("%i", &n1); } while(n1<0); do{ if(n2<2) printf("Valor invlido..."); printf("Digite outro nmero natural: \n"); scanf("%i", &n2); } while(n2<0); if(!n2){ printf("Indeterminao na diviso..."); exit(0); } for(quociente=0; n1>=n2; n1=n1-n2, quociente++); resto=n1; printf("O quociente da diviso : %i\nO resto : %i ", quociente, resto); }
C
#include "funciones.h" int MostrarMenu(float numberA, float numberB) { int options; printf("CALCULADORA\n"); printf("1- Ingresar 1er operando. A=%2.f\n",numberA); printf("2- Ingresar 2do operando. B=%2.f\n",numberB); printf("3- Calcular todas las operaciones.\na) Calcular la suma (A+B)\nb) Calcular la resta (A-B)\nc) Calcular la division (A/B)\nd) Calcular la multiplicacion (A*B)\ne) Calcular el factorial (A! y B!)\n"); printf("4- Informar resultado.\n"); printf("5- Salir.\n"); printf("Ingrese una opcion: "); scanf("%d",&options); system("cls"); return options; } float CalcularSuma(float numberA,float numberB)//no necesario que se llamen igual que en el main { float suma; suma=(numberA)+(numberB); return suma; } float CalcularResta(float numberA, float numberB) { float resta; resta= (numberA)-(numberB); return resta; } float CalcularMultiplicacion(float numberA, float numberB) { float multiplicar; multiplicar= numberA*numberB; return multiplicar; } float CalcularDivision(float numberA, float numberB) { float division; division= numberA/numberB; return division; } long int CalcularFactorial(float number) { int result; if(number == 0) { result = 1; } else { result = number * CalcularFactorial(number- 1); } return result; }
C
#include <stdio.h> #include "hash.h" typedef enum{false, true} bool; bool hashApproach(HashInt *hash, int flightLength, int nMovies, int *movies, int *firstMovie, int *secondMovie); int main(){ // Gather input printf("How much time will the flight take? (in minutes)\n"); int flightLength; scanf("%d", &flightLength); printf("How many movies are there in the list?\n"); int nMovies; scanf("%d", &nMovies); int movies[nMovies]; printf("Please write their lengths:\n"); HashInt hash; hashInit(&hash, nMovies); for(int i = 0; i < nMovies; i++){ scanf("%d", &movies[i]); hashInsert(&hash, movies[i], false); } // Process input calling hashApproach function int firstMovie, secondMovie; bool result = hashApproach(&hash, flightLength, nMovies, movies, &firstMovie, &secondMovie); // Print result if(result == true){ printf("true\n"); } else{ printf("false\n"); } return 0; } bool hashApproach(HashInt *hash, int flightLength, int nMovies, int *movies, int *firstMovie, int *secondMovie){ for(int i = 0; i < nMovies; i++){ *firstMovie = movies[i]; hashInsert(hash, *firstMovie, true); *secondMovie = flightLength - *firstMovie; int *result = hashGet(hash, *secondMovie); if(result != NULL && *result == false){ return true; } } return false; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #define SLEEP_TIME 1 #define KEY_PATHNAME "/tmp/mqueue_server_key" #define PROJECT_ID 'M' #define Q_PERMISSIONS 0666 //Un productor que envía un mensaje //random con una tasa de X/segundos. struct message_text { int id; char buf [200]; }; struct message { long message_type; struct message_text message_text; }; int config_q(); struct message p1_message; int main(){ int serv_qid = config_q(); while(1){ sleep(SLEEP_TIME); char buf [20]; sprintf (buf, "%d", rand()); strcpy (p1_message.message_text.buf, buf); printf("P1:%s\n",p1_message.message_text.buf); if(msgsnd(serv_qid, &p1_message, sizeof(struct message_text),IPC_NOWAIT) == -1){ perror("P1: msgsnd error"); exit(EXIT_FAILURE); } bzero(buf, 20); } return 0; } int config_q(){ key_t serv_q_key; int serv_qid; if((serv_q_key = ftok (KEY_PATHNAME, PROJECT_ID)) == -1){ perror("error in P1 ftok"); exit(1); } if((serv_qid = msgget(serv_q_key, Q_PERMISSIONS)) == -1){ perror("error in P1 msget"); exit(1); } p1_message.message_type = 1; p1_message.message_text.id = 1; return serv_qid; }
C
#include<stdio.h> int main() {int x,y; printf("x"); scanf("%d",&x); if(x<1) //x<1 {y=x; printf("x=%3d,y=x=%d\n",x,y); } else if(x<10) //1=<x<10 {y=2*x-1; printf("x=%d,y=2*x-1=%d\n",x,y); } else //x>=10 {y=3*x-11; printf("x=%d,y=3*x-11=%d\n",x,y); } return 0; }
C
/* ** Bit set, clear, and test operations ** ** public domain snippet by Bob Stout */ typedef enum {ERROR = -1, FALSE, TRUE} LOGICAL; #define BOOL(x) (!(!(x))) #define BitSet(arg,posn) ((arg) | (1L << (posn))) #define BitClr(arg,posn) ((arg) & ~(1L << (posn))) #define BitTst(arg,posn) BOOL((arg) & (1L << (posn)))
C
#include <stdio.h> /* 条件分岐 */ int main(void){ int score = 30; if(score >= 60){ printf("60以上\n"); }else{ printf("赤点!"); } return 0; }