language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include "channel.h" #include "stdio.h" #include "string.h" #include "stdlib.h" void ChannelInit(channel* c, int size, int elemSize) { c->size = size; c->elemSize = elemSize; if (!size) c->unbInfo = malloc(elemSize); else { c->bInfo = malloc(sizeof(queue)); QueueNew(c->bInfo, elemSize, NULL, size); } pthread_mutex_init(&c->lock, NULL); pthread_mutex_init(&c->sLock, NULL); pthread_mutex_init(&c->rLock, NULL); pthread_cond_init(&c->sCond, NULL); pthread_cond_init(&c->rCond, NULL); } void ChannelSend(channel* c, void* src) { if (!c->size) { pthread_mutex_lock(&c->sLock); pthread_mutex_lock(&c->lock); memcpy(c->unbInfo, src, c->elemSize); printf("sending %d\n", *(int*)src); // INT //printf("sending %s\n", *(char**)src); // CHAR* if (c->isReceiving) { pthread_cond_signal(&c->rCond); pthread_cond_wait(&c->sCond,&c->lock); } else { c->isSending = 1; pthread_cond_wait(&c->sCond, &c->lock); } pthread_mutex_unlock(&c->lock); pthread_mutex_unlock(&c->sLock); } else { pthread_mutex_lock(&c->sLock); pthread_mutex_lock(&c->lock); printf("want to send %d\n", *(int*)src); // INT if (QueueLength(c->bInfo) == c->size) { printf("waiting to send %d\n", *(int*)src); // INT pthread_cond_wait(&c->sCond, &c->lock); } printf("sending %d\n", *(int*)src); // INT //printf("sending %s\n", *(char**)src); // CHAR* QueuePush(c->bInfo, src); pthread_cond_signal(&c->rCond); pthread_mutex_unlock(&c->lock); pthread_mutex_unlock(&c->sLock); } } void ChannelReceive(channel* c, void* dst) { if (!c->size) { pthread_mutex_lock(&c->rLock); pthread_mutex_lock(&c->lock); if (c->isSending) { memcpy(dst, c->unbInfo, c->elemSize); c->isSending = 0; pthread_cond_signal(&c->sCond); } else { c->isReceiving = 1; pthread_cond_wait(&c->rCond, &c->lock); memcpy(dst, c->unbInfo, c->elemSize); c->isReceiving = 0; pthread_cond_signal(&c->sCond); } printf("received %d\n", *(int*)c->unbInfo); // INT //printf("received %s\n", *(char**)c->unbInfo); // CHAR* pthread_mutex_unlock(&c->lock); pthread_mutex_unlock(&c->rLock); } else { pthread_mutex_lock(&c->rLock); pthread_mutex_lock(&c->lock); printf("%d wants to receive\n", *(int*)dst); // INT if (!QueueLength(c->bInfo)) { printf("%d is waiting to receive\n", *(int*)dst); // INT pthread_cond_wait(&c->rCond, &c->lock); printf("%d woke up\n", *(int*)dst); // INT } printf("%d received %d\n", *(int*)dst, *(int*)QueueFront(c->bInfo)); // INT //printf("received %s\n", *(char**)QueueFront(c->bInfo)); // CHAR* memcpy(dst, QueueFront(c->bInfo), c->elemSize); QueuePop(c->bInfo); pthread_cond_signal(&c->sCond); pthread_mutex_unlock(&c->lock); pthread_mutex_unlock(&c->rLock); } } void ChannelDispose(channel* c) { if (!c->size) free(c->unbInfo); else { QueueDispose(c->bInfo); free(c->bInfo); } pthread_mutex_destroy(&c->lock); pthread_mutex_destroy(&c->sLock); pthread_mutex_destroy(&c->rLock); pthread_cond_destroy(&c->sCond); pthread_cond_destroy(&c->rCond); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_tab_print_one_elmnt.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ldevelle <ldevelle@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/25 21:58:05 by ldevelle #+# #+# */ /* Updated: 2019/02/25 21:58:45 by ldevelle ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" int ft_tab_print_one_elmnt(t_tab *tmp, size_t lin, size_t col, int structh) { size_t addr; addr = 14; place_cursor(lin, col); ft_putnbr(structh); place_cursor(lin, col + addr); ft_print_address_color((intmax_t)tmp->dir[0]);// UP place_cursor(lin + 1, col); ft_print_address_color((intmax_t)tmp->dir[3]);// LEFT ft_print_address_color((intmax_t)tmp);// HERE ft_print_address_color((intmax_t)tmp->dir[1]);// RIGHT place_cursor(lin + 2, col + addr); ft_print_address_color((intmax_t)tmp->dir[2]);// DOWN return (0); }
C
#ifndef TOKEN_H #define TOKEN_H typedef union token_value { int number; char operater; }token_value; typedef enum token_type { open_bracket, close_bracket, number, operater, neutral } token_type; typedef struct token { token_type type; token_value value; } token; typedef enum state { success, error, division_by_zero} state; #endif // TOKEN_H
C
//ת #include<stdio.h> int main() {int a,b,c; printf("Enter a date(mm/dd/yyyy):",a,b,c); scanf("%d/%d/%d",&a,&b,&c); printf("You entered the date:%d %d %d",c,a,b); return 0; }
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 */ struct array {scalar_t__ nelem; int /*<<< orphan*/ size; int /*<<< orphan*/ elem; } ; typedef int /*<<< orphan*/ array_compare_t ; /* Variables and functions */ int /*<<< orphan*/ ASSERT (int) ; int /*<<< orphan*/ qsort (int /*<<< orphan*/ ,scalar_t__,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ; void array_sort(struct array *a, array_compare_t compare) { ASSERT(a->nelem != 0); qsort(a->elem, a->nelem, a->size, compare); }
C
#include <stdlib.h> #include <stdio.h> void print(int n, int *p) { int i; for(i=0; i<n; i++) { printf("%d ", p[i]); } printf("\n"); } int LinearSearch(int n, int *p, int value) { int i; for(i=0; i< n; i++) { printf("%d: %d\n",i, p[i] ); if(p[i] == value) { return i; // 找到: 傳回資料位置 } } return -1; // 找不到: 回 } int BinarySearch(int n, int *p, int value) { int low=0, high=n, mid; while(low <= high) { mid = (low + high) / 2; printf("%d: %d\n",mid, p[mid] ); if(p[mid] > value) high = mid - 1; else if(p[mid] < value) low = mid+1; else //printf("%d: %d\n",mid, p[mid] ); return mid; } return -1; } int main(){ int op , key, j; int data[100]; int n = 0; while(1){ puts("1 加入並排序"); puts("2 線性搜尋"); puts("3 二元搜尋"); puts("4 列印"); puts("5 離開"); scanf("%d" , &op); switch(op){ case 1 : scanf("%d", &key); for(j = n-1 ; j >= 0 && data[j] > key ; j--){ data[j + 1] = data[j] ; } data[j+1 ] = key; n++; break; case 2 : scanf("%d", &key); if(LinearSearch(n, data, key) != -1 ){ printf("found %d\n", key); //printf("%d: %d\n",BinarySearch(n, data, key), key ); } break; case 3 : scanf("%d", &key); if(BinarySearch(n, data, key) != -1 ){ printf("found %d\n", key); } break; case 4 : print(n, data); break; case 5 : return 0; break; } system("pause"); system("cls"); } return 0; }
C
#include "flowsensor.h" #include "timerInterrupt.h" #include "heatingSys.h" #include "eeprom_calib.h" volatile uint16_t overflows=0; uint16_t freq=0; float waterConsumption =0; float calcflow =0; const uint8_t maxWaterConsumption = 200; // Liter uint8_t ErrorCodes=0; uint8_t resetTriesFlag=0; flowsensor2dtable_t lookuptable[7] = { {0, 0}, {16, 2}, {32.5, 4}, {49.3, 6}, {65.5,8}, {82,10}, {90.1,12} }; float interpolation( flowsensor2dtable_t* c, float x, uint8_t n ) { uint8_t i; for( i = 0; i < n-1; i++ ) { if ( c[i].freq <= x && c[i+1].freq >= x ) { ErrorCodes &= ~ (1<< FLOWSENSORERROR); /* Clear sensor error*/ double diffx = x - c[i].freq; double diffn = c[i+1].freq - c[i].freq; return c[i].flow + ( c[i+1].flow - c[i].flow ) * diffx / diffn; } } ErrorCodes |= 1<< FLOWSENSORERROR; return 0; // Not in Range } void initTimer0Counter(void) { DDRD &= ~(1 << DDD4); // Clear the PD4 pin // PD4 is now an input PORTD |= (1 << PORTD4); // turn On the Pull-up // PD4 is now an input with pull-up enabled /* Reset all registers*/ TCCR0B =0;TCCR0A=0;TCNT0=0;TIMSK0=0;TIFR0=0; TIMSK0 |= (1 << TOIE0); // enable timer interrupt TCCR0B |= (1 << CS02) | (1 << CS01) | (1 << CS00); // Turn on the counter, Clock on Risf } void initWaterConsumption(void) { readEEWaterConsumption(&waterConsumption); } void readFlowSensorFreq(void){ static uint16_t events_prv; static uint16_t time_prv=0; uint16_t time_now_MS=GlobalCounterInMS; uint16_t events = (overflows * 255) + TCNT0; if(time_now_MS==time_prv){ sensorTimerErrorFlag=1; /* Sensor Error*/ } else { freq = (events-events_prv); sensorTimerErrorFlag=0; /* Sensor Ok*/ } events_prv=events; time_prv=time_now_MS; } /* call this function every second*/ void calcWaterFlow(void) { calcflow = interpolation(lookuptable,freq,7); waterConsumption += ((calcflow)/60); setWaterConsumption(waterConsumption); } void storeWaterFlowinEEP(void) { static uint8_t counter=0; /* this function runs every 1min, use the counter to store every 4min the values in eeprom*/ if(WaterTimeEnabled){ SaveCALvars(); } else if(counter>4){ SaveCALvars(); counter=0; /*reset counter*/ } counter++; /*increase counter*/ } void checkErrors(void) { static uint16_t tmNow=0; static uint8_t tries=0; if(resetTriesFlag==1) { /*Task 1 second triggert a reset*/ resetTriesFlag=0; tries=0; } if(waterConsumption>maxWaterConsumption) { ErrorCodes |= 1<< MAXWATERCONSUMPTIONERROR; } else if((WaterTimeEnabled)&&(calcflow==0)&&((GlobalCounterInMS)-tmNow>3000)){ ErrorCodes |= 1<< NOWATER; tmNow = GlobalCounterInMS; } else if((WaterTimeEnabled)&&(calcflow==0)&&(((GlobalCounterInMS)-tmNow<3000))) { tries++; if(tries<6) ErrorCodes &= ~ (1<< NOWATER); } else if(sensorTimerErrorFlag==1) { ErrorCodes |= 1<< SENSORERROR; } else if(sensorTimerErrorFlag==0) { ErrorCodes &= ~ (1<< SENSORERROR); } } ISR(TIMER0_OVF_vect){ overflows++; }
C
#include <stdarg.h> #include <stdio.h> enum drink { MUDSLIDE, FUZZY_NAVEL, MONKEY_GLAND, ZOMBIE }; //in C ellpise after argument means the function should expect variable # of args void print_ints(int args, ...) { //this stores extra arguments passed to your function va_list ap; /*This says where the variable arguments start, this can be read as "the variable args will start after the args parameter". It always needs to be the last "fixed" argument. */ va_start(ap, args); //loop through all arguments, args contains the number of other arguments for (int i = 0; i < args; i++) { //va_arg takes two values, the va_list and the type of the next argument printf("argument: %i\n", va_arg(ap, int)); } //You have to say va_end so C knows you are done. va_end(ap); } double price(enum drink d) { switch (d) { case MUDSLIDE: return 6.79; case FUZZY_NAVEL: return 5.31; case MONKEY_GLAND: return 4.82; case ZOMBIE: return 5.89; default: return 0; } } double total(int args, ...) { double total = 0; va_list argsPointer; va_start(argsPointer, args); for (int i = 0; i < args; i++) { enum drink d = va_arg(argsPointer, enum drink); total += price(d); } va_end(argsPointer); return total; } int main() { //Remember first argument is number of variable args //print_ints(3, 79, 101, 32); printf("Price is %.2f\n", total(3, MONKEY_GLAND, MUDSLIDE, FUZZY_NAVEL)); printf("Price is %.2f\n", total(2, MUDSLIDE, MUDSLIDE)); printf("Price is %.2f\n", total(1, MONKEY_GLAND)); return 0; }
C
#include<stdio.h> int main() { int a,b,s; scanf("%d%d\n",&a,&b); s=a+b; printf("%d\n",s); }
C
/* * (C) Iain Fraser - GPLv3 * Util functions that suprisingly are not part of std C. */ #ifndef _MATH_UTIL_H_ #define _MATH_UTIL_H_ #define max(a,b) \ ({ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a > _b ? _a : _b; }) #define min(a,b) \ ({ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a < _b ? _a : _b; }) #define bound( a, x, c ) \ ( max( min( x, c ), a ) ) #define int_ceil_div( a, b ) \ ( ( ( a ) + ( ( b ) - 1 ) ) / ( b ) ) #define swap(a, b) \ do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0) #define safe_free( x ) do{ if( (x) ) free( (x) ); } while( 0 ) #define static_assert(x) do{switch(0){case false: case x:;}}while(0) #define array_count( x ) ( sizeof( x ) / sizeof( 0[x] ) ) /* * Credit to Pádraig Brady, the below macros have his copyright. */ #define ASSERT_CONCAT_(a, b) a##b #define ASSERT_CONCAT(a, b) ASSERT_CONCAT_(a, b) #define gl_static_assert(e) enum { ASSERT_CONCAT(assert_line_, __LINE__) = 1/(!!(e)) } #define unreachable() ( assert( false ) ) #endif
C
/* *covert from decimal to other base */ #include <stdio.h> #include <stdlib.h> int main() { int stop=0; while (stop!=1) { int inputNumber=0; while(inputNumber<=0) { printf("enter a positive integer number: "); scanf("%d",&inputNumber); } int base=0; while (base!=2 && base!=8 && base!=16) { printf("\nenter the base that you want the number to be converted: "); scanf("%d",&base); } if (base==2) { to_binary(inputNumber); } else if (base==8) { to_octal(inputNumber); } else if (base==16) { to_hexa(inputNumber); } printf ("\npress 0 to convert again"); printf ("\npress 1 to exit\n"); scanf("%d",&stop); printf("\n"); } } void to_binary(int num) { int bits[100]; int re,j; int i=0; while(num>0) { re = num % 2; num = num / 2; bits[i] = re; i++; } printf("\nthe number in binary is: "); for(j=i-1; j>=0; j--) { printf("%d",bits[j]); } printf("\n"); } void to_octal(int num) { int octal[100]; int re,j; int i=0; while(num>0) { re = num % 8; num = num / 8; octal[i] = re; i++; } printf("\nthe number in octal is: "); for(j=i-1; j>=0; j--) { printf("%d",octal[j]); } printf("\n"); } void to_hexa(int num) { int re; int i, j = 0; char hexa[100]; while (num > 0) { re= num % 16; if (re < 10) hexa[j++] = 48 + re; else hexa[j++] = 55 + re; num = num/ 16; } printf("\nthe number in hexa is: "); for (i = j; i >= 0; i--) { printf("%c", hexa[i]); } printf("\n"); }
C
#include<stdio.h> int main() { int a,b,c,d,i=0,j=0,k=0; scanf("%d%d%d",&a,&b,&c); int arr[3]={a,b,c}; for(i=0;i<3;i++){ for(j=i+1;j<3;j++){ if(arr[i]>arr[j]) { d=arr[i]; arr[i]=arr[j]; arr[j]=d; } } } for(k=0;k<3;k++){ printf("%d\n",arr[k]); } printf("\n"); printf("%d\n",a); printf("%d\n",b); printf("%d\n",c); return 0; }
C
/** * @file * @brief * * @date 03.12.12 * @author Anton Bulychev */ #include <hal/mmu.h> mmu_pgd_t *context_table[0x100] __attribute__((aligned(MMU_PAGE_SIZE))); int ctx_counter = 0; mmu_ctx_t mmu_create_context(mmu_pgd_t *pgd) { mmu_ctx_t ctx = (mmu_ctx_t) (++ctx_counter); mmu_set_ptd_entry(&context_table[ctx], pgd); return ctx; } mmu_pgd_t *mmu_get_root(mmu_ctx_t ctx) { return (mmu_pgd_t *) mmu_get_ptd_ptr(context_table[ctx]); } /* Set functions */ void mmu_pgd_set(mmu_pgd_t *pgd, mmu_pmd_t *pmd) { mmu_set_ptd_entry(pgd, pmd); } void mmu_pmd_set(mmu_pmd_t *pmd, mmu_pte_t *pte) { mmu_set_ptd_entry(pmd, pte); } void mmu_pte_set(mmu_pte_t *pte, mmu_paddr_t addr) { mmu_set_pte_entry(pte, addr, MMU_PAGE_SOMEFLAG); } /* Value functions */ mmu_pmd_t *mmu_pgd_value(mmu_pgd_t *pgd) { return (mmu_pmd_t *) mmu_get_ptd_ptr(*pgd); } mmu_pte_t *mmu_pmd_value(mmu_pmd_t * pmd) { return (mmu_pte_t *) mmu_get_ptd_ptr(*pmd); } mmu_paddr_t mmu_pte_value(mmu_pte_t *pte) { return (mmu_paddr_t) mmu_get_pte_ptr(*pte); } /* Present functions */ int mmu_pgd_present(mmu_pgd_t *pgd) { return ((unsigned int) *pgd) & MMU_ET_PRESENT; } int mmu_pmd_present(mmu_pmd_t *pmd) { return ((unsigned int) *pmd) & MMU_ET_PRESENT; } int mmu_pte_present(mmu_pte_t *pte) { return ((unsigned int) *pte) & MMU_ET_PRESENT; } /* Unset functions */ void mmu_pgd_unset(mmu_pgd_t *pgd) { mmu_set_val(pgd, 0); } void mmu_pmd_unset(mmu_pmd_t *pmd) { mmu_set_val(pmd, 0); } void mmu_pte_unset(mmu_pte_t *pte) { mmu_set_val(pte, 0); } /* Page Table flags */ void mmu_pte_set_writable(mmu_pte_t *pte, int val) { if (val) { mmu_set_val(pte, *pte | MMU_PAGE_WRITABLE); } else { mmu_set_val(pte, *pte & (~MMU_PAGE_WRITABLE)); } } void mmu_pte_set_usermode(mmu_pte_t *pte, int val) { if (val) { mmu_set_val(pte, *pte & (~MMU_PAGE_SUPERVISOR)); } else { mmu_set_val(pte, *pte | MMU_PAGE_SUPERVISOR); } } void mmu_pte_set_cacheable(mmu_pte_t *pte, int val) { if (val) { mmu_set_val(pte, *pte | MMU_PAGE_CACHEABLE); } else { mmu_set_val(pte, *pte & (~MMU_PAGE_CACHEABLE)); } } void mmu_pte_set_executable(mmu_pte_t *pte, int val) { }
C
#include "minishell.h" size_t tailledest(char *); void redir(char* mot[]){ int i,tmp; size_t reste; short separ; char *signe, *dest, *destcut, *temp; separ=0; for(i=0;mot[i] != NULL;i++){ signe=strstr(mot[i],"<"); //cas "<" if(signe!=NULL){ if(strlen(signe)==1){ //"<" et le fichier à rediriger sont séparés par un espace separ=1; //indicateur pour retirer les redirection de la commande dest=mot[i+1]; //fichier servant de redirection } else {//"<" et le fichier à rediriger n'était pas séparés separ=2; dest=signe+1; } } temp=strstr(mot[i],">>"); //cas ">>" if(temp!=NULL && (signe==NULL || strlen(temp)>strlen(signe))){ signe=temp; if(strlen(signe)==2){ separ=1; dest=mot[i+1]; } else { separ=2; dest=signe+2; } } temp=strstr(mot[i],"2>"); //cas "2>" if(temp!=NULL && (signe==NULL || strlen(temp)>strlen(signe))){ signe=temp; if(strlen(signe)==2){ separ=1; dest=mot[i+1]; } else { separ=2; dest=signe+2; } } temp=strstr(mot[i],">"); //cas ">" if(temp!=NULL && (signe==NULL || strlen(temp)>strlen(signe))){ signe=temp; if(strlen(signe)==2){ separ=1; dest=mot[i+1]; } else { separ=2; dest=signe+1; } } if(separ){ if(*signe=='<') tmp=close(0); if(*signe=='>') tmp=close(1); if(*signe=='2') tmp=close(2); if (tmp < 0){ perror("close"); exit(1); } reste=tailledest(dest); //signes pour voir s'il ne reste pas d'autre redirection non séparées par des espaces if(reste<strlen(dest)){ destcut=malloc((reste+1)*sizeof(char)); if(destcut==NULL){ perror("malloc"); exit(1); } strncpy(destcut,dest,reste); *(destcut+reste)='\0'; if((*signe=='>' && *(signe+1)!='>') || *signe=='2') tmp=open(destcut,O_WRONLY | O_CREAT | O_TRUNC,0666); if(*signe=='>' && *(signe+1)=='>') tmp=open(destcut,O_WRONLY | O_CREAT | O_APPEND,0666); if(*signe=='<') tmp=open(destcut,O_RDONLY); free(destcut); if (tmp < 0){ perror("open"); exit(1); } } else{ if((*signe=='>' && *(signe+1)!='>') || *signe=='2') tmp=open(dest,O_WRONLY | O_CREAT | O_TRUNC,0666); if(*signe=='>' && *(signe+1)=='>') tmp=open(dest,O_WRONLY | O_CREAT | O_APPEND,0666); if(*signe=='<') tmp=open(dest,O_RDONLY); if (tmp < 0){ perror("open"); exit(1); } } if (strlen(mot[i])>strlen(signe)){ //si la redirection est collée au mot d'avant if(separ==2){ //si elle est aussi collée au mot d'après if(strlen(dest)>reste) i--; strncpy(signe,dest+reste,strlen(signe)); separ=0; continue; } memset(signe,'\0',strlen(signe)); if(strlen(dest)>reste){ strncpy(dest,dest+reste,strlen(dest)); continue; } reste=strlen(dest); i++; separ=2; //permettra d'effacer le mot d'après } if(separ==1){ if(strlen(dest)>reste){ strncpy(dest,dest+reste,strlen(dest)); reste=strlen(dest); separ=2; } else{ for(tmp=i;mot[tmp]!=NULL;tmp+=2){ if(tmp+2>=MaxMot) mot[tmp]=NULL; else mot[tmp]=mot[tmp+2]; if(tmp+3>=MaxMot) mot[tmp+1]=NULL; else mot[tmp+1]=mot[tmp+3]; } } i--; } if(separ==2){ if(strlen(dest)>reste) strncpy(signe,dest+reste,strlen(signe)); else{ for(tmp=i;mot[tmp]!=NULL;tmp++){ if(tmp+1>=MaxMot) mot[tmp]=NULL; else mot[tmp]=mot[tmp+1]; } } i--; } separ=0; } } } size_t tailledest(char * suite){ size_t reste; char* temp; reste=strlen(suite); temp=strstr(suite,"2>"); if(temp!=NULL) reste-=strlen(temp); temp=strstr(suite,">"); if(temp!=NULL && (strlen(suite)-strlen(temp)<reste)) reste=strlen(suite)-strlen(temp); temp=strstr(suite,"<"); if(temp!=NULL && (strlen(suite)-strlen(temp)<reste)) reste=strlen(suite)-strlen(temp); temp=strstr(suite,"|"); if(temp!=NULL && (strlen(suite)-strlen(temp)<reste)) reste=strlen(suite)-strlen(temp); return reste; }
C
#pragma once #include "model.h" #include "factor.h" struct Graph{ // G[i][j] = bitmask(3) -> [b2 b1 b0] // b0 = transition edge // b1 = skip edge // b2 = pair skip edge vector<vector<int> > G; int n; // key = bitmask(n) -> [bn-1 bn-2 ... b1 b0] // (bi==1) => ith node is present map<int, Factor> factors; void init(const vector<int>& img1, const vector<int>& img2, const Model& model, int type){ init_graph(img1, img2, type); vector<int> img; img.insert(img.end(), img1.begin(), img1.end()); img.insert(img.end(), img2.begin(), img2.end()); init_factors(img, model, type); } void init_graph(const vector<int>& img1, const vector<int>& img2, int type){ int n1 = img1.size(), n2 = img2.size(); n = img1.size() + img2.size(); // Generating graph G.assign(n, vector<int>(n,0)); if(type>=2){ // Transition Factors for(int i=0;i<n1-1;i++)SET(G[i][i+1],0),SET(G[i+1][i],0); for(int i=0;i<n2-1;i++)SET(G[n1+i][n1+i+1],0),SET(G[n1+i+1][n1+i],0); } if(type>=3){ // Skip Factors for(int i=0;i<n1;i++) for(int j=i+1;j<n1;j++) if(img1[i]==img1[j])SET(G[i][j],1), SET(G[j][i],1); for(int i=0;i<n2;i++) for(int j=i+1;j<n2;j++) if(img2[i]==img2[j])SET(G[n1+i][n1+j],1), SET(G[n1+j][n1+i],1); } if(type>=4){ for(int i=0;i<n1;i++) for(int j=0;j<n2;j++){ if(img1[i]==img2[j])SET(G[i][n1+j],2), SET(G[n1+j][i],2); } } } void init_factors(const vector<int>& img, const Model& model, int type){ // phi(i) -> corresponding to OCR factors Factor phi; for(int i=0;i<n;i++){ phi.init((1<<i)); for(int c=0;c<10;c++){ phi.v[c] *= model.ocr[img[i]][c]; } phi.normalize(); factors[1<<i] = phi; } // phi(i,j) for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(G[i][j]==0)continue; phi.init((1<<i)+(1<<j)); if(BIT(G[i][j], 0)){ // Transition Factor (note importance of ordering) for(int c1=0;c1<10;c1++) // c1 -> assigned to i for(int c2=0;c2<10;c2++) // c2 -> assigned to j = i+1 phi.v[10*c2+c1] *= model.trans[c1][c2]; } if(BIT(G[i][j], 1)){ // Skip Factor for(int c=0;c<10;c++) phi.v[10*c + c] *= model.skip; } if(BIT(G[i][j], 2)){ // Pair-Skip Factor for(int c=0;c<10;c++) phi.v[10*c + c] *= model.pair_skip; } phi.normalize(); factors[(1<<i) + (1<<j)] = phi; } } } int key(const vector<int>& x, int mask){ int i=0, ret=0, pv=1; while(mask){ if(mask&1){ ret = x[i]*pv + ret; pv *= 10; } i++; mask>>=1; } return ret; } double factor_product(const vector<int>& x){ double ret=0; for(auto &p:factors){ ret += log(p.second.v[key(x, p.first)]); } return exp(ret); } int sample(int i, vector<int> x){ vector<double> p(10, 0); double sum=0, toss_value = double(rand())/double(INT_MAX); for(int j=0;j<10;j++){ x[i] = j; p[j] = factor_product(x); sum += p[j]; } for(int j=0;j<10;j++) p[j]/=sum; for(int j=1;j<10;j++) p[j]+=p[j-1]; for(int j=8;j>=0;j--) if(toss_value>=p[j]) return j+1; return 0; } void gibbs_sampler(vector<int>& x,vector<vector<double> >& p){ vector<vector<int> > cnt(n,vector<int>(10, 0)); for(int i=0;i<n;i++) x[i]=rand()%10; int i=0, itr=1; while(itr<=5500){ x[i] = sample(i, x); if(itr>500) // Burn out cnt[i][x[i]]++; itr++; i=(i+1)%n; } for(int i=0;i<n;i++){ x[i]=0; for(int j=0;j<10;j++) x[i] += cnt[i][j]; for(int j=0;j<10;j++) p[i][j] = double(cnt[i][j])/double(x[i]); x[i]=0; for(int j=0;j<10;j++) if(cnt[i][j]>cnt[i][x[i]]) x[i]=j; } } void print(){ printf("Graph:\n"); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ cout<<G[i][j]<<" "; } cout<<endl; } } };
C
#ifndef FILEMANIPULATOR_H_INCLUDED #define FILEMANIPULATOR_H_INCLUDED #include <stdio.h> #include <string.h> #include <malloc.h> #define YOGA_SEEK_SET 0 #define YOGA_SEEK_CUR 1 int count_char_max(FILE* t_fp) { fpos_t pos; int count_char=0; char char_scan; fgetpos(t_fp,&pos); fseek(t_fp,0,SEEK_SET); char_scan=fgetc(t_fp); while(char_scan!=EOF) { count_char++; char_scan=fgetc(t_fp); } fsetpos(t_fp,&pos); return count_char; } int count_char_left(FILE* t_fp) { fpos_t pos; int count_char=0; char char_scan; fgetpos(t_fp,&pos); char_scan=fgetc(t_fp); while(char_scan!=EOF) { count_char++; char_scan=fgetc(t_fp); } fsetpos(t_fp,&pos); return count_char; } void yogaSeek(FILE* fp,int offset,char mode) { int i=0; if(mode==YOGA_SEEK_SET) fseek(fp,0,SEEK_SET); for(i=0;i<offset;i++) { fgetc(fp); } } #endif // FILEMANIPULATOR_H_INCLUDED
C
// // Created by James on 27/11/2020. // // OPEN FILES // FILE *fd = fopen("wombat.txt", "r"); // stdio.h int open(const char *path, int flags, mode_t mode);// POSIX // Returns a positive int of file descriptor, -1 if error // CREATE FILES // int creat(const char *pathname, mode_t mode); // CLOSE FILES // int close(int fd);// unistd.h // READING & WRITING DATA // /* Both return number of bytes read/written or -1 if error * Data read to/written from buffer (buf) of size (count) */ ssize_t read(int fd, void *buf, size_t count); ssize_t write(int fd, const void *buf, size_t count); // RANDOM ACCESS FILES // off_t lseek(int fd, off_t offset, int whence); /* * OFFSETS: * SEEK_SET - the offset is relative to the start of the file. * SEEK_CUR - the offset is relative to the current position within the file. * SEEK_END - the offset is relative to the current end of the file. */ // NAVIGATING HIERARCHICAL DIRECTORY STRUCTURE // // GET CURRENT WORKING DIRECTORY // char *getcwd(char *buffer, size_t size); // buffer = null if error // CHANGE WORKING DIRECTORY // int chdir(const char *path); // Return -1 if error // MAKE A DIRECTORY // int mkdir(const char *path, mode_t mode); // mode sets attributes (access permissions) // OPENING A DIRECTORY // DIR *opendir(const char *name); // CLOSING A DIRECTORY // int closedir(DIR *dirp); // READING A DIRECTORY // /* Reads file sequentially until none left, then NULL is returned */ struct dirent *readdir(DIR *dirp); struct dirent {// DIRECTORY STRUCTURE ino_t d_ino; // I-node number of file off_t d_off; unsigned short d_reclen; unsigned char d_type; char d_name[256]; // name of file }; /* example reading directory*/ DIR *dp = opendir("/usr/bin"); struct dirent *entry; while ((entry = readdir(dp)) != NULL){ printf("%8d - %s\n", entry->d_ino, entry->d_name); } closedir(dp); // READING & MODIFYING FILE ATTRIBUTES // // READ int stat(const char *pathname, struct stat *statbuf); // Stat struct MACROS // S_ISDIR() // returns true if directory S_ISREG // returns true if a regular file // stat field st_mode contains file acces permissions getpduid() // get name of user ID getgrgid() // get primary group id to which owner belongs strftime() // get dat and time localtime() // break up time_t value // chmod and utime etc can also be used
C
/* (a) Write a program that reads a message, then prints the reversal of the * message: * * Enter a message: Don't get mad, get even. * Reversal is: .neve teg ,dam teg t'noD * * Hint: Read the message one character at a time (using getchar) and store the * characters in an array. Stop reading when the array is full or the character * read is '\n'. * * (b) Revise the program to use a pointer instead of an integer to keep track * of the current position in the array. */ #include <stdio.h> #define BUF 100 int main(void) { char *p; char input, msg[BUF]; printf("\nEnter a message: "); for (p = &msg[0]; p < &msg[0] + BUF; p++) { if ((input = getchar()) == '\n') break; *p = input; } /* print the message in reverse, starting from the last character */ printf("Reversal is: "); for (p = p-1; p >= &msg[0]; p--) putchar(*p); printf("\n\n"); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> //int main() //{ // int a = 0x11223344; // int* p = &a; // *p = 0; // return 0; //} // //int* test() //{ // static int a = 10; // return &a; //} //int main() //{ // int* p = test(); // printf("hehe\n"); // printf("%d", *p); // return 0; //} //int main() //{ // int arr[5] = { 0 }; // int* p = arr; // int i = 0; // for (i = 0; i < 5; i++) // { // *(p + i) = i; // } // for (i = 0; i < 5; i++) // { // printf("%d ", *(p + i)); // } // return 0; //} //int my_strlen(char* str) //{ // char* start = str; // while (*str != '\0') // { // str++; // } // return str - start; //} //int main() //{ // char arr[] = "abdfef"; // int len = my_strlen(arr); // printf("%d", len); // return 0; //} //int My_strlen(char* arr) //{ // int count = 0; // while (*arr != '\0') // { // count++; // arr++; // } // return count; //} //int main() //{ // char arr[] = "abcdef"; // int len = My_strlen(arr); // printf("%d", len); // return 0; //}
C
#include<stdio.h> #include<stdlib.h> #include<string.h> //#include<algorithm> int a[1000006]={0},b[1000006]={0},c[1000006]={0}; char arr[1000006]; struct node { long long int p; long long int q; }s[1000006]; int compare(const void*a,const void*b) { struct node* x=(struct node*)a; struct node* y=(struct node*)b; if(x->p==y->p) return (x->q-y->q); else return(x->p-y->p); } int main() { int i=0,len; scanf("%s",arr); len=strlen(arr); long long int cnt=0,temp=0;//p[0]=make_pair(0,0); for(i=1;i<=len;i++) { if(arr[i-1]=='A') { a[i]=a[i-1]+1; b[i]=b[i-1]; c[i]=c[i-1]; } else if(arr[i-1]=='B') { a[i]=a[i-1]; b[i]=b[i-1]+1; c[i]=c[i-1]; } else if(arr[i-1]=='C') { a[i]=a[i-1]; b[i]=b[i-1]; c[i]=c[i-1]+1; } s[i].p=(b[i]-a[i]); s[i].q=(c[i]-a[i]); } s[0].p=0;s[0].q=0; qsort(s,len+1,sizeof(struct node),compare); struct node test; test.p=-100000000;test.q=-100000000; /* for(int i=0;i<=strlen(arr);i++) printf("%d ",a[i]); printf("\n"); for(int i=0;i<=strlen(arr);i++) printf("%d ",b[i]); printf("\n"); for(int i=0;i<=strlen(arr);i++) printf("%d ",c[i]); printf("\n");*/ for(i=0;i<=len;i++) { if(!(s[i].p==test.p && s[i].q==test.q)) { test.p=s[i].p;test.q=s[i].q; temp=0; } cnt+=temp; temp+=1; } printf("%lld\n",cnt); //system("pause"); return 0; }
C
#include <assert.h> #include <stdio.h> #include <string.h> #include "sv/token.h" void scan(char* sToken) { sv_token_state_t state; memset(&state, 0, sizeof(sv_token_state_t)); state.input = sToken; state.length = strlen(sToken); state.pos.line = 1; state.pos.column = 1; state.tab_columns = 8; sv_token_t token; memset(&token, 0, sizeof(sv_token_t)); bool result = sv_token_scan(&state, &token); if (!result) { fprintf(stderr,"scan failed for token '%s'\n", sToken); exit(1); } char* sShow = sv_token_show(token); printf("%s\n", sShow); free(sShow); } int main(int argc, char* argv[]) { // end of input. scan(""); // end of input after some whitespace. scan(" "); // keywords scan("!def"); scan("!let"); scan("!rec"); scan("!in"); scan("!def "); // punctuation scan("("); scan(")"); scan("{"); scan("}"); scan("["); scan("]"); scan(","); scan(";"); scan("="); // names scan("variable"); scan("%symbol"); scan("%some'symbol"); scan("@def"); scan("@some'def"); scan("?nominal"); scan("?some'nominal"); scan("#primitive"); scan("#nat'add"); scan("#nat'add'again"); // literals scan("1234"); scan("0"); // space before token. scan(" derp"); // space after token. scan(" derp "); // tab character in input. { char str[] = " derp"; str[0] = '\t'; scan(str); } // new line character in input. { char str[] = " derp"; str[0] = '\n'; scan(str); } // variable token appears before punc. scan("variable)"); // symbol name appears before punc. scan("%symbol)"); }
C
#include <stdio.h> #include <stdlib.h> #include "Lib.h" int getNumberFromUser() { int number_from_user; //0x00: 12 printf("Pls enter a interger number!\n"); scanf("%d", &number_from_user); return number_from_user; // return 12; } float meanVector(Vector *vec) { float sum = 0.0f; for (unsigned int i = 0; i < vec->length; i++) { sum += vec->data[i]; } float mean = sum / vec->length; return mean; } int minVector(Vector *vec) { int min; for (unsigned int i = 0; i < vec->length; i++) { if (i == 0) { min = vec->data[i]; } if (vec->data[i] < min) { min = vec->data[i]; } } return min; } int maxVector(Vector *vec) { int max; for (unsigned int i = 0; i < vec->length; i++) { if (i == 0) { max = vec->data[i]; } if (vec->data[i] > max) { max = vec->data[i]; } } return max; } int *createArray(unsigned int length, int value) { int *p_data; p_data = (int *)malloc(length * sizeof(int)); for (unsigned int i = 0; i < length; i++) { p_data[i] = value; } return p_data; } void printVector(Vector *vec) { for (unsigned int i = 0; i < vec->length; i++) { printf("%d\n", vec->data[i]); } } int *freeArray(Vector *vec) { free(vec->data); vec->data = NULL; }
C
#include <stdio.h> #include "appconfigscanner.h" #include <stdlib.h> #include<string.h> #include "structs.h" extern yylex(); extern int yylineno; extern char* yytext; char *names[]={ "GRID_DIM_x", "GRID_DIM_y", "GRID_DIM_z", "BLOCK_DIM_x", "BLOCK_DIM_y", "BLOCK_DIM_z", "INTEGER", }; void printConfig(CudaConfig config){ printf("Grid Dimension X: %d\n",config.gridDimX); printf("Grid Dimension Y: %d\n",config.gridDimY); printf("Grid Dimension Z: %d\n",config.gridDimZ); printf("Block Dimension X: %d\n",config.blockDimX); printf("Block Dimension Y: %d\n",config.blockDimY); printf("Block Dimension Z: %d\n",config.blockDimZ); printf("Total Threads: %d\n", config.gridDimX*config.gridDimY*config.gridDimZ*config.blockDimX*config.blockDimY*config.blockDimZ); } int main(void){ int ntoken, vtoken; CudaConfig config; ntoken=yylex(); while(ntoken){ printf("%d",yylineno); int token2 = yylex(); int token3 = yylex(); if (ntoken == UNEXPECTED){ printf("Unexpected config option in the file\n"); break; } if(token2!=COLON){ printf("You forgot to insert a colon, found %d \n",token2); break; } if(token3!=INTEGER){ printf("Config values must be integers\n"); break; } // printf("%d\n",atoi(yytext)); switch(ntoken){ case BLOCK_DIM_x: config.blockDimX=atoi(yytext); break; case BLOCK_DIM_y: config.blockDimZ=atoi(yytext); break; case BLOCK_DIM_z: config.blockDimZ=atoi(yytext); break; case GRID_DIM_x: config.gridDimX=atoi(yytext); break; case GRID_DIM_y: config.gridDimY=atoi(yytext); break; case GRID_DIM_z: config.gridDimZ=atoi(yytext); break; default: printf("unknown setting"); } ntoken=yylex(); } printConfig(config); }
C
//ȡһеżλλֱС #define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> void print_Binary_Sequence(int num) { int count = 0; int i = 0; int arr[32] = { 0 }; while (num) { arr[i] = num % 2; count++; i++; num /= 2; } printf("żУ"); for (i = count; i >= 0; i -= 2) { printf("%d ", arr[i]); } printf("\n"); printf("У"); for (i = count - 1; i >= 0; i -= 2) { printf("%d ", arr[i]); } } int main() { int num = 0; scanf("%d", &num); print_Binary_Sequence(num); system("pause"); return 0; }
C
/* accept file name from user and read data of the file $ gcc readfile.c -o myexe $ ./myexe mydemo.txt data will read from "mydemo.txt" file depends on given len which is third parameter of prototype */ //reading file #include<stdio.h> #include<unistd.h> #include<fcntl.h> int main(int argc, char *argv[]) { int fd; char buff[45]; int iret = 0; int len = sizeof(buff); fd = open(argv[1], O_RDONLY); if(fd == -1) { printf("Error : unalble to open file\n"); close(fd); return -1; } printf("File open successfully fd is %d\n",fd); iret = read(fd, buff, len); if(iret == -1) { printf("Error: Unable to read file\n"); close(fd); return -1; } printf("data read successfully %d\n%s\n",iret,buff); close(fd); printf("File close successfully fd is %d\n",fd); return 0; }
C
#include <stdio.h> int main() { int a[100],j,i,k,t; for(i=0;i<100;i++) scanf("%d",&a[i]); printf("\n"); for(i=0;i<99;i++) { for(j=i+1;j<100-i;j++) { if(a[i]>a[j]) {t=a[i]; a[i]=a[j]; a[j]=t;} } }printf("the sort number is\n"); for(i=0;i<100;i++) printf("%3d",a[i]); return 0; }
C
#include <stdlib.h> #include <stdio.h> void itob(int n, char s[], int b); void reverse(char s[]); int main(void) { char buffer[10]; int i; for ( i = 2; i <= 20; ++i ) { itob(255, buffer, i); printf("Decimal 255 in base %-2d : %s\n", i, buffer); } return 0; } /* itob: convert n to charecters in s - base b */ void itob(int n, char s[], int b) { int i, j, sign; void reverse(char s[]); if ((sign = n) < 0) n = -n; i = 0; do { j = n%b; s[i++] = (j <= 9) ? j+'0' : j+'a'-10; } while ((n /= b) > 0); if (sign < 0) s[i++] = '-'; s[i] = '\0'; reverse(s); } /* Reverses string s[] in place */ void reverse(char s[]) { int c, i, j; for ( i = 0, j = strlen(s)-1; i < j; i++, j--) { c = s[i]; s[i] = s[j]; s[j] = c; } }
C
#include<stdio.h> int main() { int a,b,c,d,e; scanf("%d",&a); b=a%10; c=a/10%10; d=a/100; e=b*100+c*10+d*1; printf("%d",e); return 0; }
C
// poj 1007 #include <stdio.h> #define M (102) #define N (102) typedef struct a_s { int i; int v; char s[M]; } a_t; int partition(a_t a[], int left, int right) { a_t pivot = a[left]; int j = left; int i = left + 1; // 2.1 以最左边的值p为基准 // 2.2 变量j初始化为最左边的位置 // 2.3 从左到右对数组进行遍历,当遇到一个值小于p的元素,则对j加1,交换当前遍历到元素和j位置的元素 // 2.4 上述遍历过程中,保证j及其左边的值均小于等于基准值p while (i <= right) { if ((a[i].v < pivot.v ||(a[i].v == pivot.v && a[i].i <= pivot.i))) { a_t t = a[++j]; a[j] = a[i]; a[i] = t; } i++; } // 2.5 遍历完后,交换位置j和最左边的元素,即位置j的元素的值为基准值p a[left] = a[j]; a[j] = pivot; return j; } void qsort(a_t a[], int left, int right) { if (left >= right) { return; } // 1. 通过partition操作,将数组分割成两部分 // 2. 分割点所在的值为p,则左边部分的值都小于等于p,右边部分的值大于p int mid = partition(a, left, right); // 3. 递归对左、右两部分进行分割操作 qsort(a, left, mid - 1); qsort(a, mid + 1, right); } int main() { a_t b[N]; int m, n, i, j, k; while(~scanf("%d %d", &m, &n)) { for (i = 0; i < n; i++) { scanf("%s", b[i].s); } for (i = 0; i < n; i++) { b[i].i = i; b[i].v = 0; int f[30] = {0}; for (j = m-1; j >=0; j--) { int s = b[i].s[j] - 'A'; f[s]++; for (k = 0; k < s; k++) { b[i].v += f[k]; } } } qsort(b, 0, n-1); for (int i = 0; i < n; i++) { //printf("%d %s\n", b[i].v, b[i].s); printf("%s\n", b[i].s); } } return 0; }
C
#include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <limits.h> #include <stdbool.h> int main() { int x1; int v1; int x2; int v2; scanf("%i %i %i %i", &x1, &v1, &x2, &v2); int result_size; if((x1<x2) && (v1<v2)) printf("NO"); else { if((v1!=v2) && ((x2-x1)%(v1-v2))==0) printf("YES"); else printf("NO"); } }
C
//Explore cmath library #include <stdio.h> #include <math.h> int main (){ double d = 2.18; double e = 3.14; printf("double d = %.2f\n",d); printf("cos(d) = %.4f\n",cos(d)); printf("exp(d) = %.4f\n",exp(d)); printf("log(d) = %.4f\n",log(d)); printf("double e = %.2f\n",e); printf("pow(d,e) = %.4f\n",pow(d,e)); printf("sqrt(d) = %.4f\n",sqrt(d)); printf("ceil(d) = %.2f\n",ceil(d)); printf("floor(d) = %.2f\n",floor(d)); }
C
/* * drawCockpit * cockpitImage * drawControlPanel * drawPoint * drawBar */ // pos telecamera Point3 pos_present=g_camera.getPos(), pos_past=g_camera.getPos(); // variabile che tiene conto del tempo clock_t precClock, precClock1=clock(); char msgShoot[1024]; void cockpitImage(); void drawControlPanel(); void drawBar(); void drawPoint(GLfloat centerX, GLfloat centerY); void drawSight(GLfloat centerX, GLfloat centerY); void drawRectMissiles(int num); // void drawEllipse(GLfloat centerX, GLfloat centerY, GLfloat radiusX, GLfloat radiusY); /* * gluOrtho2D( left, right, bottom, up ) - setta la matrice di proiezione ortografica 2D * CONVENZIONE: * lo schermo è suddiviso in un insieme infinito di valori nell'intervallo [0,1] * i 4 valori permettono di fissare la porzione dello schermo sulla quale si vuole lavorare * * up (1,0) (1,1) * * bottom (0,0) (0,1) * * left right * per settare tutto lo schermo: * gluOrtho2D(0, 1, 0, 1); * da 0 a sinistra a 1 a destra, da 0 in basso a 1 in alto */ // main: DRAW COCKPIT void drawCockpit(){ // disabilitiamo queste opzioni in modo da poter lavorare in 2D glDisable(GL_LIGHTING); // lighting glDisable(GL_DEPTH_TEST); // z buffer glDisable(GL_CULL_FACE); // face culling glPushAttrib(GL_ALL_ATTRIB_BITS); // attiva il viewport del pannello (a tutto schermo) glViewport(0, 0, width, height); // CHIAMATA ALLA FUNZIONE COCKPITIMAGE: inserimento dell'immagine del cockpit cockpitImage(); // CHIAMATA A DRAWCONTROLPANEL: rendering delle info sullo schermo drawControlPanel(); glPopAttrib(); // riabilitiamo quanto precedentemente disabilitato glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); // per non vedere il frame buffer mentre viene disegnato glutSwapBuffers(); } // COCKPIT IMAGE: inserisce l'immagine del cockpit in primo piano void cockpitImage(){ GLfloat x1,x2,y1,y2; glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D(0,1,0,1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); // BARRA DI PRECISIONE/VELOCITA' MOUSE x1=0.4738, x2=x1+0.01058; y1=0.048, y2=y1+0.2; glColor3f(0,0,0); glRectf(x1,y1,x2,y2); GLfloat h_bar=y2-y1; glColor3f(0, 2-(5*0.2), 0.2*5); glLineWidth(1); for(float i=0;i<(precMouse-1)*0.01;i+=0.03){ glBegin(GL_LINES); glVertex2f(x1, y1+(h_bar-0.001)*i); glVertex2f(x2, y1+(h_bar-0.001)*i); glEnd(); } glColor3f(1,1,1); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // per attivare la trasparenza nelle regioni dell'immagine dove e' presente glBindTexture(GL_TEXTURE_2D,g_textureArray[0]); // per settare l'altezza dell'immagine del cockpit GLfloat imageHeight=0.42; // per settare la larghezza del cockpit (eliminare le parti nere ai lati) x1=-0.034; x2=1.0369; glBegin(GL_QUADS); glTexCoord2f(0,0);glVertex3f(x1,-0.002,0); glTexCoord2f(1,0);glVertex3f(x2,-0.002,0); glTexCoord2f(1,1);glVertex3f(x2,imageHeight,0); glTexCoord2f(0,1);glVertex3f(x1,imageHeight,0); glEnd(); glDisable(GL_BLEND); glDisable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } // DRAW CONTROL PANEL: disegna il pannello di controllo void drawControlPanel(){ glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D(0, 1, 0, 1); // resetta modelview glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glPushMatrix(); // MIRINO al centro dello schermo switch(sight){ case REDSIGHT: drawPoint(0.5, 0.5); break; case GREENSIGHT: drawSight(0.5,0.5); break; case NO: break; } // rettangoli che indicano il numero di missili presenti drawRectMissiles(nSuperShoot); // RADAR GLfloat centreX, centreY, radiusX, radiusY; // coordinate cerchio/ellisse centreX=0.3355; centreY=0.14; radiusX=0.1; radiusY=0.08; // perimetro dell'ellisse glColor3f( 1, 1, 1); glLineWidth(0.02); glBegin(GL_LINES); for(int t=0; t<720; t++) glVertex3f(centreX+(radiusX*cos(t*(PI/180.0))), centreY+(radiusY*sin(t*(PI/180.0))),0.1); glEnd(); //drawEllipse(centreX,centreY,radiusX,radiusY); // croce dentro il radar glColor3f( 1, 1, 1); glLineWidth(0.01); glBegin(GL_LINES); //linea orizzontale glVertex3f(centreX-radiusX, centreY,0.1); glVertex3f(centreX+radiusX, centreY,0.1); //linea verticale glVertex3f(centreX, centreY-radiusY,0.1); glVertex3f(centreX, centreY+radiusY,0.1); glEnd(); // puntino verde (fronte) o rosso (retro) /* * x,y coordinate che permettono di visualizzare la posizione dell'oggetto sul radar * z coordinata che permette di capire se l'oggetto è davanti o dietro alla telecamera * */ float x,y,z; Point3 u; //visualizzazione dei 9 pianeti sul radar for(int i=0;i<9;i++){ u=g_camera.getPos(); // prendiamo la posizione di ogni pianeta u.x -= posPlanet[i].x; u.y -= posPlanet[i].y; u.z -= posPlanet[i].z; u = Normalize(u); x = -ProdScal(u,g_camera.getRight()); y = -ProdScal(u,g_camera.getUp()); z = -ProdScal(u,g_camera.getView()); //printf("x=%f\ty=%f\tz=%f\n",x,y,z); fflush(stdout); glPointSize(6); // HENRY: colore modificato glBegin(GL_POINTS); if (z>=0) glColor3f(0, 1, 0); // se e' davanti: verde else glColor3f(0, 0.4, 0); // se e' dietro: verde scuro glVertex2f(centreX+(radiusX*x), centreY+(radiusY*y)); glEnd(); } // posizione nemici sul radar for(int i=0;i<NUM_ENEMY;i++){ u=g_camera.getPos(); if(enemy[i].life>0 && distance(u,enemy[i].pos)<=DIST_RADAR){ //if(true){ // prendiamo la posizione di ogni nemico u.x -= enemy[i].pos.x; u.y -= enemy[i].pos.y; u.z -= enemy[i].pos.z; u = Normalize(u); x = -ProdScal(u,g_camera.getRight()); y = -ProdScal(u,g_camera.getUp()); z = -ProdScal(u,g_camera.getView()); glPointSize(3.5); glBegin(GL_POINTS); if (z>=0) glColor3f(1, 0, 0); // se e' davanti: rosso else glColor3f(0.5, 0, 0); // se e' dietro: rosso scuro glVertex2f(centreX+(radiusX*x), centreY+(radiusY*y)); glEnd(); } } //polizia for(int i=0;i<NUM_POLICE;i++){ u=g_camera.getPos(); if(police[i].life>0 && distance(u,police[i].pos)<=DIST_RADAR){ //if(true){ // prendiamo la posizione di ogni nemico u.x -= police[i].pos.x; u.y -= police[i].pos.y; u.z -= police[i].pos.z; u = Normalize(u); x = -ProdScal(u,g_camera.getRight()); y = -ProdScal(u,g_camera.getUp()); z = -ProdScal(u,g_camera.getView()); glPointSize(3.5); glBegin(GL_POINTS); if (z>=0) glColor3f(0, 0, 1); // se e' davanti: blu else glColor3f(0, 0.5, 0.5); // se e' dietro: blu scuro glVertex2f(centreX+(radiusX*x), centreY+(radiusY*y)); glEnd(); } } // MESSAGGI DI BORDO int n=checkDistPlanet(g_camera.getPos()); // indice pianeta se abb vicino //printf("pianeta %d", n); if(n>=0){ glColor3f(1,1,1); sprintf(temp ,"Welcome to %s: press T", getPlanetName(n)); glRasterPos2f(0.515, 0.325); renderBitmapString(GLUT_BITMAP_HELVETICA_12, temp); } //ALBERTO if( (hitEnemy!=-1 || hitPolice!=-1) && abs(clock()-precClock)>=CLOCKS_PER_SEC*1){ precClock=clock(); if(hitEnemy!=-1) sprintf(msgShoot ,"Hit Enemy! Energy remained: %d%%", (int) (enemy[hitEnemy].life>=0? enemy[hitEnemy].life : 0)); if(hitPolice!=-1) sprintf(msgShoot ,"Hit Police! Energy remained: %d%%", (int) (police[hitPolice].life>=0? police[hitPolice].life : 0)); } else if( (hitEnemy==-1 && hitPolice==-1) && abs(clock()-precClock1)>=CLOCKS_PER_SEC*2){ precClock1=clock(); sprintf(msgShoot ,""); } glColor3f(1,1,1); glRasterPos2f(0.515, 0.3); renderBitmapString(GLUT_BITMAP_HELVETICA_12, msgShoot); // si disegnano le barre di velocita', energia e carburante drawBar(); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); } // DRAW RECTANGLE MISSILE: disegna sul cockpit il numero di missili disponibili void drawRectMissiles(int num){ GLfloat x1=0.2715, y1=0.2935, w=0.0323, h=0.0265; if(num>0) glColor3f(0, 0.14, 0); else glColor3f(0.5, 0, 0); glRectf(x1,y1,x1+w,y1+h); x1+=0.082; if(num>1) glColor3f(0, 0.14, 0); else glColor3f(0.5, 0, 0); glRectf(x1,y1,x1+w,y1+h); x1+=0.082; if(num>2) glColor3f(0, 0.14, 0); else glColor3f(0.5, 0, 0); glRectf(x1,y1,x1+w,y1+h); } // DRAW BAR: disegna le barre di velocita', energia e carburante void drawBar(){ GLfloat x1, x2, y1, y2; /* coordinate quadrilatero * * y2 * * * * y1 * * * * 0 x1 x2 * */ // la coordinata x e la lunghezza sono uguali per tutte x1=0.575; x2=x1+0.175; //x2=0.75; // BARRA DELLA VELOCITA' // settiamo la coordinata y y1=0.175; y2=y1+0.015; // posizionamento e inserimento della scritta SPEED glColor3f( 1, 1, 1); glRasterPos2f(x1, y2+0.01); renderBitmapString(GLUT_BITMAP_HELVETICA_12, "SPEED"); // si determina la velocita' GLfloat v = (g_camera.getSpeed())/(g_camera.MAXSPEED); // si setta il colore a seconda della velocita' che varia tra 0 e 1 glColor3f(2*v, 2-(v*2), 0); GLfloat w_bar=x2-x1; //GLfloat h_bar=y2-y1; glLineWidth(2); glBegin(GL_QUADS); glVertex3f(x1+0.001, y1+0.0015, 0.1); glVertex3f(x1+0.001, y2-0.0015, 0.1); glVertex3f(x1+(w_bar-0.001)*v, y2-0.0015, 0.1); glVertex3f(x1+(w_bar-0.001)*v, y1+0.0015, 0.1); glEnd(); // quadrilatero esterno glLineWidth(2); glColor3f( 1, 1, 1); glBegin(GL_LINE_LOOP); glVertex2f(x1, y1); glVertex2f(x1, y2); glVertex2f(x2, y2); glVertex2f(x2, y1); glEnd(); // posizioniamo la percentuale di velocita' sprintf(temp ,"%d%%", (int)(v*100)); glRasterPos2f(x2+0.006, y1); renderBitmapString(GLUT_BITMAP_HELVETICA_12, temp); // BARRA DELL'ENERGIA // settiamo la coordinata y y1=y1-0.05; y2=y1+0.015; // posizionamento e inserimento della scritta ENERGY glColor3f( 1, 1, 1); glRasterPos2f(x1, y2+0.01); renderBitmapString(GLUT_BITMAP_HELVETICA_12, "ENERGY"); // per intanto è l'inverso della velocità //energy=1-v; GLfloat en= energy/100.0; glColor3f(2*(1-en), 2-((1-en)*2), 0); w_bar=x2-x1; //GLfloat h_bar=y2-y1; glLineWidth(2); glBegin(GL_QUADS); glVertex3f(x1+0.001, y1+0.0015, 0.1); glVertex3f(x1+0.001, y2-0.0015, 0.1); glVertex3f(x2-(w_bar-0.001)*(1-en), y2-0.0015, 0.1); glVertex3f(x2-(w_bar-0.001)*(1-en), y1+0.0015, 0.1); glEnd(); // quadrilatero esterno glLineWidth(2); glColor3f(1, 1, 1); glBegin(GL_LINE_LOOP); glVertex2f(x1, y1); glVertex2f(x1, y2); glVertex2f(x2, y2); glVertex2f(x2, y1); glEnd(); // posizioniamo la percentuale di velocita' sprintf(temp ,"%d%%", (int) energy); glRasterPos2f(x2+0.006, y1); renderBitmapString(GLUT_BITMAP_HELVETICA_12, temp); // BARRA DEL CARBURANTE // settiamo la coordinata y y1=y1-0.05; //y1=0.125; y2=y1+0.015; // posizionamento e inserimento della scritta FUEL glColor3f( 1, 1, 1); glRasterPos2f(x1, y2+0.01); renderBitmapString(GLUT_BITMAP_HELVETICA_12, "FUEL"); // consumo del carburante pos_present=g_camera.getPos(); if(abs((int) (fuel*100))>0 && (abs(pos_present.x-pos_past.x)>5.0 || abs(pos_present.y-pos_past.y)>5.0 || abs(pos_present.z-pos_past.z)>5.0)){ // diminuiamo un po' il carburante fuel-= 0.002; //fuel-= 0.2; // aggiorniamo la posizione passata pos_past=g_camera.getPos(); } // se finisce il carburante si porta diminuisce la velocita' fino a fermare la navetta if(abs((int)(fuel*100))<=0 && v>0.0 && abs(clock()-precClock)>=CLOCKS_PER_SEC*0.1){ g_camera.accelerate(-CAM_SPEED_STEP); glutPostRedisplay(); // calcoliamo il tempo precedente, per diminuire la velocita' con gradualita' precClock=clock(); } glColor3f(2*(1-fuel), 2-((1-fuel)*2), 0); w_bar=x2-x1; //GLfloat h_bar=y2-y1; glLineWidth(2); glBegin(GL_QUADS); glVertex3f(x1+0.001, y1+0.0015, 0.1); glVertex3f(x1+0.001, y2-0.0015, 0.1); glVertex3f(x2-(w_bar-0.001)*(1-fuel), y2-0.0015, 0.1); glVertex3f(x2-(w_bar-0.001)*(1-fuel), y1+0.0015, 0.1); glEnd(); // quadrilatero esterno glLineWidth(2); glColor3f( 1, 1, 1); glBegin(GL_LINE_LOOP); glVertex2f(x1, y1); glVertex2f(x1, y2); glVertex2f(x2, y2); glVertex2f(x2, y1); glEnd(); // posizioniamo la percentuale di velocita' sprintf(temp ,"%d%%", (int) (fuel*100)); glRasterPos2f(x2+0.006, y1); renderBitmapString(GLUT_BITMAP_HELVETICA_12, temp); } // DRAW POINT: disegna il punto che indica dove si spara void drawPoint(GLfloat centerX, GLfloat centerY){ // puntino rosso glColor3f(1, 0, 0); GLfloat radiusX=0.0023, radiusY=0.0042; //radiusY=radiusX+0.0005; drawEllipse(centerX,centerY,radiusX,radiusY); } void drawSight(GLfloat centerX, GLfloat centerY){ glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D(0,1,0,1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // per attivare la trasparenza nelle regioni dell'immagine dove e' presente glBindTexture(GL_TEXTURE_2D,g_textureArray[6]); glBegin(GL_QUADS); glTexCoord2f(0,0);glVertex3f(centerX-0.5,centerY-0.51,0); glTexCoord2f(1,0);glVertex3f(centerX+0.5,centerY-0.51,0); glTexCoord2f(1,1);glVertex3f(centerX+0.5,centerY+0.49,0); glTexCoord2f(0,1);glVertex3f(centerX-0.5,centerY+0.49,0); glEnd(); glDisable(GL_BLEND); glDisable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } // DISEGNO DI UN ELLISSE: se si vuole un cerchio radiusX=radiusY void drawEllipse(GLfloat centerX, GLfloat centerY, GLfloat radiusX, GLfloat radiusY){ glBegin(GL_TRIANGLE_FAN); glVertex2f(centerX, centerY); for(int angle=0;angle<720;angle+=1) glVertex2f(centerX + radiusX*sin(angle/2.0), centerY + radiusY*cos(angle/2.0)); glEnd(); }
C
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *link; }; struct node *start = NULL; void insert(int el) { struct node *newNode = malloc(sizeof(struct node)); newNode->data = el; newNode->link = NULL; if (!start) { start = newNode; return; } struct node *tempNode = start; while (tempNode->link) tempNode = tempNode->link; tempNode->link = newNode; } void display() { struct node *tempNode = start; while (tempNode) { printf("%d", tempNode->data); if (tempNode->link) printf(" -> "); tempNode = tempNode->link; } printf("\n"); } void reverse() { struct node *prev = NULL; struct node *curr = start; struct node *next = NULL; while (curr) { next = curr->link; curr->link = prev; prev = curr; curr = next; } curr->link = prev; start = curr; } void main() { int num, el, i; printf("\n\t\tLinked list Reversal\n"); printf("How many elements do you want to enter? "); scanf("%d", &num); for (i = 0; i < num; i++) { printf("Enter element %d: ", i + 1); scanf("%d", &el); insert(el); } printf("\nThe entered linked list is:\n"); display(); reverse(); printf("\nAfter reversing:\n"); display(); }
C
// // id_checking.c // // // Created by Juan García on 1/24/19. // #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #define PROGRAM_FILE "fz_function.cl" #define KERNEL_NAME_FUNC "fz_function" #define Gx 256 #define Gy 256 #define Lx 16 #define Ly 16 #define N_WORK_ITEMS 64; #ifdef __APPLE__ #define CL_SILENCE_DEPRECATION #include <OpenCL/cl.h> #else #include <CL/cl.h> #endif void check_error(cl_int err, char *str) { if(err<0) { printf("SORRY,THERE IS AN ERROR IN %s\n",str); exit(1); } } // FUNCTION TO SET THE DEVICES cl_device_id CreateDevice() { cl_platform_id platform; cl_device_id dev; cl_int err; err = clGetPlatformIDs(1,&platform,NULL); check_error(err, "DEVICE CREATION"); err = clGetDeviceIDs(platform,CL_DEVICE_TYPE_GPU,1,&dev,NULL); if(err==CL_DEVICE_NOT_FOUND) { err = clGetDeviceIDs(platform,CL_DEVICE_TYPE_CPU,1,&dev,NULL); } check_error(err,"DEVICE CREATION"); return dev; } cl_program BuildProgram(cl_context cntx, cl_device_id dev, const char *filename) { cl_program program; cl_int err; FILE *program_handle; char *program_buffer, *program_log; size_t program_size,log_size; program_handle = fopen(filename,"r"); if(program_handle==NULL) { perror("FILE NOT FOUND"); exit(1); } fseek(program_handle,0,SEEK_END); program_size = ftell(program_handle); rewind(program_handle); program_buffer = (char *)malloc(program_size + 1); program_buffer[program_size] = '\0'; fread(program_buffer,sizeof(char),program_size,program_handle); fclose(program_handle); // CREATE THE PROGRAM FROM A FILE program = clCreateProgramWithSource(cntx,1,(const char**)&program_buffer,&program_size,&err); check_error(err,"PROGRAM CREATION"); free(program_buffer); //BUILD THE PROGRAM err = clBuildProgram(program,0,NULL,NULL,NULL,NULL); if(err<0) { clGetProgramBuildInfo(program,dev,CL_PROGRAM_BUILD_LOG,0,NULL,&log_size); program_log = (char *)malloc(log_size+1); program_log[log_size] = '\0'; clGetProgramBuildInfo(program,dev,CL_PROGRAM_BUILD_LOG,log_size+1,program_log,NULL); printf("%s\n",program_log); free(program_log); exit(1); } return program; } void user_input(int *Nx,int *Ny, int *Nz,float *x0, float *xN,float *y0,float *yN,float *z0,float *zN,float *hx, float *hy,float *hz,int *Ntot) { //MODULE TO GET THE USER INPUT printf("NUMBER OF POINTS IN X,Y & Z\n"); scanf("%d %d %d",Nx,Ny,Nz); printf("INITIAL AN FINAL POINTS IN X COORDINATE\n"); scanf("%f %f",x0,xN); printf("INITIAL AN FINAL POINTS IN Y COORDINATE\n"); scanf("%f %f",y0,yN); printf("INITIAL AN FINAL POINTS IN Z COORDINATE\n"); scanf("%f %f",z0,zN); *hx = (*xN-(*x0))/(float)(*Nx-1); *hy = (*yN-(*y0))/(float)(*Ny-1); *hz = (*zN-(*z0))/(float)(*Nz-1); *Ntot = (*Nx)*(*Ny)*(*Nz); } void get_3Dcube_file(int Nx,int Ny,int Nz,float x0,float y0,float z0,float hx,float hy,float hz,float *f,int Ntot) { int i,j; FILE *cube_out; cube_out=fopen("out.cube","w"); if(cube_out==NULL) { perror("COULD NOT CREATE FILE\n"); exit(1); } fprintf(cube_out,"CUBE FILE FORMAT 3D\n"); fprintf(cube_out,"GRID EVALUATION\n"); fprintf(cube_out,"%4d \t% 10.6f \t% 10.6f \t% 10.6f\n",1,x0,y0,z0); fprintf(cube_out,"%4d \t% 10.6f \t% 10.6f \t% 10.6f\n",Nx,hx,0.,0.); fprintf(cube_out,"%4d \t% 10.6f \t% 10.6f \t% 10.6f\n",Ny,0.,hy,0.); fprintf(cube_out,"%4d \t% 10.6f \t% 10.6f \t% 10.6f\n",Nz,0.,0.,hz); fprintf(cube_out,"%4d \t% 10.6f \t% 10.6f \t% 10.6f \t% 10.6f\n",3,3.,0.,0.,0.); for(i=0,j=0; i<Ntot; i++) { j++; fprintf(cube_out,"\t%10.6E",f[i]); if(j==6 || i==Ntot-1) { fprintf(cube_out,"\n"); j=0; } } fclose(cube_out); } int main(void) { cl_device_id device; cl_context context; cl_command_queue cQ; cl_program program; cl_kernel kernel; cl_int err; int Nx,Ny,Nz,Ntot; float x0,xN,y0,yN,z0,zN,hx,hy,hz; user_input(&Nx,&Ny,&Nz,&x0,&xN,&y0,&yN,&z0,&zN,&hx,&hy,&hz,&Ntot); printf("STEPS IN X = %f, STEPS IN Y = %f, STEPS IN Z = %f\n",hx,hy,hz); printf("TOTAL POINTS = %d\n",Ntot); float step[]={hx,hy,hz}; float point0[]={x0,y0,z0}; float test[Ntot]; //WORK-ITEMS DATA****************** size_t dim = 2; size_t global_offset[] = {0,0}; size_t global_size[] = {Gx,Gy}; size_t local_size[] = {Lx,Ly}; //MEMORY OBJECTS******************** cl_mem read_buff,buff_step,buff_points; // CREATE A DEVICE AND A CONTEXT device = CreateDevice(); // FUNCTION ABOVE context = clCreateContext(NULL,1,&device,NULL,NULL,&err); check_error(err,"CONTEXT CREATION"); // BUILD THE PROGRAM AND CREATE THE KERNEL program = BuildProgram(context,device,PROGRAM_FILE); kernel = clCreateKernel(program,KERNEL_NAME_FUNC,&err); check_error(err,"KERNEL CREATION"); //CREATE A WRITE ONLY BUFFER TO HOLD THE OUTPUT DATA read_buff = clCreateBuffer(context,CL_MEM_WRITE_ONLY,sizeof(test),NULL,&err); check_error(err,"BUFFER CREATION"); buff_step = clCreateBuffer(context,CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR,sizeof(step),step,&err); check_error(err,"BUFFER CREATION"); buff_points = clCreateBuffer(context,CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR,sizeof(point0),point0,&err); check_error(err,"BUFFER CREATION"); //CREATE KERNEL ARGUMENT //check_error(err, "KERNEL SETTING ARGUMENT"); err = clSetKernelArg(kernel,0,sizeof(cl_mem),&read_buff); err |= clSetKernelArg(kernel,1,sizeof(cl_mem),&buff_step); err |= clSetKernelArg(kernel,2,sizeof(cl_mem),&buff_points); err |= clSetKernelArg(kernel,3,sizeof(Ny),&Ny); err |= clSetKernelArg(kernel,4,sizeof(Nz),&Nz); err |= clSetKernelArg(kernel,5,sizeof(Ntot),&Ntot); check_error(err, "KERNEL SETTING ARGUMENT"); // CREATING THE COMMAND QUEUE TO SEND INSTRUCTIONS TO THE DEVICE cQ = clCreateCommandQueue(context,device,0,&err); check_error(err, "COMMAND QUEUE CREATION"); // ENQUEUE THE KERNEL err = clEnqueueNDRangeKernel(cQ,kernel,dim,global_offset,global_size,local_size,0,NULL,NULL); check_error(err,"THE KERNEL ENQUEUEING"); // READ AND PRINT THE RESULT err = clEnqueueReadBuffer(cQ,read_buff,CL_TRUE,0,sizeof(test),&test,0,NULL,NULL); check_error(err, "BUFFER READING"); /*for(cl_int i=0; i<24; i+=6) { printf("%.2f %.2f %.2f %.2f %.2f %.2f\n", test[i],test[i+1],test[i+2],test[i+3],test[i+4],test[i+5]); }*/ printf("NUMBER OF LAUNCHED WORK-ITEMS: %d\n",Gx*Gy); printf("NUMBER OF LAUNCHED WORK-GROUPS: %d\n",(Gx*Gy)/(Lx*Ly)); printf("WORK-GROUPS SIZE: (%dx%d)\n",Lx,Ly); printf("2D GRID TO 1D GRID:\n"); /*for(cl_int i=0; i<Gx*Gy; i++) { printf("work_item[%d] = %10.6f\n",i,test[i]); }*/ get_3Dcube_file(Nx,Ny,Nz,x0,y0,z0,hx,hy,hz,test,Ntot); // FREE RESOURCES clReleaseMemObject(read_buff); clReleaseKernel(kernel); clReleaseCommandQueue(cQ); clReleaseProgram(program); clReleaseContext(context); return 0; }
C
// Exercise 3-1. // Our binary search makes two tests inside the loop, when one would suffice // (at the price of more tests outside.) Write a version with only one test // inside the loop and measure the difference in run-time. #include <stdio.h> int main() { fprintf(stderr, "not yet done\n"); return 1; }
C
/* * FIT VUT - PDS PROJECT 2012/2013 - LONGEST PREFIX MATCH * (c) Ondrej Fibich <xfibic01@stud.fit.vutbr.cz> */ #ifndef PREFIX_TREE_MATCH_H #define PREFIX_TREE_MATCH_H #include <stdlib.h> #include <stdint.h> /* * Tree for storing prefixes and searching for longest match on stored prefixes. */ /** * Node of tree */ typedef struct _node_t { /** Left children */ struct _node_t *l; /** Right children */ struct _node_t *r; /** destination */ uint32_t next_hop_ip; uint8_t next_hop_interface; } node_t; #define TRIE_MEMORY_CELL_SIZE 32768 /** * Memory stack for nodes */ typedef struct _trie_memory_t { /** Count of used memory cells */ int ln; /** Next memory cell */ struct _trie_memory_t *next; /** Memory cells */ node_t cells[TRIE_MEMORY_CELL_SIZE]; } trie_memory_t; /** * Trie tree */ typedef struct _trie_t { /** Root node */ node_t *root; /** First memory cell */ trie_memory_t *first; /** Current memory cell */ trie_memory_t *last; } trie_t; /** * Initializes the trie tree * * @param t */ void trie_init(trie_t *t); /** * Destroys allocated memory * * @param t */ void trie_destroy(trie_t *t); /** * Puts the given network address to prefix tree * * @param t trie tree * @param ip IP of subnet * @param cidr subnet length * @param as value */ void trie_node_put(trie_t *t, uint8_t *ip, uint8_t cidr, uint32_t next_hop_ip, uint8_t next_hop_interface); /** * Searches for network for the given IP address * * @param t trie tree * @param ip IP of subnet * @param as store value to * @return if success than >0 else 0 */ uint8_t trie_node_search(trie_t *t, uint8_t *ip, uint32_t *next_hop_ip, uint8_t *next_hop_interface); #endif
C
#include <stdio.h> #include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */ struct node { int data; struct node* left; struct node* right; }; int max(int a,int b) { if(a>b) return a; else return b; } int depth(struct node *root) { if(!root) return 0; int left=0,right=0; left=depth(root->left); right=depth(root->right); return max(left,right)+1; } struct node* newNode(int data) { struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node); } /* Driver program to test above functions*/ void getwidth(struct node *root,int *array,int level) { if(!root) return; array[level]++; getwidth(root->left,array,level+1); getwidth(root->right,array,level+1); } int getMaxWidth(int *array,int n) { int max=array[0],i; for (i = 0; i < n; ++i) { if(array[i]>max) max=array[i]; } return max; } int main() { struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(8); root->right->right->left = newNode(6); root->right->right->right = newNode(7); /* Constructed bunary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */ int length=depth(root),i; int array[length]; for (i = 0; i < length; ++i) { array[i]=0; } getwidth(root,array,1); printf("Maximum width is %d \n", getMaxWidth(array,length)); return 0; }
C
#include <stdio.h> #include <memory.h> #define maxn 10000000 #define maxp 1000000 char mk[maxn] ; int prime[maxp] , pnum ; void GenPrime ( int n ){ int i,j,k; pnum = 0; memset(mk, 0, n+1); for(i=2,k=4; i<=n; i++, k+=i+i-1){ if(!mk[i]){ prime[pnum++] = i; if(k<=n) for(j=i+i; j<=n; j+=i) mk[j] = 1; } } } int main() { GenPrime(10000000); printf("%d\n", pnum); for(int i=0; i<pnum; ++i) printf("%d ", prime[i]); printf("\n"); return 0; }
C
#include "Instruction.h" /* isInstruction: this methods gets a Line from declerationCmd. Line stores the data from assembly row. its read the information from Line: L.label,L.cmd and L.data and set it in tmpCmd. tmpCmd represents an assembly insruction with operands. returns False by eror, other wise returns True. ---------------------------------------------------------*/ int isInstructionRow(Line L,int scan,int* Syntax_Eror) { Command tmpCmd; /*Stores an assembly instruction with operands*/ /*Instruction has no a label*/ if(!strcmp(L.cmd,END_OF_STRING)) { /*gets instruction index*/ tmpCmd.index = getCmdType(L.label); /*Instruction is undefined*/ if(tmpCmd.index == Eror){ fprintf(stderr,"LINE %d: Eror, invalid syntax:%s.\n",L.index,L.label); *Syntax_Eror = False; return False; } /*Set addressing type of the operands Immediat,Direct,Matrix,Register and gets their data*/ if(!setOperandType(&tmpCmd,L.data,Syntax_Eror)){ /*operands data or addressing type is invalid*/ *Syntax_Eror = False; return False; } } /*Instruction has a label*/ else { int eror_type; /*Indicates the eror type*/ /*Checks valid label*/ if(!isValidLabel(L.label)){ *Syntax_Eror = False; return True; } if(scan == FIRST_SCAN){ /*Insert label of instruction to symbol table*/ if((eror_type = insertSymbol(L.label,IC,True,False,False))!=True){ if(eror_type == False){ /*label is already defined in program*/ fprintf(stderr,"Line %d: Eror - Label: %s, is already defined in program.\n", L.index,L.label); *Syntax_Eror = False; } else{ fprintf(stderr,"Eror - Failure by allocating memory.\n"); *Syntax_Eror = False; } /*Instruction label cannot be inserted into symbol table*/ return False; } } /*Gets instruction index */ tmpCmd.index = getCmdType(L.cmd); /*Instruction is undefined*/ if(tmpCmd.index == Eror){ printf("\nLine %d: Eror - invalid insturction %s.\n",L.index,L.cmd); *Syntax_Eror = False; return False; } /*Set addressing type of the operands Immediat,Direct,Matrix,Register*/ if(!setOperandType(&tmpCmd,L.data,Syntax_Eror)){ /*operands data or addressing type is invalid*/ *Syntax_Eror = False; return False; } } /*Checks valid operands for the given insturction*/ if(!opcodeParam(tmpCmd)) { /*undefined operands for the given instruction*/ *Syntax_Eror = False; return False; } /*Encode data in Second scan*/ if(scan == SECOND_SCAN){ /*creates a machine code for the given instruction*/ /*coding the insturction to the binarycode array*/ if(!encode(tmpCmd,tmpCmd.src,tmpCmd.dst)){ *Syntax_Eror = False; return False; } } return True; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <float.h> #include "cchess.h" #include "ai.h" #include "gameState.h" #include "valid.h" #include "piece.h" #include "linkedList.h" #include "move.h" // Function for evaluating a game to determine who is winning // Positive number = current turn winning // Negative number = current turn losing // The higher the better double eval(GameState *game, int depth) { // At depth zero, evaluate and return score if (depth == 0) { double score = 0; Piece *temp; // Go through board for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { temp = game->board->board[i][j]; if (temp != NULL) { if (temp->color == game->turn) score += pointVal(temp); else score -= pointVal(temp); } } } return score; } else { // Recusive step // Find the average of playing and evaluating all possible moves // Get all of current players pieces LinkedList *pieces = findPieces(game, game->turn); LinkedList *currentPieceList = pieces; Move *headMove = createMove(-1, -1, -1, -1); LinkedList *allMoves = createList(headMove, NULL); LinkedList *pieceMoves; PiecePos *currentPiece; // Loop through pieces while (currentPieceList != NULL && currentPieceList->data != NULL) { currentPiece = currentPieceList->data; // Get all moves for that piece pieceMoves = findMoves(game, currentPiece); // Add moves to collection of all moves allMoves = listConcat(allMoves, pieceMoves); // Move to next piece currentPieceList = currentPieceList->next; } freePiecePosList(pieces); int moves = 0; LinkedList *currentMove = allMoves->next; GameState *new; char move[4]; double score = 0, tempScore; while (currentMove != NULL && currentMove->data != NULL) { // Create a copy of the current game state new = createGameState(game); // Play move moveToChar(currentMove->data, move); makeMove(move, new->board); // Simulate next player's turn new->turn ^= 1; // Decrease depth and evaluate new state tempScore = eval(new, depth - 1); score += tempScore; moves++; #ifdef DEBUG //printf("Player %d Testing move: %.4s Score: %f\n", new->turn, move, tempScore); #endif freeGameState(new); currentMove = currentMove->next; } freeMoveList(allMoves); // Return average score of moves return score / moves; } } // Find all of a player's pieces // Return in linked list LinkedList * findPieces(GameState *game, int turn) { // Create a list to store result LinkedList *results = createList(NULL, NULL); /*LinkedList *current = results;*/ PiecePos *temp; // Traverse board looking for players pieces for (int rank = 0; rank < 8; rank++) { for (int file = 0; file < 8; file++) { if (game->board->board[rank][file] && game->board->board[rank][file]->color == turn) { // Store piece position in structure temp = createPiecePos(rank, file); // Add piece position to list results = listPush(results, temp); // Advance list //current = current->next; } } } return results; } // Find all the moves a piece can make LinkedList * findMoves(GameState *game, PiecePos *piecePos) { // Create a list to store result LinkedList *results = NULL; //LinkedList *current = results; Move *tempMove, *copyTempMove; char charTempMove[4]; int direction; Piece *piece = game->board->board[piecePos->rank][piecePos->file]; // Possible moves for a pawn static int pawnMoves[4][2] = {{1, -1}, {1, 0}, {1, 1}, {2, 0}}; // Possible moves for a knight static int knightMoves[8][2] = {{-2, -1}, {-1, -2}, {1, -2}, {2, -1}, {2, 1}, {1, 2}, {-1, 2}, {-2, 1}}; // Possible moves for a king static int kingMoves[8][2] = {{1, -1}, {1, 0}, {1, 1}, {0, -1}, {0, 1}, {-1, -1}, {-1, 0}, {-1, 1}}; switch (piece->type) { case PAWN: // Switch move direction based on turn if (game->turn == WHITE) { direction = -1; } else { direction = 1; } // Check four possible moves for (int i = 0; i < 4; i++) { tempMove = createMove(piecePos->rank, piecePos->file, piecePos->rank + (direction * pawnMoves[i][0]), piecePos->file + pawnMoves[i][1]); moveToChar(tempMove, charTempMove); if (validMove(charTempMove, game->turn, game->board)) { copyTempMove = copyMove(tempMove); results = listPush(results, copyTempMove); } free(tempMove); } break; case KNIGHT: // Check all 8 possible moves for a knight for (int i = 0; i < 8; i++) { tempMove = createMove(piecePos->rank, piecePos->file, piecePos->rank + knightMoves[i][0], piecePos->file + knightMoves[i][1]); moveToChar(tempMove, charTempMove); if (validMove(charTempMove, game->turn, game->board)) { copyTempMove = copyMove(tempMove); results = listPush(results, copyTempMove); } free(tempMove); } break; case BISHOP: // Check diagonal moves for (int i = 0; (piecePos->rank + i < 8) && (piecePos->file + i < 8); i++) { tempMove = createMove(piecePos->rank, piecePos->file, piecePos->rank + i, piecePos->file + i); moveToChar(tempMove, charTempMove); if (validMove(charTempMove, game->turn, game->board)) { copyTempMove = copyMove(tempMove); results = listPush(results, copyTempMove); } free(tempMove); } for (int i = 0; (piecePos->rank - i >= 0) && (piecePos->file - i >= 0); i++) { tempMove = createMove(piecePos->rank, piecePos->file, piecePos->rank - i, piecePos->file - i); moveToChar(tempMove, charTempMove); if (validMove(charTempMove, game->turn, game->board)) { copyTempMove = copyMove(tempMove); results = listPush(results, copyTempMove); } free(tempMove); } for (int i = 0; (piecePos->rank - i >= 0) && (piecePos->file + i < 8); i++) { tempMove = createMove(piecePos->rank, piecePos->file, piecePos->rank - i, piecePos->file + i); moveToChar(tempMove, charTempMove); if (validMove(charTempMove, game->turn, game->board)) { copyTempMove = copyMove(tempMove); results = listPush(results, copyTempMove); } free(tempMove); } for (int i = 0; (piecePos->rank + i < 8) && (piecePos->file - i >= 0); i++) { tempMove = createMove(piecePos->rank, piecePos->file, piecePos->rank + i, piecePos->file - i); moveToChar(tempMove, charTempMove); if (validMove(charTempMove, game->turn, game->board)) { copyTempMove = copyMove(tempMove); results = listPush(results, copyTempMove); } free(tempMove); } break; case ROOK: // Check vertical moves for (int i = 0; piecePos->rank + i < 8; i++) { tempMove = createMove(piecePos->rank, piecePos->file, piecePos->rank + i, piecePos->file); moveToChar(tempMove, charTempMove); if (validMove(charTempMove, game->turn, game->board)) { copyTempMove = copyMove(tempMove); results = listPush(results, copyTempMove); } free(tempMove); } for (int i = 0; piecePos->rank - i >= 0; i++) { tempMove = createMove(piecePos->rank, piecePos->file, piecePos->rank - i, piecePos->file); moveToChar(tempMove, charTempMove); if (validMove(charTempMove, game->turn, game->board)) { copyTempMove = copyMove(tempMove); results = listPush(results, copyTempMove); } free(tempMove); } // Check horizontal moves for (int i = 0; piecePos->file + i < 8; i++) { tempMove = createMove(piecePos->rank, piecePos->file, piecePos->rank, piecePos->file + i); moveToChar(tempMove, charTempMove); if (validMove(charTempMove, game->turn, game->board)) { copyTempMove = copyMove(tempMove); results = listPush(results, copyTempMove); } free(tempMove); } for (int i = 0; piecePos->file - i >= 0; i++) { tempMove = createMove(piecePos->rank, piecePos->file, piecePos->rank, piecePos->file - i); moveToChar(tempMove, charTempMove); if (validMove(charTempMove, game->turn, game->board)) { copyTempMove = copyMove(tempMove); results = listPush(results, copyTempMove); } free(tempMove); } break; case QUEEN: // Check diagonal moves for (int i = 0; (piecePos->rank + i < 8) && (piecePos->file + i < 8); i++) { tempMove = createMove(piecePos->rank, piecePos->file, piecePos->rank + i, piecePos->file + i); moveToChar(tempMove, charTempMove); if (validMove(charTempMove, game->turn, game->board)) { copyTempMove = copyMove(tempMove); results = listPush(results, copyTempMove); } free(tempMove); } for (int i = 0; (piecePos->rank - i >= 0) && (piecePos->file - i >= 0); i++) { tempMove = createMove(piecePos->rank, piecePos->file, piecePos->rank - i, piecePos->file - i); moveToChar(tempMove, charTempMove); if (validMove(charTempMove, game->turn, game->board)) { copyTempMove = copyMove(tempMove); results = listPush(results, copyTempMove); } free(tempMove); } for (int i = 0; (piecePos->rank - i >= 0) && (piecePos->file + i < 8); i++) { tempMove = createMove(piecePos->rank, piecePos->file, piecePos->rank - i, piecePos->file + i); moveToChar(tempMove, charTempMove); if (validMove(charTempMove, game->turn, game->board)) { copyTempMove = copyMove(tempMove); results = listPush(results, copyTempMove); } free(tempMove); } for (int i = 0; (piecePos->rank + i < 8) && (piecePos->file - i >= 0); i++) { tempMove = createMove(piecePos->rank, piecePos->file, piecePos->rank + i, piecePos->file - i); moveToChar(tempMove, charTempMove); if (validMove(charTempMove, game->turn, game->board)) { copyTempMove = copyMove(tempMove); results = listPush(results, copyTempMove); } free(tempMove); } // Check vertical moves for (int i = 0; piecePos->rank + i < 8; i++) { tempMove = createMove(piecePos->rank, piecePos->file, piecePos->rank + i, piecePos->file); moveToChar(tempMove, charTempMove); if (validMove(charTempMove, game->turn, game->board)) { copyTempMove = copyMove(tempMove); results = listPush(results, copyTempMove); } free(tempMove); } for (int i = 0; piecePos->rank - i >= 0; i++) { tempMove = createMove(piecePos->rank, piecePos->file, piecePos->rank - i, piecePos->file); moveToChar(tempMove, charTempMove); if (validMove(charTempMove, game->turn, game->board)) { copyTempMove = copyMove(tempMove); results = listPush(results, copyTempMove); } free(tempMove); } // Check horizontal moves for (int i = 0; piecePos->file + i < 8; i++) { tempMove = createMove(piecePos->rank, piecePos->file, piecePos->rank, piecePos->file + i); moveToChar(tempMove, charTempMove); if (validMove(charTempMove, game->turn, game->board)) { copyTempMove = copyMove(tempMove); results = listPush(results, copyTempMove); } free(tempMove); } for (int i = 0; piecePos->file - i >= 0; i++) { tempMove = createMove(piecePos->rank, piecePos->file, piecePos->rank, piecePos->file - i); moveToChar(tempMove, charTempMove); if (validMove(charTempMove, game->turn, game->board)) { copyTempMove = copyMove(tempMove); results = listPush(results, copyTempMove); } free(tempMove); } break; case KING: // Check all 8 possible moves for a king for (int i = 0; i < 8; i++) { tempMove = createMove(piecePos->rank, piecePos->file, piecePos->rank + kingMoves[i][0], piecePos->file + kingMoves[i][1]); moveToChar(tempMove, charTempMove); if (validMove(charTempMove, game->turn, game->board)) { copyTempMove = copyMove(tempMove); results = listPush(results, copyTempMove); } free(tempMove); } break; default: printf("Error: piece type not recognized %d\n", piece->type); exit(EXIT_FAILURE); } return results; } void findMove(GameState *game, char move[4], int turn, int depth) { #ifdef DUMB_AI // Setup some variables. int randMove[4]; move[0] = '?'; // Generate random moves until a valid one is found. while (validMove(move, turn, game->board) != 1) { // Make some random integers for the move randMove[0] = (rand() % 8) + 97; randMove[1] = (rand() % 8) + 49; randMove[2] = (rand() % 8) + 97; randMove[3] = (rand() % 8) + 49; // Combine them to make a move. move[0] = (char)randMove[0]; move[1] = (char)randMove[1]; move[2] = (char)randMove[2]; move[3] = (char)randMove[3]; } #endif #ifdef SMART_AI // Get all of current players pieces LinkedList *pieces = findPieces(game, turn); LinkedList *currentPieceList = pieces; //Move *headMove = createMove(-1, -1, -1, -1); LinkedList *allMoves = NULL; LinkedList *pieceMoves; PiecePos *currentPiece; // Loop through pieces while (currentPieceList != NULL && currentPieceList->data != NULL) { currentPiece = currentPieceList->data; // Get all moves for that piece pieceMoves = findMoves(game, currentPiece); // Add moves to collection of all moves allMoves = listConcat(allMoves, pieceMoves); // Move to next piece currentPieceList = currentPieceList->next; } freePiecePosList(pieces); LinkedList *currentMove = allMoves; #ifdef DEBUGZ while (currentMove != NULL && currentMove->data != NULL) { printMove(currentMove->data); currentMove = currentMove->next; } currentMove = allMoves; #endif GameState *new; char tempMove[4]; char *copyTempMove; double bestScore = -DBL_MAX; double score; // List of string moves that all have same score LinkedList *bestMoves = NULL; int numBestMoves = 0; while (currentMove != NULL && currentMove->data != NULL) { // Create a copy of the current game state new = createGameState(game); // Play move moveToChar(currentMove->data, tempMove); makeMove(tempMove, new->board); // Simulate next turn new->turn ^= 1; // Recursively evaluate that state score = eval(new, depth); #ifdef DEBUG //printf("Testing move %.4s, Score: %f\n", tempMove, score); #endif if (score > bestScore) { bestScore = score; // Free old best moves freeList(bestMoves); bestMoves = NULL; // Copy the move string copyTempMove = malloc(sizeof(char) * 4); strncpy(copyTempMove, tempMove, 4); // Add move to list of best moves bestMoves = listPush(bestMoves, copyTempMove); numBestMoves = 1; #ifdef DEBUG //printf("New best move: %.4s\n", bestMove); #endif } else if (score == bestScore) { // Copy the move string copyTempMove = malloc(sizeof(char) * 4); strncpy(copyTempMove, tempMove, 4); // Add move to list of best moves bestMoves = listPush(bestMoves, copyTempMove); numBestMoves++; } freeGameState(new); currentMove = currentMove->next; } freeMoveList(allMoves); if (bestScore == -DBL_MAX) { printf("findMove: Error: no valid moves found\n"); exit(EXIT_FAILURE); } // Choose a bestMove int randMoveIndex = rand() % numBestMoves; LinkedList *currentBestMove = bestMoves; for (int i = 0; i < randMoveIndex; i++) { currentBestMove = currentBestMove->next; } strncpy(move, currentBestMove->data, 4); // Free best moves freeList(bestMoves); #endif }
C
#include "ft_corewar.h" #include "libft.h" #include <fcntl.h> static int buff_int_from_chars(int32_t fd) { char buff[4]; int32_t r; char *rr; read(fd, buff, 4); rr = (char *)&r; rr += 3; *rr-- = *buff; *rr-- = *(buff + 1); *rr-- = *(buff + 2); *rr = *(buff + 3); return (r); } static void champ_error(t_vm *vm, t_champ *champ, int32_t fd, char *string) { ft_putstr_fd(string, 2); close(fd); free(champ->header); free(champ); vm_exit_failure(vm); } static int read_the_part(int fd, void *dst, uint32_t size) { uint32_t count; ft_bzero(dst, size + 1); count = read(fd, dst, size); return (count < size ? 0 : 1); } static void read_champ(t_vm *vm, t_champ *champ, char *filename) { int32_t fd; char buff[1]; if ((fd = open(filename, O_RDONLY)) < 0) vm_exit_sys_failure(vm, "Error: Can not open file\n"); if (buff_int_from_chars(fd) != COREWAR_EXEC_MAGIC) vm_exit_sys_failure(vm, "Wrong magic\n"); if (!read_the_part(fd, champ->header->prog_name, PROG_NAME_LENGTH)) champ_error(vm, champ, fd, "Error: File is too small\n"); lseek(fd, 4, SEEK_CUR); if ((champ->header->prog_size = buff_int_from_chars(fd)) > CHAMP_MAX_SIZE) champ_error(vm, champ, fd, "Error: File program code is too long\n"); if (!read_the_part(fd, champ->header->comment, COMMENT_LENGTH)) champ_error(vm, champ, fd, "Error: File is too small\n"); lseek(fd, 4, SEEK_CUR); if (!(champ->code = (uint8_t *)malloc(sizeof(uint8_t) * \ (champ->header->prog_size + 1)))) vm_exit_malloc_failure(vm); if (!read_the_part(fd, champ->code, champ->header->prog_size)) champ_error(vm, champ, fd, "Error: Wrong file's code\n"); if (read(fd, buff, 1) > 0) champ_error(vm, champ, fd, "Error: champion has a wrong code size\n"); close(fd); } t_champ *parse_champ(t_vm *vm, char *filename, int id) { t_champ *champ; if (!(champ = (t_champ*)malloc(sizeof(t_champ))) || !(champ->header = (t_header*)malloc(sizeof(t_header)))) vm_exit_malloc_failure(vm); read_champ(vm, champ, filename); champ->id = id; champ->next = NULL; add_champ_to_list(vm, champ); return (champ); }
C
#include "breadthfirstsearch.h" BreadthFirstSearch::BreadthFirstSearch() { } QList<StateSpace *> *BreadthFirstSearch::search(StateSpace *startState) { Node *startNode = new Node(startState, nullptr); QList<Node*> *explored = new QList<Node*>(); QQueue<Node*> *frontier = new QQueue<Node*>(); Node *currentNode = new Node(); frontier->enqueue(startNode); while (frontier->length() > 0) { currentNode = frontier->dequeue(); if (currentNode->getCurrentState()->isItGoal()) { break; } for (Direction dir: Operator::dirs) { Operator *o = new Operator(dir); if (o->precondition(currentNode->getCurrentState())) { Node *newNode = new Node(o->apply(currentNode->getCurrentState()), currentNode); if (!explored->contains(newNode) && !frontier->contains(newNode)) { explored->append(newNode); newNode->setParent(currentNode); frontier->enqueue(newNode); } } delete o; } explored->append(currentNode); } QList<StateSpace*> *solution = new QList<StateSpace*>(); if (frontier->count() > 0) { Node *curr = currentNode; for (; curr != nullptr; curr = curr->getParent()) { solution->push_front(curr->getCurrentState()); } } return solution; }
C
#include "joy.h" #include "adc.h" #include "math.h" #include "settings.h" int x; int y; int z = 0; int xmin = 0; int xmean = 127; int xmax = 255; int ymin = 0; int ymean = 127; int ymax = 255; void joy_init(){ clear_bit(DDRB,PB2); //Set joystick button pin to input set_bit(PORTB,PB2); //Set the internal pull-up resistor needed for the button //joy_calibrate(); } void joy_calibrate(){ xmean = adc_read('x'); ymean = adc_read('y'); xmax = 0; xmin = 255; ymax = 0; ymin = 255; oled_print_string("Please calibrate joystick!",0,0,8,0); oled_refresh(); while (z == 0){ x = adc_read('x'); y = adc_read('y'); z = !test_bit(PINB, PB2); if (x > xmax){ xmax = x; } if (y > ymax){ ymax = y; } if (x < xmin){ xmin = x; } if (y < ymin){ ymin = y; } } oled_clear_screen(); oled_print_string("Calibrated!",0,0,8,0); oled_refresh(); } Position joy_get_position(){ x = adc_read('x'); y = adc_read('y'); z = !test_bit(PINB, PB2); if (x > xmean){ x = ((x - xmean) * 100) / (xmax - xmean); } else { x = ((x - xmean) * 100) / (xmean - xmin); } if (y > ymean){ y = ((y - ymean) * 100) / (ymax - ymean); } else { y = ((y - ymean) * 100) / (ymean - ymin); } Position pos; //pos.x = x; pos.x = 0; pos.y = y; pos.z = z; pos.r_slider = adc_read('r'); if (x < 4 && x > -4){ pos.x = 0; } if (y < 4 && y > -4){ pos.y = 0; } return pos; } Position_polar joy_get_position_polar(){ Position pos_cart = joy_get_position(); Position_polar pos_pol; pos_pol.angle = atan2(pos_cart.y,pos_cart.x) * (180.0/ M_PI); pos_pol.amplitude = sqrt((uint16_t)(pos_cart.y*pos_cart.y) + (uint16_t)(pos_cart.x*pos_cart.x)); return pos_pol; } Direction joy_get_direction(){ Position_polar pos_pol = joy_get_position_polar(); if(pos_pol.amplitude > 80){ if (pos_pol.angle > 135){ return LEFT; } else if(pos_pol.angle > 45){ return UP; } else if(pos_pol.angle > -45){ return RIGHT; } else if(pos_pol.angle > -135){ return DOWN; } else{ return LEFT; } } return NEUTRAL; } void joy_print(){ Position pos = joy_get_position(); Position_polar pos_pol = joy_get_position_polar(); //printf("x = %4d, y = %4d, X= %4d, Y = %4d, Z = %1d, amplitude = %4d, angle = %4d, direction = %2d\r", adc_read('x'), adc_read('y'), pos.x, pos.y, pos.z, pos_pol.amplitude, pos_pol.angle, joy_get_direction()); }
C
#include <stdio.h> #include<string.h> #include <time.h> #include<stdlib.h> #include "acbe.h" #include <sodium.h> #include <pbc/pbc_test.h> #define NUMTEST 100 extern pairing_t pairing; extern Param param; extern element_t MK; extern Users users[MAX_USER]; void random_set(Set *S, int len) { S->len = len; srand(time(NULL)); for (size_t i = 0; i < MAX_USER; i++) { S->s[i] = i; } for (size_t j = 0; j < len; j++) { int r = j + rand() % (MAX_USER - j); int t = S->s[r]; S->s[r] = S->s[j]; S->s[j] = t; } } int main(int argc, char const *argv[]) { pairing_init(); double time1, time2; time1 = pbc_get_time(); Setup(); time2 = pbc_get_time(); //printf ("\nSetup (): %fs\n", (time2 - time1)*1000.0); int N = atoi(argv[1]); int r= atoi(argv[2]); // printf ("n = %d", n); int n = N -r; Set S; random_set(&S, n); for (int i = 0; i < S.len; ++i) { KeyGen(S.s[i]); CertGen(S.s[i], users[S.s[i]].pk); } CipherText CT; unsigned char M[MESSAGE_LEN]; H(M, (unsigned char*)"ACBE",4); double everage = 0; for (int l = 0; l < NUMTEST; ++l) { time1 = pbc_get_time(); Encrypt(&CT, &S, M); time2 = pbc_get_time(); everage += (time2 - time1); } printf("\nEncrypt: %fms & \t", everage * 1000.0 / NUMTEST); unsigned char M2[MESSAGE_LEN]; everage = 0; for (int l = 0; l < NUMTEST; ++l) { time1 = pbc_get_time(); Decrypt(M2, &CT, S.s[1], users[S.s[1]].sk, users[S.s[1]].cert); time2 = pbc_get_time(); everage += (time2 - time1); } printf("\n Decrypt: %fms & \t", everage * 1000.0 / NUMTEST); /* if(!memcmp(M,M2,MESSAGE_LEN)) printf ("OK\n"); else printf("Not OK\n"); */ return 0; }
C
#ifndef _SVECTOR2_H #define _SVECTOR2_H //==================================================================================================== // Constants //==================================================================================================== static const float kPI = 3.1415926535f; static const float kEpsilon = 0.000001f; struct SVector2 { float x; float y; // Constructors SVector2(void); SVector2(float _x, float _y); SVector2(const SVector2& v); // Helper functions void Invert(void); void PerpendicularLH(void); void PerpendicularRH(void); float Length(void) const; float LengthSquared(void) const; void Normalize(void); void Truncate(float max); void Rotate(float rad); void Reflect(const SVector2& normal); // Overloaded operators SVector2 operator+(const SVector2& v) const; SVector2 operator-(const SVector2& v) const; SVector2 operator*(float f) const; SVector2 operator/(float f) const; SVector2& operator+=(const SVector2& v); SVector2& operator-=(const SVector2& v); SVector2& operator*=(float f); SVector2& operator/=(float f); SVector2& operator=(const SVector2& v); bool operator==(const SVector2& v) const; bool operator!=(const SVector2& v) const; }; #endif
C
/** * \file debug.h * \brief Debugging macros. * \author k.edeline * \version 0.1 */ #ifndef DEBUG_H #define DEBUG_H #ifdef HAVE_CONFIG_H #include "config.h" #endif /* HAVE_CONFIG_H */ /** * \def UNUSED * \brief Unused var macro. */ #ifdef UNUSED #elif defined(__GNUC__) # define UNUSED(x) UNUSED_ ## x __attribute__((unused)) #elif defined(__LCLINT__) # define UNUSED(x) /*@unused@*/ x #else # define UNUSED(x) x #endif //#define DEBUG #ifdef DEBUG #include <stdio.h> /** * \def debug_print(fmt, ...) * \brief Debugging stderr printing macro * Will only print if DEBUG is defined. Otherwise, will be removed. */ #define debug_print(fmt, ...) fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, \ __LINE__, __func__, ##__VA_ARGS__) /** * \def debug_perror() * \brief Debugging stderr errno printing macro * Will only print if DEBUG is defined. Otherwise, will be removed. */ #define debug_perror() perror(NULL) #else #define debug_print(fmt, ...) #define debug_perror() #endif /* DEBUG */ #endif /* DEBUG_H */
C
#include "binary_trees.h" #include <stdio.h> /** * binary_tree_insert_left - inserts a node as the left-child of another node * @parent: parent node * @value: value for the new node * Return: the new node */ binary_tree_t *binary_tree_insert_left(binary_tree_t *parent, int value) { binary_tree_t *new; if (parent == NULL) return (NULL); new = malloc(sizeof(binary_tree_t)); if (new == NULL) return (NULL); new->left = NULL; new->right = NULL; new->n = value; new->parent = parent; if (parent->left == NULL) { parent->left = new; return (new); } else { new->left = parent->left; parent->left = new; new->left->parent = new; return (new); } }
C
#include <stdlib.h> #include <string.h> #include <sys/param.h> void realpath_ (char *filename, char *pathname) { #ifdef LINUX char resolvedname[PATH_MAX]; #else char resolvedname[MAXPATHLEN]; #endif if (realpath(filename,resolvedname)==NULL) { perror(filename); exit(-1); } strcpy(pathname,resolvedname); }
C
#include "BSP_OTA.h" uint8 OTA_RxBuf[OTA_RX_LEN] __attribute__ ((at(0X20001000))); //ջ,OTA_RX_LENֽ,ʼַΪ0X20001000. struct OTA_struct OTA; uint16 Usart_Rx_Cnt, oldCount, AppLenth; iapfun jump2app; /** * @brief תӦó * @param appxaddr:ûʼַ. * @retval None */ static void Iap_Load_App(uint32 Addr) { if(((*(vu32*)Addr) & 0x2FFE0000) == 0x20000000) //ջַǷϷ. { jump2app = (iapfun)*(vu32*)(Addr + 4); //ûڶΪʼַ(λַ) __set_MSP(*(vu32*) Addr); //ʼAPPջָ(ûĵһڴջַ) jump2app(); //תAPP. } } /** * @brief 桢ִй̼ * @retval 0 ݷǹ̼ */ static uint8 Update_Firmware(uint32 addr) { if(((*(vu32*)(addr + 4)) & 0xFF000000) == 0x08000000)//жǷΪ0X08XXXXXX. { printf("ʼִFLASHû!!\r\n"); Iap_Load_App(addr); //ִFLASH APP } printf("FLASHӦó,޷ִ!\r\n"); OTA.RunStatu = OTA_WAIT; Usart_Rx_Cnt = 0; oldCount = 0; AppLenth = 0; return 0; } /** * @brief APPдFLASH * @param appxaddr:Ӧóʼַ * @param appbuf: ӦóCODE. * @param appsize: ӦóС(ֽ). * @retval None */ static void IAP_Write_APP(uint32 App_Addr, uint8 *App_Buf, uint32 App_Size) { uint32 t; uint16 buf[512]; uint16 i = 0; uint8 *dfu = App_Buf; printf("Static write flash...\r\n"); printf("write addr = 0x%x\r\n",App_Addr); for(t = 0; t < App_Size; t += 2) { buf[i] = (uint16)dfu[1] << 8; buf[i] += (uint16)dfu[0]; dfu += 2; //ƫ2ֽ i++; if(i == 512) { i = 0; BSP_FLASHWrite(App_Addr, buf, 512); App_Addr += 1024; //ƫ2048 32 = 4*8.Ҫ4. } } if(i) BSP_FLASHWrite(App_Addr, buf, i);//һЩֽдȥ. App_Addr += i*2; printf("Write flash OK...\r\n"); } /** * @brief չ̼,д뵽flash * @param void * @retval NONE */ void Receive_Firmware(void) { if (OTA.RunStatu == OTA_RXD_UART_OK) { IAP_Write_APP(OTA_ADDR, OTA_RxBuf, AppLenth); Update_Firmware(OTA_ADDR); } } /** * @brief check_Firmware * @note ̼Ƿ * @param void * @retval NONE */ void check_Firmware(void) { static uint16 oldCount = 0; if (Usart_Rx_Cnt) { if (Usart_Rx_Cnt == oldCount) { AppLenth = Usart_Rx_Cnt; Usart_Rx_Cnt = 0; oldCount = 0; printf("û!\r\n"); printf("볤:%dBytes\r\n",AppLenth); OTA.RunStatu = OTA_RXD_UART_OK; } else oldCount = Usart_Rx_Cnt; } } /** * @brief عѡز֣ظΣɲflashдǷɹ * @note ϵʱȡflash * @retval None */ void BSP_Flash_Init(void) { uint16 flag = 0; // Run_Bootloader(); flag = BSP_FLASHReadHalfWord(OTA_FLAG_ADDR); switch (flag) { case FLAG_FIRMWARE: printf("\r\n"); printf("----- Have Firmware -----\r\n"); printf("----- Run Firmware! -----\r\n"); printf("\r\n"); Iap_Load_App(OTA_ADDR); break; case FLAG_NO_FIRMWARE: printf("\r\n"); printf("----- One Download -----\r\n"); printf("----- No Firmware! -----\r\n"); printf("\r\n"); break; case FLAG_RX_FIRMWARE: printf("\r\n"); printf("----- Update Firmware -----\r\n"); printf("\r\n"); flag = FLAG_NO_FIRMWARE; BSP_FLASHWrite(OTA_FLAG_ADDR, &flag, 1); Android_Uart_Send_Data(&Usart2SendData[0], OTA_VERSION_UPDATE, 0); break; default: flag = FLAG_NO_FIRMWARE; BSP_FLASHWrite(OTA_FLAG_ADDR, &flag, 1); printf("\r\n"); printf("----- flash error, init -----\r\n"); printf("\r\n"); break; } }
C
#include <stdio.h> int main () { char test[100] = "word1 word2 , word3"; char a[15], b[15]; char res[15]; //sscanf(test, "%s%[^,]%s", res, a, b); //sscanf(test, "%s%s%s", res, a, b); sscanf(test, "%s %[^ ] , %s", res, a, b); //sscanf(test, "%s%[^,], %s", res, a, b); //sscanf(test, "%s%[^,] %*[,]%s", res, a, b); printf("%s|%s|%s|\n", res, a, b); return 0; }
C
// Microsoft Public License (MS-PL) - Copyright (C) Shawn Rakowski // This file is subject to the terms and conditions defined in // file 'LICENSE', which is part of this source code package. #include <assert.h> #include <stdlib.h> #include "util.h" #include "engine.h" #define NUM_CHIP_SLOTS 16 typedef struct pixelVisionEngine { Chip chips[NUM_CHIP_SLOTS]; int chipCount; GetChip getChip; } pixelVisionEngine; PixelVisionEngine pixelVisionEngine_Create() { PixelVisionEngine self = NULL; self = (PixelVisionEngine)calloc(1, sizeof(pixelVisionEngine)); if (self == NULL) return NULL; self->getChip = func_Create(self, pixelVisionEngine_GetChip); if (self->getChip == NULL) { free(self); return NULL; } return self; } void pixelVisionEngine_Destroy(PixelVisionEngine self) { assert(self); for (int idx = 0; idx < self->chipCount; idx++) chip_Destroy(self->chips[idx]); memset(self, 0, sizeof(pixelVisionEngine)); free(self); } void pixelVisionEngine_InsertChip(PixelVisionEngine self, Chip chip) { assert(self); assert(chip); assert(self->chipCount < NUM_CHIP_SLOTS); self->chips[self->chipCount] = chip; self->chipCount++; } Chip pixelVisionEngine_GetChip(PixelVisionEngine self, const char *chipName) { assert(self); assert(chipName); Chip result = NULL; for (int idx = 0; idx < self->chipCount && result == NULL; idx++) result = strequals(self->chips[idx]->name, chipName) ? self->chips[idx] : result; return result; } void pixelVisionEngine_Init(PixelVisionEngine self) { assert(self); for (int idx = 0; idx < self->chipCount; idx++) chip_Init(self->chips[idx], self->getChip); } void pixelVisionEngine_Update(PixelVisionEngine self, float timeDelta) { assert(self); for (int idx = 0; idx < self->chipCount; idx++) chip_Update(self->chips[idx], timeDelta); } void pixelVisionEngine_Draw(PixelVisionEngine self) { assert(self); for (int idx = 0; idx < self->chipCount; idx++) { Chip currentChip = self->chips[idx]; chip_Draw(self->chips[idx]); } }
C
#include <stdio.h> #include <string.h> #include <unistd.h> #define LENGTH 64 /* Output: Writing string to pipe in parent: Some text String read from pipe by child: Some text */ int main() { int p[2]; pipe(p); if (fork() == 0) { char input[LENGTH] = ""; read(p[0], input, LENGTH); printf("String read from pipe by child: %s\n", input); } else { char output[LENGTH] = "Some text"; printf("Writing string to pipe in parent: %s\n", output); write(p[1], output, LENGTH); } return 0; }
C
#include <stdio.h> #include <string.h> #define TAMFRASE 80 #define TAMPAL 15 int func(char frase[], char palavra[], int tamf, int tamp); void main() { char f[TAMFRASE], p[TAMPAL]; printf("Indique frase: "); gets(f); printf("Indique palavra: "); gets(p); if(func(f,p,TAMFRASE,TAMPAL)) printf("Frase modificada: \n\t%s\n",f); else printf("Frase nao modificada!\n"); } int func(char frase[], char palavra[], int tamf, int tamp) { int i = strlen(frase), j, k; while(frase[i-1] == ' ') i--; while(frase[i-1] != ' ' && i - 1 >= 0) i--; if(i + strlen(palavra) <= tamf) { j = i + tamp; for(k=0;k<strlen(palavra);k++) { frase[i] = palavra[k]; i++; } frase[i] = '\0'; return 1; } else return 0; }
C
#include <gmp.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <time.h> #include "libqform/qform_group.h" #include "libqform/tests/sanity_qform.h" #include "liboptarith/group_pow.h" #include "liboptarith/math_mpz.h" #define iterations 10000 #define groups 100 #define min_bits 16 #define max_bits 140 #define total_bits (max_bits+1-min_bits) #define min_exp_bits 256 #define max_exp_bits 1024 #define skip_exp_bits 64 #define very_verbose 0 /** * Runs qforms from 16bit discriminants up to 120bit discriminants. * Randomly chooses compose,square,cube for a random element. * If compose is chosen for a destination element, the destination * element will be the composition of the other two elements. * * The test is run with multiple discriminants for each bit sized discriminant. */ void test_basic(void) { gmp_randstate_t rands; sanity_qform_group_t sanity_group; sanity_qform_t A; sanity_qform_t B; sanity_qform_t C; mpz_t discriminant; int action; int dest; int i; int g; int rand_seed; int bits; mpz_init(discriminant); sanity_qform_group_init(&sanity_group); sanity_qform_init(&sanity_group, &A); sanity_qform_init(&sanity_group, &B); sanity_qform_init(&sanity_group, &C); rand_seed = time(0); srand(rand_seed); gmp_randinit_default(rands); gmp_randseed_ui(rands, rand_seed); printf("Performing %d iterations on %d groups for each discriminant bit length.\n", iterations, groups); for (bits = min_bits; bits <= max_bits; bits ++) { printf("Using a discriminant of %d bits.\n", bits); for (g = 0; g < groups; g ++) { mpz_random_semiprime_discriminant(discriminant, rands, bits); gmp_printf("Discriminant is %Zd\n", discriminant); sanity_qform_group_set_discriminant(&sanity_group, discriminant); // generate three random prime forms for the base qform_random_primeform(&sanity_group.desc, &A); qform_random_primeform(&sanity_group.desc, &B); qform_random_primeform(&sanity_group.desc, &C); if (very_verbose) { printf("A = "); sanity_qform_print(&sanity_group, &A); printf("\n"); printf("B = "); sanity_qform_print(&sanity_group, &B); printf("\n"); printf("C = "); sanity_qform_print(&sanity_group, &C); printf("\n"); } // perform random operations of compose, square, and cube on the above for (i = 0; i < iterations; i ++) { action = rand() % 3; dest = rand() % 3; if (action == 0) { if (dest == 0) { if (very_verbose) printf("A = B*C\n"); sanity_qform_compose(&sanity_group, &A, &B, &C); } else if (dest == 1) { if (very_verbose) printf("B = C*A\n"); sanity_qform_compose(&sanity_group, &B, &C, &A); } else { if (very_verbose) printf("C = A*B\n"); sanity_qform_compose(&sanity_group, &C, &A, &B); } } else if (action == 1) { if (dest == 0) { if (very_verbose) printf("A = A^2\n"); sanity_qform_square(&sanity_group, &A, &A); } else if (dest == 1) { if (very_verbose) printf("B = B^2\n"); sanity_qform_square(&sanity_group, &B, &B); } else { if (very_verbose) printf("C = C^2\n"); sanity_qform_square(&sanity_group, &C, &C); } } else { if (dest == 0) { if (very_verbose) printf("A = A^3\n"); sanity_qform_cube(&sanity_group, &A, &A); } else if (dest == 1) { if (very_verbose) printf("B = B^3\n"); sanity_qform_cube(&sanity_group, &B, &B); } else { if (very_verbose) printf("C = C^3\n"); sanity_qform_cube(&sanity_group, &C, &C); } } } } printf("\n"); } gmp_randclear(rands); sanity_qform_clear(&sanity_group, &A); sanity_qform_clear(&sanity_group, &B); sanity_qform_clear(&sanity_group, &C); sanity_qform_group_clear(&sanity_group); mpz_clear(discriminant); printf("All tests completed successfully\n"); } void test_pow(void) { gmp_randstate_t rands; sanity_qform_group_t sanity_group; sanity_qform_t B; sanity_qform_t P1; sanity_qform_t P2; group_pow_t pow; mpz_t discriminant; mpz_t ex; int exp_bits; int rand_seed; int bits; two_three_term_t* rep; int rep_count; factored_two_three_term16_t* frep; int frep_count; mpz_init(discriminant); mpz_init(ex); sanity_qform_group_init(&sanity_group); sanity_qform_init(&sanity_group, &B); sanity_qform_init(&sanity_group, &P1); sanity_qform_init(&sanity_group, &P2); group_pow_init(&pow, &sanity_group.desc.group); rand_seed = time(0); //rand_seed = 0; srand(rand_seed); gmp_randinit_default(rands); gmp_randseed_ui(rands, rand_seed); printf("Performing %d iterations on %d groups for each discriminant bit length.\n", iterations, groups); for (bits = min_bits; bits <= max_bits; bits ++) { printf("Using a discriminant of %d bits.\n", bits); // perform exponentiation for (exp_bits = min_exp_bits; exp_bits < max_exp_bits; exp_bits += skip_exp_bits) { // Generate a random discriminant. mpz_random_semiprime_discriminant(discriminant, rands, bits); gmp_printf("Discriminant is %Zd\n", discriminant); sanity_qform_group_set_discriminant(&sanity_group, discriminant); // generate large exponents mpz_urandomb(ex, rands, exp_bits); gmp_printf("ex=%Zd\n", ex); // generate a random prime form for the base qform_random_primeform(&sanity_group.desc, &B); printf("B = "); sanity_qform_print(&sanity_group, &B); printf("\n"); // perform exponentiation by NAF group_pow_naf_r2l(&pow, &P1, &B, ex); printf("P1 = "); sanity_qform_print(&sanity_group, &P1); printf("\n"); // perform exponentiation by 2,3 k-closest rep = rep_prune_closest(&rep_count, ex, &s64_qform_costs, 512); frep = factored_rep(&frep_count, rep, rep_count); group_pow_factored23(&pow, &P2, &B, frep, frep_count); free(rep); free(frep); printf("P2 = "); sanity_qform_print(&sanity_group, &P2); printf("\n"); // Verify forms are equal. if (sanity_qform_equal(&sanity_group, &P1, &P2) == 0) { printf("Forms disagree!\n"); exit(-1); } printf("\n"); } printf("\n"); } gmp_randclear(rands); group_pow_clear(&pow); sanity_qform_clear(&sanity_group, &B); sanity_qform_clear(&sanity_group, &P1); sanity_qform_clear(&sanity_group, &P2); sanity_qform_group_clear(&sanity_group); mpz_clear(ex); mpz_clear(discriminant); printf("All tests completed successfully\n"); } int main(int argc, char** argv) { if (argc != 2) { printf("Usage: %s <opt>\n", argv[0]); printf("\n"); printf("Where <opt> is one of:\n"); printf(" --basic\t test compose, square, cube for 64, 128, mpz, and generic\n"); printf(" --pow\t\t test NAF against DBNS\n"); printf("\n"); return 0; } if (strcmp(argv[1], "--basic") == 0) { test_basic(); } else if (strcmp(argv[1], "--pow") == 0) { test_pow(); } else { printf("Unrecognized command line option\n"); } return 0; }
C
/* * Make sure that scandir function works OK. * * Copyright (C) 1998-2019 Toni Ronkko * This file is part of dirent. Dirent may be freely distributed * under the MIT license. For all details and documentation, see * https://github.com/tronkko/dirent */ /* Silence warning about fopen being insecure (MS Visual Studio) */ #define _CRT_SECURE_NO_WARNINGS /* Include prototype for versionsort (Linux) */ #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <dirent.h> #include <errno.h> #include <time.h> #include <limits.h> #undef NDEBUG #include <assert.h> /* Filter and sort functions */ static int only_readme(const struct dirent *entry); static int no_directories(const struct dirent *entry); static int reverse_alpha(const struct dirent **a, const struct dirent **b); int main(int argc, char *argv[]) { struct dirent **files; int i; int n; (void) argc; (void) argv; /* Initialize random number generator */ srand((unsigned) time(NULL)); /* Basic scan with simple filter function */ { /* Read directory entries */ n = scandir("tests/3", &files, only_readme, alphasort); assert(n == 1); /* Make sure that the filter works */ assert(strcmp(files[0]->d_name, "README.txt") == 0); /* Release file names */ for (i = 0; i < n; i++) { free(files[i]); } free(files); } /* Basic scan with default sorting function */ { /* Read directory entries in alphabetic order */ n = scandir("tests/3", &files, NULL, alphasort); assert(n == 13); /* Make sure that we got all the names in the proper order */ assert(strcmp(files[0]->d_name, ".") == 0); assert(strcmp(files[1]->d_name, "..") == 0); assert(strcmp(files[2]->d_name, "3zero.dat") == 0); assert(strcmp(files[3]->d_name, "666.dat") == 0); assert(strcmp(files[4]->d_name, "Qwerty-my-aunt.dat") == 0); assert(strcmp(files[5]->d_name, "README.txt") == 0); assert(strcmp(files[6]->d_name, "aaa.dat") == 0); assert(strcmp(files[7]->d_name, "dirent.dat") == 0); assert(strcmp(files[8]->d_name, "empty.dat") == 0); assert(strcmp(files[9]->d_name, "sane-1.12.0.dat") == 0); assert(strcmp(files[10]->d_name, "sane-1.2.30.dat") == 0); assert(strcmp(files[11]->d_name, "sane-1.2.4.dat") == 0); assert(strcmp(files[12]->d_name, "zebra.dat") == 0); /* Release file names */ for (i = 0; i < n; i++) { free(files[i]); } free(files); } /* Custom filter AND sort function */ { /* Read directory entries in alphabetic order */ n = scandir("tests/3", &files, no_directories, reverse_alpha); assert(n == 11); /* Make sure that we got file names in the reverse order */ assert(strcmp(files[0]->d_name, "zebra.dat") == 0); assert(strcmp(files[1]->d_name, "sane-1.2.4.dat") == 0); assert(strcmp(files[2]->d_name, "sane-1.2.30.dat") == 0); assert(strcmp(files[3]->d_name, "sane-1.12.0.dat") == 0); assert(strcmp(files[4]->d_name, "empty.dat") == 0); assert(strcmp(files[5]->d_name, "dirent.dat") == 0); assert(strcmp(files[6]->d_name, "aaa.dat") == 0); assert(strcmp(files[7]->d_name, "README.txt") == 0); assert(strcmp(files[8]->d_name, "Qwerty-my-aunt.dat") == 0); assert(strcmp(files[9]->d_name, "666.dat") == 0); assert(strcmp(files[10]->d_name, "3zero.dat") == 0); /* Release file names */ for (i = 0; i < n; i++) { free(files[i]); } free(files); } /* Trying to read from non-existent directory leads to an error */ { files = NULL; n = scandir("tests/invalid", &files, NULL, alphasort); assert(n == -1); assert(files == NULL); assert(errno == ENOENT); } /* Trying to open file as a directory produces ENOTDIR error */ { files = NULL; n = scandir("tests/3/666.dat", &files, NULL, alphasort); assert(n == -1); assert(files == NULL); assert(errno == ENOTDIR); } /* Sort files using versionsort() */ { files = NULL; n = scandir("tests/3", &files, no_directories, versionsort); assert(n == 11); /* * Make sure that we got all the file names in the proper order: * 1.2.4 < 1.2.30 < 1.12.0 */ assert(strcmp(files[0]->d_name, "3zero.dat") == 0); assert(strcmp(files[1]->d_name, "666.dat") == 0); assert(strcmp(files[2]->d_name, "Qwerty-my-aunt.dat") == 0); assert(strcmp(files[3]->d_name, "README.txt") == 0); assert(strcmp(files[4]->d_name, "aaa.dat") == 0); assert(strcmp(files[5]->d_name, "dirent.dat") == 0); assert(strcmp(files[6]->d_name, "empty.dat") == 0); assert(strcmp(files[7]->d_name, "sane-1.2.4.dat") == 0); assert(strcmp(files[8]->d_name, "sane-1.2.30.dat") == 0); assert(strcmp(files[9]->d_name, "sane-1.12.0.dat") == 0); assert(strcmp(files[10]->d_name, "zebra.dat") == 0); /* Release file names */ for (i = 0; i < n; i++) { free(files[i]); } free(files); } /* Scan large directory */ { char dirname[PATH_MAX+1]; int i; int ok; /* Copy name of temporary directory to variable dirname */ #ifdef WIN32 i = GetTempPathA(PATH_MAX, dirname); assert(i > 0); #else strcpy(dirname, "/tmp/"); i = strlen(dirname); #endif /* Append random characters to dirname */ for (int j = 0; j < 10; j++) { char c; /* Generate random character */ c = "abcdefghijklmnopqrstuvwxyz"[rand() % 26]; /* Append character to dirname */ assert(i < PATH_MAX); dirname[i++] = c; } /* Terminate directory name */ assert(i < PATH_MAX); dirname[i] = '\0'; /* Create directory */ #ifdef WIN32 ok = CreateDirectoryA(dirname, NULL); assert(ok); #else ok = mkdir(dirname, 0700); assert(ok == /*success*/0); #endif /* Create one thousand files */ assert(i + 5 < PATH_MAX); for (int j = 0; j < 1000; j++) { FILE *fp; /* Construct file name */ dirname[i] = '/'; dirname[i+1] = 'z'; dirname[i+2] = '0' + ((j / 100) % 10); dirname[i+3] = '0' + ((j / 10) % 10); dirname[i+4] = '0' + (j % 10); dirname[i+5] = '\0'; /* Create file */ fp = fopen(dirname, "w"); assert(fp != NULL); fclose(fp); } /* Cut out the file name part */ dirname[i] = '\0'; /* Scan directory */ n = scandir(dirname, &files, no_directories, alphasort); assert(n == 1000); /* Make sure that all 1000 files are read back */ for (int j = 0; j < n; j++) { char match[100]; /* Construct file name */ match[0] = 'z'; match[1] = '0' + ((j / 100) % 10); match[2] = '0' + ((j / 10) % 10); match[3] = '0' + (j % 10); match[4] = '\0'; /* Make sure that file name matches that on the disk */ assert(strcmp(files[j]->d_name, match) == 0); } /* Release file names */ for (int j = 0; j < n; j++) { free(files[j]); } free(files); } printf("OK\n"); return EXIT_SUCCESS; } /* Only pass README.txt file */ static int only_readme(const struct dirent *entry) { return strcmp(entry->d_name, "README.txt") == 0; } /* Filter out directories */ static int no_directories(const struct dirent *entry) { return entry->d_type != DT_DIR; } /* Sort in reverse direction */ static int reverse_alpha(const struct dirent **a, const struct dirent **b) { return strcoll((*b)->d_name, (*a)->d_name); }
C
// Written by: someone too ashamed to actually put their name here // Determines if the user is in highschool or not. #include <stdio.h> #define FIRST_HIGHSCHOOL_YEAR 7 #define LAST_HIGHSCHOOL_YEAR 12 int main(void) { printf("What year are you in? "); int year = 0; scanf("%d", &year); if (year >= FIRST_HIGHSCHOOL_YEAR && year <= LAST_HIGHSCHOOL_YEAR) { printf("You are in high school\n"); } else { printf("You are not in high school\n"); } return 0; }
C
/* ** EPITECH PROJECT, 2018 ** left ** File description: ** left.c */ #include "server.h" void get_left(player_t *tmp, int fd) { if (tmp->fd == fd) { tmp->axe = ((tmp->axe - 2 + 4) % 4) + 1; dprintf(fd, "ok\n"); } } void left(server_t *srv, int fd, __attribute__((unused)) char *arg) { int i; player_t *tmp; for (i = 0; i < srv->nb_team; i++) { tmp = srv->team[i].player; while (tmp) { get_left(tmp, fd); tmp = tmp->next; } } }
C
/* Adel Danandeh Graph.h is the header file for Graph implementation. All the function protypes which will do certain operations are listed in this file. */ #include <stdio.h> #include <stdlib.h> #include"List.h" #define UNDEF -1 #define NIL 0 #define WHITE 1 #define GRAY 2 #define BLACK 3 typedef struct GraphObj* Graph; /* Constructors-Destructors */ Graph newGraph(int n); void freeGraph(Graph* pG); /* Access functions */ int getOrder(Graph G); int getSize(Graph G); int getParent(Graph G, int u); /* Pre: 1<=u<=n=getOrder(G) */ int getDiscover(Graph G, int u); /* Pre: 1<=u<=n=getOrder(G) */ int getFinish(Graph G, int u); /* Pre: 1<=u<=n=getOrder(G) */ /* Manipulation procedures */ void addArc(Graph G, int u, int v); /* Pre: 1<=u<=n, 1<=v<=n */ void addEdge(Graph G, int u, int v); /* Pre: 1<=u<=n, 1<=v<=n */ void DFS(Graph G, List S); /* Pre: getLength(S)==getOrder(G) */ /* Other Functions */ Graph transpose(Graph G); Graph copyGraph(Graph G); void printGraph(FILE* out , Graph G);
C
// Eric Moss // Advent of code 2019 // Day 5 part 1 // Run an intcode computer through a diagnostic program // input: <program> #include <stdio.h> #include <stdlib.h> #include <string.h> #define PROGRAM_LENGTH 256 #define OPCODE_SIZE 4 // returns a pointer to an int array of size OPCODE_SIZE // array[0] is the opcode, array[i] is the mode for argument i int *parseOpcode(int opcode){ int *parsedOpcode = calloc(OPCODE_SIZE, sizeof(int)); parsedOpcode[0] = opcode % 100; opcode = (opcode - (opcode % 100)) / 100; for(int i=1; i<OPCODE_SIZE; i++){ parsedOpcode[i] = opcode % 10; opcode = (opcode - (opcode % 10)) / 10; } return parsedOpcode; } // gets value from $target while program is in $mode int getVal(int program[], int target, int mode){ switch(mode){ case 0: return program[program[target]]; case 1: return program[target]; } } void runProgram(int program[]){ int pc = 0; int val1, val2, result; while(program[pc] != 99){ int *opcode = parseOpcode(program[pc]); switch(opcode[0]){ case 1: val1 = getVal(program, pc+1, opcode[1]); val2 = getVal(program, pc+2, opcode[2]); result = val1 + val2; program[program[pc+3]] = result; pc += 4; break; case 2: val1 = getVal(program, pc+1, opcode[1]); val2 = getVal(program, pc+2, opcode[2]); result = val1 * val2; program[program[pc+3]] = result; pc += 4; break; case 3: printf("in: "); scanf("%d", &val1); program[program[pc+1]] = val1; pc += 2; break; case 4: val1 = getVal(program, pc+1, opcode[1]); printf("out: %d\n", val1); pc += 2; break; } } } int main(int argc, char *argv[]){ // parse program from comma-separated input string int program[PROGRAM_LENGTH]; char *token = strtok(argv[1], ","); for(int i=0; token != NULL; i++){ program[i] = atoi(token); token = strtok(NULL, ","); } runProgram(program); return 0; }
C
#include"rttimer.h" #include<string.h> #ifdef _WIN32 # include<Windows.h> #else # define UNIX_CLOCK_GETTIME # include<unistd.h> # include<time.h> # include<errno.h> #endif // _WIN32 //============================================================================= // Func: _get_raw_time // Desc: Get the raw time from the system timer. //----------------------------------------------------------------------------- static double _get_raw_time(rttimer_p tmr) { #if _WIN32 LARGE_INTEGER li; QueryPerformanceCounter(&li); return li.QuadPart / tmr->perf_freq; #elif defined(UNIX_CLOCK_GETTIME) struct timespec ts; if(clock_gettime(CLOCK_MONOTONIC_RAW, &ts) == 0) { return ts.tv_sec + (time_real_t)ts.tv_nsec * 0.000000001; } else if(clock_gettime(CLOCK_MONOTONIC, &ts) == 0) { return ts.tv_sec + (time_real_t)ts.tv_nsec * 0.000000001; } else { return (double)clock() / tmr->perf_freq; } #endif } void rttimer_init(rttimer_p tmr, int init_pause) { #if _WIN32 LARGE_INTEGER li; memset(tmr, 0, sizeof *tmr); QueryPerformanceFrequency(&li); tmr->perf_freq = (time_real_t)li.QuadPart; #elif defined(UNIX_CLOCK_GETTIME) tmr->perf_freq = CLOCKS_PER_SEC; #endif tmr->is_paused = init_pause; tmr->start_time = tmr->pause_time = _get_raw_time(tmr); } void rttimer_start(rttimer_p tmr) { if(tmr->is_paused) { time_real_t start_time = _get_raw_time(tmr); tmr->is_paused = 0; tmr->start_time += start_time - tmr->pause_time; } } void rttimer_pause(rttimer_p tmr) { if(!tmr->is_paused) { tmr->is_paused = 1; tmr->pause_time = _get_raw_time(tmr); } } double rttimer_gettime(rttimer_p tmr) { if(tmr->is_paused) return tmr->pause_time - tmr->start_time; else return _get_raw_time(tmr) - tmr->start_time; } void rttimer_settime(rttimer_p tmr, time_real_t timeval) { if(tmr->is_paused) tmr->start_time = tmr->pause_time - timeval; else tmr->start_time = _get_raw_time(tmr) - timeval; } void rttimer_cleanup(rttimer_p tmr) { memset(tmr, 0, sizeof *tmr); }
C
#include <stdio.h> /* main() { int x, z; A: printf("unesite broj:"); scanf( "%d", &x ); while (x > 0) { z = z + x; goto A; } printf("%d", z); return 0; } */ main() { int x = 1, z = 0; while (x > 0) { printf("unesite broj:"); scanf( "%d", &x ); z = z + x; } z = z - x; printf("%d", z); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<errno.h> #include<systemd/sd-bus.h> static int checker(sd_bus_message *m, void * , sd_bus_error *); static int exiting(sd_bus_message *m, void * , sd_bus_error *); //static int method_multiply(sd_bus_message *m, void *userdata, sd_bus_error *ret_error); static int method_multiply(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) { int64_t x, y; int r; /* Read the parameters */ r = sd_bus_message_read(m, "xx", &x, &y); if (r < 0) { fprintf(stderr, "Failed to parse parameters: %s\n", strerror(-r)); return r; } /* Reply with the response */ return sd_bus_reply_method_return(m, "x", x * y); } // The vtable of our little object, implements the interface static const sd_bus_vtable service_vtable[] = { SD_BUS_VTABLE_START(0), SD_BUS_METHOD("S_START", "s", "x", checker, SD_BUS_VTABLE_UNPRIVILEGED), SD_BUS_METHOD("EXIT_SERV","x","x", exiting,SD_BUS_VTABLE_UNPRIVILEGED), SD_BUS_METHOD("Multiply", "xx", "x", method_multiply, SD_BUS_VTABLE_UNPRIVILEGED), SD_BUS_VTABLE_END }; int main(int argc, char * argv[]) { sd_bus_slot *slot = NULL; sd_bus *bus = NULL; int prt; // Connecting to the user bus prt = sd_bus_open_user(&bus); if(prt<0) { fprintf(stderr, "Failed to connect to system bus: %s\n", strerror(-prt)); goto end; } else fprintf(stderr,"Connected to bus\n"); //Installing the object prt = sd_bus_add_object_vtable(bus, &slot, "/home/mybus/Sdbus", //Object Path "com.mohit.dbus", //Interface name service_vtable, NULL); if(prt<0){ fprintf(stderr, "Failed to issue method call %s \n",strerror(-prt)); goto end; } fprintf(stderr,"Issued method call\n"); //Taking a well known service name prt = sd_bus_request_name(bus,"com.mohit.dbus",0); if(prt<0) { fprintf(stderr, "Failed to acquire service name: %s\n", strerror(-prt)); goto end; } fprintf(stderr,"Got a service name\n"); while(1) { prt = sd_bus_process(bus,NULL); if(prt<0){ fprintf(stderr, "Failed to process bus: %s\n", strerror(-prt)); goto end; } if(prt>0) { fprintf(stderr,"Got Request \n"); continue; } prt=sd_bus_wait(bus,(uint64_t) -1); if(prt<0) { fprintf(stderr, "Failed to wait on bus: %s\n", strerror(-prt)); goto end; } } end: sd_bus_slot_unref(slot); sd_bus_unref(bus); return prt < 0 ? EXIT_FAILURE : EXIT_SUCCESS ; } int checker(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) { char com[20]; if(sd_bus_message_read(m,"s",&com)) { printf("Error in read in checker \n"); return -1; } char command[70]; snprintf(command,sizeof(command),"systemctl start %s",com); //system(command); int flag=0; FILE * fp; fp = popen(command, "r"); if (fp == NULL) { printf("Failed to run command\n" ); flag = -1; exit(1); } pclose(fp); return sd_bus_reply_method_return(m,"x",flag); } static int exiting(sd_bus_message *m, void *userdata , sd_bus_error *ret_error) { uint64_t a; int pr; pr = sd_bus_message_read(m, "x", &a); if (pr < 0) { fprintf(stderr, "Failed to parse parameters: %s\n", strerror(-pr)); return pr; } printf("Exiting with status %" PRIu64 " \n",a); sd_bus_reply_method_return(m,"x",a); sd_bus_slot_unref(slot); sd_bus_unref(bus); exit(a); }
C
// ______________________________________________________________ // // Program: tfreq // Author : Timothy A.V. Teatro <timothy.teatro@uoit.ca> // Date : July 2008 // // Description: // This code reads in a set of atomic trajectories in .pos // format and computes the velocity autocorrelation function // (VAC). The VAC algorithm was adapted from the formulas // given in J. Kohanoff Comp. Mat. Sci. 2 221-232 (1994). // The estimator formulation used here is unbiased and // statistically consistent, but may yield a non-valid VAC. // Using the FFTW package, the Fourier transform is computed // and the resultant frequency spectrum is printed to stdout. // // NB: Alpha stage: FFT data is not yet abscissiated properly. // // Usage: // Simply compile: // :> make all // (optionally, substitute your compiler of choice). Then // run from the command line: // ./tfreq case.vel > case.freq // // WARNINGS: // There is no error checking, so don't forget to specify the // vel file and verify its integrity. // // BEGIN_________________________________________________________ // #include <complex.h> #include <fftw3.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> // // User configurable variables // int padd = 15; // // Define constants. // const double H_PLANCK_SI = 6.6260693E-34; // J s const double HARTREE_SI = 4.35974417E-18; // J const double K_BOLTZMANN_SI = 1.3806505E-23; // J K^-1 const double BOHR_RADIUS_SI = 0.5291772108E-10; // m const double AMU_SI = 1.66053886E-27; // Kg const double AU_SEC = 2.41888432E-17; // s // // Define global variables. // int ts = 0; // Stores the current MD time step. double mdTime = 0.00f; // Stores the MD time in fs. int nat = 1; // Number of atoms. FILE *velfile; // The input stream. double ***v; // Matrix of atom velocities. // // Prototype function(s). // void getnat(); // Get the number of atoms. int main(int argc, char **argv) { int i = 0; // Dummy. int j = 0; // Dummy. int m = 0; // Dummy. int n = 0; // Dummy. int M = 0; // Total number of time steps. char file[256] = ""; fftw_complex *Z; // Velocity autocorrelation vector. double a; // Junk/Temporary storage. char eof; // EOF state of velfile. int tsstart = 0; // Starting time-step. int tsstop = 0; // Starting time-step. double tstart = 0.0f; // double tstop = 0.0f; // double sqtp = 2.506628274631000; // sqrt of 2 Pi fftw_complex norm = 1.0f; double sigma = 1.0f; fftw_complex *dft_out; fftw_plan dft_plan; FILE *zfile; FILE *ftfile; // // Open file // printf("\n"); printf("# TFREQ\n"); printf("# VDOS Calculator\n"); printf("# Version 0.5.1 beta\n"); printf("# Timothy A.V. Teatro <timothy.teatro@uoit.ca>\n"); printf("#\n# Starting Program.\n"); if ((velfile = fopen(argv[1], "r")) == NULL) { printf("ERROR: Cannot open file\n"); exit(1); } strncpy(file, "Z.", 2); strncat(file, argv[1], 256); if ((zfile = fopen(file, "w")) == NULL) { printf("ERROR: Cannot open Z file\n"); exit(1); } strncpy(file, " ", 256); strncpy(file, "FT.", 3); strncat(file, argv[1], 256); if ((ftfile = fopen(file, "w")) == NULL) { printf("ERROR: Cannot open FT file\n"); exit(1); } printf("# All files succesffully opened\n"); // // Count each time step in the file so we can dimension our variables. // Obviously, this isn't ideal. I'd like to dynamically dimension the // memory and store it in the same loop, but it's more trouble than it's // worth for now. // fscanf(velfile, "%d%lg", &tsstart, &tstart); rewind(velfile); getnat(); rewind(velfile); while (1) { fscanf(velfile, "%d%lg", &tsstop, &tstop); if (feof(velfile)) break; for (i = 0; i < nat; i++) { fscanf(velfile, "%lG%lG%lG", &a, &a, &a); } M++; } rewind(velfile); printf("# Number of atoms: %d\n", nat); printf("# MD Start time is %f ps, and end time is %f ps.\n", tstart, tstop); printf("# MD Duration is %f ps\n", tstop - tstart); printf( "# Data starts at time step %d and ends at step %d, totalling %d " "steps.\n#\n", tsstart, tsstop, M); // // Dimension the matrices. // printf("# Allocating memory...\n"); v = (double ***) malloc(M * sizeof(double **)); for (i = 0; i < M; i++) { v[i] = (double **) malloc(nat * sizeof(double *)); for (j = 0; j < nat; j++) v[i][j] = (double *) malloc(3 * sizeof(double)); } Z = (fftw_complex *) fftw_malloc(M * padd * sizeof(fftw_complex)); dft_out = (fftw_complex *) fftw_malloc(M * padd * sizeof(fftw_complex)); // // Rewind and start populating our velocity matrix. This is a 3D matrix // which contains the velocities of each atom at each time step, // indexed as v[t][a][x] where t is the timestep (0..M-1), a is // the number of atoms (0..nat-1) and x is the coordinate specifier (0..2). // printf("# done.\n# Reading %d velocity array into primary memory...\n", M); for (i = 0; i < M; i++) { fscanf(velfile, "%d%lg", &ts, &mdTime); for (j = 0; j < nat; j++) { fscanf(velfile, "%lG%lG%lG", &v[i][j][0], &v[i][j][1], &v[i][j][2]); } } printf("# Successfully read %d time steps of velocity data.\n#\n", M); fclose(velfile); // Zero the Z vector - for (m = 0; m < M; m++) Z[m] = 0.000000f; // // Now compute the VAC sequence. // // This algorithm was adapted from the formulas given in // J. Kohanoff Comp. Mat. Sci. 2 221-232 (1994). The estimator // formulation used here is unbiased and statistically consistent, // but may yield a non-valid VAC. // // // Looping through all time origins to collect an average - // printf("# Starting autocorrelation...\n"); for (m = 0; m < M; m++) // // Looping through each calculation that is part of Z[m] - // for (n = 0; n < M - m - 1; n++) // // Looping to take the average over all atoms - // for (i = 0; i < nat; i++) // // Dot product - // for (j = 0; j < 3; j++) Z[m] += v[n + m][i][j] * v[n][i][j]; // // VAC calculation done. Applying scaling. // printf("# done.\n# Scaling Z[m]\n"); for (m = 0; m < M; m++) { Z[m] /= (M - m); } for (m = 1; m < M; m++) { Z[m] /= Z[0]; } Z[0] = 1.0f; // // Zero our padding and apply gaussian smoothing, then rescale. // printf("# done.\n# Padding with zeros and gaussian smoothing...\n"); for (i = M; i < M * padd; i++) Z[i] = 0.000f; sigma = M / 2.50; for (i = 0; i < M * padd; i++) Z[i] *= exp(-i * i / (2 * sigma * sigma)) / (sigma * sqtp); for (m = 1; m < M * padd; m++) { Z[m] /= Z[0]; } Z[0] = 1.0f; // // DFT // dft_plan = fftw_plan_dft_1d(M * padd, Z, dft_out, FFTW_FORWARD, FFTW_ESTIMATE); printf("# done.\n# Executing FFT\n"); fftw_execute(dft_plan); // // Normalize the data (two methods)... // printf("# done.\n# Normalizing data...\n"); // // Normalize the peak so that < F | F* > = 1 // // norm = 0.000f; // for ( m = 0; m < M*padd; m++ ) // norm += dft_out[m] * conj(dft_out[m]); // norm *= (tstop - tstart)*1E-12 / M; // norm = 1/norm; // // Normalize max peak to 1 // norm = 0.00f; for (m = 0; m <= (M * padd) / 2; m++) if (creal(dft_out[m] * conj(dft_out[m])) > creal(norm)) norm = dft_out[m] * conj(dft_out[m]); norm = 1 / norm; // // Print Output: // printf("# done.\n# Writing output...\n"); for (m = 0; m < M * padd; m++) { fprintf(zfile, "%14.9E %14.9f\n", tstart + (tstop - tstart) * m / M, Z[m]); } for (m = 0; m <= ((M * padd) / 2); m++) { fprintf(ftfile, "%17.9E %17.9E %17.9E %17.9E\n", m / (2.99792458E10 * (tstop - tstart) * padd * 1E-12), creal(dft_out[m]), cimag(dft_out[m]), norm * dft_out[m] * conj(dft_out[m])); } printf("# done.\n# !! Program Complete !!\n"); } void getnat() { char item[20]; char eof; fscanf(velfile, "%d%lg", &ts, &mdTime); nat = 0; do { eof = fscanf(velfile, " %s", item); nat++; } while (strchr(item, '.') != NULL && eof != EOF); nat /= 3; }
C
#include <stdio.h> int main(){ int cod1, cod2, quant1, quant2; double valunit1, valunit2, totpagar, valtot1, valtot2; scanf("%i",&cod1); scanf("%i",&quant1); scanf("%lf",&valunit1); scanf("%i",&cod2); scanf("%i",&quant2); scanf("%lf",&valunit2); valtot1=valunit1*quant1; valtot2=valunit2*quant2; totpagar=valtot1+valtot2; printf("VALOR A PAGAR: R$ %.2lf\n",totpagar); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/wait.h> #include <signal.h> #define PORT "3490" // the port users wil be connecting to #define BACKLOG 10 // how many pending connection queue will hold #define MAXDATASIZE 8 // max number of bytes we can get at once #define SIZE_FILENAME 1024 char* get_filename_from_path(char* fp){ char filepath[SIZE_FILENAME]; if (fp[0] != '/') { strcpy(filepath, "/"); strcat(filepath, fp); }else{ strcpy(filepath, fp); } char *filename = (char*)calloc(1, sizeof(SIZE_FILENAME)); filename = (strrchr(filepath, '/'))+1; return filename; } void sigchld_handler(int s) { while (waitpid(-1, NULL, WNOHANG) > 0); } // get sockaddr, IPv4 or IPv6 void *get_in_addr(struct sockaddr *sa) { if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*)sa)->sin_addr); } return &(((struct sockaddr_in6*)sa)->sin6_addr); } int main(int argc, char *argv[]) { int sockfd, new_fd; // listen on sockd_fd, new connection on new_fd struct addrinfo hints, *servinfo, *p; struct sockaddr_storage their_addr; // connector's address information socklen_t sin_size; struct sigaction sa; int yes = 1; char s[INET6_ADDRSTRLEN]; int rv; int numbytes; char buf[MAXDATASIZE]; FILE *file; char *buffer; // For transferring characters ssize_t byteSend; // Byte send to receiver ssize_t byteReceive; char filename[SIZE_FILENAME]; buffer = (char *)malloc(MAXDATASIZE * sizeof(char)); if (argc < 2 || argc > 3) { printf("Invalid! number of arguments\n"); } memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // use my IP switch (argc) { case 2: { if ((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and connect to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("client: socket"); continue; } while (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1); break; } if (p == NULL) { fprintf(stderr, "client: failed to connect\n"); return 2; } inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s); printf("client: connecting to %s\n", s); freeaddrinfo(servinfo); // all done with this structure FILE *fp; fp = fopen("tmp", "w+"); while (*buffer != EOF) { byteReceive = recv(sockfd, buffer, MAXDATASIZE, 0); if (*buffer != EOF) { fwrite(buffer, 1, sizeof(buffer), fp); } } byteReceive = recv(sockfd, buffer, MAXDATASIZE, 0); fclose(fp); strcpy(filename, "files/"); strcat(filename, buffer); rename("tmp", filename); printf("file received\n"); close(sockfd); break; } case 3: { if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } file = fopen(argv[2], "r"); if (file == 0) { // Could not open file perror("file open"); return 0; } // loop through all the results and bind to the first we can for (p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("server: socket"); continue; } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("server: bind"); continue; } break; } if (p == NULL) { fprintf(stderr, "server: failed to bind\n"); return 2; } freeaddrinfo(servinfo); // all done with this structure if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } sa.sa_handler = sigchld_handler; // reap all dead processes sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, &sa, NULL) == -1) { perror("sigaction"); } printf("server: waiting for connection...\n"); while (1) { sin_size = sizeof their_addr; new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); if (new_fd == -1) { perror("accept"); continue; } inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s); printf("server: got connection from %s\n", s); if (!fork()) { // this is the child process close(sockfd); // child doesn't need the listener fseek(file, SEEK_SET, 0); while (!feof(file)) { fread(buffer, sizeof(char), MAXDATASIZE, file); byteSend = send(new_fd, buffer, MAXDATASIZE, 0); if (byteSend == -1) { perror("send"); return 0; } } *buffer = EOF; byteSend = send(new_fd, buffer, MAXDATASIZE, 0); buffer = get_filename_from_path(argv[2]); byteSend = send(new_fd, buffer, MAXDATASIZE, 0); printf("file successfully send"); close(new_fd); exit(0); // if (send(new_fd, buff, sizeof(buff), 0) == -1) // { // perror("send"); // } close(new_fd); exit(0); } close(new_fd); // parent doesn't need this } break; } } return 0; }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> char* decToHexa(int n) { // char array to store hexadecimal number char hexaDeciNum[100]; // counter for hexadecimal number array int i = 0; while(n!=0) { // temporary variable to store remainder int temp = 0; // storing remainder in temp variable. temp = n % 16; // check if temp < 10 if(temp < 10) { hexaDeciNum[i] = temp + 48; i++; } else { hexaDeciNum[i] = temp + 55; i++; } n = n/16; } char *res; res = (char*) malloc(100*sizeof(char)); int z=0; // printing hexadecimal number array in reverse order for(int j=i-1; j>=0; j--) { res[z] = hexaDeciNum[j]; z++; } return (char*)res; } char* reallocate(char *l,char *h,char *start) { //printf("%s%s\n",h,l); char a[10]; strcat(a,h); strcat(a,l); printf("%s\n",a); int add = hex_decimal(a)+hex_decimal(start); printf("%d\n",add); return decToHexa(add); } int main() { char *res; res = (char*)malloc(10*sizeof(char)); res = reallocate("01","00","2000"); printf("%s\n",res); return 0; }
C
// character into integer conversion using atoi(): #include<stdio.h> int atoi(char x[]) { int n = 0,i; for(i=0;x[i]>='0' && x[i]<='9';++i) n = n * 10 + (x[i]-'0'); return n; } void main() { char a[12]; int i; printf("Enter the string for 'A':\n"); gets(a); i = atoi(a); printf("The value of 'A' is: %s\t The value of 'i' is: %d\n",a,i); }
C
#include "clib.h" #include "print.h" #include "intr.h" void mem_cpy(void *src, void *dst, uint64 size) { char *cSrc = (char *) src; char *cDst = (char *) dst; while (size--) { *(cDst++) = *(cSrc++); } } void mem_set(void *src, uint8 val, uint64 size) { while (size--) { *(uint8 *) src = val; src = (void *) ((uintptr) src + 1); } } void mem_mv(void *src, void *dst, uint64 size) { if (src >= dst) { mem_cpy(src, dst, size); return; } src = (void *) ((uintptr) src + size - 1); dst = (void *) ((uintptr) dst + size - 1); while (size--) { *(char *) dst = *(char *) src; dst = (void *) ((uintptr) dst - 1); src = (void *) ((uintptr) src - 1); } } uint64 str_len(char const *str) { uint64 length = 0; while (*str != 0) { str++; length++; } return length; } uint64 str_cmp(char const *str1, char const *str2) { uint64 length = str_len(str1); if (length != str_len(str2)) { return 0; } while (length--) { if (*(str1 + length) != *(str2 + length)) { return 0; } } return 1; } void poor_sleep(uint32 dat) { for(uint32 i = 0; i < dat; i++) { } } void kassert_ex(const char *expr_str, const char *file, int32 line, int32 expr) { if (!expr) { kprintf("Assertion \"%s\" failed at %s:%d.\n", expr_str, file, line); stop_cpu(); } }
C
#include <limits.h> #include <stdio.h> int main() { printf("Valeur de NAME_MAX: %i\n", NAME_MAX); printf("Valeur de PATH_MAX: %i\n",PATH_MAX ); return 0; }
C
#include<stdio.h> #include<conio.h> typedef struct { char nome[50]; char endereco[80]; char profissao[50]; char nascimento [10]; int conta; float valor_conta; }reg; reg* inserir (reg *g, int tam){ int i; for(i = 0; i<tam; i++){ scanf("%d", &g[i]->conta); } return g; } main(){ reg r[2], *g; g = inserir (&r, 2); for(i = 0; i<tam; i++){ printf("%d", g.conta); } getch(); }
C
/************************************************ * filename: Ngoc_Son_Nguyen_M5_Programming_4.c * Exercise: Module 5, Programming, Exercise 4 * Name: Ngoc Son Nguyen * Date Created: May 06, 2019 * * Description: This program uses a 10-element integer array and prompts the user for 10 integer values to populate the array. Pass a pointer of this array to a function called sort() that you create as part of your program. The function sort() arranges the numbers in the array from smallest to largest. Have the function main() output the sorted numbers to the user. *************************************************/ #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #define SIZE 10 void sort(int* arr[SIZE]); /*Declare custom function*/ int main(void) { /*Initialize a regular array and a pointer array*/ int arr_int[SIZE]; int *arr_ptr[SIZE]; int i; /*Prompt user input. Read and immediately assign each regular element to a pointer element*/ printf("Enter 10 integers below: \n"); for (i = 0; i < SIZE; i++) { scanf("%d", &arr_int[i]); arr_ptr[i] = &arr_int[i]; } sort(&arr_ptr); /*Call custom sort function*/ /*Print sorted array*/ for (i = 0; i < SIZE; i++) printf("%d\n", *arr_ptr[i]); return 0; } /*Custom sort function*/ void sort(int* arr[SIZE]) { int j,k; int comp = 0; /*Temp variable to swap when compare*/ for (j = 0 ; j < SIZE ; j++) /*Start with the first element, compare it with the rest of the array*/ { for (k = j + 1; k < SIZE; k++) { if (*arr[j] > *arr[k]) { comp = *arr[j]; *arr[j] = *arr[k]; *arr[k] = comp; } } } }
C
#include<sys/types.h> #include<unistd.h> #include<sys/stat.h> #include<stdio.h> #include<fcntl.h> #include<string.h> int main() { int fd,i; char msg[101]; fd= open("/dev/chardev0",O_RDWR,S_IRUSR|S_IWUSR); if(fd!=-1) { while(1) { for(i=0;i<101;i++) //初始化 msg[i]='\0'; read(fd,msg,100); printf("%s\n",msg); if(strcmp(msg,"quit()")==0) { close(fd); break; } } } else { printf("device open failure,%d\n",fd); } return 0; }
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #define COMPARE(x,y) (((x)>(y))? 1 : ((x)==(y))? 0 : -1 ) // 이진탐색 int binsearch(int left, int right, int searchnum, int S[]); int main() { int S[9] = {112,4,7,425,37,12,99,101,47 }; int result; result = binsearch(0, 8, 4, S); printf("%d", result); return 0; } int binsearch(int left, int right, int searchnum, int S[]) { int mid; if (left > right) return -1; else { mid = (left + right) / 2; switch (COMPARE(S[mid], searchnum)) { case -1: return binsearch(mid + 1, right, searchnum, S); case 0: return mid; case 1: return binsearch(left, mid - 1, searchnum, S); } } }
C
#include<stdio.h> void main() { int m,n,c; printf("enter the nnumber"); scanf("%d",&m); printf("enter the nnumber"); scanf("%d",&n); c=m*n; if(c/2) { printf("it is even number"); } else { printf("it is odd number"); } }
C
/* C Preprocesor Source Code | Preprocesor | Pre-procesed program | Compiler | Binary Executable File Include Files #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include "stdio.h" #include "\dir\files\headers\my_file.h" Macros (Symbolic names) #define SIZE 10 #define PI 3.14 #define NUM 10 #define BEGIN { #define END } int main() BEGIN int num = 0; END #undef NUM | // No longer will be used | #define NUM 20 Arrgument (Parameter) #define SQAURE(N) (N)+(N) int main() { int result = 0; result = SQUARE(2); } */
C
/* SDL_main.c, placed in the public domain by Sam Lantinga 4/13/98 The WinMain function -- calls your program's main() function */ #include <stdio.h> #include <stdlib.h> #define WIN32_LEAN_AND_MEAN #include <windows.h> #ifdef _WIN32_WCE # define DIR_SEPERATOR TEXT("\\") # undef _getcwd # define _getcwd(str,len) wcscpy(str,TEXT("")) # define setbuf(f,b) # define setvbuf(w,x,y,z) # define fopen _wfopen # define freopen _wfreopen # define remove(x) DeleteFile(x) #else # define DIR_SEPERATOR TEXT("/") # include <direct.h> #endif /* Include the SDL main definition header */ #include "SDL.h" #include "SDL_main.h" #ifdef main # ifndef _WIN32_WCE_EMULATION # undef main # endif /* _WIN32_WCE_EMULATION */ #endif /* main */ /* The standard output files */ #define STDOUT_FILE TEXT("stdout.txt") #define STDERR_FILE TEXT("stderr.txt") /* Set a variable to tell if the stdio redirect has been enabled. */ static int stdioRedirectEnabled = 0; #ifdef _WIN32_WCE static wchar_t stdoutPath[MAX_PATH]; static wchar_t stderrPath[MAX_PATH]; #else static char stdoutPath[MAX_PATH]; static char stderrPath[MAX_PATH]; #endif #if defined(_WIN32_WCE) && _WIN32_WCE < 300 /* seems to be undefined in Win CE although in online help */ #define isspace(a) (((CHAR)a == ' ') || ((CHAR)a == '\t')) #endif /* _WIN32_WCE < 300 */ static void UnEscapeQuotes( char *arg ) { char *last = NULL; while( *arg ) { if( *arg == '"' && *last == '\\' ) { char *c_curr = arg; char *c_last = last; while( *c_curr ) { *c_last = *c_curr; c_last = c_curr; c_curr++; } *c_last = '\0'; } last = arg; arg++; } } /* Parse a command line buffer into arguments */ static int ParseCommandLine(char *cmdline, char **argv) { char *bufp; char *lastp = NULL; int argc, last_argc; argc = last_argc = 0; for ( bufp = cmdline; *bufp; ) { /* Skip leading whitespace */ while ( isspace(*bufp) ) { ++bufp; } /* Skip over argument */ if ( *bufp == '"' ) { ++bufp; if ( *bufp ) { if ( argv ) { argv[argc] = bufp; } ++argc; } /* Skip over word */ while ( *bufp && ( *bufp != '"' || (lastp && *lastp == '\\') ) ) { lastp = bufp; ++bufp; } } else { if ( *bufp ) { if ( argv ) { argv[argc] = bufp; } ++argc; } /* Skip over word */ while ( *bufp && ! isspace(*bufp) ) { ++bufp; } } if ( *bufp ) { if ( argv ) { *bufp = '\0'; } ++bufp; } /* Strip out \ from \" sequences */ if( argv && last_argc != argc ) { UnEscapeQuotes( argv[last_argc] ); } last_argc = argc; } if ( argv ) { argv[argc] = NULL; } return(argc); } /* Show an error message */ static void ShowError(const char *title, const char *message) { /* If USE_MESSAGEBOX is defined, you need to link with user32.lib */ #ifdef USE_MESSAGEBOX MessageBox(NULL, message, title, MB_ICONEXCLAMATION|MB_OK); #else fprintf(stderr, "%s: %s\n", title, message); #endif } /* Pop up an out of memory message, returns to Windows */ static BOOL OutOfMemory(void) { ShowError("Fatal Error", "Out of memory - aborting"); return FALSE; } /* SDL_Quit() shouldn't be used with atexit() directly because calling conventions may differ... */ static void cleanup(void) { SDL_Quit(); } /* Remove the output files if there was no output written */ static void cleanup_output(void) { FILE *file; int empty; /* Flush the output in case anything is queued */ fclose(stdout); fclose(stderr); /* Without redirection we're done */ if (!stdioRedirectEnabled) { return; } /* See if the files have any output in them */ if ( stdoutPath[0] ) { file = fopen(stdoutPath, TEXT("rb")); if ( file ) { empty = (fgetc(file) == EOF) ? 1 : 0; fclose(file); if ( empty ) { remove(stdoutPath); } } } if ( stderrPath[0] ) { file = fopen(stderrPath, TEXT("rb")); if ( file ) { empty = (fgetc(file) == EOF) ? 1 : 0; fclose(file); if ( empty ) { remove(stderrPath); } } } } /* Redirect the output (stdout and stderr) to a file */ static void redirect_output(void) { DWORD pathlen; #ifdef _WIN32_WCE wchar_t path[MAX_PATH]; #else char path[MAX_PATH]; #endif FILE *newfp; pathlen = GetModuleFileName(NULL, path, SDL_arraysize(path)); while ( pathlen > 0 && path[pathlen] != '\\' ) { --pathlen; } path[pathlen] = '\0'; #ifdef _WIN32_WCE wcsncpy( stdoutPath, path, SDL_arraysize(stdoutPath) ); wcsncat( stdoutPath, DIR_SEPERATOR STDOUT_FILE, SDL_arraysize(stdoutPath) ); #else SDL_strlcpy( stdoutPath, path, SDL_arraysize(stdoutPath) ); SDL_strlcat( stdoutPath, DIR_SEPERATOR STDOUT_FILE, SDL_arraysize(stdoutPath) ); #endif /* Redirect standard input and standard output */ newfp = freopen(stdoutPath, TEXT("w"), stdout); #ifndef _WIN32_WCE if ( newfp == NULL ) { /* This happens on NT */ #if !defined(stdout) stdout = fopen(stdoutPath, TEXT("w")); #else newfp = fopen(stdoutPath, TEXT("w")); if ( newfp ) { *stdout = *newfp; } #endif } #endif /* _WIN32_WCE */ #ifdef _WIN32_WCE wcsncpy( stderrPath, path, SDL_arraysize(stdoutPath) ); wcsncat( stderrPath, DIR_SEPERATOR STDOUT_FILE, SDL_arraysize(stdoutPath) ); #else SDL_strlcpy( stderrPath, path, SDL_arraysize(stderrPath) ); SDL_strlcat( stderrPath, DIR_SEPERATOR STDERR_FILE, SDL_arraysize(stderrPath) ); #endif newfp = freopen(stderrPath, TEXT("w"), stderr); #ifndef _WIN32_WCE if ( newfp == NULL ) { /* This happens on NT */ #if !defined(stderr) stderr = fopen(stderrPath, TEXT("w")); #else newfp = fopen(stderrPath, TEXT("w")); if ( newfp ) { *stderr = *newfp; } #endif } #endif /* _WIN32_WCE */ setvbuf(stdout, NULL, _IOLBF, BUFSIZ); /* Line buffered */ setbuf(stderr, NULL); /* No buffering */ stdioRedirectEnabled = 1; } #if defined(_MSC_VER) && !defined(_WIN32_WCE) /* The VC++ compiler needs main defined */ #define console_main main #endif /* This is where execution begins [console apps] */ int console_main(int argc, char *argv[]) { size_t n; char *bufp, *appname; int status; /* Get the class name from argv[0] */ appname = argv[0]; if ( (bufp=SDL_strrchr(argv[0], '\\')) != NULL ) { appname = bufp+1; } else if ( (bufp=SDL_strrchr(argv[0], '/')) != NULL ) { appname = bufp+1; } if ( (bufp=SDL_strrchr(appname, '.')) == NULL ) n = SDL_strlen(appname); else n = (bufp-appname); bufp = SDL_stack_alloc(char, n+1); if ( bufp == NULL ) { return OutOfMemory(); } SDL_strlcpy(bufp, appname, n+1); appname = bufp; /* Load SDL dynamic link library */ if ( SDL_Init(SDL_INIT_NOPARACHUTE) < 0 ) { ShowError("WinMain() error", SDL_GetError()); return(FALSE); } atexit(cleanup_output); atexit(cleanup); /* Sam: We still need to pass in the application handle so that DirectInput will initialize properly when SDL_RegisterApp() is called later in the video initialization. */ SDL_SetModuleHandle(GetModuleHandle(NULL)); /* Run the application main() code */ status = SDL_main(argc, argv); /* Exit cleanly, calling atexit() functions */ exit(status); /* Hush little compiler, don't you cry... */ return 0; } /* This is where execution begins [windowed apps] */ #ifdef _WIN32_WCE int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPWSTR szCmdLine, int sw) #else int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw) #endif { HMODULE handle; char **argv; int argc; char *cmdline; char *env_str; #ifdef _WIN32_WCE wchar_t *bufp; int nLen; #else char *bufp; size_t nLen; #endif /* Start up DDHELP.EXE before opening any files, so DDHELP doesn't keep them open. This is a hack.. hopefully it will be fixed someday. DDHELP.EXE starts up the first time DDRAW.DLL is loaded. */ handle = LoadLibrary(TEXT("DDRAW.DLL")); if ( handle != NULL ) { FreeLibrary(handle); } /* Check for stdio redirect settings and do the redirection */ if ((env_str = SDL_getenv("SDL_STDIO_REDIRECT"))) { if (SDL_atoi(env_str)) { redirect_output(); } } #ifndef NO_STDIO_REDIRECT else { redirect_output(); } #endif #ifdef _WIN32_WCE nLen = wcslen(szCmdLine)+128+1; bufp = SDL_stack_alloc(wchar_t, nLen*2); wcscpy (bufp, TEXT("\"")); GetModuleFileName(NULL, bufp+1, 128-3); wcscpy (bufp+wcslen(bufp), TEXT("\" ")); wcsncpy(bufp+wcslen(bufp), szCmdLine,nLen-wcslen(bufp)); nLen = wcslen(bufp)+1; cmdline = SDL_stack_alloc(char, nLen); if ( cmdline == NULL ) { return OutOfMemory(); } WideCharToMultiByte(CP_ACP, 0, bufp, -1, cmdline, nLen, NULL, NULL); #else /* Grab the command line */ bufp = GetCommandLine(); nLen = SDL_strlen(bufp)+1; cmdline = SDL_stack_alloc(char, nLen); if ( cmdline == NULL ) { return OutOfMemory(); } SDL_strlcpy(cmdline, bufp, nLen); #endif /* Parse it into argv and argc */ argc = ParseCommandLine(cmdline, NULL); argv = SDL_stack_alloc(char*, argc+1); if ( argv == NULL ) { return OutOfMemory(); } ParseCommandLine(cmdline, argv); /* Run the main program (after a little SDL initialization) */ console_main(argc, argv); /* Hush little compiler, don't you cry... */ return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_display.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: srossi <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/04/26 18:19:40 by srossi #+# #+# */ /* Updated: 2018/04/26 18:26:41 by srossi ### ########.fr */ /* */ /* ************************************************************************** */ #include "lem_in.h" int ft_display_lst(t_room *room) { t_room *alst; t_link *link; alst = room; if (alst == NULL) return (0); while (alst != NULL) { ft_putstr("Room ("); ft_putnbr(alst->nb_room); ft_putstr(") : "); ft_putendl(alst->name); ft_putstr("Liaisons : "); link = alst->next_map; while (link) { ft_putstr(link->room->name); ft_putstr(" ; "); link = link->next; } ft_putchar('\n'); alst = alst->next; } return (0); } int ft_display_lines(t_game *game) { t_line *ptr; ptr = game->lines; while (ptr) { ft_putendl(ptr->str); ptr = ptr->next; } return (0); }
C
#include <stdio.h> #include <stdlib.h> typedef struct node * link; struct node { char item; struct node *l, *r; }; link root = NULL; link make_node(char item) //创建节点 { link p; p = malloc(sizeof(*p)); p->item = item; p->l = NULL; p->r = NULL; return p; } void traverse(link t) //遍历 { if (t == NULL) { printf("()"); return; } printf("(%c", t->item); // printf("demo binary tree!\n"); traverse(t->l); traverse(t->r); printf(")"); return; } #if 0 int count(link t) { int count = 0; if (t = NULL) return 0; return 1 + count(t->l) + count(t->r); } #endif int main(void) { link a, b, c; link d, e, f, g; // printf("demo binary tree!\n"); a = make_node('a'); b = make_node('2'); c = make_node('5'); d = make_node('1'); e = make_node('3'); f = make_node('6'); g = make_node('g'); // printf("demo binary tree!\n"); a->l = b; a->r = c; //b->r = c; b->l = d; b->r = e; c->r = f; f->r = g; root = a; // printf("demo binary tree!\n"); printf("\\tree "); f = make_node('6'); traverse(root); printf("\n"); // printf("count = %d\n", count(root)); return 0; }
C
/************************************************ * creator: vingc zhang * time: 2017.03.27 *************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> /* ref: http://www.geeksforgeeks.org/count-triplets-with-sum-smaller-that-a-given-value/ Count triplets with sum smaller than a given value Given an array of distinct integers and a sum value. Find count of triplets with sum smaller than given sum value. Expected Time Complexity is O(n2). Examples: Input : arr[] = {-2, 0, 1, 3} sum = 2. Output : 2 Explanation : Below are triplets with sum less than 2 (-2, 0, 1) and (-2, 0, 3) Input : arr[] = {5, 1, 3, 4, 7} sum = 12. Output : 4 Explanation : Below are triplets with sum less than 4 (1, 3, 4), (1, 3, 5), (1, 3, 7) and (1, 4, 5) 1. A Simple Solution is to run three loops to consider all triplets one by one. For every triplet, compare the sums and increment count if triplet sum is smaller than given sum. 2. An Efficient Solution can count triplets in O(n2) by sorting the array first, and then using method of "array_pair_sum_equal_value.c" in a loop. 1) Sort the input array in increasing order. 2) Initialize result as 0. 3) Run a loop from i = 0 to n-2. An iteration of this loop finds all triplets with arr[i] as first element. a) Initialize other two elements as corner elements of subarray arr[i+1..n-1], i.e., j = i+1 and k = n-1 b) Move j and k toward each other until they meet, i.e., while (j < k) (i) if (arr[i] + arr[j] + arr[k] >= sum), then do k-- // Else for current i and j, there can (k-j) possible third elements // that satisfy the constraint. (ii) Else Do ans += (k - j) followed by j++ */ int partition( int a[], int begin, int end ) { int mid = end; int i = begin - 1; int j = begin; int tmp; while( j < end ) { if( a[j] < a[mid] ) { i++; tmp = a[j]; a[j] = a[i]; a[i] = tmp; } j++; } i++; tmp = a[mid]; a[mid] = a[i]; a[i] = tmp; return i; } void quikSort( int a[], int begin, int end ) { if( begin >= end ) { return; } int p = partition( a, begin, end ); quikSort( a, begin, p - 1 ); quikSort( a, p + 1, end ); return; } int cntTriplets( int a[], int n, int sum ) { quikSort( a, 0, n - 1 ); int i,j,k,cnt; cnt = 0; for( i = 0; i < n - 2; i++ ) { //a[i] as the first item of triplets. j = i + 1; k = n - 1; while( j < k ) { //a[j] and a[k] as the second and third item of triplets respectively. if( a[i] + a[j] + a[k] >= sum ) { k--; //move the left forward, take the smaller value as the third item. } else { //there are k-j third items making the sum of triplets smaller than sum cnt += k - j; j++; //move the right forward, take the bigger value as the second item. } } } return cnt; } void main( void ) { int arr[] = {5, 1, 3, 4, 7}; int n = sizeof arr / sizeof arr[0]; int sum = 12; printf( "cnt:%d\n", cntTriplets( arr, n, 12 ) ); }
C
/******************************************************************************* * File Name: Ana.c * Version 2.0 * * Description: * This file contains API to enable firmware control of a Pins component. * * Note: * ******************************************************************************** * Copyright 2008-2014, Cypress Semiconductor Corporation. All rights reserved. * You may use this file only in accordance with the license, terms, conditions, * disclaimers, and limitations in the end user license agreement accompanying * the software package with which this file was provided. *******************************************************************************/ #include "cytypes.h" #include "Ana.h" /******************************************************************************* * Function Name: Ana_Write ******************************************************************************** * * Summary: * Assign a new value to the digital port's data output register. * * Parameters: * prtValue: The value to be assigned to the Digital Port. * * Return: * None * *******************************************************************************/ void Ana_Write(uint8 value) { uint8 staticBits = (Ana_DR & (uint8)(~Ana_MASK)); Ana_DR = staticBits | ((uint8)(value << Ana_SHIFT) & Ana_MASK); } /******************************************************************************* * Function Name: Ana_SetDriveMode ******************************************************************************** * * Summary: * Change the drive mode on the pins of the port. * * Parameters: * mode: Change the pins to one of the following drive modes. * * Ana_DM_STRONG Strong Drive * Ana_DM_OD_HI Open Drain, Drives High * Ana_DM_OD_LO Open Drain, Drives Low * Ana_DM_RES_UP Resistive Pull Up * Ana_DM_RES_DWN Resistive Pull Down * Ana_DM_RES_UPDWN Resistive Pull Up/Down * Ana_DM_DIG_HIZ High Impedance Digital * Ana_DM_ALG_HIZ High Impedance Analog * * Return: * None * *******************************************************************************/ void Ana_SetDriveMode(uint8 mode) { CyPins_SetPinDriveMode(Ana_0, mode); } /******************************************************************************* * Function Name: Ana_Read ******************************************************************************** * * Summary: * Read the current value on the pins of the Digital Port in right justified * form. * * Parameters: * None * * Return: * Returns the current value of the Digital Port as a right justified number * * Note: * Macro Ana_ReadPS calls this function. * *******************************************************************************/ uint8 Ana_Read(void) { return (Ana_PS & Ana_MASK) >> Ana_SHIFT; } /******************************************************************************* * Function Name: Ana_ReadDataReg ******************************************************************************** * * Summary: * Read the current value assigned to a Digital Port's data output register * * Parameters: * None * * Return: * Returns the current value assigned to the Digital Port's data output register * *******************************************************************************/ uint8 Ana_ReadDataReg(void) { return (Ana_DR & Ana_MASK) >> Ana_SHIFT; } /* If Interrupts Are Enabled for this Pins component */ #if defined(Ana_INTSTAT) /******************************************************************************* * Function Name: Ana_ClearInterrupt ******************************************************************************** * * Summary: * Clears any active interrupts attached to port and returns the value of the * interrupt status register. * * Parameters: * None * * Return: * Returns the value of the interrupt status register * *******************************************************************************/ uint8 Ana_ClearInterrupt(void) { return (Ana_INTSTAT & Ana_MASK) >> Ana_SHIFT; } #endif /* If Interrupts Are Enabled for this Pins component */ /* [] END OF FILE */
C
/* Yanling Wang Fall 2018 */ #ifndef LIST_H #define LIST_H typedef struct listNode{ char host[MAXLINE]; char port[MAXLINE]; char query[MAXLINE]; char *memory; int memsize; struct listNode *next; struct listNode *prev; } listNode; /*typedef struct listNode { int value; struct listNode *next; struct listNode *prev; } listNode;*/ typedef struct doublyLinkedList { struct listNode *head; struct listNode *tail; int block_count; int size; } doublyLinkedList; void insertHead(doublyLinkedList *listPtr, listNode *head); int removeTail(doublyLinkedList *listPtr); void showHead(doublyLinkedList *listPtr); void showTail(doublyLinkedList *listPtr); void freeList(doublyLinkedList *listPtr); listNode* constructor(char *host, char *port, char *query, char *memory, int size); void deleteNode(doublyLinkedList *listPtr, listNode *node); #endif //LIST_H
C
/************************************************************************************* * Programmer: Kristin Onorati * Class: CPTS 122, Summer 2013 * Programming Assignment: 1 * Date: June 9th, 2013 * Description: Gets a string from the user and applies a Caesar shift cipher based on a * shift determined by the user. **************************************************************************************/ #include "CaesarShift.h" int main(void) { int shift = 0; char* pSentence = NULL; char* pEncrypted = NULL; pSentence = getSentence(); shift = getShift(); pEncrypted = caesarShiftCipher(pSentence, shift); puts("\nOriginal Sentence: "); puts(pSentence); puts("\nEncrypted Sentence: "); puts(pEncrypted); return 0; }
C
#include <stdio.h> // #include <stdlib.h> #include <math.h> #include "random.h" static const double two_pi = 2.0 * 3.14159265358979323846; // static const double sqrt_2 = 1.41421356237309504880; // Returns a random number in [min, max]. inline Number uniform_random(void *rng, Number min, Number max) { return (max - min) * rng32_nextFloat(rng) + min; } // Box–Muller transform, generate two 'Number' following the distribution N(0,1): void Box_Muller(void *rng, Number *x1, Number *x2) { double u1; double u2 = rng32_nextFloat(rng); // ~ U[0, 1] do { u1 = rng32_nextFloat(rng); } // ~ U]0, 1], needs to be > 0 !!! while (u1 == 0); double rho = sqrt(-2. * log(u1)); double theta = two_pi * u2; *x1 = (Number) (rho * cos(theta)); *x2 = (Number) (rho * sin(theta)); } // Generate two 'Number' following the distribution N(mean, std_dev²): void gaussian_random(void *rng, Number *x1, Number *x2, Number mean, Number std_dev) { Box_Muller(rng, x1, x2); *x1 = mean + std_dev * *x1; *x2 = mean + std_dev * *x2; } // Shuffling: // Fisher–Yates shuffle, for an array of pointers: void shuffle(void *rng, void* *array, int len) { // In case RNG32_MAX is small, for some (terrible) RNG... if (len >= RNG32_MAX) printf("\nArray length (%d) is greater or equal to RNG32_MAX!\n\n", len); for (unsigned int i = len - 1; i >= 1; --i) { unsigned int j = rng32_nextInt(rng) % (i + 1); // 0 ≤ j ≤ i. Biased, but negligeable. void* temp = array[i]; array[i] = array[j]; array[j] = temp; } } // Readable if every element of array is the address of a Number... void demo_print(Number* *array, int len) { if (array == NULL) return; for (int i = 0; i < len; ++i) printf("%8.f", *(array[i])); // only printing the integer part. printf("\n"); }
C
/* * File: iMapaDeBits.h * Author: Monty * * Created on 19 de marzo de 2016, 01:10 */ #ifndef IMAPADEBITS_H #define IMAPADEBITS_H #include "../../Bloque/Headers/iBloque.h" typedef class iMapaDeBits { public: // Devuelve la referencia al bloque interno virtual const iBloquePtr Leer() = 0; virtual size_t ObtenerTamanio() = 0; // pueden tirar excepcion virtual bool ObtenerBit(size_t posicion) = 0; virtual void SetearBit(size_t posicion, bool valor) = 0; virtual void Dispose() = 0; } *iMapaDeBitsPtr; #endif /* IMAPADEBITS_H */
C
/* * Copyright (c) 2020 Lucas Müller * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <stdio.h> #include <unistd.h> //for access() #include <string.h> #include <locale.h> #include <json-actor.h> #define TEXT1 "{\"a\": 12, \"ab\": 481}" char *get_json_text(char filename[]); json_item_t *callback_test(json_item_t *item); int main(int argc, char *argv[]) { char *locale = setlocale(LC_CTYPE, ""); assert(NULL != locale); char *json_text = get_json_text(argv[1]); json_item_t *root = json_parse(json_text, strlen(json_text)); struct sized_buffer str = json_stringify(root, JSON_ANY); fprintf(stderr, "%.*s", (int)str.size, str.start); json_cleanup(root); root = json_parse(TEXT1, sizeof(TEXT1)); fprintf(stderr, "%Lf\n", json_get_number(json_get_child(root, "ab"))); return EXIT_SUCCESS; } /* returns file size in long format */ static long fetch_filesize(FILE *p_file) { fseek(p_file, 0, SEEK_END); long filesize = ftell(p_file); assert(filesize > 0); fseek(p_file, 0, SEEK_SET); return filesize; } /* returns file content */ static char* read_file(FILE* p_file, long filesize) { char *buffer = malloc(filesize+1); assert(NULL != buffer); //read file into buffer fread(buffer,1,filesize,p_file); buffer[filesize] = 0; return buffer; } /* returns buffer containing file content */ char* get_json_text(char filename[]) { FILE *file = fopen(filename, "rb"); assert(NULL != file); long filesize = fetch_filesize(file); char *buffer = read_file(file, filesize); fclose(file); return buffer; } json_item_t *callback_test(json_item_t *item) { if (NULL != item && json_keycmp(item, "m")){ fprintf(stdout, "%s\n", json_get_string(item, NULL)); } return item; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define N_TOKEN_HASH 73176001 typedef struct token{ char* content; int len; } token; int trans(char c); unsigned int hash(token* c, int base); unsigned int weirdhash(token* c, int base); int cmpfunc(const void* a, const void* b) {return (*(unsigned int*) a - *(unsigned int*) b);} int appeared[N_TOKEN_HASH] = {0}; int main(){ FILE* tok; tok = fopen("tokens", "r"); token tokens[138078]; for (int i = 0; i < 138078; i++) tokens[i].content = (char*) malloc(sizeof(char) * 52); int collision[1000]; int col = 0; for (int i = 0; i < 138078; i++){ fscanf(tok, "%s", tokens[i].content); tokens[i].len = strlen(tokens[i].content); unsigned int h = hash(tokens+i, N_TOKEN_HASH); if (appeared[h]){ collision[col++] = i; } appeared[h]++; } printf("%d\n", col); int rehash_base = 1000000; while (rehash_base < 10000000){ int T[600]; int tlen = 0; for (int i = 0; i < col; i++){ unsigned int h = weirdhash(tokens+collision[i], rehash_base) + hash(tokens+collision[i], N_TOKEN_HASH); if (!appeared[h]){ T[tlen++] = h; } else break; } if (tlen == col){ qsort(T, tlen, sizeof(unsigned int), cmpfunc); int collisionagain = 0; for (int i = 0; i < tlen-1; i++){ if (T[i] == T[i+1]){ collisionagain = 1; break; } } if (!collisionagain){ printf("%d\n", rehash_base); } } rehash_base++; } return 0; } unsigned int hash(token* c, int base){ unsigned int r = 0; for (int i = 0; i < c->len; i++){ r *= 37; r += trans(c->content[i]); r %= base; } return r; } unsigned int weirdhash(token* c, int base){ unsigned int r = 0; for (int i = 0; i < c->len; i++){ r *= 37; r += trans(c->content[i]); r %= base; r *= 37; r += 25; r %= base; } return r; } int trans(char c){ if ((c >= '0') && (c <= '9')) return c-'0'; if ((c >= 'a') && (c <= 'z')) return c-'a'+10; if ((c >= 'A') && (c <= 'Z')) return c-'A'+10; }
C
/* $Id: sig_block.c 4723 2009-11-16 18:57:09Z kobus $ */ #include "l/l_incl.h" static TRAP_FN_RETURN_TYPE trap_fn_0(int); static TRAP_FN_RETURN_TYPE trap_fn_1(int); static TRAP_FN_RETURN_TYPE trap_fn_2(int); static TRAP_FN_RETURN_TYPE trap_fn_3(int); static TRAP_FN_RETURN_TYPE trap_fn_4(int); static TRAP_FN_RETURN_TYPE trap_fn_5(int); static TRAP_FN_RETURN_TYPE trap_fn_6(int); static TRAP_FN_RETURN_TYPE trap_fn_7(int); static TRAP_FN_RETURN_TYPE trap_fn_8(int); /*ARGSUSED*/ int main(int argc, char **argv) { char line [ 100 ]; kjb_int32 res; kjb_int32 level = 0; TRAP_FN_RETURN_TYPE (*trap_fns[ 9 ])(); trap_fns[ 0 ] = (void(*)())trap_fn_0; trap_fns[ 1 ] = (void(*)())trap_fn_1; trap_fns[ 2 ] = (void(*)())trap_fn_2; trap_fns[ 3 ] = (void(*)())trap_fn_3; trap_fns[ 4 ] = (void(*)())trap_fn_4; trap_fns[ 5 ] = (void(*)())trap_fn_5; trap_fns[ 6 ] = (void(*)())trap_fn_6; trap_fns[ 7 ] = (void(*)())trap_fn_7; trap_fns[ 8 ] = (void(*)())trap_fn_8; set_atn_trap(trap_fn_0, RESTART_AFTER_SIGNAL); while ((res = term_get_line("trap> ", line, sizeof(line))) != EOF) { dbi(res); dbs(line); if (STRCMP_EQ(line, "s")) { level++; EPE(set_atn_trap((void(*)(int))trap_fns[ level ], RESTART_AFTER_SIGNAL)); dbi(level); } else if (STRCMP_EQ(line, "u")) { if (level > 0 ) level--; EPE(unset_atn_trap()); dbi(level); } else if (STRCMP_EQ(line, "d")) { EPE(dont_restart_on_atn()); } else if (STRCMP_EQ(line, "r")) { EPE(restart_on_atn()); } else if (STRCMP_EQ(line, "a")) { EPE(allow_user_signals()); } else if (STRCMP_EQ(line, "b")) { EPE(block_user_signals()); } else if (STRCMP_EQ(line, "t")) { EPE(reset_signals()); } else if (STRCMP_EQ(line, "e")) { EPE(reset_restart_on_atn()); } else { dbm("No level change.\n"); } } return EXIT_SUCCESS; } /*ARGSUSED*/ static TRAP_FN_RETURN_TYPE trap_fn_0(int sig) { p_stderr("Zero.\n"); } /*ARGSUSED*/ static TRAP_FN_RETURN_TYPE trap_fn_1(int sig) { p_stderr("One.\n"); } /*ARGSUSED*/ static TRAP_FN_RETURN_TYPE trap_fn_2(int sig) { p_stderr("Two.\n"); } /*ARGSUSED*/ static TRAP_FN_RETURN_TYPE trap_fn_3(int sig) { p_stderr("Three.\n"); } /*ARGSUSED*/ static TRAP_FN_RETURN_TYPE trap_fn_4(int sig) { p_stderr("Four.\n"); } /*ARGSUSED*/ static TRAP_FN_RETURN_TYPE trap_fn_5(int sig) { p_stderr("Five.\n"); } /*ARGSUSED*/ static TRAP_FN_RETURN_TYPE trap_fn_6(int sig) { p_stderr("Six.\n"); } /*ARGSUSED*/ static TRAP_FN_RETURN_TYPE trap_fn_7(int sig) { p_stderr("Seven.\n"); } /*ARGSUSED*/ static TRAP_FN_RETURN_TYPE trap_fn_8(int sig) { p_stderr("Eight.\n"); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "liczbyRzymskie.h" char *znaki[] ={ "M\0", "CM\0", "D\0", "CD\0", "C\0", "XC\0", "L\0", "XL\0", "X\0", "IX\0", "V\0", "IV\0", "I\0" }; int wartosci[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; int decToRoman(int liczba, char* bufor){ if(liczba < 0) {printf("Za mala liczba\n"); return 1;} else if(liczba > 3999) {printf("Za duza liczba\n"); return 1;} int i; for(i =0; i < 13; i++){ if(liczba >= wartosci[i]){ strcat(bufor,znaki[i]); liczba -= wartosci[i]; i--; } } return 0; } int GetWartosc(char znak){ if (znak == 'I') return 1; if (znak == 'V') return 5; if (znak == 'X') return 10; if (znak == 'L') return 50; if (znak == 'C') return 100; if (znak == 'D') return 500; if (znak == 'M') return 1000; return -1; } int romanToDec(char* liczba) { int wynik = 0; int i; int dlugosc = strlen(liczba); for (i=0; i< dlugosc; i++) { int w1 = GetWartosc(*(liczba+i)); if(w1 == -1) return -1; if (i+1 < dlugosc) { int nast = GetWartosc(*(liczba+i+1)); if(nast == -1) return -1; if (w1 >= nast) { wynik = wynik + w1; } else { wynik = wynik + nast - w1; i++; } } else { wynik = wynik + w1; i++; } } return wynik; }
C
#include "headers.h" void IO(char **comm) { int append=0,greater=0,less=0; int i=0; char inp[1024]; char out[1024]; int fl=0; int pehla,doosra; for(i=0;comm[i]!=NULL;i++) { if(!strcmp(comm[i],">")) {greater=1; fl=0; comm[i]=NULL; if(comm[i+1]==NULL) {global=-1;printf("error: wrong command\n");return;} else {strcpy(out,comm[i+1]);} } else if(!strcmp(comm[i],"<")) {less=1; comm[i]=NULL; if(comm[i+1]==NULL) {global=-1;printf("error: wrong command\n");return;} else {strcpy(inp,comm[i+1]);} } else if(!strcmp(comm[i],">>")) {append=1; comm[i]=NULL; fl=1; if(comm[i+1]==NULL) {global=-1;printf("error: wrong command\n");return;} else {strcpy(out,comm[i+1]);} } } if(less==1) { int fd=open(inp,O_RDONLY,0644); if(fd<0) {global=-1;perror("error:\n"); return; } pehla=dup(0); dup2(fd,0); } if(greater==1||append==1) { if(fl==1) { int fd2=open(out,O_WRONLY|O_CREAT|O_APPEND,0644); if(fd2<0){global=-1;perror("couldn't open file\n");return;} doosra=dup(1); dup2(fd2,1); } else { int fd2=open(out,O_WRONLY|O_CREAT|O_TRUNC,0644); if(fd2<0){global=-1;perror("couldn't open file\n");return;} doosra=dup(1); dup2(fd2,1); } } int ppip[2];ppip[0]=0;ppip[1]=0;pipe(ppip); pid_t pid=fork(); if(pid<0) {global=-1;perror("error while forking:\n");return ;} else if(pid==0) { if(execvp(comm[0],comm)==-1) { int a=-1; close(ppip[0]); write(ppip[1],&a,sizeof(&a)); close(ppip[1]); perror("wrong command\n"); exit(EXIT_FAILURE); } } else { int statu; waitpid(pid,&statu,WUNTRACED); if(statu>0) {global=-1;} close(ppip[1]); read(ppip[0],&global,sizeof(&global)); close(ppip[0]); dup2(pehla,0); dup2(doosra,1); } }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #define N 100 #define LINE "************************************************" void transform(double [], double [], int, double (*) (double)); void display(double [], int); double add_one(double); double squared(double); int main(void) { srand((unsigned) time(NULL)); double source[N], target[N]; for (int i = 0; i < N; i++) source[i] = rand() % 181; display(source, N); puts(LINE); puts("apply to sin: "); transform(source, target, N, sin); display(target, N); puts(LINE); puts("apply to cos: "); transform(source, target, N, cos); display(target, N); puts(LINE); puts("apply to add_one: "); transform(source, target, N, add_one); display(target, N); puts(LINE); puts("apply to squared: "); transform(source, target, N, squared); display(target, N); return 0; } double squared(double n) { return n * n; } double add_one(double n) { return n + 1; } void display(double arr[], int n) { for (int i = 0; i < n; i++) { printf("%.2f ", arr[i]); if (i % 10 == 0 && i != 0) putchar('\n'); } putchar('\n'); } void transform(double source[], double target[], int n, double (* func) (double)) { for (int i = 0; i < n; i++) { target[i] = func(source[i]); } }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include "DekoFunkcijos.h" void SukurtiDeka(DekoRodykles *zymiuData) { Dekas *naujas = (Dekas*)malloc(1*sizeof(Dekas)); zymiuData->pradinis = naujas; if (naujas == NULL) return; naujas->next = NULL; naujas->prev = NULL; zymiuData->kiekis = 0; zymiuData->priekis = naujas; zymiuData->galas = naujas; //return naujas; } void IterptiTop(int data, DekoRodykles *zymiuData) { if (zymiuData->kiekis == 0) { zymiuData->pradinis->info = data; (zymiuData->kiekis)++; } else { Dekas *naujasPrieky = (Dekas*)malloc(1*sizeof(Dekas)); zymiuData->priekis->prev = naujasPrieky; naujasPrieky->next = zymiuData->priekis; naujasPrieky->info = data; zymiuData->priekis = naujasPrieky; naujasPrieky->prev = NULL; (zymiuData->kiekis)++; } } void IterptiBottom(int data, DekoRodykles *zymiuData) { if (zymiuData->kiekis == 0) { zymiuData->pradinis->info = data; (zymiuData->kiekis)++; } else { Dekas *naujasGale = (Dekas*)malloc(1*sizeof(Dekas)); zymiuData->galas->next = naujasGale; naujasGale->prev = zymiuData->galas; naujasGale->info = data; zymiuData->galas = naujasGale; naujasGale->next = NULL; (zymiuData->kiekis)++; } } void IstrintiPirma(DekoRodykles *zymiuData) { Dekas *istrinti; istrinti = zymiuData->priekis; zymiuData->priekis = zymiuData->priekis->next; if (zymiuData->kiekis != 1) istrinti->next->prev = NULL; free(istrinti); (zymiuData->kiekis)--; if (zymiuData->kiekis == 0) { zymiuData->priekis = NULL; zymiuData->galas = NULL; } } void IstrintiPaskutini(DekoRodykles *zymiuData) { Dekas *istrinti; istrinti = zymiuData->galas; zymiuData->galas = zymiuData->galas->prev; if (zymiuData->kiekis != 1) istrinti->prev->next = NULL; free(istrinti); (zymiuData->kiekis)--; if (zymiuData->kiekis == 0) { zymiuData->priekis = NULL; zymiuData->galas = NULL; } } int DekoDuomKiekis(DekoRodykles zymiuData) { if(zymiuData.kiekis == 0) return 0; else if (zymiuData.kiekis == 1) return 1; else return zymiuData.kiekis; } int PradziosDuom(DekoRodykles zymiuData) { if(zymiuData.kiekis == 0) return 0; else return zymiuData.priekis->info; } int PabaigosDuom(DekoRodykles zymiuData) { if(zymiuData.kiekis == 0) return 0; else return zymiuData.galas->info; } void PerziuretiVisaDeka(DekoRodykles zymiuData) { Dekas *spausdinimas = zymiuData.priekis; while(spausdinimas != NULL) { printf(" %d", spausdinimas->info); spausdinimas = spausdinimas->next; } } bool ArTuscias(DekoRodykles zymiuData) { if(zymiuData.kiekis == 0) return true; else return false; } void Sunaikinti(DekoRodykles *zymiuData) { Dekas *istrinti = zymiuData->priekis; Dekas *istrintiSekantis = NULL; while(istrinti != NULL) { istrintiSekantis = istrinti->next; free(istrinti); istrinti = istrintiSekantis; } zymiuData->kiekis = 0; zymiuData->priekis = NULL; zymiuData->galas = NULL; printf(" Dekas sunaikintas \n"); }
C
#include<stdio.h> #include<stdlib.h> #include<conio.h> typedef struct node{ char harf; int frekans; struct node *left,*right,*next; }NODE; NODE* add_node(NODE*,char,int); void insert_after(NODE **,NODE *); void delete_node(char*); void print_list(NODE*); void insertion_sort(NODE**); NODE* huffman(NODE*); void print_huffman(NODE*); NODE* enkucuknode_cikar(NODE**); int tree_height(NODE*); void print_tree_node(NODE*,int); void print_tree_node(NODE* iter,int level){ //Fonksiyon, kendisine gonderilen bir agac seviyesindeki node'lari if(iter==NULL){ //recursive olarak surekli tum yollardan ayni node seviyesine return; //inip geri cikarak yazd�rmaktadir. NULL nodelar� yazdirmiyoruz. } if(level == 1){ if(iter->harf==' '){ printf("(' '%d) ",iter->frekans); //bosluklarin gorunurlugu icin } else if(iter->harf=='$'){ //child olmayan node'larin harfini '$' olarak kodlamistik printf("(%d) ",iter->frekans); //bu sayede parent node'lari bosluk sayisi ile karistirmiyoruz. } else{ printf("(%c%d) ",iter->harf,iter->frekans); } } else if(level>1){ print_tree_node(iter->left,level-1); //girilen herhangi bir level sayisi kadar //level=1 olana kadar left'e gidiyoruz //NULL degilse 1 olunca indigimiz node'u yazdirip print_tree_node(iter->right,level-1); //ayni node'un bir ustunden tekrar level=1 olana kadar //right'a iniyoruz. onu da yazdirip sonra geri ciktikca mumkun olan dallara //tekrar inerek o leveldeki tum node'lari yazdirmis oluyoruz. } } int tree_height(NODE* head){ //Bu fonksiyonla agacin yuksekligini buluyoruz ki //tum node'lari eksiksiz yazdirabilelim if(head==NULL){ return 0; } else{ int height_L=tree_height(head->left); //NULL node gorene kadar sol en derine iniyoruz, NULL gordugumuz int height_R=tree_height(head->right); //yerde bir level geri donup tekrar solda NULL yoksa tekrar //en derine inmeye devam ederek en alttaki tum child node'lar� //dolasmis oluyoruz. if(height_L>height_R){ //her dip node'a inince sayaclarimiz fonksiyonlari cagirabildikleri return height_L+1; //kadar sayiyi bir ust node'a aktariyor } //tum node'lar gezildikten sonra en derin yolun level sayisi donmus oluyor. else{ return height_R+1; } } } void print_huffman(NODE *head){ // Tree'mizi yazdirma fonksiyonu int height=tree_height(head); //Yazdirmadan once agacimizin yuksekligini hesapl�yoruz int i=0; for(i=1;i<=height;i++){ //tum node seviyelerini sirayla seviye yazdirma fonksiyonuna gonderiyoruz int j; for(j=0;j<height-i;j++){ printf(" "); } print_tree_node(head, i); printf("\n"); } } NODE* enkucuknode_cikar(NODE** head){ //Huffman Tree'ye donustururken olusturdugumuz //gecici tree'nin child'larini her defasinda listeden //en kucuk olan node'u cikartip alarak ayarliyoruz NODE *tmp; tmp=*head; if((*head)->next==NULL){ //son eleman bir eleman kaldiysa tmp=(*head); *head=NULL; return tmp; } *head=(*head)->next; //giren eleman son eleman degilse listede o andaki //en kucuk elemandir, onu gecici tree'ye ekleyecegimiz icin return tmp; //listeden cikarttik, listenin yeni head'i bir sonraki eleman oldu } void insertion_sort(NODE** head){ NODE *tmp_list=NULL; //kaydirdigimiz indisimize kadar olan sirali NODE *current=*head; //listeyi gosteren gecici listemizin head'i while(current!=NULL){ //listenin en basindan itibaren elemanlari sirayla alip NODE *next =current->next; //uygun yere insert edecegiz, bunun icin sirali listemizi ve onceki insert_after(&tmp_list,current); //siralanmamis listekimizdeki o anki indisi insert fonksiyonuna current=next; //gonderiyoruz } *head=tmp_list; //ilk listemizdeki indis NULL gorene kadar insert ile siraladik //yeni head'imiz gecici olusturdugumuz sirali listenin head'i } void insert_after(NODE** head,NODE* tmp){ //insertion_sort'un asil uygun yere koyma isini bu fonksiyon yapiyor NODE* current; if(*head==NULL||(*head)->frekans>tmp->frekans){ tmp->next=*head; *head=tmp; } else{ current=*head; while(current->next!=NULL && current->next->frekans <= tmp->frekans){ current = current->next; //tmp'in sirali listede uygun oldugu yeri bulana } //kadar current'i iterasyon yaptiriyoruz tmp->next = current->next; // uygun yer bulundu ve current->next=tmp; //tmp current ile current->next arasina insert edildi } } NODE* add_node(NODE *head,char harf,int frekans){ //girilen metnimizdeki harfler ve frekans sayilari NODE *new; // sirasiz linkli listeye ekleniyor new=(NODE*) malloc(sizeof(NODE)); if(new==NULL){ printf("malloc hatasi! \n"); exit(1); } if(head==NULL){ // ilk node ise head ata head=new; head->next=NULL; head->left=NULL; head->right=NULL; head->frekans=frekans; head->harf=harf; return head; } new->next= head; new->left=NULL; new->right=NULL; new->frekans=frekans; new->harf=harf; head=new; //ilk node degilse yeni olusturulan node'u head yap return head; } NODE* huffman(NODE *head){ //Liste'den Tree'ye donusturdugumuz fonksiyon int node_n=0,i; NODE *counter; //kac kez gecici agac olusturacagimizi bilmek icin linkli listedeki for(counter=head;counter!=NULL;counter=counter->next){ //node sayisini buluyoruz node_n++; } for(i=1;i<node_n;i++){ NODE *tmp_root; //olusturacagimiz gecici agacin pointeri tmp_root=(NODE*)malloc(sizeof(NODE)); //gecici agaci initialize ettik tmp_root->left=enkucuknode_cikar(&head); //left icin listedeki en kucuk frekansli harf bulundu tmp_root->right=enkucuknode_cikar(&head); //right icin tekrar cagrildi tmp_root->frekans = tmp_root->left->frekans + tmp_root->right->frekans; //gecici agacimizin //root'unun frekansi, child node'larin frekanslari toplamina esit tmp_root->harf='$'; //yazdirirken ayirt etmek icin boyle kodladik insert_after(&head,tmp_root); //olusturdugumuz gecici agaci o anki listedeki //uygun yere insert ediyoruz. head zaten enkucuknode_cikar //cagrilinca guncellenmisti. } return head; } void print_list(NODE* head){ if(head==NULL){ printf("Liste bos \n"); return; } NODE* i; for(i=head; i!=NULL; i=i->next){ printf("(%c %d)",i->harf, i->frekans); } printf("\n"); } int main(){ char input[250]; int frekans[27]={0},i=0; // frekanslari tutacagimiz alfabe+space buyuklugunde dizi olusturduk NODE *head=NULL; //olusturacagimiz linkli listenin node'u printf("bir metin giriniz: "); gets(input); printf("%s \n",input); for(i=0;input[i]!='\0';i++){ if(input[i]>='a' && input[i]<='z'){ frekans[input[i]-'a']++; //kucuk harf ise ilgili indisteki sayaci arttir } else if(input[i]=' '){ //bosluk ise o hucreyi arttir frekans[26]++; } } for(i=0;i<27; i++){ if(frekans[i]!=0 && i<26){ head=add_node(head,'a'+i,frekans[i]); //frekans dizimizden linkli listeye geciste uygun harfi atamak icin // 'a'+indis } else if(frekans[i]!=0&&i==26){ // frekans dizisinde bosluk icin ayrilan gozdeki sayac, bosluk head=add_node(head,' ',frekans[i]); // karakteriyle birlikte listeye eklendi } } insertion_sort(&head); // liste siralanacak print_list(head); head=huffman(head); //sirali liste agaca donusturulecek print_huffman(head); getch(); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { srand((unsigned)time()); int n =rand()&1000; n = rand() & 1000; // deuxime initialisation de rand car on n'a pas beaucoup de variations // Il est difficile, en se basant sur le temps, d'obtenir des nombres vraiment alatoires int i = 0; // lorsque l'on excute le programme plusieurs fois en peu de temps. int score = 0; while (i != n) { printf("\n Entrez un nombre : "); scanf_s("%d", &i); if (i < n) { printf("\nTrop petit"); } if (i > n) { printf("\nTrop grand"); } score += 1; } printf("\nBravo, votre score est de %d", score); }
C
/* https://raw.githubusercontent.com/adafruit/Adafruit_SleepyDog/master/utility/WatchdogSAMD.cpp */ #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include "samd20.h" extern uint8_t wdt_wakeup; void wdt_reset() { // Write the watchdog clear key value (0xA5) to the watchdog // clear register to clear the watchdog timer and reset it. WDT->CLEAR.reg = WDT_CLEAR_CLEAR_KEY; while(WDT->STATUS.bit.SYNCBUSY); } int wdt_enable(int maxPeriodMS, bool isForSleep) { // Enable the watchdog with a period up to the specified max period in // milliseconds. // Review the watchdog section from the SAMD21 datasheet section 17: // http://www.atmel.com/images/atmel-42181-sam-d21_datasheet.pdf int cycles, actualMS; uint8_t bits; WDT->CTRL.reg = 0; // Disable watchdog for config while(WDT->STATUS.bit.SYNCBUSY); // You'll see some occasional conversion here compensating between // milliseconds (1000 Hz) and WDT clock cycles (~1024 Hz). The low- // power oscillator used by the WDT ostensibly runs at 32,768 Hz with // a 1:32 prescale, thus 1024 Hz, though probably not super precise. if((maxPeriodMS >= 16000) || !maxPeriodMS) { cycles = 16384; bits = 0xB; } else { cycles = (maxPeriodMS * 1024L + 500) / 1000; // ms -> WDT cycles if(cycles >= 8192) { cycles = 8192; bits = 0xA; } else if(cycles >= 4096) { cycles = 4096; bits = 0x9; } else if(cycles >= 2048) { cycles = 2048; bits = 0x8; } else if(cycles >= 1024) { cycles = 1024; bits = 0x7; } else if(cycles >= 512) { cycles = 512; bits = 0x6; } else if(cycles >= 256) { cycles = 256; bits = 0x5; } else if(cycles >= 128) { cycles = 128; bits = 0x4; } else if(cycles >= 64) { cycles = 64; bits = 0x3; } else if(cycles >= 32) { cycles = 32; bits = 0x2; } else if(cycles >= 16) { cycles = 16; bits = 0x1; } else { cycles = 8; bits = 0x0; } } // Watchdog timer on SAMD is a slightly different animal than on AVR. // On AVR, the WTD timeout is configured in one register and then an // interrupt can optionally be enabled to handle the timeout in code // (as in waking from sleep) vs resetting the chip. Easy. // On SAMD, when the WDT fires, that's it, the chip's getting reset. // Instead, it has an "early warning interrupt" with a different set // interval prior to the reset. For equivalent behavior to the AVR // library, this requires a slightly different configuration depending // whether we're coming from the sleep() function (which needs the // interrupt), or just enable() (no interrupt, we want the chip reset // unless the WDT is cleared first). In the sleep case, 'windowed' // mode is used in order to allow access to the longest available // sleep interval (about 16 sec); the WDT 'period' (when a reset // occurs) follows this and is always just set to the max, since the // interrupt will trigger first. In the enable case, windowed mode // is not used, the WDT period is set and that's that. // The 'isForSleep' argument determines which behavior is used; // this isn't present in the AVR code, just here. It defaults to // 'false' so existing Arduino code works as normal, while the sleep() // function (later in this file) explicitly passes 'true' to get the // alternate behavior. if(isForSleep) { WDT->INTENSET.bit.EW = 1; // Enable early warning interrupt WDT->CONFIG.bit.PER = 0xB; // Period = max WDT->CONFIG.bit.WINDOW = bits; // Set time of interrupt WDT->CTRL.bit.WEN = 1; // Enable window mode while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write } else { WDT->INTENCLR.bit.EW = 1; // Disable early warning interrupt WDT->CONFIG.bit.PER = bits; // Set period for chip reset WDT->CTRL.bit.WEN = 0; // Disable window mode while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write } actualMS = (cycles * 1000L + 512) / 1024; // WDT cycles -> ms wdt_reset(); // Clear watchdog interval WDT->CTRL.bit.ENABLE = 1; // Start watchdog now! while(WDT->STATUS.bit.SYNCBUSY); return actualMS; } void wdt_disable() { WDT->CTRL.bit.ENABLE = 0; while(WDT->STATUS.bit.SYNCBUSY); } void WDT_Handler(void) { // ISR for watchdog early warning, DO NOT RENAME! WDT->CTRL.bit.ENABLE = 0; // Disable watchdog while(WDT->STATUS.bit.SYNCBUSY); // Sync CTRL write WDT->INTFLAG.reg = 1; // Clear interrupt flag wdt_wakeup=1; } int wdt_sleep(int maxPeriodMS) { int actualPeriodMS = wdt_enable(maxPeriodMS, true); // true = for sleep SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; // system_set_sleepmode(SYSTEM_SLEEPMODE_STANDBY); // Deepest sleep // system_sleep() : __DSB(); // (Data Synchronisation Barrier) -> finish all ongoing memory accesses __WFI(); // (Wait For Interrupt) // Code resumes here on wake (WDT early warning interrupt) return actualPeriodMS; } void wdt_init(void) { // One-time initialization of watchdog timer. // Insights from rickrlh and rbrucemtl in Arduino forum! // Generic clock generator 2, divisor = 32 (2^(DIV+1)) GCLK->GENDIV.reg = GCLK_GENDIV_ID(2) | GCLK_GENDIV_DIV(4); // Enable clock generator 2 using low-power 32KHz oscillator. // With /32 divisor above, this yields 1024Hz(ish) clock. GCLK->GENCTRL.reg = GCLK_GENCTRL_ID(2) | GCLK_GENCTRL_GENEN | GCLK_GENCTRL_SRC_OSCULP32K | GCLK_GENCTRL_DIVSEL; while(GCLK->STATUS.bit.SYNCBUSY); // WDT clock = clock gen 2 GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID_WDT | GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK2; // Enable WDT early-warning interrupt NVIC_DisableIRQ(WDT_IRQn); NVIC_ClearPendingIRQ(WDT_IRQn); NVIC_SetPriority(WDT_IRQn, 0); // Top priority NVIC_EnableIRQ(WDT_IRQn); }
C
//백준 2750번 문제 //선택 정렬 #include<stdio.h> #include<stdlib.h> void swap(int*, int*); int main() { int n=5, min; scanf("%d", &n); int* a = malloc(n*sizeof(int)); for(int i=0; i<n; i++) { scanf("%d", &a[i]); } //start sorting for(int i=0; i<n-1; i++) { min = i; //find minimum number for(int j=i+1; j<n; j++) { if(a[min] > a[j]) { min = j; } } swap(&a[min], &a[i]); } for(int i=0; i<n; i++) { printf("%d\n", a[i]); } return 0; } void swap(int* a, int* b) { int temp=*a; *a = *b; *b = temp; }
C
#include <stdio.h> #include <stdlib.h> void Verifica(int N); int main() { int valor; printf("Digite um valor: "); scanf("%s", &valor); Verifica(valor); system("pause>>null"); return 0; } void Verifica(int N) { if(N%2==0) printf("Valor par"); else printf("Valor impar"); return; }
C
#include "LCD1602.h" #include "delay.h" #include "string.h" void LCD1602_Configuration(void) { delay_init(); LCD1602_RCC_Configuration(); LCD1602_GPIO_Configuration(); delay_ms(400); LCD1602_WriteCommand(0x38); LCD1602_WriteCommand(0x0c); LCD1602_WriteCommand(0x06); LCD1602_WriteCommand(0x01); } void LCD1602_RCC_Configuration(void) { RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD, ENABLE); } void LCD1602_GPIO_Configuration(void) { GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5| GPIO_Pin_6 | GPIO_Pin_7; GPIO_Init(GPIOD, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0| GPIO_Pin_1 | GPIO_Pin_2| GPIO_Pin_3| GPIO_Pin_4| GPIO_Pin_5| GPIO_Pin_6| GPIO_Pin_7; GPIO_Init(GPIOC, &GPIO_InitStructure); } void LCD1602_WriteCommand(u8 command) { GPIO_ResetBits(GPIOD,GPIO_Pin_6); GPIO_ResetBits(GPIOD,GPIO_Pin_5); delay_ms(5); GPIO_SetBits(GPIOD,GPIO_Pin_7); delay_ms(5); GPIOC->ODR = command; delay_ms(5); GPIO_ResetBits(GPIOD,GPIO_Pin_7); } void LCD1602_WriteData(u8 data) { GPIO_SetBits(GPIOD,GPIO_Pin_5); GPIOC->ODR = data; GPIO_SetBits(GPIOD,GPIO_Pin_7); delay_ms(10); GPIO_ResetBits(GPIOD,GPIO_Pin_7); } void LCD1602_show_str(const char *str,int line) { LCD1602_Configuration(); LCD1602_WriteCommand(0x80); while(*str != '\0') { LCD1602_WriteData(*str); //delay_ms(500); str++; } }
C
#ifndef HT_H #define HT_H /***************************************************************************** * * File: ht.h * Author: Alex Stivala * Created: April 2009 * * Declarations for separate chaining hash table. * * * $Id: ht.h 4556 2013-01-13 02:20:29Z astivala $ * *****************************************************************************/ #include "bpautils.h" /* size of the hash table (must be a power of 2)*/ /*#define HT_SIZE 134217728 */ /* 2^27 */ /* too large */ /*#define HT_SIZE 67108864 */ /* 2^26 */ #define HT_SIZE 131072 /* 2^17 */ typedef struct ht_entry_s { struct ht_entry_s *next; char data[1]; /* overlaid with key followed by value, sizes defined by user. FIXME: of course this is dodgy because of alignment padding etc., but it seems to work... */ } ht_entry_t; /* hash function type */ typedef unsigned int (*hash_function_t)(const void *key); /* key/value copy function type */ typedef void *(*copy_function_t)(void *dest, const void *src); /* key match function type */ typedef int (*keymatch_function_t)(const void *k1, const void *k2); /* setup hashtable key and value types and functions */ void ht_initialize(size_t keysize, size_t valuesize, hash_function_t hashfunc, copy_function_t keycopy, keymatch_function_t keymatch, copy_function_t valuecopy); /* insert into hashtable */ void ht_insert(void *key, void *value); /* lookup in hashtable */ void *ht_lookup(void *key); /* test for invalid structure */ int ht_validate(void); /* compute and print stats about hash table */ void ht_printstats(void); #endif /* HT_H */
C
#include <stdlib.h> #include <stdio.h> /* for fprintf(), stderr, BUFSIZ */ #include <errno.h> /* declare errno */ #include <fcntl.h> /* for flags for open() */ #include <string.h> /* declare strerror() */ #include <unistd.h> /* for ssize_t */ #include <sys/types.h> #include <sys/stat.h> /* for mode_t */ // ./get_args -i -lr 'hi there' -f fred.c -q int main(int argc, char *argv[]) { int opt; while((opt = getopt(argc, argv, ":if:lr")) != -1) { switch(opt) { case 'i': case 'l': case 'r': printf("option:%c\n", opt); break; case 'f': printf("filename:%s\n", optarg); break; case ':': printf("option needs a value\n"); break; case '?': printf("unknown option:%c\n", opt); break; } } for ( ; optind < argc; optind++) { printf("argument: %s\n", argv[optind]); } return 0; }
C
/** * @file server.c * @brief Server side of a local client-server system, implemented using named pipes * @version 0.1 * @date 2021-04-22 * * @copyright Copyright (c) 2021 * */ #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <time.h> #include <string.h> #include <ctype.h> #include <pthread.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <signal.h> #include "utils.h" #include "lib.h" #include "queue.h" #include "semaphore.h" #define ERROR -1 #define RECVD "RECVD" #define TSKEX "TSKEX" #define TSKDN "TSKDN" #define TLATE "2LATE" #define FAILD "FAILD" #define DEALLOC 1000 //structure used to communicate with client /*--------------------GLOBAL VARIABLES--------------------*/ pthread_mutex_t lock; //structure used to implement mutex char public_fifo[100]; //holds the public fifo name/path bool time_is_up = false; //to keep track of server execution time bool public_fifo_closed = true; //to keep track of public fifo bool debug = true; //used to keep track of debugging printfs int bufsz = 1; //server buffer size (default 1) bool buffer_is_empty = false; //to keep track if buffer is empty or not queue* buffer; int activeThreads = 0; sem_t empty; sem_t full; queue* deallocator; message_t* reque; /*------------------END GLOBAL VARIABLES------------------*/ /** * @brief handles signals (for now just needed sigalam) * * @param signum the identifier of the signal */ void sig_handler(int signum){ time_t now; time(&now); time_is_up = true; fprintf(stderr,"[server] timeout reached: %ld\n", now); } /** * @brief executed by prodcuer threads, that produce a task into buffer * * @param arg the request message from client * @return void* */ void *producer_thread(void * arg){ activeThreads++; //request message from client message_t * request = malloc(sizeof(message_t)); *request = *(message_t *)arg; insert(deallocator,request); //get current time and current thread info time_t cur_secs; time(&cur_secs); pthread_t tid = pthread_self(); int pid = getpid(); fprintf(stdout, "%ld; %d; %d; %d; %lu; %d; %s\n", cur_secs, request->rid, request->tskload, pid, tid, request->tskres, RECVD); //doing the designated task calling library B int task_res = task(request->tskload); //getting time after task execution time(&cur_secs); fprintf(stdout, "%ld; %d; %d; %d; %lu; %d; %s\n", cur_secs, request->rid, request->tskload, pid, tid, task_res, TSKEX); //send task result to buffer message_t *request_result = malloc( sizeof(message_t) ); request_result->pid = request->pid; request_result->rid = request->rid; request_result->tid = request->tid; request_result->tskload = request->tskload; request_result->tskres = task_res; //semaphore initialization // sem_init(&empty, 0, 0); // sem_init(&full, 0, bufsz); sem_wait(&full); pthread_mutex_lock(&lock); insert(buffer, request_result); //unlocking code wiht mutex pthread_mutex_unlock(&lock); //Insert so later we can deallocate memory //insert(deallocator, request_result); sem_post(&empty); activeThreads--; } /** * @brief executed by the consumer thread, wich will retrieve tasks from buffer * * @param arg * @return void* */ void *consumer_thread(void * arg){ //info about the consumer thread itself pthread_t tid; int pid; time_t now; //info that if going to be retrieved from buffer //loop while time isn't up while(activeThreads != 0 || !time_is_up){ message_t* answer = malloc( sizeof(message_t) ); ssize_t bytes_written = ERROR; //locking code wiht mutex sem_wait(&empty); pthread_mutex_lock(&lock); *answer = *(front(buffer)); //TODO pop(buffer); pthread_mutex_unlock(&lock); sem_post(&full); if(answer != NULL){ char *private_fifo_path = NULL; int path_size = snprintf(private_fifo_path, 0, "/tmp/%d.%lu",answer->pid, answer->tid) + 1; if (path_size == -1) { return NULL; } private_fifo_path = malloc(path_size); if (private_fifo_path == NULL) { return NULL; } if (snprintf(private_fifo_path, path_size, "/tmp/%d.%lu",answer->pid, answer->tid) < 0 ) { free(private_fifo_path); return NULL; } if(time_is_up){ time(&now); fprintf(stdout, "%ld; %d; %d; %d; %lu; %d; %s\n", now, answer->rid, answer->tskload, answer->pid, answer->tid, answer->tskres, TLATE); answer->tskres = -1; } //open private fifo int priv_fd = open(private_fifo_path, O_WRONLY | O_NONBLOCK); if(priv_fd != 0){ fprintf(stderr, "Error opening private fifo!\n"); } //write answer to client in the private fifo bytes_written = write(priv_fd, answer, sizeof(message_t)); //maybe sleep(1) in the end? if(time_is_up) continue; if(bytes_written < 0){ time(&now); fprintf(stdout, "%ld; %d; %d; %d; %lu; %d; %s\n", now, answer->rid, answer->tskload, answer->pid, answer->tid, answer->tskres, FAILD); } else{ time(&now); fprintf(stdout, "%ld; %d; %d; %d; %lu; %d; %s\n", now, answer->rid, answer->tskload, answer->pid, answer->tid, answer->tskres, TSKDN); } } free(answer); } } /*-------------------END UTIL FUNCTIONS-------------------*/ /** * @brief main server function, where program it is intialized, main loop and ended * * @param argc the number of arguments passed * @param argv the arguments itself * @return int 0 on success, ERROR on fail */ int main(int argc, char* argv[]){ /* # ARGV 0 -> ./s ARGV 3 -> fifoname / -l # # ARGV 1 -> -t ARGV 4 -> bufsize # # ARGV 2 -> nsecs ARGV 5 -> fifoname # */ //getting initial time of program execution time_t initial_time; time(&initial_time); /*--------------------INPUT ERROR VERIFICATION--------------------*/ //when less than the minimun arguments number is given if(argc < 4) input_error(); //when -t or time is not passed correctly if(!str_cmp(argv[1], "-t") || !is_number(argv[2])) input_error(); //-l passed but with no arguments if(str_cmp(argv[3], "-l") && argc != 6) input_error(); //-l not passed or bufsize argmuent is not a number if(argc == 6 && (!str_cmp(argv[3], "-l") || !is_number(argv[4]))) input_error(); //after this the program assumes inputs are correctly inputted /*------------------END INPUT ERROR VERIFICATION------------------*/ /*---------------------PROGRAM INITIALIZATION---------------------*/ if(str_cmp(argv[3], "-l")){ bufsz = atoi(argv[4]); strcat(public_fifo, argv[5]); } else{ strcat(public_fifo, argv[3]); } //initializing pthread mutex structure if (pthread_mutex_init(&lock, NULL) != 0) { fprintf(stderr, "[server] Mutex init has failed\n"); return ERROR; } //semaphore initialization sem_init(&empty,0,0); sem_init(&full,0,bufsz); //registreing signal handler signal(SIGALRM, sig_handler); //retrieving arguments inputted int nsecs = atoi(argv[2]); //setting alarm alarm(nsecs); if(debug) printf("Fifo path: %s\n", public_fifo); //DEBUG //printing final and initial time to user and the rest of the parameters to user long int nsecs_long = (long) (int) nsecs; fprintf(stderr,"[server] initial time: %lu, expected final time: %lu\n", initial_time, initial_time + nsecs_long); fprintf(stderr,"[server] got: nsecs=%d, bufsize=%d, fifoname=%s\n", nsecs, bufsz, public_fifo); //creating public fifo file if(mkfifo(public_fifo, 0777) == ERROR){ fprintf(stderr, "[server] Error when creating public fifo: %s\n", strerror(errno)); return ERROR; } //Create queues both deallocator and buffer buffer = createQueue(bufsz); deallocator = createQueue(DEALLOC); //thread unique identifier long int id = 1; //used to get current seconds in main thread loop time_t cur_secs; int bytes_read = ERROR, public_fd = ERROR; int tout = 1; //DEBUG //getting the request from client //openning public fifo public_fd = open(public_fifo, O_RDONLY); if(public_fd < 0){ if(debug) printf("[server] Error while opening public fifo file: %s\n", strerror(errno)); //DEBUG } //creating consumer thread pthread_t con_thread_id; if(debug) printf("created consumer thread!\n"); //DEBUG if(pthread_create(&con_thread_id, NULL, &consumer_thread, (void*)0) != 0) return ERROR; /*---------------------MAIN THREAD (C0) LOOP---------------------*/ //reading requests from client while(!time_is_up){ message_t *request = malloc( sizeof(message_t) ); //Era isto bytes_read = read(public_fd, request, sizeof(message_t)); //atualize time_is_up time_t now; time(&now); //checking if nsecs have passed already if(now - initial_time >= nsecs){ fprintf(stderr,"[server] timeout reached: %ld\n", now); time_is_up = true; break; } //to check if there was a resquest or not if(bytes_read > 0){ //creating producer threads pthread_t prod_thread_id; if(debug) printf("created producer thread number: %ld\n", id); //DEBUG if(pthread_create(&prod_thread_id, NULL, &producer_thread, (void*)request) != 0) return ERROR; id++; } else{ //TODO: IF READ TIMEOUTS FOR LONG ASSUME CLIENT IT'S CLOSED AND EXIT if(debug) printf("timeout read: %d", tout); //DEBUG tout++; //DEBUG break; //sleep(1); } //free(request); } //insert(deallocator,request); /*-------------------------ENDING PROGRAM-------------------------*/ //closing public fifo close(public_fd); if(remove(public_fifo) != 0){ fprintf(stderr, "Not successfully deleted public file\n"); } while(activeThreads != 0){ printf("Active Threads -> %d", activeThreads); sleep(2); } //freeing memory fprintf(stderr, "Deallocating memory\n"); free_memory(deallocator); fprintf(stderr, "Memory deallocated\n"); //releasing pthread mutex structure pthread_mutex_destroy(&lock); //realeasing semaphore sem_destroy(&empty); sem_destroy(&full); printf("Ended\n"); //main thread waits for all threads to exit pthread_exit(NULL); return 0; }