language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
// This is the global flag inspected by both the semaphore task and event polling task to turn on the on board yellow led. uint16_t event_poll_flag = 0; // initialize adc void adc_init() { // AREF = AVcc ADMUX = (1<<REFS0); // ADC Enable and prescaler of 128; 16 MHz/128 = 125kHz ADCSRA = (1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0); // Define analog signal input form ADC8 (pin 4, port D4) DIDR2 |= (1 << ADC8D); // disable digital input to use analog input // Use pin 4 to read analog ADCSRB |= (1 << MUX5); // Set ADC mode: free-running ADCSRA |= (1<<ADATE); // Start ADC ADCSRA |= (1<<ADEN); ADCSRA |= (1<<ADSC); } // read adc value uint16_t adc_read() { uint16_t adc_results = ADC; return adc_results; } uint16_t adc_read_percent(){ uint16_t reading = adc_read(); uint16_t percent = 100*(uint32_t)reading/1023 ; return percent; } void powerOnPE6(){ DDRE |= (1 << PORTE6); PORTE |= (1 << PORTE6); } void read_pot_UI_task(){ USB_Mainloop_Handler(); cli(); printf("Potentiomenter read %u%%\r\n", adc_read_percent()); sei(); } int event_polling_task(){ static uint16_t lastPotReading = 0; uint16_t newPotReading; cli(); // Get a new reading from potentiometer newPotReading = adc_read_percent(); // Set flag if changed if(newPotReading != lastPotReading) { event_poll_flag = 1; lastPotReading = newPotReading; } sei(); return 1; }
C
// 5.Write a program which accept accept range from user and display all numbers in // between that range in reverse order. // Input : 23 35 // Output : 35 34 33 32 31 30 29 28 27 26 25 24 23 // Input : 10 18 // Output : 18 17 16 15 14 13 12 11 10 // Input : 10 10 // Output : 10 // Input : -10 2 // Output : 2 1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 // Input : 90 18 // Output : Invalid range #include "header.h" int main() { int iNo=0; int iNo1=0; printf("Enter range:\n"); scanf("%d %d",&iNo,&iNo1); ReverseOrderRange(iNo,iNo1); return 0; }
C
/* Filename : ShmOS.C ** Author : Anung Barlianto/1292000058 ** fork()-nya di sini ** Revision history: ** 1996.12.06 Finished! Semaphre and Shared memory removal. ** 1996.12.06 Pengembangan berikutnya.. coba hapus sem dan shm. ** 1996.11.30 Shared Memory version finished!. ** Actually shm is much easier and shorter. ** Gilee.. siapa dulu asistennya? ** 1996.11.29 <SunSITE> Coba pake shared memory. ** shared_memory: 3 * sizeof (int): shm[0]=INITIAL_TURN; ** shm[1]=NUM_OF_PROCESS; shm[2]=NUM_OF_PERIOD; ** 1996.11.01 Finished! ** 1996.10.29 Got bright ideas on the algorithm. ** 1996.10.02 Start playing semaphore for Down() and Up(). ** 1996.10.01 Start programming; fork 2 children. ** 1996.09.30 Description was posted on "forum.iki.os". */ #include "shmos.h" main () { int child_pid; int process; int sem_id; int shm_id; /* Variabel untuk shared memory */ char *shm_char; int *shm_int; /* Make NUM_OF_SEM semaphores */ if ((sem_id = semget (SEM_KEY, NUM_OF_SEM, SEM_FLAG)) == -1) { perror ("semget failed"); exit (1); } /* Untuk kemudahan portabilitas, semaphore yang banyak itu ** nggak diutak-utik dulu. Pake aja shared memory yang tiga ** itu. */ /* Bikin shared memory */ if ((shm_id = shmget (SHM_KEY, (3*sizeof (int)), SHM_FLAG)) == -1) { perror ("shmget() failed"); exit (2); } /* Inisialisasi nilai shared memory */ /* Pertama, attach dulu ke shared memory.. */ if ((shm_char = shmat (shm_id, 0, SHM_RND)) == (char *)-1) { perror ("shmat() init failed"); exit (3); } /* Inisialisasinya di sini. */ /* Dijadiin int[3] dulu */ shm_int = (int *) (void *) shm_char; shm_int[IDX_TURN] = INITIAL_TURN; shm_int[IDX_NUMOFPROC] = NUM_OF_PROCESS; shm_int[IDX_PERIOD] = 0; /* Detach! */ if (shmdt (shm_char) == -1) { perror ("shmdt() init failed"); exit (4); } for (process=0; process<MAKE_CHILD; process++) { /* Parent code forks one more process. */ if ((child_pid = fork ()) < 0) { perror ("Fork error"); exit (5); } else if (child_pid == 0) { /* Child code goes here */ child (process+1, sem_id, shm_id, process+2); } } /* Real parent code goes here */ child (0, sem_id, shm_id, 1); return 0; } /* Nge-print info, sekalian kasih delay */ void my_info (int proc, int proc_id, int ctr_jatah, int jatah, int sem_id, int shm_id, int periode) { fprintf (stdout, "\tProc %d: pid %5d; jatah %d/%d; periode %d; sem_id %d; shm_id %d\n", proc, proc_id, ctr_jatah, jatah, periode, sem_id, shm_id); sleep (1); } /* Tiap proses mengerjakan tiap-tiap bagiannya di sini, ** setelah di-fork() */ void child (int child_id, int sem_id, int shm_id, int jatah) { int old_periode; int counter_jatah = jatah; /* Shared memory variables. */ char* shm_addr; int* shared_m; union semun arg; struct shmid_ds *buf; /* Attach to shared memory.. hii.. */ if ((shm_addr = shmat (shm_id, 0, SHM_RND)) == (char *)-1) { perror ("shmat() failed"); exit (3); } /* Take the array of integer from shm_addr. */ shared_m = (int *) (void *) shm_addr; /* Ambil periode. */ old_periode = shared_m[IDX_PERIOD]; while (1) { /* Attempt to Down(). */ Down (sem_id); /* Ok, we got the semaphore.. Entering critical section. */ /* Whose TURN is it? Get shared_m[IDX_TURN]'s value. */ /* If this is process' turn: ** 1. It prints its own message. ** 2. Set shared_m[IDX_TURN] so other process could gain their turns. ** 3. It also decrements its own counter_jatah. */ if (child_id == shared_m[IDX_TURN]) { if (counter_jatah > 0) { my_info (child_id+1, getpid(), counter_jatah, jatah, sem_id, shm_id, old_periode); /* Decrease counter_jatah. If it is equal zero, decrease ** number of process involved. */ if (--counter_jatah == 0) { /* Decrease number of process. If it is equal zero, ** decrease number of period. */ if (--shared_m[IDX_NUMOFPROC] == 0) { /* Tambah satu periode. */ shared_m[IDX_PERIOD]++; } } } /* Set untuk giliran proses berikutnya. */ shared_m[IDX_TURN] = ((shared_m[IDX_TURN] - 1) + NUM_OF_PROCESS) % NUM_OF_PROCESS; /* If num_of_process becomes zero, set SEM_NUM_OF_PROC's value ** back to NUM_OF_PROCESS. */ if (shared_m[IDX_NUMOFPROC] == 0) shared_m[IDX_NUMOFPROC] = NUM_OF_PROCESS; /* If counter_jatah equals zero, check if new ** SEM_PERIOD's value differs from old_periode. */ if (old_periode != shared_m[IDX_PERIOD]) { counter_jatah = jatah; old_periode = shared_m[IDX_PERIOD]; } } /* Jika periodenya udah empat kali, detach shared memory, ** dan exit. Process selesai. */ if (old_periode >= NUM_OF_PERIOD) { /* Jika saya adalah satu-satunya proses yang masih ada, ** sebelum exit, remove dulu semaphore dan shared memory. */ if (shared_m[IDX_NUMOFPROC] == 1) { /* Remove semaphore.. */ arg.val = 0; // if ((semctl (sem_id, 0, 0, arg.val)) == -1) if ((semctl (sem_id, 0, 0, arg)) == -1) { perror ("semctl (IPC_RMID) failed"); exit (1); } /* Remove shared memory.. */ /* But first, detached shared memory. */ if (shmdt (shm_addr) == -1) { perror ("shmdt() done failed"); exit (4); } if ((shmctl (shm_id, 0, buf)) == -1) { perror ("shmctl (IPC_RMID) failed"); exit (1); } } /* ..bila bukan, kurangi jumlah proses yang tinggal. ** dan detached shared memory. */ else { shared_m[IDX_NUMOFPROC]--; if (shmdt (shm_addr) == -1) { perror ("shmdt() done failed"); exit (4); } } exit (0); } /* Kalo udah, di-UP lagi dong semaphore-nya! Jangan rakus! */ Up (sem_id); } } /* Nge-Down semaphore */ void Down (int sem_id) { if (semop (sem_id, &op_lock[0], 2) < 0) { perror ("semop lock (Down) error."); exit (6); } } /* Nge-Up semaphore */ void Up (int sem_id) { if (semop (sem_id, &op_unlock[0], 1) < 0) { perror ("semop unlock (Up) error"); exit (7); } }
C
#include <stdio.h> int main() { int count = 0; int array[500] = { '\n' }; scanf("%d", &count); for (int i = 1; i <= count; i++) { scanf("%d", &array[i]); } for (int j = count; j >= 1; j--) { printf("%d ", array[j]); } // printf("\n"); return 0; }
C
/* ********************************************************************************************************* * * ģ : SPI(ͨ) * ļ : BSP_SPI_HW.h * : V1.1 * ˵ : SPIߵײṩSPIáշݡ豸SPI֧֡ * v1.1ʹٺõĿ * * ********************************************************************************************************* */ #include "includes.h" // #define PIN_SCK GPIO_Pin_5 // #define PIN_MOSI GPIO_Pin_7 // #define PIN_MISO GPIO_Pin_6 #define SPI_HARD SPI1 #define RCC_SPI RCC_APB2Periph_SPI1 /* SPI or I2S mode selection masks */ #define SPI_Mode_Select ((uint16_t)0xF7FF) #define I2S_Mode_Select ((uint16_t)0x0800) /* SPI registers Masks */ #define CR1_CLEAR_Mask ((uint16_t)0x3040) #define I2SCFGR_CLEAR_Mask ((uint16_t)0xF040) /* SPI SPE mask */ #define CR1_SPE_Set ((uint16_t)0x0040) #define CR1_SPE_Reset ((uint16_t)0xFFBF) uint8_t g_spi_busy = 0; /* SPI ߹־ */ /* ********************************************************************************************************* * : bsp_InitSPIBus * ˵: SPIߡ ֻ SCK MOSI MISOߵáƬѡCSҲоƬеINTBUSY * : * ֵ: ********************************************************************************************************* */ void bsp_InitSPIBus(void) { /* ӲSPI */ GPIO_InitTypeDef GPIO_InitStructure; /* GPIOʱ */ RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); /* SCK, MISO MOSI Ϊù */ GPIO_PinAFConfig(GPIOA, GPIO_PinSource5, GPIO_AF_SPI1); GPIO_PinAFConfig(GPIOA, GPIO_PinSource6, GPIO_AF_SPI1); GPIO_PinAFConfig(GPIOA, GPIO_PinSource7, GPIO_AF_SPI1); GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_25MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7; GPIO_Init(GPIOA, &GPIO_InitStructure); /* SPIʱ */ RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE); bsp_SPI_Init(SPI_Direction_2Lines_FullDuplex | SPI_Mode_Master | SPI_DataSize_8b | SPI_CPOL_Low | SPI_CPHA_1Edge | SPI_NSS_Soft | SPI_BaudRatePrescaler_64 | SPI_FirstBit_MSB); /* Activate the SPI mode (Reset I2SMOD bit in I2SCFGR register) */ SPI_HARD->I2SCFGR &= SPI_Mode_Select; /* ѡSPIģʽI2Sģʽ */ /*---------------------------- SPIx CRCPOLY Configuration --------------------*/ /* Write to SPIx CRCPOLY */ SPI_HARD->CRCPR = 7; /* һ㲻 */ SPI_Cmd(SPI_HARD, DISABLE); /* ȽֹSPI */ SPI_Cmd(SPI_HARD, ENABLE); /* ʹSPI */ } /* ********************************************************************************************************* * : bsp_SPI_Init * ˵: STM32ڲSPIӲĹģʽ 򻯿⺯ִЧʡ SPIӿڼл * : _cr1 Ĵֵ * ֵ: ********************************************************************************************************* */ void bsp_SPI_Init(uint16_t _cr1) { SPI_HARD->CR1 = ((SPI_HARD->CR1 & CR1_CLEAR_Mask) | _cr1); //SPI_Cmd(SPI_HARD, DISABLE); /* ȽֹSPI */ SPI_HARD->CR1 &= CR1_SPE_Reset; /* Disable the selected SPI peripheral */ //SPI_Cmd(SPI_HARD, ENABLE); /* ʹSPI */ SPI_HARD->CR1 |= CR1_SPE_Set; /* Enable the selected SPI peripheral */ } /* ********************************************************************************************************* * : bsp_spiWrite0 * ˵: SPI߷һֽڡSCKزɼ, SCKʱΪ͵ƽ * : * ֵ: ********************************************************************************************************* */ __STATIC_INLINE void bsp_spiWrite0(uint8_t _ucByte) { #if 0 /* ȴͻ */ while(SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET); /* һֽ */ SPI_I2S_SendData(SPI1, _ucByte); /* ȴݽ */ while(SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET); /* ȡյ */ SPI_I2S_ReceiveData(SPI1); #endif SPI1->DR = _ucByte; while (!(SPI1->SR & ((uint16_t)0x0001))); SPI1->DR; } /* ********************************************************************************************************* * : bsp_spiRead0 * ˵: SPI߽8bitݡ SCKزɼ, SCKʱΪ͵ƽ * : * ֵ: ********************************************************************************************************* */ __STATIC_INLINE uint8_t bsp_spiRead0(void) { uint8_t read; /* ȴͻ */ while(SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET); /* һֽ */ SPI1->DR = 0; /* ȴݽ */ while(SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET); /* ȡյ */ read = SPI1->DR; /* ض */ return read; } /* ********************************************************************************************************* * : bsp_SpiBusEnter * ˵: ռSPI * : * ֵ: 0 ʾæ 1ʾæ ********************************************************************************************************* */ void bsp_SpiBusEnter(void) { g_spi_busy = 1; } /* ********************************************************************************************************* * : bsp_SpiBusExit * ˵: ͷռõSPI * : * ֵ: 0 ʾæ 1ʾæ ********************************************************************************************************* */ void bsp_SpiBusExit(void) { g_spi_busy = 0; } /* ********************************************************************************************************* * : bsp_SpiBusBusy * ˵: жSPIæǼSPIоƬƬѡźǷΪ1 * : * ֵ: 0 ʾæ 1ʾæ ********************************************************************************************************* */ uint8_t bsp_SpiBusBusy(void) { return g_spi_busy; }
C
/* solitaire.c */ /* * The Solitaire encryption algorithm programmed in C. * solitaire encryption system by Bruce Schneier * based on a deck of cards * See <http://www.counterpane.com/solitaire.html> for details. * programming by Lloyd Miller, Sept 2000 */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /* * usage : * to encrypt * solitair -e key <plaintext >cyphertext * to decrypt * solitair -d key <cyphertext >plaintext * */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <ctype.h> void usage(void) { fprintf(stderr, "usage:\n" " to encrypt\n" " solitair -e key <plaintext >cyphertext\n" " to decrypt\n" " solitair -d key <cyphertext >plaintext\n"); exit(EXIT_FAILURE); } int getalpha(void) { int a; while (1) { a = getchar(); if (a == EOF) return 0; if (a >= 'A' && a <= 'Z') return a; if (a >= 'a' && a <= 'z') return a - 'a' + 'A'; } } int findit(char *deck, int val, int siz) { int i = 0; while(siz--) { if (*deck == val) return i; deck++; i++; } return -1; } int step(char *deck) { int c; int b; int a; char tmp[54]; do { /* step 1 */ c = findit(deck, 53, 54); if (c < 53) { a = c + 1; deck[c] = deck[a]; } else { for (a = 53; a > 1; a--) deck[a] = deck[a - 1]; a = 1; } deck[a] = 53; /* step 2 */ b = findit(deck, 54, 54); if (b < 52) { c = b + 1; deck[b] = deck[c]; if (a == c) a = b; b = c + 1; deck[c] = deck[b]; if (a == b) a = c; } else { c = b; b = b - 51; for (; c > b; c--) { deck[c] = deck[c - 1]; if (a == c - 1) a = c; } } deck[b] = 54; /* step 3 */ if (a > b) { c = a; a = b; b = c; } tmp[53] = deck[b++]; c = 0; while (b < 54) tmp[c++] = deck[b++]; b = a; while (deck[b] != tmp[53]) tmp[c++] = deck[b++]; tmp[c++] = tmp[53]; b = 0; while (b < a) tmp[c++] = deck[b++]; assert(c == 54); /* step 4 */ b = tmp[53]; if (b == 54) b = 53; a = 0; for (c = b; c < 53; c++) deck[a++] = tmp[c]; for (c = 0; c < b; c++) deck[a++] = tmp[c]; assert(a == 53); deck[53] = tmp[53]; /* step 5 */ a = deck[0]; if (a == 54) a = 53; a = deck[a]; } while (a > 52); return (a - 1) % 26 + 1; } int sumchar(int a, int b) { return 'A' + (toupper(a) - 'A' + b + 26) % 26; } int main(int argc, char **argv) { char deck[54]; int i, j; int mode = 0; /* default mode is encode, non-zero is decode */ for (i = 0; i < 54; i++) deck[i] = i + 1; if (argc > 1 && argv[1][0] == '-') { if(argv[1][1] == 'd') { mode = 1; } else if (argv[1][1] == 'e') { mode = 0; } else usage(); } else usage(); argc--; argv++; /* do key */ while (argc-- > 1) { char *ap = *++argv; while (*ap) { int c = *ap++; char tmp[53]; if (c >= 'a' && c <= 'z') c = c - 'a' + 'A'; if (c >= 'A' && c <= 'Z') { c = c - 'A' + 1; step(deck); i = 0; for (j = c; j < 53; j++) tmp[i++] = deck[j]; for (j = 0; j < c; j++) tmp[i++] = deck[j]; for (j = 0; j < 53; j++) deck[j] = tmp[j]; } } } j = 0; while ((i = getalpha()) != 0) { putchar(mode ? sumchar(i, -step(deck)) : sumchar(i, step(deck))); j++; if (j % 5 == 0) { if (j == 50) { j = 0; putchar('\n'); } else putchar (' '); } } j = j % 5; if (j) while (j < 5) { i = 'X'; putchar(mode ? sumchar(i, -step(deck)) : sumchar(i, step(deck))); j++; } printf("\n"); return EXIT_SUCCESS; } /* end of file */
C
#include <stdio.h> //Calculo dp permetro da circunferncia int main() { float C; float raio; printf("informe o valor do raio: "); scanf("%f", &raio); C = 2 * 3.14 * raio; printf("perimetro da circunferencia do raio informado eh: %0.2f ", C); return 0; }
C
/* * ===================================================================================== * * Filename: mydup2.c * * Description: * * Version: 1.0 * Created: 2013年01月06日 02时10分26秒 * Revision: none * Compiler: gcc * * Author: YOUR NAME (), * Organization: * * ===================================================================================== */ #include "apue.h" #include "myerr.h" int mydup2(const int fildes1, const int fildes2); int main(int argc, char* argv[]) { printf("%d\n", mydup2(0, 1)); } int mydup2(const int fildes1, const int fildes2) { int tmp; if(fildes1 == fildes2) return fildes2; tmp = dup(fildes1); if(tmp > fildes2) { close(fildes2); tmp = dup(fildes1); } printf("try: %d\n", tmp); if(tmp != fildes2) tmp = mydup2(fildes1, fildes2); return tmp; }
C
/* * Samantha Foley * * Project 4: Dining Philosophers (Common header) * */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <errno.h> #include <pthread.h> #include "semaphore_support.h" /***************************** * Defines *****************************/ #define TRUE 0 #define FALSE 1 /* 1.0 second = 1000000 usec */ //#define TIME_TO_SLEEP 100000 /* 0.5 second = 500000 usec */ //#define TIME_TO_SLEEP 50000 #define TIME_TO_SLEEP 5000 #define CLOCKS_PER_SECOND 1000000 #define THINKING 0 #define HUNGRY 1 #define EATING 2 /***************************** * Structures *****************************/ struct phil { int numAte; int numThought; //int done; //0= false, 1 = true -- probably do not need }; typedef struct phil phil; /***************************** * Global Variables *****************************/ semaphore_t mutex; //semaphore to protect access to taking and releasing a certain chopstick semaphore_t *chopstick; //semaphore to protect each individual chopstick int *state; //pointer to an array of the state of each philosopher int stillEating; //global var for threads to check if they are done phil* philosophers; //pointer to the array of philosophers struct int numDiners; //the number of philosophers dining /***************************** * Function Declarations *****************************/ /* * function for threads to make a new dining philosopher */ void* philosopher(void* threadId); /* * function for threads to take a chopstick if it can */ void take_chopsticks(int i); /* * function for threads to release chopsticks */ void release_chopsticks(int i); /* * function to test each thread if a philosopher should switch to the EATING stage */ void test(int i);
C
// // main.c // PARTIBREJKERI_C // // Created by Borna on 30/04/2020. // Copyright © 2020 hr.fer.majstorovic.borna. All rights reserved. // #include <stdio.h> #include <pthread.h> #include <unistd.h> #include <stdlib.h> #include <sys/shm.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <signal.h> #include <sys/syscall.h> pthread_mutex_t monitor; pthread_cond_t studos; pthread_cond_t brejker; int brojStudenataUSobi = 0; int brejkerUSobi = 0; // 0 nije 1 je int N = 4; //broj studenata fiksno mjenjati void *student(void * K){ int stud =*((int*)K); srand((unsigned)time(NULL)); int x; x = rand()%400 + 100; usleep(x*1000); for(int i = 0; i < 3; i++){ pthread_mutex_lock(&monitor); while(brejkerUSobi == 1) pthread_cond_wait(&studos, &monitor); pthread_mutex_unlock(&monitor); pthread_mutex_lock(&monitor); brojStudenataUSobi++; if(brojStudenataUSobi > 3) pthread_cond_signal(&brejker); printf("Student %d je usao u sobu\n", stud); pthread_mutex_unlock(&monitor); int y = rand()%1000 + 1000; usleep(y*1000); pthread_mutex_lock(&monitor); brojStudenataUSobi--; if(brojStudenataUSobi == 0) { //salji signal brejkeri da smije izac pthread_cond_signal(&brejker); } printf("Student %d je izasao iz sobe\n", stud); pthread_mutex_unlock(&monitor); usleep(y*1000); } pthread_mutex_lock(&monitor); N--; pthread_mutex_unlock(&monitor); return NULL; } void *partibrejker(){ while (N>0) { srand((unsigned)time(NULL)); int x; x = rand()%900 + 100; usleep(x*1000); pthread_mutex_lock(&monitor); while (brojStudenataUSobi < 3) { pthread_cond_wait(&brejker, &monitor); } if (brojStudenataUSobi >=3 && brejkerUSobi == 0) { pthread_cond_signal(&brejker); brejkerUSobi = 1; printf("Partibrejker je uso u sobu \n"); pthread_cond_signal(&studos); } pthread_mutex_unlock(&monitor); pthread_mutex_lock(&monitor); while (brojStudenataUSobi != 0) { pthread_cond_wait(&brejker, &monitor); } if (brojStudenataUSobi == 0) { printf("Partibrejker izlazi iz sobe \n"); brejkerUSobi = 0; pthread_cond_signal(&studos);//vrati studentima mogucnot ulaska } pthread_cond_signal(&brejker); pthread_mutex_unlock(&monitor); } return NULL; } void brisi(){ pthread_mutex_destroy(&monitor); pthread_cond_destroy(&studos); pthread_cond_destroy(&brejker); exit(0); } int main(int argc, const char * argv[]) { pthread_t dretvaStudent[N]; pthread_t dretvaBrejker; sigset(SIGINT, brisi); pthread_mutex_init(&monitor, NULL); pthread_cond_init(&studos, NULL); pthread_cond_init(&brejker, NULL); for (int i = 1; i <= N; i++) { pthread_create(&dretvaStudent[i], NULL, student, &i); sleep(1); } pthread_create(&dretvaBrejker, NULL, partibrejker(), NULL); for (int i = 1; i <= N; i++) { pthread_join(dretvaStudent[i], NULL); } pthread_join(dretvaBrejker, NULL); brisi(); return 0; }
C
/* Copyright (C) 2015-2016 Autotalks Ltd. */ #include <stdio.h> #include <assert.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <sys/stat.h> #include <tx_api.h> #include <atlk/sdk.h> #include <atlk/gnss.h> #include <atlk/gnss_teseo.h> #include <craton/fs.h> /* CRATON ThreadX Teseo FW Update Example This example demonstrates basic usage of Teseo firmware update API for code running on top of CRATON processor with ThreadX RTOS. Expected firmware image format is a Teseo UPG image. For simplicty, the example assumes a valid firmware image is at 'A:/image.bin' (i.e. on microSD). */ /* Firmware update thread priority */ #define TESEO_FW_UPDATE_THREAD_PRIORITY 20 /* Firmware update thread */ static TX_THREAD gnss_teseo_fw_update_thread; static uint8_t gnss_teseo_fw_update_thread_stack[0x8000]; static void gnss_teseo_fw_update_thread_entry(ULONG input); /* Firmware image path */ #define FW_IMAGE_PATH "A:/image.bin" /* Firmware image max size */ #define FW_IMAGE_SIZE_MAX 0x100000 /* Firmware image buffer */ static uint8_t fw_image_buffer[FW_IMAGE_SIZE_MAX]; void craton_user_init(void) { /* ThreadX return value */ ULONG trv = TX_SUCCESS; /* Create firmware update thread */ trv = tx_thread_create(&gnss_teseo_fw_update_thread, "gnss_teseo_fw_update_thread", gnss_teseo_fw_update_thread_entry, 0, gnss_teseo_fw_update_thread_stack, sizeof(gnss_teseo_fw_update_thread_stack), TESEO_FW_UPDATE_THREAD_PRIORITY, TESEO_FW_UPDATE_THREAD_PRIORITY, TX_NO_TIME_SLICE, TX_AUTO_START); assert(trv == TX_SUCCESS); return; } static void gnss_teseo_fw_update_thread_entry(ULONG input) { /* Autotalks return code */ atlk_rc_t rc = ATLK_OK; /* POSIX return value */ int rv = 0; /* File statistics */ struct stat st; /* Size of firmware image file */ uint32_t fw_image_size; /* File descriptor */ int fd = -1; /* Teseo firmware update parameters */ gnss_teseo_fw_update_params_t params = GNSS_TESEO_FW_UPDATE_PARAMS_INIT; /* Not using input */ (void)input; printf("Start Teseo firmware update example...\n"); /* Enable the usage of file system in this thread */ rv = fs_thread_enable(); if (rv == -1) { fprintf(stderr, "fs_thread_enable failed, errno: %d\n", errno); return; } /* Get firmware image file statistics */ rv = stat(FW_IMAGE_PATH, &st); if (rv == -1) { fprintf(stderr, "stat failed, errno: %d\n", errno); return; } /* Size of firmware image file */ assert(st.st_size <= INT32_MAX); fw_image_size = (uint32_t)st.st_size; /* Make sure firmware image size makes sense */ assert(fw_image_size <= sizeof(fw_image_buffer)); /* Open firmware image in read-only mode */ fd = open(FW_IMAGE_PATH, O_RDONLY); if (fd == -1) { fprintf(stderr, "open failed, errno %d\n", errno); return; } /* Read image into buffer */ rv = read(fd, fw_image_buffer, fw_image_size); if (rv == -1) { fprintf(stderr, "read failed, errno %d\n", errno); goto exit; } assert((uint32_t)rv == fw_image_size); /* Set Teseo firmware update parameters */ params.fw_image = fw_image_buffer; params.fw_image_size = fw_image_size; params.nmea_speed_bps = UART_SPEED_230400_BPS; params.download_speed_bps = UART_SPEED_921600_BPS; params.erase_nvm_area = 1; params.nvm_area_size_kb = 0; params.recovery_mode = 0; params.sched_params.priority = TESEO_FW_UPDATE_THREAD_PRIORITY; /* Update Teseo firmware */ rc = gnss_teseo_fw_update(&params); if (atlk_error(rc)) { fprintf(stderr, "gnss_teseo_fw_update failed: %s\n", atlk_rc_to_str(rc)); goto exit; } printf("Firmware updated successfully!\n"); exit: /* Clean-up resources */ close(fd); return; }
C
#include <stdio.h> int main() { int qtdAlunos = 5; int qtdNotas = 4; const char *nome[qtdAlunos]; int nota[qtdAlunos][qtdNotas]; float media[qtdAlunos]; float maior = 0; int quemTemAMaior = 0; for(int i = 0; i < qtdAlunos; i++){ printf("Informe a primeira letra do nome do aluno %d: ", i); scanf("%s", nome[i]); for(int j = 0; j < qtdNotas; j++){ printf("Informe a %d nota de %s: ", j, nome[i]); scanf("%d", &nota[i][j]); } } for(int i = 0; i < qtdAlunos; i++){ float total = 0; for(int j = 0; j < qtdNotas; j++){ total += nota[i][j]; } media[i] = total / qtdNotas; printf("Média de %c: &f", nome[i], total); if(media[i] > maior){ maior = media[i]; quemTemAMaior = i; } } printf("A maior media é de %c, de valor: %f", nome[quemTemAMaior], maior); return 0; }
C
/* Author : Chaitaly Kundu Date : 20th June, 2021 */ /* Enter a decimal number. Convert it in binary */ #include<stdio.h> #include<math.h> int binary_to_decimal(int B) { //code here int i=0, num=0, d ; while(B>0) { d = B % 10; num = num + (d * pow(2,i++)); B = B/10; } return num; } int main() { int n, num; printf("Enter a binary number: "); scanf("%d",&n); num = binary_to_decimal(n); printf("%d",num); return 0; }
C
#include <stdio.h> void swap(int *, int *); int main(void) { int a = 10; int b = 20; swap(&a, &b); printf("a:%d b:%d", a, b); return 0; } void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; }
C
/* ** EPITECH PROJECT, 2021 ** ftp ** File description: ** cd */ #include "server.h" status_t cwd(client_t *client, char *param) { client->path = param; ftpsend( client->controlSocket, "250", "Requested file action okay, completed."); return OK; } status_t cdup(client_t *client, char *param) { int cut = 0; int i = 0; char *cpy = NULL; printf("in\n"); if (strcmp(client->path, "/") == 0) { ftpsend(client->controlSocket, "200", "Command okay.."); return OK; } while (client->path[i]) { if (client->path[i] == '/') cut = i; i++; } cpy = strndup(client->path, cut); printf("current: %s\n", cpy); free(client->path); client->path = cpy; ftpsend(client->controlSocket, "200", "Command okay."); return OK; }
C
/* * pc_comms.c * * Created on: 28 Aug 2021 * Author: Pradeepa */ #include <stdio.h> #include "pc_comms.h" #include "usart.h" static uint8_t recieve_buffer[20]; static uint8_t star_count = 0; uint8_t next_read_size = 1; uint8_t reading_time = 0; static event_cb device_event_cb; uint8_t pc_comms_yy = 0; uint8_t pc_comms_mm = 0; uint8_t pc_comms_dd = 0; uint8_t pc_comms_hh = 0; uint8_t pc_comms_min = 0; uint8_t pc_comms_ss = 0; static void process(uint8_t index); void pc_comms_init(event_cb cb) { device_event_cb = cb; HAL_UART_Receive_IT(&huart1, recieve_buffer, next_read_size); } void send_temperature_reading(const temperature_reading* reading) { /* 0x | datetime | : | temperature in integer | \r | \n 0x | max 8 chars | : | 7 chars | \r | \n */ uint8_t output[30]; int length = sprintf(output, "0x%X:%d\n", reading->datetime, reading->value); HAL_UART_Transmit(&huart1, output, length, 0xFFFFFFFF); } void data_received_from_pc() { process(0); HAL_UART_Receive_IT(&huart1, &recieve_buffer[0], next_read_size); } void process(uint8_t index) { next_read_size = 1; if (reading_time) { pc_comms_yy = recieve_buffer[0]; pc_comms_mm = recieve_buffer[1]; pc_comms_dd = recieve_buffer[2]; pc_comms_hh = recieve_buffer[3]; pc_comms_min = recieve_buffer[4]; pc_comms_ss = recieve_buffer[5]; reading_time = 0; star_count = 0; device_event_cb(DEVICE_EVENT_UPDATE_TIME); } if (recieve_buffer[index] == '*') { star_count++; } else if (star_count == 5) { if (recieve_buffer[index] == 'E') { // Chip erase device_event_cb(DEVICE_EVENT_CHIP_ERASE); star_count = 0; } else if (recieve_buffer[index] == 'R') { // Chip read device_event_cb(DEVICE_EVENT_CHIP_READ); star_count = 0; } else if (recieve_buffer[index] == 'T') { // Chip read reading_time = 1; next_read_size = 6; } } else { star_count = 0; } }
C
#include<stdio.h> #include<stdlib.h> void main() { int *v1; float *v2; TAluno *v3; . . . v1 = (int*) malloc(10*sizeof(int)); //vetor de inteiros de tamanho 10 v2 = (float*) malloc(20*sizeof(float)); //vetor de floats de tamanho 20 v3 = (TAluno*) malloc(30*sizeof(TAluno)); }
C
/* Programa: ForkDigits.c Objetivo: Crear un proceso hijo que realizara el programa digits.c lee dos nmeros enteros a y b (0 <= a <= b <= 100000). Posteriormente, el programa crear un proceso hijo quien ejecutar el cdigo del programa digits.c (ver archivo con definicin del problema "Digits") y que imprima los resultados. Nota: La funcion fork, retorna un 0 al proceso hijo y el PID del proceso hijo al proceso padre. Autor: Michael Duarte Fecha: Septiembre 2012 */ #include <stdlib.h> #include <stdio.h> #include <string.h> //#include <unistd.h> // No es necesario char string[50]; int num1,num2,i; int j,es_hijo; void main(){ printf("Dame 2 numeros: "); scanf("%d",&num1); scanf("%d",&num2); es_hijo=fork(); if(!es_hijo){//solo el hijo hara esto int cont[]={0,0,0,0,0,0,0,0,0,0}; for(i=num1;i<=num2;i++){ sprintf(string, "%d",i);//se convierte a String for(j=0;j<strlen(string);j++){//se recorren caracteres cont[(string[j]-'0')]++;}//se incrementa dependiendo de caracter que es } for(i=0;i<10;i++)//se imprime vector con resultados printf("%d ",cont[i]); printf("\n"); } /* else printf("Soy Padre, no hago nada!\n"); */ }
C
#include<stdio.h> #include<stdlib.h> #include <ws2tcpip.h> #include <winsock2.h> #define DATA "Hello World Socket" int main(int argc, char *argv[]){ int sock; struct sockaddr_in server; struct hostent *hp; char buff[1024]; /*CREATE SOCKET*/ sock = socket(AF_INET, SOCK_STREAM, 0); if(sock<0){ perror("Failed to create socket"); exit(1); } server.sin_family = AF_INET; hp = gethostbyname(argv[1]); if(hp==0){ perror("gethostbyname failed"); close(sock); exit(1); } memcpy(&server.sin_addr, hp->h_addr, hp->h_length); server.sin_port=htons(5000); if(connect(sock, (struct sockaddr *) &server, sizeof(server))<0){ perror("connect failed"); close(sock); exit(1); } if(send(sock,DATA,sizeof(DATA),0)<0){ perror("send failed"); close(sock); exit(1); } printf("Sent %s\n",DATA); close(sock); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> //ݹ鷽ʽʵִӡһÿһλ.1234ӡ1 2 3 4 //int Print(int i) //{ // if (i < 10) // return (i % 10); // return Print(i / 10); //} //void Print(int i) //{ // if (i > 9) // { // Print(i / 10); // } // printf("%d ", i % 10); // //} // //int main() //{ // int i = 0; // scanf("%d", &i); // Print(i); // return 0; //} // ////(123) 4 ////(12) 3 4 ////(1) 2 3 4 //ݹͷǵݹֱʵnĽ׳ˣ⣩ //ݹ //int Sulp1(int n) //{ // if (n == 1) // return 1; // return n*Sulp1(n - 1); // //} ////ǵݹ //int Sulp2(int n) //{ // int s = 1; // for (int i = 1; i <= n; i++) // { // s *= i; // } // return s; //} //int main() //{ // int n; // scanf("%d", &n); // printf("%d\n", Sulp1(n)); // printf("%d\n", Sulp2(n)); // return 0; //} //ݹͷǵݹֱʵstrlen //ݹ //int my_strlen1(char* ptr) //{ // if (*ptr == 0) // return 0; // return 1 + my_strlen1(ptr+1); //} ////ǵݹ //int my_strlen2(char* ptr) //{ // int i = 0; // while (*ptr != 0) // { // i++; // ptr++; // } // return i; //} //int main() //{ // char arr[] = "abcdefg"; // printf("%d\n", my_strlen1(arr)); // printf("%d\n", my_strlen2(arr)); // // return 0; //} //дһ reverse_string(char * string)ݹʵ֣ //ʵַ֣еַУӡ //Ҫ󣺲ʹCеַchar arr[] = "abcdef";֮ݱɣfedcba //abcde f //abcd e //abc d //ab c //a b //a //... //void pp(char* str) //{ // int sz = 0; // char* ptr = NULL; // while (*str != '\0')//ַ // { // sz++; // } // ptr =str+ sz; //} // //int reverse_string(char* str) //{ // pp(str); // char* ptr = NULL; // char* p = NULL; // ptr -= 1; //ptrǰ // *p = *ptr; //βԪصĽ // *ptr = *str; // *str = *p; // if (str < ptr) // { // return reverse_string(str + 1);//str // } // return 0; //} int main() { char arr[] = "abcdef"; printf("%s\n", reverse_string(arr)); return 0; } //дһݹ麯DigitSum(n)һǸ֮ //磬DigitSum(1729)Ӧ÷1 + 7 + 2 + 9ĺ19 //룺172919 //static int s;//̬s //s = 0; //void DigitSum(int i) //{ // if (i > 9) // { // DigitSum(i/10); // } // s += i % 10;//λ //} // //int main() //{ // int n = 0; // scanf("%d", &n); // DigitSum(n); // printf("%d\n", s); // return 0; //} //дһʵnkηʹõݹʵ //int my_pow(int n, int k) //{ // if (k == 1) // { // return n; // } // return n*my_pow(n, k - 1); //} // //int main() //{ // int n, k; // scanf("%d%d", &n, &k); // printf("%d\n", my_pow(n, k)); // return 0; //} //ݹͷǵݹֱʵn쳲 //1 1 2 3 5 8 13 21 34 55 //ݹ //int fac1(int n) //{ // if (n <= 2) // return 1; // return fac1(n - 1) + fac1(n - 2); //} ////ǵݹ //int fac2(int n) //{ // int a=1, b=1, c=1; // while (n-2) // { // a = b; // b = c; // c = a + b; // n--; // } // return c; //} //int main() //{ // int n = 0; // scanf("%d", &n); // printf("%d\n", fac1(n)); // printf("%d\n", fac2(n)); // return 0; //}
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #define WORD_SIZE 20 #define BUF_SIZE 80 #define LETTER_COUNT 26 typedef struct _Dict { char freq[LETTER_COUNT]; char orig_str[WORD_SIZE + 1]; int count_rep; struct _Dict *next; } Dict; typedef struct _Index { Dict *dict_head; Dict *dict_tail; } Index; void check_ananagram(Index*, int*, char*); void generate_answer(Index*); void delete_dictionary(Index*); int sort_word(const void*, const void*); int main() { int len_str, size_dict; char *word; Index idx_dict; char buf[BUF_SIZE + 1]; size_dict = 0; idx_dict.dict_head = NULL; idx_dict.dict_tail = NULL; while (true) { memset(buf, 0, sizeof(char) * (BUF_SIZE + 1)); if (fgets(buf, (BUF_SIZE + 1), stdin) == NULL) { break; } len_str = strlen(buf); buf[--len_str] = 0; /* Check for the process termination. */ if (strcmp(buf, "#") == 0) { break; } /* Split the input line into several words for processing. */ word = strtok(buf, " "); while (word != NULL) { check_ananagram(&idx_dict, &size_dict, word); word = strtok(NULL, " "); } } /* Sort and output the answer words. */ generate_answer(&idx_dict); /* Release the allocated resource. */ delete_dictionary(&idx_dict); return 0; } void check_ananagram(Index *p_idx_dict, int *p_size_dict, char *word) { int i, rc, len_word; bool is_ananagram; Dict *curr; char new_freq[LETTER_COUNT]; /* printf("debug %d %s\n", strlen(word), word); */ /* Profile the character frequency of the input word. */ memset(new_freq, 0, sizeof(char) * LETTER_COUNT); len_word = strlen(word); for (i = 0 ; i < len_word ; i++) { /* Check if the character is upper case. */ if ((word[i] >= 'A') && (word[i] <= 'Z')) { new_freq[word[i] - 'A']++; } /* Check if the character is lower case. */ else if ((word[i] >= 'a') && (word[i] <= 'z')) { new_freq[word[i] - 'a']++; } } is_ananagram = true; curr = p_idx_dict->dict_head; while (curr != NULL) { rc = memcmp(curr->freq, new_freq, sizeof(char) * LETTER_COUNT); if (rc == 0) { is_ananagram = false; curr->count_rep++; break; } curr = curr->next; } if (is_ananagram == true) { curr = (Dict*)malloc(sizeof(Dict)); curr->next = NULL; /* Record the character frequency data. */ memcpy(curr->freq, new_freq, sizeof(char) * LETTER_COUNT); /* Record the original word. */ memset(curr->orig_str, 0, sizeof(char) * (WORD_SIZE + 1)); strcpy(curr->orig_str, word); /* Initialize the repeat count. */ curr->count_rep = 1; if (p_idx_dict->dict_head == NULL) { p_idx_dict->dict_head = curr; p_idx_dict->dict_tail = curr; } else { p_idx_dict->dict_tail->next = curr; p_idx_dict->dict_tail = curr; } (*p_size_dict)++; } return; } void generate_answer(Index *p_idx_dict) { int idx, size_real; Dict *curr; char **list_word; /* Count the number of ananagrams. */ size_real = 0; curr = p_idx_dict->dict_head; while (curr != NULL) { if (curr->count_rep == 1) { size_real++; } curr = curr->next; } /* Collect the ananagrams for sorting. */ list_word = (char**)malloc(sizeof(char*) * size_real); idx = 0; curr = p_idx_dict->dict_head; while (curr != NULL) { if (curr->count_rep == 1) { list_word[idx++] = curr->orig_str; } curr = curr->next; } /* Sort the ananagrams with lexicographical order. */ qsort(list_word, size_real, sizeof(char*), sort_word); /* Print the answer. */ for (idx = 0 ; idx < size_real ; idx++) { printf("%s\n", list_word[idx]); } free(list_word); return; } int sort_word(const void *ptr_src, const void *ptr_tge) { const char **word_src, **word_tge; word_src = (const char**)ptr_src; word_tge = (const char**)ptr_tge; return strcmp(*word_src, *word_tge); } void delete_dictionary(Index *p_idx_dict) { Dict *curr, *pred; curr = p_idx_dict->dict_head; while (curr != NULL) { pred = curr; curr = curr->next; free(pred); } return; }
C
// #include <stdio.h> int main() { int arr[10] = {5,6,8,4,2,3,7,1,9,10}; int temp; for (int i = 0; i < 9; i++) { int j = i; while (j >= 0 && arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; j--; } } for (int i = 0; i < 10; i++) { printf("%d ", arr[i]); } return 0; }
C
#include<stdio.h> #include<conio.h> void main() { int a,p,r,n,t,b,c; printf("\n enter the value"); scanf("\n %d%d%d%d",&p,&r,&n,&t); b=(1+(r/n)); c=n*t; a=p*(pow(b,c)); printf("\n compound intrest %d",a); }
C
/** * CS2106 AY 20/21 Semester 1 - Lab 3 * * This file contains declarations. You should only modify the entry_controller_t struct, * as the method signatures will be needed to compile with the runner. */ #ifndef __CS2106_ENTRY_CONTROLLER_H_ #define __CS2106_ENTRY_CONTROLLER_H_ #include <semaphore.h> #define ENTRY_CONTROLLER_MAX_USES 5000 // we impose a limit on the number of uses we can // have typedef struct entry_controller { // define your variables here int loading_bays; sem_t *into_bay; sem_t *lock; sem_t *trains[ENTRY_CONTROLLER_MAX_USES]; int front; int back; } entry_controller_t; void entry_controller_init( entry_controller_t *entry_controller, int loading_bays ); void entry_controller_wait( entry_controller_t *entry_controller ); void entry_controller_post( entry_controller_t *entry_controller ); void entry_controller_destroy( entry_controller_t *entry_controller ); #endif // __CS2106_ENTRY_CONTROLLER_H_
C
#include <stdio.h> #include <stdlib.h> /** * main - prints number of arguments passed into it. * @argc: integer * @argv: pointer to an array * Return: int **/ int main(int argc, char **argv __attribute__((unused))) { printf("%i\n", argc - 1); return (0); }
C
///first question sorting. automatic a b and c additions. #include<stdio.h> #include<stdlib.h> #include<time.h> char text[10000];//For a more flexible approach I could make these arrays dynamically at load-time int answers[300]; int ansamount[300]; int startpoint[300]; int end; int convert(char a) { switch (a) { case 'a': case 'A': return 1; case'b': case 'B': return 2; case 'c': case 'C': return 3; case 'd': case 'D': return 4; case 'e': case 'E': return 5;//up to five choices. This is easy to expand. default: return 100;//invalid choice,as number will be too high } } int quiz()//this is the presentation to the end user. the file has already been parsed by load() { int print=0,run=1,asked=1,wrong=0; char choice='e'; while (run==1) { while (print<startpoint[asked+1])//+1 as using new questions start point as old questions endpoint { printf("%c",text[print]); print++; } choice=getchar(); while (convert(choice)>ansamount[asked]) { printf("Invalid choice. Please choose again\n\n");//if multiple chars are fed in, will get multiple prints choice=getchar();//gets rid of endline while (choice!='\n')// prevents multi-character invalid choices { choice=getchar(); } choice=getchar(); } if (convert(choice)!=answers[asked])//this means invalid choices also count as wrong. { printf("You got the answer wrong!\n"); wrong++; } choice=getchar();//remove the end-line. printf("You have got %d out of %d questions right.\n\n",asked-wrong,asked); asked++; if (asked==end) { return 0;//all questions have now been asked } } } int load() { char filename [25];//can do dynamic, just prefer this for ease-of code for now int temp=0,position=0,run=1,question=1, answer=1;//starting from question 1, as that's how I feel like doing it. FILE *fp; printf("Welcome to Console . Please choose the quiz you wish to take.\n\n"); while (temp<19) { filename[temp]=getchar(); if (filename[temp]=='\n') { filename[temp]='.';//all quizzes have to be saved as .txt filename[temp+1]='t'; filename[temp+2]='x'; filename[temp+3]='t'; filename[temp+4]='\0'; break; } temp++; } fp=fopen(filename,"r"); if (fp==NULL) { printf("Disaster! The file doesn't open! Please try again, or choose a different file \n"); return 0;//instead of stderr. } while (run==1) { text[position]=getc(fp); if (text[position]==EOF)//loading finished { ansamount[question-1]=answer;//for last question text[position]='\n';//to make sure at least one new line for input, regardless of what quiz-writer did. end=question;//so that quiz()knows which question is last. startpoint[question]=position;//print till beginning of next question in quiz() , then carry on from there return 1;//successful load, breaks do-while loop; } if (text[position]=='\n') { while (text[position]=='\n')//removes multiple spaces between question/answers, so a bit more user-friendly . { position++; text[position]=getc(fp); { if (text[position]=='Q'||text[position]=='q')//could also have chosen a switch { startpoint[question]=position;//as start from after the 'q' ansamount[question-1]=answer;//-1 as answer is currently the total answers to the last question question++; answer=1;//resets for next question } else if (text[position]=='a'||text[position]=='A') { answer++;//so that we know what number the correct answer is } else if (text[position]=='r'||text[position]=='R') { answers [question-1]=answer;//correct answer is saved for question before, as there was++ at Q } } } } else { position++;//if A, Q, or R, it is overwritten by loop, so doesn't appear in the text . } } } int main() { int run=1; while (run==1) { int success=0; do { success=load(); } while (success==0);//do while to keep on re-running load until successful if (quiz()==0) { printf("To exit, enter 'e'. To take another quiz, choose any other letter\n\n");///switch around? int temp=getchar(); while (temp=='\n') { temp=getchar(); } if (temp=='e'||temp=='E') { return 0; } temp=getchar(); //newline clearup for new quiz } } }
C
#include "filesys/inode.h" #include "filesys/ifile.h" #include "filesys/tools.h" static void empty_it(){ return; } void usage(){ printf("Utilisation: mkfile\n"); printf("\n"); printf("Retourne et affiche l'inoeud du fichier créé.\n"); printf("\n"); printf("Exemple:\n"); printf("\t$mkfile\n"); } int main(int argc, char**argv){ unsigned int i; unsigned int inumber; /* gestion des arguments */ if(argc != 1){ usage(); exit(EXIT_SUCCESS); } /* init hardware */ if(!init_hardware(HW_CONFIG)) { fprintf(stderr, "Initialization error\n"); exit(EXIT_FAILURE); } /* Interreupt handlers */ for(i=0; i<NB_EMPTY_FUNCTION; i++) IRQVECTOR[i] = empty_it; /* Allows all IT */ _mask(1); /* chargement du mbr */ if(!load_mbr()){ fprintf(stderr, "Erreur lors du chargement du Master Boot Record.\n"); exit(EXIT_FAILURE); } /* initialise le super du premier volume */ init_super(CURRENT_VOLUME); /* charge le super du premier volume dans la variable globale */ load_super(CURRENT_VOLUME); /* création du fichier */ inumber = create_ifile(IT_FILE); if(!inumber){ fprintf(stderr, "Erreur lors de la creation du fichier\n"); exit(EXIT_FAILURE); } printf("Création d'un fichier:\n"); printf("\tinumber: %d.\n", inumber); exit(inumber); }
C
#include "csr_load_matrix.h" #include "../../fcl_file.h" #include "../../fcl_logging.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <ctype.h> /** * @brief Read line from input. * * @param[in] input * @param[out] line * @param[out] max_line_len * @return */ char* readline(FILE *input, char** line, size_t* max_line_len); /** * @brief Read line from input. * * @param[in] input_str String which shall be read line by line * @param[in/out] offset Starting position of the next line * @param[out] line Buffer which contains the read string. * @param[in/out] max_line_len Maximum number of bytes line can hold. * @return */ size_t readline_string(const char* input_str, uint64_t *offset, char** line, size_t* max_line_len); char* readline(FILE *input, char** line, size_t* max_line_len) { size_t len; if(fgets(*line, *max_line_len, input) == NULL) return NULL; while(strrchr(*line, '\n') == NULL) { *max_line_len *= 2; *line = (char *) realloc(*line,*max_line_len); len = (int) strlen(*line); if(fgets(*line + len,*max_line_len - len,input) == NULL) break; } return *line; } size_t readline_string(const char* input_str, uint64_t *offset, char** line, size_t* max_line_len) { size_t len; uint32_t line_feed_found; len = 0; line_feed_found = 0; while (1) { while (len < *max_line_len) { if ((input_str[*offset + len] == '\0') || (input_str[*offset + len] == '\n')) { (*line)[len] = '\0'; if (input_str[*offset + len] == '\n') line_feed_found = 1; goto readline_end; } (*line)[len] = input_str[*offset + len]; len += 1; } *max_line_len *= 2; *line = (char *) realloc(*line,*max_line_len); } readline_end: *offset += len; /* continue after the linefeed when calling again */ if (line_feed_found) (*offset)++; return len; } uint32_t convert_libsvm_file_to_csr_matrix_wo_labels(const char *input_string, struct csr_matrix **mtrx) { int32_t* labels; uint32_t status; status = convert_libsvm_file_to_csr_matrix(input_string, mtrx, &labels); free_null(labels); return status; } uint32_t convert_libsvm_file_to_csr_matrix(const char *input_string, struct csr_matrix **mtrx, int32_t** labels) { uint64_t nnz, i, no_samples; KEY_TYPE key_id; int64_t inst_max_index; FILE *fp; char *endptr; char *idx, *val, *label; char *line = NULL; size_t max_line_len; uint32_t status; uint32_t is_file; uint64_t offset; *labels = NULL; *mtrx = NULL; fp = NULL; status = 0; offset = 0; is_file = exists(input_string); if (is_file) { fp = fopen(input_string,"r"); if(fp == NULL) { LOG_ERROR("can't open input file %s",input_string); status = 1; goto error; } } no_samples = 0; nnz = 0; max_line_len = 1024; line = (char*) malloc(sizeof(char) * max_line_len); while(1){ char *p; if (is_file) { if (readline(fp, &line, &max_line_len) == NULL) break; } else { /* check if end of string reached */ if (input_string[offset] == '\0') break; readline_string(input_string, &offset, &line, &max_line_len); } p = strtok(line," \t"); while(1) { p = strtok(NULL," \t"); if(p == NULL || *p == '\n') break; ++nnz; } ++no_samples; } if (is_file) { /* rewind to the beginning of the file */ rewind(fp); } else { /* set offset to the beginning of the string */ offset = 0; } *mtrx = (struct csr_matrix*) malloc(sizeof(struct csr_matrix)); (*mtrx)->pointers = NULL; (*mtrx)->values = NULL; (*mtrx)->keys = NULL; (*mtrx)->sample_count = 0; (*mtrx)->dim = 0; (*mtrx)->keys = (KEY_TYPE *) malloc(nnz * sizeof(KEY_TYPE)); (*mtrx)->values = (VALUE_TYPE *) malloc(nnz * sizeof(VALUE_TYPE)); (*mtrx)->sample_count = no_samples; (*mtrx)->pointers = (POINTER_TYPE *) malloc(((*mtrx)->sample_count + 1) * sizeof(POINTER_TYPE)); (*mtrx)->pointers[0] = 0; *labels = (int32_t *) malloc((*mtrx)->sample_count * sizeof(int32_t)); key_id = 0; for(i=0;i < no_samples;i++) { inst_max_index = -1; if (is_file) { readline(fp, &line, &max_line_len); } else { readline_string(input_string, &offset, &line, &max_line_len); } label = strtok(line," \t\n"); if(label == NULL) { LOG_ERROR("invalid libsvm data. label missing in line %ld", i + 1); status = 1; goto error; } errno = 0; (*labels)[i] = (int32_t) strtol(label, &endptr, 10); /* Check for various possible errors */ if (errno != 0 || endptr == label || *endptr != '\0') { LOG_ERROR("invalid libsvm data. invalid label (errno=%d) in line %ld\n", errno, i + 1); status = 1; goto error; } while(1) { idx = strtok(NULL,":"); val = strtok(NULL," \t"); if(val == NULL) break; errno = 0; (*mtrx)->keys[key_id] = (KEY_TYPE) (strtoul(idx, &endptr, 10) - 1); if(endptr == idx || errno != 0 || *endptr != '\0' || (*mtrx)->keys[key_id] <= inst_max_index){ LOG_ERROR("invalid libsvm data. keys invalid or not sorted (errno=%d) in line %ld\n!",errno , i + 1); status = 1; goto error; } else { inst_max_index = (*mtrx)->keys[key_id]; } if ((*mtrx)->keys[key_id] + 1 > (*mtrx)->dim) { (*mtrx)->dim = (*mtrx)->keys[key_id] + 1; } errno = 0; (*mtrx)->values[key_id] = (VALUE_TYPE) strtod(val,&endptr); if(endptr == val || errno != 0 || (*endptr != '\0' && !isspace((unsigned char) *endptr))){ LOG_ERROR("invalid libsvm data. error while reading values! line: %ld\n %s Key:%" KEY_TYPE_PRINTF_MODIFIER "u", i + 1, endptr, key_id); status = 1; goto error; } ++key_id; } (*mtrx)->pointers[i + 1] = key_id; } error: free_null(line); if (is_file && fp) fclose(fp); if (status != 0) { /* some error occured */ if (*mtrx != NULL) { free_csr_matrix(*mtrx); free_null(*mtrx); } if (*labels != NULL) { free_null(*labels); } } return status; }
C
#include"..\header\header.h" #include"..\header\function.h" extern char* loginID; //ѡ void chooseLoginOrReg(){ char choice; char inputs[10]; while(1){ puts("ѡ[1-3]"); gets(inputs); if(strlen(inputs) > 1){ puts("ѡ񲻺Ϸ"); continue; } choice = inputs[0]; if(choice == '1' || choice == '2'|| choice == '3'){ break; }else{ puts("ѡ񲻺Ϸ"); continue; } } switch(choice){ case '1': login(); break; case '2': registerUser(); break; case '3': quit(); } return; } // void view(){ while(1){ LoginAndRegmenu(); chooseLoginOrReg(); } return; } //˵ѡ void LoginAndRegmenu(){ char options[3][10] = {"1.¼", "2.ע","3.˳"}; printBorder("*"); printf(" "); puts("ӭС⣡"); printBorder("-"); int i; for(i = 0; i < 3; i++){ printf("\t"); printf(options[i]); printf("\n"); } printBorder("*"); return; } //˵ѡ void menu(){ char options[6][10] = {"0.", "1.", "2.֧", "3.ѯ", "4.ͳ", "5.˳"}; printBorder("*"); printf("\t"); printf("ӭ,%s",loginID); printf("\n"); printBorder("-"); int i; for(i = 0; i < 6; i++){ printf("\t"); printf(options[i]); printf("\n"); } printBorder("*"); return; } //ѡ void choose(char* ID){ char choice; char inputs[10]; while(1){ puts("ѡ[0-5]"); //scanf("%c",&choice); //char ch = getchar(); //getchar(); //choice = ch; gets(inputs); if(strlen(inputs) > 1){ puts("ѡ񲻺Ϸ"); continue; } choice = inputs[0]; //printf("----%c\n",choice); if(choice == '0' ||choice == '1' || choice == '2' || choice == '3' || choice == '4' || choice == '5'){ break; }else{ puts("ѡ񲻺Ϸ"); continue; } } switch(choice){ case '0': updatePass(); break; case '1': income(); break; case '2': expend(); break; case '3': find(); break; case '4': count(); break; case '5': quit(); } return; }
C
/* -*- coding: iso-latin-1-unix; -*- */ /* DECLARO QUE SOU O UNICO AUTOR E RESPONSAVEL POR ESTE PROGRAMA. // TODAS AS PARTES DO PROGRAMA, EXCETO AS QUE FORAM FORNECIDAS // PELO PROFESSOR OU COPIADAS DO LIVRO OU DAS BIBLIOTECAS DE // SEDGEWICK OU ROBERTS, FORAM DESENVOLVIDAS POR MIM. DECLARO // TAMBEM QUE SOU RESPONSAVEL POR TODAS AS COPIAS DESTE PROGRAMA // E QUE NAO DISTRIBUI NEM FACILITEI A DISTRIBUICAO DE COPIAS. // // Autor: Victor Wichmann Raposo // Numero USP: 9298020 // Sigla: VICTORWI // Data: 2015-11-2 // // Este arquivo faz parte da tarefa H // da disciplina MAC0121. // ////////////////////////////////////////////////////////////// */ #ifndef ORDENACAO_H #define ORDENACAO_H #include <stdlib.h> #include <stdio.h> /* Recebe um vetor v[0...n-1] de inteiros e chama a funcao que rearranja-o em // ordem crescente.*/ void heap_sort (int *v, int n); /* Recebe um vetor v[0...n-1] de strings e chama a funcao que rearranja-o em // ordem lexicografica.*/ void ordenacao_Digital (char *v[], int n); #endif
C
/* ------------------------------------------------------------------------ phase2.c University of Arizona Computer Science 452 ------------------------------------------------------------------------ */ #include <usloss.h> #include <usyscall.h> #include <phase1.h> #include <phase2.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <message.h> #include <handler.c> /* ------------------------- Prototypes ----------------------------------- */ int start1 (char *); void disableInterrupts(); void enableInterrupts(); void isKernelMode(char *); void InitialSlot(int); void InitialBox(int); void InitialQueue(queue*, int); void enqueue(queue*, void*); void *dequeue(queue*); void *head(queue*); void dumpSlots(int); /* -------------------------- Globals ------------------------------------- */ int debugflag2 = 0; // the mail boxes mailbox MailBoxTable[MAXMBOX]; // also need array of mail slots, array of function ptrs to system call // handlers, ... // mail slots mailSlot MailSlotTable[MAXSLOTS]; // processes mboxProc mboxProcTable[MAXPROC]; int boxNum, slotNum, curSlot; int nextBoxID = 0, nextSlotID = 0, nextProc = 0; //system call void (*syscall_vec[MAXSYSCALLS])(USLOSS_Sysargs *args); /* -------------------------- Functions ----------------------------------- */ /* ------------------------------------------------------------------------ Name - start1 Purpose - Initializes mailboxes and interrupt vector. Start the phase2 test process. Parameters - one, default arg passed by fork1, not used here. Returns - one to indicate normal quit. Side Effects - lots since it initializes the phase2 data structures. ----------------------------------------------------------------------- */ int start1(char *arg) { int kidPid; int status; if (DEBUG2 && debugflag2) USLOSS_Console("start1(): at beginning\n"); //Test for kernel mode isKernelMode("start1()"); //disable interrupts disableInterrupts(); // Initialize the mail box table, slots, & other data structures. for (int i = 0; i < MAXMBOX; i++){ InitialBox(i); } for (int i = 0; i < MAXSLOTS; i++){ InitialSlot(i); } boxNum = 0; slotNum = 0; curSlot = 0; // Initialize USLOSS_IntVec and system call handlers, USLOSS_IntVec[USLOSS_CLOCK_INT] = clockHandler2; USLOSS_IntVec[USLOSS_DISK_INT] = diskHandler; USLOSS_IntVec[USLOSS_TERM_INT] = termHandler; USLOSS_IntVec[USLOSS_SYSCALL_INT] = syscallHandler; // allocate mailboxes for interrupt handlers. Etc... Mbox[CLOCK] = MboxCreate(0, sizeof(int)); // clock Mbox[DISK] = MboxCreate(0, sizeof(int)); // disk 1 Mbox[DISK+1] = MboxCreate(0, sizeof(int)); // disk 2 Mbox[TERM] = MboxCreate(0, sizeof(int)); // terminal 1 Mbox[TERM+1] = MboxCreate(0, sizeof(int)); // terminal 2 Mbox[TERM+2]= MboxCreate(0, sizeof(int)); // terminal 3 Mbox[TERM+3] = MboxCreate(0, sizeof(int)); // terminal 4 for (int i = 0; i < MAXSYSCALLS; i++) { syscall_vec[i] = nullsys; } enableInterrupts(); // Create a process for start2, then block on a join until start2 quits if (DEBUG2 && debugflag2) USLOSS_Console("start1(): fork'ing start2 process\n"); kidPid = fork1("start2", start2, NULL, 4 * USLOSS_MIN_STACK, 1); if ( join(&status) != kidPid ) { USLOSS_Console("start2(): join returned something other than "); USLOSS_Console("start2's pid\n"); } return 0; } /* start1 */ // Initializes the mailbox. i: index of the box in the mailbox table. void InitialBox(int i) { MailBoxTable[i].mboxID = -1; MailBoxTable[i].curSlots = 0; MailBoxTable[i].status = INACTIVE; MailBoxTable[i].totalSlots = -1; MailBoxTable[i].slotSize = -1; boxNum--; } // Initializes a mail slot. i: Index of the mail slot in the mail slot table. void InitialSlot(int i) { MailSlotTable[i].mboxID = -1; MailSlotTable[i].status = EMPTY; MailSlotTable[i].slotID = -1; slotNum--; } /* ------------------------------------------------------------------------ Name - MboxCreate Purpose - gets a free mailbox from the table of mailboxes and initializes it Parameters - maximum number of slots in the mailbox and the max size of a msg sent to the mailbox. Returns - -1 to indicate that no mailbox was created, or a value >= 0 as the mailbox id. Side Effects - initializes one element of the mail box array. ----------------------------------------------------------------------- */ int MboxCreate(int slots, int slot_size) { //Test for kernel mode isKernelMode("MboxCreate()"); //disable interrupts disableInterrupts(); //check the mail box avilable if(boxNum == MAXMBOX || slots < 0 || slot_size < 0 || slot_size > MAX_MESSAGE){ if(DEBUG2 && debugflag2) USLOSS_Console("MboxCreate(): illegal args or max boxes reached, returning -1\n"); return -1; } //find the first available index if(nextBoxID >= MAXMBOX || MailBoxTable[nextBoxID].status == ACTIVE){ for(int i=0; i< MAXMBOX; i++){ if(MailBoxTable[i].status == INACTIVE){ nextBoxID = i; break; } } } mailbox *box = &MailBoxTable[nextBoxID]; box->mboxID = nextBoxID++; box->totalSlots = slots; box->slotSize = slot_size; box->status = ACTIVE; InitialQueue(&box->slotq, SLOTQUEUE); InitialQueue(&box->bProcS, PROCQUEUE); InitialQueue(&box->bProcR, PROCQUEUE); boxNum++; if (DEBUG2 && debugflag2){ USLOSS_Console("MboxCreate(): created mailbox with id = %d, totalSlots = %d, slot_size = %d, numBoxes = %d\n", box->mboxID, box->totalSlots, box->slotSize, boxNum); } enableInterrupts(); return box->mboxID; } /* MboxCreate */ /* ------------------------------------------------------------------------ Name - MboxSend Purpose - Put a message into a slot for the indicated mailbox. Block the sending process if no slot available. Parameters - mailbox id, pointer to data of msg, # of bytes in msg. Returns - zero if successful, -1 if invalid args. Side Effects - none. ----------------------------------------------------------------------- */ int MboxSend(int mbox_id, void *msg_ptr, int msg_size) { disableInterrupts(); isKernelMode("MboxSend"); //USLOSS_Console("MboxSend: checking for errors\n"); if (MailBoxTable[mbox_id].status == INACTIVE) { //USLOSS_Console("MboxSend(): mailbox %d is inactive\n", mbox_id); return -1; } if (msg_size > MailBoxTable[mbox_id].slotSize) { //USLOSS_Console("MboxSend(): message size %d is too large\n", msg_size); return -1; } queue * waitq = &MailBoxTable[mbox_id].bProcR; if (waitq != NULL) { mboxProc * proc = waitq->head; if (proc != NULL) { while (proc->messageReceived == TRUE) { proc = proc->nextMboxProc; } memcpy(proc->msg_ptr, msg_ptr, msg_size); int size = proc->msg_size; proc->msg_size = msg_size; proc->messageReceived = TRUE; unblockProc(proc->pid); enableInterrupts(); if (size < msg_size) { return -1; } return 0; } } if (MailBoxTable[mbox_id].curSlots == MailBoxTable[mbox_id].totalSlots) { //USLOSS_Console("MboxSend(): mailbox has no slots available\n"); mboxProc mproc; mproc.nextMboxProc = NULL; mproc.pid = getpid(); mproc.msg_size = msg_size; mproc.messageReceived = FALSE; enqueue(&(MailBoxTable[mbox_id]).bProcS, &mproc); //dumpSlots(mbox_id); blockMe(FULL); //USLOSS_Console("mBoxSend(): process %d starting again\n", getpid()); disableInterrupts(); } if (isZapped() || MailBoxTable[mbox_id].status == INACTIVE) { return -3; } if (slotNum == MAXSLOTS) { //USLOSS_Console("MboxSend(): No slots left\n"); USLOSS_Halt(1); } //USLOSS_Console("MboxSend: after checking for errors\n"); // Find an unused slot in the slot table while (MailSlotTable[curSlot%MAXSLOTS].status == USED) { curSlot++; } int slot = curSlot % MAXSLOTS; //USLOSS_Console("MboxSend(): adding to slot %d\n", slot); //USLOSS_Console("MboxSend: found a slot\n"); MailSlotTable[slot].status = USED; //USLOSS_Console("MboxSend(): memcpy '%s'\n", msg_ptr); memcpy(MailSlotTable[slot].message, msg_ptr, msg_size); //USLOSS_Console("MboxSend(): memcpy'd '%s'\n", MailSlotTable[slot].message); MailSlotTable[slot].mboxID = mbox_id; MailSlotTable[slot].messageLen = msg_size; MailBoxTable[mbox_id].curSlots++; slotNum++; //USLOSS_Console("MboxSend: num slots %d\n", MailBoxTable[mbox_id].curSlots); enqueue(&MailBoxTable[mbox_id].slotq, &MailSlotTable[curSlot%MAXSLOTS]); //dumpSlots(mbox_id); // Unblock the first process in the list of processes waiting queue *temp = &MailBoxTable[mbox_id].bProcR; //USLOSS_Console("======================%d\n", temp->size); if (temp->size > 0) { mboxProc *proc = NULL; proc = dequeue(temp); //USLOSS_Console("MboxSend(): unblock proc %d", proc->pid); unblockProc(proc->pid); enableInterrupts(); } return 0; } /* MboxSend */ /* ------------------------------------------------------------------------ Name - MboxReceive Purpose - Get a msg from a slot of the indicated mailbox. Block the receiving process if no msg available. Parameters - mailbox id, pointer to put data of msg, max # of bytes that can be received. Returns - actual size of msg if successful, -1 if invalid args. Side Effects - none. ----------------------------------------------------------------------- */ int MboxReceive(int mbox_id, void *msg_ptr, int msg_size) { disableInterrupts(); isKernelMode("MboxRecieve"); // USLOSS_Console("MboxRecieve() called\n"); // check for errors if (MailBoxTable[mbox_id].status == INACTIVE) { //USLOSS_Console("MboxRecieve(): mailbox %d is inactive\n", mbox_id); return -1; } // block proc if empty if (MailBoxTable[mbox_id].curSlots == 0) { // USLOSS_Console("MboxSend(): mailbox has no slots available\n"); mboxProc mproc; mproc.nextMboxProc = NULL; mproc.pid = getpid(); //mproc.msg_ptr = msg_ptr; mproc.msg_size = msg_size; enqueue(&(MailBoxTable[mbox_id]).bProcR, &mproc); // USLOSS_Console("before blockme() in receive\n"); blockMe(NONE); // USLOSS_Console("After blockme() in receive\n"); disableInterrupts(); if (mproc.messageReceived == TRUE) { // USLOSS_Console("MboxRecieve(): message recieved is TRUE\n"); // USLOSS_Console("MboxRecieve(): message size is %d\n", mproc.msg_size); // USLOSS_Console("MboxRecieve(): buffer size is %d\n", msg_size); if (mproc.msg_size > msg_size) { return -1; } memcpy(msg_ptr, mproc.msg_ptr, mproc.msg_size); dequeue(&(MailBoxTable[mbox_id]).bProcR); return mproc.msg_size; } } queue * slotq = NULL; slotq = &MailBoxTable[mbox_id].slotq; mailSlot * slot = slotq->head; if (slot != NULL && msg_size < slot->messageLen) { return -1; } if (isZapped() || MailBoxTable[mbox_id].status == INACTIVE) { return -3; } // copy message to the buffer mailSlot * temp = NULL; int previousSlotNum = MailBoxTable[mbox_id].curSlots; temp = dequeue(&(MailBoxTable[mbox_id].slotq)); MailBoxTable[mbox_id].curSlots--; curSlot--; //USLOSS_Console("MboxRecieve(): message to memcpy '%s'\n", temp->message); memcpy(msg_ptr, temp->message, temp->messageLen); //USLOSS_Console("MboxRecieve(): message memcpy'd `%s'\n", msg_ptr); InitialSlot(temp->slotID); // Unblock the first process in the list of processes waiting queue *box = &MailBoxTable[mbox_id].bProcS; //USLOSS_Console("--------------------------%d\n", box->size); if (box->size > 0) { mboxProc *proc = NULL; proc = dequeue(box); //USLOSS_Console("MboxSend(): unblock proc %d", proc->pid); unblockProc(proc->pid); //enableInterrupts(); if (previousSlotNum > MailBoxTable[mbox_id].curSlots) { mboxProc mproc; mproc.nextMboxProc = NULL; mproc.pid = getpid(); //mproc.msg_ptr = msg_ptr; mproc.msg_size = msg_size; enqueue(&(MailBoxTable[mbox_id]).bProcR, &mproc); //USLOSS_Console("+++++++++++++++++++++++++++++%d\n", (&MailBoxTable[mbox_id].bProcR)->size); blockMe(WAIT); } } return temp->messageLen; } /* MboxReceive */ int MboxCondSend(int mbox_id, void *msg_ptr, int msg_size) { disableInterrupts(); isKernelMode("MboxSend"); //USLOSS_Console("MboxSend: checking for errors\n"); if (MailBoxTable[mbox_id].status == INACTIVE) { //USLOSS_Console("MboxSend(): mailbox %d is inactive\n", mbox_id); return -1; } if (msg_size > MailBoxTable[mbox_id].slotSize) { //USLOSS_Console("MboxSend(): message size %d is too large\n", msg_size); return -1; } if ((MailBoxTable[mbox_id].curSlots == MailBoxTable[mbox_id].totalSlots) && condition == 0) { // USLOSS_Console("condition: %d", condition); // USLOSS_Console("MboxSend(): curslot size %d is too large\n", msg_size); return -2; } if (isZapped() || MailBoxTable[mbox_id].status == INACTIVE) { //USLOSS_Console("MboxSend(): status is INACTIVE\n"); return -3; } if (slotNum == MAXSLOTS) { //USLOSS_Console("MboxSend(): slotNum %d is too large\n", slotNum); return -2; } //USLOSS_Console("MboxSend: after checking for errors\n"); // Find an unused slot in the slot table while (MailSlotTable[curSlot%MAXSLOTS].status == USED) { curSlot++; } int slot = curSlot % MAXSLOTS; //USLOSS_Console("MboxSend(): adding to slot %d\n", slot); //USLOSS_Console("MboxSend: found a slot\n"); MailSlotTable[slot].status = USED; //USLOSS_Console("MboxSend(): memcpy '%s'\n", msg_ptr); memcpy(MailSlotTable[slot].message, msg_ptr, msg_size); //USLOSS_Console("MboxSend(): memcpy'd '%s'\n", MailSlotTable[slot].message); MailSlotTable[slot].mboxID = mbox_id; MailSlotTable[slot].messageLen = msg_size; MailBoxTable[mbox_id].curSlots++; slotNum++; //USLOSS_Console("MboxSend: num slots %d\n", MailBoxTable[mbox_id].curSlots); enqueue(&MailBoxTable[mbox_id].slotq, &MailSlotTable[curSlot%MAXSLOTS]); //dumpSlots(mbox_id); // Unblock the first process in the list of processes waiting queue *temp = &MailBoxTable[mbox_id].bProcR; if (temp->size > 0) { mboxProc *proc = NULL; proc = dequeue(temp); Procblocked--; // USLOSS_Console("MboxSend(): unblock proc %d", proc->pid); unblockProc(proc->pid); enableInterrupts(); } return 0; } int MboxCondReceive(int mbox_id, void *msg_ptr, int msg_size) { disableInterrupts(); isKernelMode("MboxRecieve"); // check for errors if (MailBoxTable[mbox_id].status == INACTIVE) { //USLOSS_Console("MboxRecieve(): mailbox %d is inactive\n", mbox_id); return -1; } // block proc if empty if (MailBoxTable[mbox_id].curSlots == 0) { return -2; } if (isZapped() || MailBoxTable[mbox_id].status == INACTIVE) { return -3; } // copy message to the buffer mailSlot * temp = NULL; temp = dequeue(&(MailBoxTable[mbox_id].slotq)); MailBoxTable[mbox_id].curSlots--; curSlot--; //USLOSS_Console("MboxRecieve(): message to memcpy '%s'\n", temp->message); memcpy(msg_ptr, temp->message, temp->messageLen); //USLOSS_Console("MboxRecieve(): message memcpy'd `%s'\n", msg_ptr); InitialSlot(temp->slotID); // Unblock the first process in the list of processes waiting queue *box = &MailBoxTable[mbox_id].bProcS; if (box->size > 0) { mboxProc *proc = NULL; proc = dequeue(box); //USLOSS_Console("MboxSend(): unblock proc %d", proc->pid); unblockProc(proc->pid); enableInterrupts(); } return temp->messageLen; } int MboxRelease(int mailboxID) { disableInterrupts(); isKernelMode("MboxRelease()"); mailbox *mb = &MailBoxTable[mailboxID]; //check if mailID is valid if(mailboxID < 0 || mailboxID >= MAXMBOX){ if(DEBUG2 && debugflag2) USLOSS_Console("MboxRelease(): called with invalid mailboxID: %d, returning -1\n", mailboxID); return -1; } //check if mailbox is in use if(mb == NULL || mb->status == INACTIVE){ if(DEBUG2 && debugflag2) USLOSS_Console("MboxRelease(): mailbox %d is already released, returning -1\n", mailboxID); return -1; } //check if the process has been zapped if(isZapped() || mb->status == INACTIVE){ if(DEBUG2 && debugflag2) USLOSS_Console("MboxRelease(): process was zapped, returning -3\n"); return -3; } //remove all slots in the mailbox while(mb->slotq.size > 0){ slotPtr slot = (slotPtr)dequeue(&mb->slotq); InitialSlot(slot->slotID); } //release the maibox InitialBox(mailboxID); if(DEBUG2 && debugflag2){ USLOSS_Console("MboxRelease(): release mailbox %d\n", mailboxID); } //unblock processes blocked by receive while(mb->bProcR.size > 0){ mboxProcPtr proc = (mboxProcPtr)dequeue(&mb->bProcR); unblockProc(proc->pid); disableInterrupts(); } //unblock processes blocked by send while(mb->bProcS.size > 0){ mboxProcPtr proc = (mboxProcPtr)dequeue(&mb->bProcS); unblockProc(proc->pid); disableInterrupts(); } enableInterrupts(); return 0; } /* * Disables the interrupts. */ void disableInterrupts() { // turn the interrupts OFF iff we are in kernel mode // if not in kernel mode, print an error message and // halt USLOSS //Check kernel mode isKernelMode("disableInterrupts()"); int status = USLOSS_PsrSet( USLOSS_PsrGet() & ~USLOSS_PSR_CURRENT_INT ); if(status == USLOSS_ERR_INVALID_PSR){ USLOSS_Console("disableInterrupts(): error invalid psr, (halting)"); USLOSS_Halt(1); } } /* disableInterrupts */ /* * Enables the interrupts. */ void enableInterrupts() { // turn the interrupts ON if we are in kernel mode // if not in kernel mode, print an error message and // halt USLOSS isKernelMode("enableInterrupts()"); int status = USLOSS_PsrSet( USLOSS_PsrGet() | USLOSS_PSR_CURRENT_INT ); if(status == USLOSS_ERR_INVALID_PSR){ USLOSS_Console("enableInterrupts(): error invalid psr, (halting)"); USLOSS_Halt(1); } } /* * Checks if currently in kernel mode */ void isKernelMode(char *method) { if (!(USLOSS_PSR_CURRENT_MODE & USLOSS_PsrGet())) { USLOSS_Console("%s: called while in user mode, by process %d. Halting...\n", method, getpid()); USLOSS_Halt(1); } } /* ------------------------------------------------- Help functions for data structure queue ------------------------------------------------- */ // Initialize the data structure void InitialQueue(queue* q, int ID){ q->head = NULL; q->tail = NULL; q->size = 0; q->ID = ID; } // Insert the pointer to the end of the exiting queue void enqueue(queue* q, void* p){ if (q->head == NULL && q->tail == NULL) { q->head = q->tail = p; } else { /* TODO: handle different ID here, if it's for slot or process */ if (q->ID == SLOTQUEUE) { ((slotPtr)(q->tail))->nextSlotPtr = p; //q->tail = ((slotPtr)p)->nextSlotPtr; } else if (q->ID == PROCQUEUE) { ((mboxProcPtr)(q->tail))->nextMboxProc = p; //q->tail = ((mboxProcPtr)p)->nextMboxProc; } q->tail = p; } q->size++; } // Remove and return the head of the queue void* dequeue(queue* q){ void* temp = q->head; if (q->head == NULL) { return NULL; } if (q->head == q->tail) { q->head = q->tail = NULL; } else { /* TODO: handle different ID here, if it's for slot or process */ if(q->ID == SLOTQUEUE) q->head = ((slotPtr)(q->head))->nextSlotPtr; //q->head = ((slotPtr)(q->head))->nextSlotPtr; if(q->ID == PROCQUEUE) q->head = ((mboxProcPtr)(q->head))->nextMboxProc; } q->size--; return temp; } // Return the head of the queue void* head(queue* q){ return q->head; } int check_io(void) { if (DEBUG2 && debugflag2) USLOSS_Console("check_io(): called\n"); // USLOSS_Console("procblocked: %d", Procblocked); return Procblocked > 0 ? 1 : 0; } void dumpSlots(int mbox_id) { USLOSS_Console("dumpSlot(): mailbox %d\n", mbox_id); queue * temp = NULL; temp = &(MailBoxTable[mbox_id].slotq); mailSlot * slot = temp->head; while (slot != NULL) { USLOSS_Console("----------slot: %d, message: %s\n", slot->slotID, slot->message); slot = slot->nextSlotPtr; } queue * procq = &MailBoxTable[mbox_id].bProcS; mboxProc * proc = procq->head; while (proc != NULL) { USLOSS_Console("----------------waiting: %d, message: %s\n", proc->pid, proc->msg_ptr); proc = proc->nextMboxProc; } }
C
#include <stdlib.h> #include "../headers/BinaryTree.h" #include "../headers/Node.h" /************************************************************* * CREATE AVL TREE * @author Lucas Bittencourt * * Creates the AVL Tree by receiving its root Node. * * @param root is the Node that will serve as the root * @return the AVL Tree allocated on memory * ***********************************************************/ BinaryTree* CreateAVLTree(Node* root) { BinaryTree* tree = (BinaryTree*) malloc(sizeof(BinaryTree)); tree->root = root; return tree; }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <string.h> void ReplaceSpace(char str[], int length) { if (str == NULL || length <= 0) { return; } int LenSpace = 0; //ո񳤶 int i = 0; while (str[i] != '\0') { if (str[i] == ' ') { ++LenSpace; } i++; } //滻ַij int NewLength = length + LenSpace * 2; while (length >= 0 && length < NewLength) { if (str[length] == ' ') { str[NewLength--] = '0'; str[NewLength--] = '2'; str[NewLength--] = '%'; } else { str[NewLength--] = str[length]; } length--; } } int main() { char str[32] = "We are happy."; int len = strlen(str); printf("滻ǰַΪ"); for (int i = 0; i < len; i++) { printf("%c", str[i]); } ReplaceSpace(str, len); int len1 = strlen(str); printf("\n滻ַΪ"); for (int i = 0; i < len1; i++) { printf("%c", str[i]); } printf("\n"); return 0; }
C
#include<stdio.h> int main() { FILE *f; int i,j; char a[100],b; f=fopen("abc.txt","w"); printf("Enter the text you want to input in the file:\n"); scanf("%[^\n]%*c",a); fprintf(f,"%s\n",a); fclose(f); printf("\nPress \"Enter\" key to input data directly to the file or Press \"E\" to exit:"); b=getchar(); if(b=='E'||b=='e') { return 0; } else printf("\nEnter the data(Press \"Ctrl+D\" to exit):\n"); f=fopen("abc.txt","a"); while((b=getchar())!=EOF) { putc(b,f); } fclose(f); printf("\n\nPress \"Enter\" key to read data from the file:\n"); getchar(); f=fopen("abc.txt","r"); if(!(f=fopen("abc.txt","r"))) { printf("\nError! File not found!\n"); return 0; } else while((b=getc(f))!=EOF) { printf("%c",b); } fclose(f); return 0; }
C
#include <stdio.h> #include<string.h> int main(void) { char str[100]; int len,i; scanf("%s",str); len=strlen(str); for(i=0;i<len;i++) { if(i<len-1) { printf("%c",str[i]); } else { printf("%c.",str[i]); } } return 0; }
C
#include<stdio.h> main () { float x,y; printf ("Please enter the coordinates of a point(x,y)\n"); scanf("%f,%f",&x,&y); if(x>0) { if(y>0) printf("1"); if(y<0) printf("4"); } if(x<0) { if(y>0) printf("2"); if(y<0) printf("3"); } if(x=0) printf("5"); if(y=0) printf("5"); }
C
#include "angle.h" Angle create_angle(double angle) { Angle ret = {.angle = angle, .tg = tan(angle), .sin = sin(angle), .cos = cos(angle)}; return ret; }
C
#include "holberton.h" /** *set_bit - function that sets the value of a bit to 1 at a given index. *@n: *n pointer numbers *@index: index * *Description: function that sets the value of a bit to 1 at a given index. *section header: Section description *Return: 1 for works, -1 if error */ int set_bit(unsigned long int *n, unsigned int index) { unsigned long int num = 1; if (index > (sizeof(unsigned long int) * 8)) return (-1); num = num << index; *n = *n | num; return (1); }
C
#include <assert.h> #include <string.h> #include <stdio.h> #include "comm/objective.h" int main(void) { obj_t *obj = obj_create(); assert(!obj_active(obj)); assert(obj_remaining(obj) == 0); char *cmds1[] = {"hej", "hejsan"}; assert(!obj_set_mission(obj, sizeof(cmds1)/sizeof(*cmds1), cmds1)); assert(obj_remaining(obj) == 0); char *cmds2[] = {"entr", "cont", "exit"}; assert(obj_set_mission(obj, sizeof(cmds2)/sizeof(*cmds2), cmds2)); assert(obj_remaining(obj) == sizeof(cmds2)/sizeof(*cmds2)); obj_set_state(obj, true); assert(obj_active(obj)); assert(obj_set_mission(obj, 0, NULL)); assert(obj_remaining(obj) == 0); obj_destroy(obj); return 0; }
C
// // main.c // recursive // // Created by mac on 16/4/11. // Copyright © 2016年 mac. All rights reserved. // #include <stdio.h> int getFactorial(int n){ if (n<=1) { return 1; } return getFactorial(n-1) * n; } int getSum(int m){ if (m>=100) { return 100; } return getSum(m+1) + m; } void printTriangle(int blank, int star){ if (star < 1) { return; } //正立的三角形 printTriangle(blank+1, star-2); for (int i = 0; i<blank; i++) { printf(" "); } for (int i=0; i<star; i++) { printf("*"); } printf("\n"); //printTriangle(blank+1, star-2); 倒置的三角形 } int main(int argc, const char * argv[]) { //递归求阶乘 int n = getFactorial(5); printf("%d\n",n); //递归求和 int m = getSum(1); printf("%d\n",m); //递归画等边三角形 printTriangle(0, 5); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strsplit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mmerabet <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/11/09 23:09:09 by mmerabet #+# #+# */ /* Updated: 2017/11/15 12:04:59 by mmerabet ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static int ft_count_words(const char *s, char sep) { int count; int pos; count = 0; while (s) { pos = ft_strchr_pos(s, sep); if (pos != 0 && s[0]) ++count; s = (pos != -1 ? s + (pos + 1) : NULL); } return (count); } char **ft_strsplit(const char *s, char sep) { char **t; int sz; int pos; if (!s) return (NULL); t = NULL; sz = 0; t = (char **)ft_memalloc(sizeof(char *) * (ft_count_words(s, sep) + 1)); if (t == NULL) return (NULL); while (s) { pos = ft_strchr_pos(s, sep); if (pos != 0 && s[0]) t[sz++] = (pos != -1 ? ft_strndup(s, pos) : ft_strdup(s)); s = (pos != -1 ? s + (pos + 1) : NULL); } return (t); }
C
int countSegments(char* s) { char *p = s; int cnt = 0; if (*p != '\0' && *p == 0) return 0; while (*p != '\0') { if (*p != ' ' && (*(p+1) == ' ' || *(p+1) == '\0')) { cnt++; } p++; } return cnt; }
C
/* * Ejercicio 15 de TP Procesos */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> // Define pid_t #include <unistd.h> // Define fork, getpid y getppid int main(void) { int err; err = execl ("/bin/ls", "ls", "-l", (char *)NULL); //err = execl("/otro_directorio/ls", "ls", "-l", (char *)NULL); if (err == -1) printf("Este printf se ejecuta en caso de error. Por que?\n"); exit(0); }
C
/* ** EPITECH PROJECT, 2020 ** find_sol.c ** File description: ** runner */ #include "my_runner.h" int find_sol(game_t *game) { game->map = move_beginning(game->map); while (game->map->next) { if ((game->mario->pos.x + 130 > (game->map->element)->pos.x && game->mario->pos.x < ((game->map->element)->pos.x + 120)) && game->map->element->pos.y > game->mario->pos.y + 120) return (game->map->element->pos.y); game->map = game->map->next; } return (960); }
C
main() { int a=10,b=20; if(a=b) printf("a and b are equal"); else printf("a and b are not equal"); }
C
#include "minimath.h" #include <math.h> #include <string.h> #define Y_PI (3.14159265358979323846f) vec4 *vec4_zero(vec4 *dst) { dst->x = dst->y = dst->z = dst->w = 0.0f; return dst; } vec4 *vec4_copy(vec4 *dst, const vec4 *src) { memcpy(dst->components, src->components, sizeof(dst->components)); return dst; } vec4 *vec4_set(vec4 *dst, float x, float y, float z, float w) { dst->x = x; dst->y = y; dst->z = z; dst->w = w; return dst; } vec4 *vec4_add(vec4 *dst, const vec4 *lhs, const vec4 *rhs) { dst->x = lhs->x + rhs->x; dst->y = lhs->y + rhs->y; dst->z = lhs->z + rhs->z; dst->w = lhs->w + rhs->w; return dst; } vec4 *vec4_sub(vec4 *dst, const vec4 *lhs, const vec4 *rhs) { dst->x = lhs->x - rhs->x; dst->y = lhs->y - rhs->y; dst->z = lhs->z - rhs->z; dst->w = lhs->w - rhs->w; return dst; } vec4 *vec4_mul(vec4 *dst, const vec4 *lhs, const vec4 *rhs) { dst->x = lhs->x * rhs->x; dst->y = lhs->y * rhs->y; dst->z = lhs->z * rhs->z; dst->w = lhs->w * rhs->w; return dst; } vec4 *vec4_div(vec4 *dst, const vec4 *lhs, const vec4 *rhs) { dst->x = lhs->x / rhs->x; dst->y = lhs->y / rhs->y; dst->z = lhs->z / rhs->z; dst->w = lhs->w / rhs->w; return dst; } float vec4_dot(const vec4 *lhs, const vec4 *rhs) { return (lhs->x * rhs->x) + (lhs->y * rhs->y) + (lhs->z * rhs->z) + (lhs->w * rhs->w); } float vec4_length(const vec4 *vec) { float sq_length = vec4_dot(vec, vec); return sqrtf(sq_length); } mat4x4 *mat4x4_identity(mat4x4 *dst) { vec4_set(&dst->rows[0], 1.0f, 0.0f, 0.0f, 0.0f); vec4_set(&dst->rows[1], 0.0f, 1.0f, 0.0f, 0.0f); vec4_set(&dst->rows[2], 0.0f, 0.0f, 1.0f, 0.0f); vec4_set(&dst->rows[3], 0.0f, 0.0f, 0.0f, 1.0f); return dst; } vec4 *mat4x4_row(vec4 *dst, const mat4x4 *mat, size_t row) { return vec4_copy(dst, &mat->rows[row]); } vec4 *mat4x4_col(vec4 *dst, const mat4x4 *mat, size_t col) { return vec4_set(dst, mat->data[0][col], mat->data[1][col], mat->data[2][col], mat->data[3][col]); } mat4x4 *mat4x4_mul(mat4x4 *dst, const mat4x4 *lhs, const mat4x4 *rhs) { vec4 tmp1, tmp2; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { dst->data[i][j] = vec4_dot(mat4x4_row(&tmp1, lhs, i), mat4x4_col(&tmp2, rhs, j)); } } return dst; } vec4 *mat4x4_mul_vec4(vec4 *dst, const mat4x4 *lhs, const vec4 *rhs) { float x = vec4_dot(&lhs->rows[0], rhs); float y = vec4_dot(&lhs->rows[1], rhs); float z = vec4_dot(&lhs->rows[2], rhs); float w = vec4_dot(&lhs->rows[3], rhs); vec4_set(dst, x, y, z, w); return dst; } mat4x4 *mat4x4_rotate_x(mat4x4 *dst, float angle) { float rads = angle * (Y_PI / 180.0f); float s = sinf(rads); float c = cosf(rads); vec4_set(&dst->rows[0], 1.0f, 0.0f, 0.0f, 0.0f); vec4_set(&dst->rows[1], 0.0f, c, -s, 0.0f); vec4_set(&dst->rows[2], 0.0f, s, c, 0.0f); vec4_set(&dst->rows[3], 0.0f, 0.0f, 0.0f, 1.0f); return dst; } mat4x4 *mat4x4_rotate_y(mat4x4 *dst, float angle) { float rads = angle * (Y_PI / 180.0f); float s = sinf(rads); float c = cosf(rads); vec4_set(&dst->rows[0], c, 0.0f, s, 0.0f); vec4_set(&dst->rows[1], 0.0f, 1.0f, 0.0f, 0.0f); vec4_set(&dst->rows[2], -s, 0.0f, c, 0.0f); vec4_set(&dst->rows[3], 0.0f, 0.0f, 0.0f, 1.0f); return dst; } mat4x4 *mat4x4_translate(mat4x4 *dst, float x, float y, float z) { vec4_set(&dst->rows[0], 1.0f, 0.0f, 0.0f, x); vec4_set(&dst->rows[1], 0.0f, 1.0f, 0.0f, y); vec4_set(&dst->rows[2], 0.0f, 0.0f, 1.0f, z); vec4_set(&dst->rows[3], 0.0f, 0.0f, 0.0f, 1.0f); return dst; } mat4x4 *mat4x4_ortho(mat4x4 *dst, float width, float height, float znear, float zfar) { float hw = width / 2.0f; float hh = height / 2.0f; float left = -hw; float right = hw; float bottom = -hh; float top = hh; vec4_set(&dst->rows[0], 2.0f / (right - left), 0.0f, 0.0f, (left + right) / (left - right)); vec4_set(&dst->rows[1], 0.0f, 2.0f / (top - bottom), 0.0f, (top + bottom) / (bottom - top)); vec4_set(&dst->rows[2], 0.0f, 0.0f, 1.0f / (znear - zfar), znear / (znear - zfar)); vec4_set(&dst->rows[3], 0.0f, 0.0f, 0.0f, 1.0f); return dst; } mat4x4 *mat4x4_perspective(mat4x4 *dst, float fov, float aspect, float znear, float zfar) { float fov_rads = fov * (Y_PI / 180.0f); float half_fov = fov_rads / 2.0f; float sin_half_fov = sinf(fov_rads); float cos_half_fov = cosf(fov_rads); float y_scale = cos_half_fov / sin_half_fov; float x_scale = y_scale / aspect; vec4_set(&dst->rows[0], x_scale, 0.0f, 0.0f, 0.0f); vec4_set(&dst->rows[1], 0.0f, y_scale, 0.0f, 0.0f); vec4_set(&dst->rows[2], 0.0f, 0.0f, zfar / (znear - zfar), znear * zfar / (znear - zfar)); vec4_set(&dst->rows[3], 0.0f, 0.0f, -1.0f, 0.0f); return dst; }
C
#include <stdio.h> #include <string.h> #include <conio.h> void demomembers(); void inputname(); void myacc(); void balance(); struct info { char name[50]; int accnum, accbal; }bank[50]; int total = 4, flag = 0; int main() { if(flag != 1) { demomembers(); flag = 1; } system("cls"); int n; printf("<--------------Total Members: %d----------->\n\n\n", total); printf("1. New Member"); printf("\n2. My Account"); printf("\n3. Search Members via Balance"); printf("\n\nChoose: "); scanf("%d", &n); system("cls"); if(n == 1) { inputname(); } else if(n == 2) { myacc(); } else if(n == 3) { balance(); } else { printf("There's no option for that!"); getch(); main(); } } void inputname() { int i, n; for(i = total; n != 0; i++) { printf("<--------------Total Bank Members: %d----------->\n", total); printf("### New Membership ####\n\n\n"); printf("Person's Name: "); scanf("%s", bank[i].name); printf("Person's Account Number: "); scanf("%d", &bank[i].accnum); printf("Person's Account Balance: "); scanf("%d", &bank[i].accbal); printf("\n--------------------------------------------\n\nWant to add more? [Yes = 1/No = 0]: "); scanf("%d", &n); system("cls"); total++; } main(); } void myacc() { system("cls"); int n, i, acc, index, flag; printf("\n<================== Withdrawal/Deposit Section ======================>\n\n\n"); printf("Account Number: "); scanf("%d", &acc); printf("\n1. Deposit Money\n\n"); printf("2. Withdraw Money\n\n"); printf("Choose: "); scanf("%d", &n); if(n == 1) { system("cls"); printf("<--------------Account Number %d----------->\n\n", acc); printf("### Money Deposit ####\n\n\n"); for(i = 0; i < total; i++) { if(acc == bank[i].accnum) { index = i; flag = 1; } } if(flag == 1) { printf("Name: %s\n", bank[index].name); printf("Current Balance: %d", bank[index].accbal); printf("\n\nAdd Money: "); scanf("%d", &n); bank[index].accbal += n; printf("Money %d Added Successfully!", n); getch(); } else { printf("There's no Account for that number!"); getch(); myacc(); } flag = 0; } else if(n == 2) { system("cls"); printf("<--------------Account Number %d----------->\n\n", acc); printf("### Money Withdrawal ####\n\n\n"); for(i = 0; i < total; i++) { if(acc == bank[i].accnum) { index = i; flag = 1; } } if(flag == 1) { printf("Name: %s\n", bank[index].name); printf("Current Balance: %d", bank[index].accbal); printf("\n\nWithdraw Money: "); scanf("%d", &n); if(n <= bank[index].accbal) { bank[index].accbal -= n; printf("Money %d Withdrawn Successfully!", n); } else { printf("Insufficient Fund!"); } } else { printf("There's no Account for that number!"); getch(); myacc(); } } else { printf("Invalid Option Selected!"); getch(); myacc(); } flag = 0; getch(); main(); } void balance() { int n, i, flag; printf("<--------------Total Bank Members: %d----------->\n", total); printf("### Members Balance Search ####\n\n\n"); printf("Enter Balance Amount: "); scanf("%d", &n); system("cls"); for(i = 0; i < total; i++) { if(bank[i].accbal <= n) { if(flag != 1) { printf("<---------------Balance Below %d--------------------->\n\n\n", n); } flag = 1; printf("Account Name: %s", bank[i].name); printf("\nAccount Number: %d", bank[i].accnum); printf("\nAccount Balance: %d\n\n", bank[i].accbal); printf("||--------------------------------------------------||\n\n"); } } if(flag != 1) { printf("\nNo members have balance below %d", n); } getch(); main(); } void demomembers() { //--------------------------Demo Informations-------------------------------------- //Member 1 Info strcpy(bank[0].name, "MD. Samiur Rahman Mian"); bank[0].accnum = 1111; bank[0].accbal = 2250; //Member 2 Info strcpy(bank[1].name, "Soaib Ahmed"); bank[1].accnum = 2222; bank[1].accbal = 3000; //Member 3 Info strcpy(bank[2].name, "Tarif Shariar Arnob"); bank[2].accnum = 3333; bank[2].accbal = 2070; //Member 4 Info strcpy(bank[3].name, "Jubair Dihan"); bank[3].accnum = 4444; bank[3].accbal = 5800; //--------------------------------------------------------------------------------- }
C
/* ** my_cos.c for my_cos.c in /home/han_d/Dropbox/EPITECH PROJET/Raytracer/RT_MULTISPOT ** ** Made by han_d ** Login <han_d@epitech.net> ** ** Started on Sat Jun 7 22:53:16 2014 han_d ** Last update Sun Jun 8 21:57:29 2014 kauch_j */ #include <stdlib.h> #include <math.h> #include "pauvray.h" #include "rotate.h" void my_cos_2(t_all *all, t_object *object, t_spobject *lum) { object->color_tmp[0] = all->norm.cos * object->color[0]; object->color_tmp[1] = all->norm.cos * object->color[1]; object->color_tmp[2] = all->norm.cos * object->color[2]; if (object->bright > 0) { object->color_tmp[0] = all->norm.cos * (object->color[0] * (1 - object->bright) + lum->color[0] * object->bright); object->color_tmp[1] = all->norm.cos * (object->color[1] * (1 - object->bright) + lum->color[1] * object->bright); object->color_tmp[2] = all->norm.cos * (object->color[2] * (1 - object->bright) + lum->color[2] * object->bright); } if (object->check == 1) effect_check(all, object); translate2(object, lum); punrotate(lum); unrotate(lum); } void my_cos(t_all *all, double k, t_object *object, t_spobject *lum) { protate(lum, object); translate1(object, lum); all->norm.pointx = all->eye.x + (k * all->eye.vx); all->norm.pointy = all->eye.y + (k * all->eye.vy); all->norm.pointz = all->eye.z + (k * all->eye.vz); my_normal(all, object); lum->vx = lum->x - all->norm.pointx; lum->vy = lum->y - all->norm.pointy; lum->vz = lum->z - all->norm.pointz; rotate(lum, object); all->norm.cos = (all->norm.normx * (lum->vx)) + (all->norm.normy * (lum->vy)) + (all->norm.normz * (lum->vz)); all->norm.a2 = (lum->vx) * (lum->vx) + (lum->vy) * (lum->vy) + (lum->vz) * (lum->vz); if (all->norm.cos < 0) all->norm.cos = 0; else { all->norm.a1 = all->norm.normx * all->norm.normx + all->norm.normy * all->norm.normy + all->norm.normz * all->norm.normz; all->norm.cos = all->norm.cos / sqrt(all->norm.a1 * all->norm.a2); } my_cos_2(all, object, lum); }
C
#include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #define Round(x) ( (int)( x + (abs(x) / x) * .5)) typedef struct person { char name[30]; int age; union { struct { char school[30]; } Child; struct { char school[30]; double GPA; } collegeStudent; struct adult { char company[30]; double salary; } Adult; } Kind; enum { kid, Student, Adult } KindOfPerson; } Person; void printPerson(Person*); void main() { Person P1; strcpy(P1.name, "Bob"); P1.age = 20; strcpy(P1.Kind.collegeStudent.school, "K-State"); P1.Kind.collegeStudent.GPA = 3.5; P1.KindOfPerson = Student; printPerson(&P1); printf("\n"); Person* P2 = malloc(sizeof(Person)); strcpy((*P2).name, "Alison");// bd (*P2).age = 10; //gsdgsdf strcpy((*P2).Kind.Child.school, "Amanda Arnold Elementary"); (*P2).KindOfPerson = kid; printPerson(P2); free(P2); printf("\n2.2 -> %d\n", Round(2.2)); printf("\n2.7 -> %d\n", Round(2.7)); printf("\n-2.2 -> %d\n", Round(-2.2)); printf("\n-2.7 -> %d\n", Round(-2.7)); } void printPerson(Person* p) { printf("Name is %s\n", (*p).name); printf("Age is %d\n", (*p).age); if ((*p).KindOfPerson == kid) { printf("School is %s\n", (*p).Kind.Child.school); } else if ((*p).KindOfPerson == Student) { printf("School is %s\n", (*p).Kind.collegeStudent.school); printf("GPA is %e\n", (*p).Kind.collegeStudent.GPA); } else if ((*p).KindOfPerson == Adult) { printf("Company is %s\n", (*p).Kind.Adult.company); printf("Salray is %e\n", (*p).Kind.Adult.salary); ////gvsdfg } }
C
#include <string.h> #include <stdlib.h> #include <stdio.h> #include <Windows.h> #include "lab1.h" COORD CurrPos; HANDLE consHndlr; //TOURNIQUETS FUNCTIONS GO HERE struct turn_s { int passStud; int passTeach; int passStuff; }; struct turnSystem_s { int size; turn_t * thyTurns; }; turnSystem_t * turn_new(int size) { turnSystem_t * turnSample = malloc(sizeof(struct turnSystem_s)); turnSample->thyTurns = calloc(size, sizeof(turn_t)); turnSample->size = size; return turnSample; } void turn_free(turnSystem_t * self) { free(self->thyTurns); free(self); } void turn_fill(turnSystem_t * self) { for (int i = 0; i < self->size; i++) { self->thyTurns[i].passStud = 0; self->thyTurns[i].passTeach = 0; self->thyTurns[i].passStuff = 0; } } void turn_rand(turnSystem_t * self) { int idT; int idH; for (int i = 0; i < HUM; i++) { idT = rand() % self->size; idH = rand() % 3; if (idH == STUFF) { self->thyTurns[idT].passStuff++; } else if (idH == TEACHER) { self->thyTurns[idT].passTeach++; } else if (idH == STUDENT) { self->thyTurns[idT].passStud++; } } } //TERMINALS FUNCTIONS GO HERE struct termSystem_s { int size; term_t * thyTerms; }; struct term_s { char name[30]; int passed; }; termSystem_t * term_new(int size) { termSystem_t * termSample = malloc(sizeof(struct termSystem_s)); termSample->thyTerms = calloc(size, sizeof(term_t)); termSample->size = size; return termSample; } void term_free(termSystem_t * self) { free(self->thyTerms); free(self); } void term_fill(termSystem_t * self) { if (self->size >= 1) { if (self->size >= 2) { if (self->size >= 3) { strcpy(self->thyTerms[0].name, "STUFF_TERMINAL"); strcpy(self->thyTerms[1].name, "TEACHERS_TERMINAL"); strcpy(self->thyTerms[2].name, "STUDENTS_TERMINAL"); } else { strcpy(self->thyTerms[0].name, "STUFF_TERMINAL"); strcpy(self->thyTerms[1].name, "TEACHERS_TERMINAL"); } } else { strcpy(self->thyTerms[0].name, "STUFF_TERMINAL"); } } for (int i = 0; i < self->size; i++) { self->thyTerms[i].passed = 0; } } void term_from_turn(const turnSystem_t * selfTurn, termSystem_t * selfTerm) { for (int i = 0; i < selfTurn->size; i++) { for (int j = 0; j < selfTerm->size; j++) { if (strcmp(selfTerm->thyTerms[j].name, "STUFF_TERMINAL") == 0) { selfTerm->thyTerms[j].passed = selfTerm->thyTerms[j].passed + selfTurn->thyTurns[i].passStuff; } else if (strcmp(selfTerm->thyTerms[j].name, "TEACHERS_TERMINAL") == 0) { selfTerm->thyTerms[j].passed = selfTerm->thyTerms[j].passed + selfTurn->thyTurns[i].passTeach; } else if (strcmp(selfTerm->thyTerms[j].name, "STUDENTS_TERMINAL") == 0) { selfTerm->thyTerms[j].passed = selfTerm->thyTerms[j].passed + selfTurn->thyTurns[i].passStud; } } } } void term_print(const termSystem_t * self) { for (int i = 0; i < self->size; i++) { if (strcmp(self->thyTerms[i].name, "STUFF_TERMINAL") == 0) { interface_chngCurPos(0, 0); printf("%s statistics:", self->thyTerms[i].name); interface_chngCurPos(0, 1); printf("STUFF passed: %i", self->thyTerms[i].passed); } else if (strcmp(self->thyTerms[i].name, "TEACHERS_TERMINAL") == 0) { interface_chngCurPos(42, 0); printf("%s statistics:", self->thyTerms[i].name); interface_chngCurPos(42, 1); printf("TEACHERS passed: %i", self->thyTerms[i].passed); } else if (strcmp(self->thyTerms[i].name, "STUDENTS_TERMINAL") == 0) { interface_chngCurPos(26, 11); printf("%s statistics:", self->thyTerms[i].name); interface_chngCurPos(26, 12); printf("STUDENTS passed: %i", self->thyTerms[i].passed); } } } //ADDITIONAL INTERFACE FUNCTIONS GO HERE void interface_chngCurPos(int x, int y) { consHndlr = GetStdHandle(STD_OUTPUT_HANDLE); CurrPos.X = x; CurrPos.Y = y; SetConsoleCursorPosition(consHndlr, CurrPos); } void interface_borders(void) { for (int i = 0; i < 10; i++) { interface_chngCurPos(40, i); puts("|"); } interface_chngCurPos(0, 10); for (int i = 0; i < 80; i++) { printf("-"); } interface_chngCurPos(0, 20); for (int i = 0; i < 80; i++) { printf("-"); } } void interface_all(const termSystem_t * self) { interface_borders(); term_print(self); } //ADDITIONAL FUNCTIONS REQUIRED FOR TESTING GO HERE int test_turnGetCounter(const turnSystem_t * self, int info, int index) { if ((info != STUFF && info != TEACHER && info != STUDENT) || (index < 0 || index>= self->size)) { return -1; } else if (info == STUFF) { return self->thyTurns[index].passStuff; } else if (info == TEACHER) { return self->thyTurns[index].passTeach; } else if (info == STUDENT) { return self->thyTurns[index].passStud; } } int test_termGetCounter(const termSystem_t * self,int index) { if (index < 0 || index >= self->size) { return -1; } else { return self->thyTerms[index].passed; } } char * test_termGetName(char * resultStr, const termSystem_t * self, int index) { if (index < 0 || index >= self->size) { strcpy(resultStr, "-1"); return resultStr; } else { strcpy(resultStr, self->thyTerms[index].name); return resultStr; } }
C
// // Codec.c // // // Created by Benjamin Fernandez on 16/12/2017. // #include "Codec.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> void menu(){ printf("\n1/ Encrypt a file"); printf("\n2/ Decrypt a file"); printf("\n3/ Quitter"); } void emptyBuffer(){ fflush(stdin); fflush(stdout); } unsigned long long fileSelection(unsigned char *filename, FILE* file){ int i; unsigned long long size; filename = NULL; fileSize = 0; for (i = 0; i < 255; i++) { filename[i] = 0; } // Demande le nom du fichier tant que le fichier n'existe pas. while (file == NULL) { printf("\nEnter a filename: "); fgets(filename, 255, stdin); for (i = 0; i < 255; i++) { if (filename[i] == '\n') { filename[i] = 0; break; } } file = fopen(filename, "r"); if (file == NULL) { printf("File does not exist.\n"); } } fclose(file); emptyBuffer(); } unsigned short checkMatrixFile (FILE * matrixFile){ unsigned char matrix [41]; unsigned short i; unsigned short j; unsigned short result = 1; fseek(matrixFile,0,SEEK_SET); fread(matrix,sizeof(char),41,matrixFile); // Vérification du début et de la fin du fichier contenant les caractères G4C=[] if (matrix[0] != 'G' || matrix[1] != '4' || matrix[2] != 'C' || matrix[3] != '=' || matrix[4] != '[' || matrix[40] != ']'){ result = 0; } // Vérification de la matrice for (i = 0; i < 4; i ++){ for (j = (i*9)+5; j < ((i*9)+8)+5; y++){ if ( matrix[j] != '0' && matrix[j] != '1'){ result = 0; } } } return result; } void stockMatrix (FILE * matrixFile, unsigned char matrix[][8]){ unsigned char key [41]; unsigned short i; unsigned short j; unsigned short k; fseek(matrixFile,0,SEEK_SET); fread(key,1,41,matrixFile); for (i = 0; i < 4; i ++){ k = 0; for (j = (i*9)+5; j < ((i*9)+8)+5; j++){ matrix[i][k] = key[j]; k++; } } } unsigned short makeNewFilename(unsigned char *filename, unsigned char *encryptedDecryptedFilename, unsigned short mode){ unsigned short result = 0; if(*filename != NULL){ for (i = 0; i < 255; i++) { encryptedDecryptedFilename[i] = '\0'; } for (i = 0; i < 255; i++) { encryptedDecryptedFilename[i] = filename[i]; } switch (mode) { case 1: encryptedDecryptedFilename[strlen(encryptedDecryptedFilename)] = 'c'; break; case 2: encryptedDecryptedFilename[strlen(encryptedDecryptedFilename)] = 'd'; break; default: break; } if ( encryptedDecryptedFilename[strlen(encryptedDecryptedFilename)-1] == 'c' || encryptedDecryptedFilename[strlen(encryptedDecryptedFilename)-1] == 'd' ) { result = 1; } else { result = 0; } } else { result = 0; } return result; }
C
#include "parse.h" /*-------- * create ---------*/ grammar_table *grammar_table_create() { grammar_table *grammars = (grammar_table *) malloc(sizeof(grammar_table)); grammars->symbol = NULL; grammars->first = NULL; grammars->last = NULL; grammars->len = 0; return grammars; } grammar_symbol_table *grammar_symbol_table_create() { grammar_symbol_table *grammar_symbols = (grammar_symbol_table *) malloc(sizeof(grammar_symbol_table)); grammar_symbols->first = NULL; grammar_symbols->last = NULL; grammar_symbols->len = 0; return grammar_symbols; } grammar_symbol *grammar_symbol_create() { grammar_symbol *ptr = (grammar_symbol *) malloc(sizeof(*ptr)); ptr->next = NULL; ptr->first = NULL; ptr->id = 0; ptr->type = 0; ptr->value = NULL; return ptr; } generator *grammar_generator_create() { generator *ptr = (generator *) malloc(sizeof(*ptr)); ptr->next = NULL; ptr->left = NULL; ptr->first = NULL; ptr->last = NULL; return ptr; } right_generator *right_generator_create() { right_generator *ptr = (right_generator *) malloc(sizeof(*ptr)); ptr->next = NULL; ptr->first = NULL; ptr->last = NULL; ptr->len = 0; return ptr; } generator_symbol *generator_symbol_create() { generator_symbol *ptr; ptr = (generator_symbol *) malloc(sizeof(*ptr)); ptr->next = NULL; ptr->symbol = NULL; return ptr; } item *item_create() { item *ptr = (item *) malloc(sizeof(*ptr)); ptr->next = NULL; ptr->left = NULL; ptr->right = NULL; ptr->situation = NULL; ptr->ahead = NULL; return ptr; } item_set *item_set_create() { item_set *ptr = (item_set *) malloc(sizeof(*ptr)); ptr->next = NULL; ptr->first = NULL; ptr->last = NULL; ptr->len = 0; return ptr; } item_set_collection *item_set_collection_create() { item_set_collection *ptr = (item_set_collection *) malloc(sizeof(*ptr)); ptr->first = NULL; ptr->last = NULL; ptr->len = 0; return ptr; } first_symbol *first_symbol_create() { first_symbol *ptr = (first_symbol *) malloc(sizeof(*ptr)); ptr->next = NULL; ptr->symbol = NULL; return ptr; } first_set *first_set_create() { first_set *ptr = (first_set *) malloc(sizeof(*ptr)); ptr->first = NULL; ptr->last = NULL; ptr->len = 0; ptr->have_null = 0; return ptr; } /*-------- * free ---------*/ void first_set_free(first_set *ptr) { if (ptr->first) first_free(ptr->first); free(ptr); } void first_free(first_symbol *ptr) { if (ptr->next) first_free(ptr->next); free(ptr); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { int n, i, *p, sum; printf("Please input the n:\n"); scanf("%d", &n); if ((p = (int *) malloc (n, sizeof(int))) == NULL){ printf("Not able to allocate memory.\n"); exit(1); } printf("Please input the %d integers:\n", n); for(i = 0; i < n; i++){ scanf("%d", p+i); } sum = 0; for(i = 0; i < n; i++){ sum += *(p+i); } printf("The sum is: %d", sum); free(p); return 0; }
C
//find number of characters in string using dma #include<stdio.h> #include<conio.h> int count(char *string) { int i,count; for(i=0;*(i+string)!=NULL;++i) { count++; } return count; } void main() { char *ptr; int i; ptr=(char*)malloc(sizeof(char)); if(ptr==NULL) { printf("memory not allocated"); exit(0); } printf("enter string\n"); gets(ptr); i=count(ptr); printf("Length of string is %d\n",i); free(ptr); }
C
#include <stdio.h> #include <math.h> #define NUMBER 600851475143 int isPrime(int test) { int i=0; int calculateTo=( (int) sqrt(test) ); for(i = 3; i <= calculateTo; i+=2) { if(test % i == 0) { return 0; } } return 1; } int main() { int highest=0; int i=0; while(1) { for(i=3; ; i+=2) { if(isPrime(i)) { if(NUMBER%i==0) highest=i; if(i>=(sqrt(NUMBER))) goto END; } } } END: printf("%d", highest); return 0; }
C
#include<stdio.h> #include<string.h> int main() { char c1[105],c2[105]; int i; scanf("%s",c1); scanf("%s",c2); for(i=0;i<strlen(c1);i++){ if(c1[i]==c2[i]) printf("0"); else printf("1"); } printf("\n"); return 0; }
C
/* * Created by Ricardo Rodrigues on 18/10/2017. */ #include <stdlib.h> #include <memory.h> #include <stdio.h> #include <string.h> #include "Course.h" Course* Course_new(const char name[50], unsigned int id) { Course* course = malloc(sizeof(Course)); course->id = id; strcpy(course->name, name); course->newsCount = 0; return course; } void Course_delete(Course* course) { if (course == NULL) return; free(course); } void Course_addNews(Course *course, char news[50]) { if (course->newsCount > 10) { return; } strcpy(course->news[course->newsCount], news); course->newsCount++; } void Course_info(Course *course) { unsigned int i; printf("\tName: %s; Id: %d;\n", course->name, course->id); printf("\t\tNews:\n"); for (i = 0; i < course->newsCount; ++i) { printf("\t\t\t%s\n", course->news[i]); } }
C
#include <stdio.h> #include <time.h> #include <math.h> #include <stdlib.h> #include "utils.h" void subtract_timespec(struct timespec *result, const struct timespec *a, const struct timespec *b) { if ((a->tv_sec < b->tv_sec) || ((a->tv_sec == b->tv_sec) && (a->tv_nsec <= b->tv_nsec))) { /* TIME1 <= TIME2? */ result->tv_sec = result->tv_nsec = 0 ; } else { /* TIME1 > TIME2 */ result->tv_sec = a->tv_sec - b->tv_sec ; if (a->tv_nsec < b->tv_nsec) { result->tv_nsec = a->tv_nsec + 1000000000L - b->tv_nsec ; result->tv_sec-- ; /* Borrow a second. */ } else { result->tv_nsec = a->tv_nsec - b->tv_nsec ; } } } void timeval_add_ms(struct timeval *a, unsigned int ms) { a->tv_usec += ms * 1000; while (a->tv_usec >= 1000000L) { a->tv_sec += 1; a->tv_usec -= 1000000L; } } void timeval_add_us(struct timeval *a, unsigned long int us) { a->tv_usec += us; while (a->tv_usec >= 1000000L) { a->tv_sec += 1; a->tv_usec -= 1000000L; } } /* Given a [rate], generate an interarrival sample according to a Poisson process and store it in [tv]. */ void generate_poisson_interarrival(struct timeval* tv, double rate) { double u = drand48(); double interarrival = - log(1. - u) / rate; tv->tv_sec = (time_t) floor(interarrival); tv->tv_usec = lrint(interarrival * 1000000.) % 1000000; } void log_print(FILE *file, int use_syslog, int code, const char *fmt, ...) { char *msg = ""; if (file == NULL) { file = stdout; } switch (code) { case LOG_ERR: msg = "ERR"; break; case LOG_INFO: msg = "INFO"; break; case LOG_DEBUG: msg = "DEBUG"; break; } char buffer[2014]; if (use_syslog) { va_list ap; va_start(ap, fmt); vsprintf(buffer, fmt, ap); va_end(ap); syslog(code|LOG_LOCAL0, buffer); } else { log_date_time(buffer); fprintf(file, "%s [%s] ", buffer, msg); va_list ap; va_start(ap, fmt); vfprintf(file, fmt, ap); va_end(ap); fputc('\n',file); fflush(file); } }
C
#include <pthread.h> #include <stdio.h> pthread_mutex_t x, y; void *jack(void *dontcare) { while (1) { pthread_mutex_lock(&x); pthread_mutex_lock(&y); printf("jack!\n"); pthread_mutex_unlock(&x); pthread_mutex_unlock(&y); } return NULL; } void *jill(void *dontcare) { while (1) { pthread_mutex_lock(&y); pthread_mutex_lock(&x); printf("jill!\n"); pthread_mutex_unlock(&x); pthread_mutex_unlock(&y); } return NULL; } int main() { pthread_t jack_t, jill_t; pthread_mutex_init(&x, NULL); pthread_mutex_init(&y, NULL); pthread_create(&jack_t, NULL, jack, NULL); pthread_create(&jill_t, NULL, jill, NULL); pthread_join(jack_t,NULL); pthread_join(jill_t,NULL); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> int i,j,k; char nome[7][10]; char nomeMaior[10]; char nomeMenor[10]; float media[7]; float maior = 0; float menor = 0; int menores6 = 0; float mediaAlunos = 0; float acumulador = 0; int calculoMaior() { for(k = 0; k < 7; k++) { if(media[k] < 6) { menores6++; } if(maior == 0) { maior = media[k]; strcpy(nomeMaior,nome[k]); } if(media[k] > maior) { maior = media[k]; strcpy(nomeMaior,nome[k]); } } } int calcularMedia(){ for(i = 0; i < 7 ;i++){ acumulador += media[i]; } mediaAlunos = acumulador / 7; } int calculoMenor() { for(k = 0; k < 7; k++) { if(menor == 0) { menor = media[k]; strcpy(nomeMenor,nome[k]); } if(media[k] < menor) { menor = media[k]; strcpy(nomeMenor,nome[k]); } } for(k = 0; k < 7; k++) { if (media[k] == 0) { strcpy(nomeMenor,nome[k]); } } } int entradas() { while(j < 7) { printf("Digite o nome\n"); scanf("%s",&nome[j]); fflush(stdin); printf("Digite a media\n"); scanf("%f",&media[j]); fflush(stdin); j++; } } int impressao() { i = 0; while(i < 7) { printf("%s %.2f\n",nome[i],media[i]); i++; } printf("A quantidade de notas menores que 6 e %d\n",menores6); printf("O nome do maior e %s\n",nomeMaior); printf("O nome do menor e %s\n",nomeMenor); printf("A media dos alunos %.2f",mediaAlunos); } int main() { entradas(); system("cls"); calcularMedia(); calculoMaior(); calculoMenor(); impressao(); return 0; }
C
/* * File: main.c * Author: zh99998 * * Created on 2014年3月9日, 上午9:18 */ #include <stdio.h> #include <stdbool.h> //bool #include <assert.h> //assert #include <string.h> //memset, memcpy #include <math.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> #include <iconv.h> #include <opencc/opencc.h> #include "cp_strlen_utf8.c" #include "word_statistics.h" //配置 const int max_length = 6; //最大长度 const int min_frequencies = 20; //最小词频 const double min_cohesion = 300; //最小凝固度, 参考 http://www.matrix67.com/blog/archives/5044 const double min_entropy = 1; //自由程度, 同上 const size_t utf8_max_char_length = 6; //UTF-8 编码一个字符最大长度 int suffix_compare(const ucs4_t **ptr1, const ucs4_t **ptr2) { //偷个懒用双字节比较, 反正都是中文应该没问题的吧.. return memcmp(*ptr1, *ptr2, (max_length+1) * sizeof (ucs4_t)); } int suffix_compare_left(const ucs4_t **ptr1, const ucs4_t **ptr2){ for(int i=0; i<=max_length; i++){ if(*((*ptr1) - i) < *((*ptr2) - i)){ return -1; }else if(*((*ptr1) - i) > *((*ptr2) - i)){ return 1; } } return 0; } int word_compare(const word *key, const word_statistics *elem){ //同上 return memcmp(key->start, elem->word, key->length * sizeof (ucs4_t)); } int main(int argc, char** argv) { if (argc == 1) { puts("Usage: nekoime-analyser files"); return (EXIT_FAILURE); } iconv_t iconv_input = iconv_open("UTF-32//IGNORE", " UTF-8"); iconv_t iconv_output = iconv_open("UTF-8//IGNORE", "UTF-32"); opencc_t opencc = opencc_open(OPENCC_DEFAULT_CONFIG_TRAD_TO_SIMP); int total_count = 0; int articles_count = argc - 1; size_t articles_length[articles_count]; ucs4_t * articles[articles_count]; for (int i = 1; i < argc; i++) { //i: 文件 uint8_t * file; int origin_count; int count; struct stat sb; int fd = open(argv[i], O_RDONLY); fstat(fd, &sb); // 取得文件大小 file = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (file == MAP_FAILED) // 判断是否映射成功 return EXIT_FAILURE; // 转换 UTF-8 到 UTF-32 origin_count = cp_strlen_utf8(file); size_t inbytesleft = sb.st_size; size_t outbytesleft = origin_count * sizeof (ucs4_t); size_t conv_result; ucs4_t *article_origin = malloc(outbytesleft); conv_result = iconv(iconv_input, (char**) &file, &inbytesleft, (char**) &article_origin, &outbytesleft); file -= sb.st_size; article_origin -= origin_count; // 去除非中文字符 ucs4_t *article_cleaned = malloc(origin_count * sizeof (ucs4_t)); ucs4_t *article_cleaned_current = article_cleaned; count = 0; for (int j = 0; j < origin_count; j++) { //j: 在原始文章中的序号 if ((article_origin[j] >= 0x4E00) && (article_origin[j] <= 0x9FA5)) { *article_cleaned_current = article_origin[j]; article_cleaned_current++; count++; } } total_count += count; free(article_origin); // 繁体转简体 ucs4_t *article = malloc(count * sizeof (ucs4_t)); size_t inbufleft = count; size_t outbufleft = count; opencc_convert(opencc, &article_cleaned, &inbufleft, &article, &outbufleft); article_cleaned -= count - inbufleft; article -= count - outbufleft; free(article_cleaned); articles[i - 1] = article; articles_length[i - 1] = count; } ucs4_t **sorted_index = malloc(total_count * sizeof (ucs4_t*)); ucs4_t **sorted_index_left = malloc(total_count * sizeof (ucs4_t*)); ucs4_t **sorted_index_current = sorted_index; for (int i = 0; i < articles_count; i++) { //i: 文章 for (int j = 0; j < articles_length[i]; j++) { //j: 文章中的字 *sorted_index_current = articles[i] + j; *sorted_index_current++; } } memcpy(sorted_index_left, sorted_index, total_count * sizeof (ucs4_t*)); qsort(sorted_index, total_count, sizeof (size_t), (int (*)(const void *, const void *))suffix_compare); qsort(sorted_index_left, total_count, sizeof (size_t), (int (*)(const void *, const void *))suffix_compare_left); word_statistics * words[max_length]; word_statistics * words_current[max_length]; size_t word_statistics_count[max_length]; int *right_neighbors[max_length]; int *left_neighbors[max_length]; int *right_neighbors_current[max_length]; int *left_neighbors_current[max_length]; for (int i = 0; i < max_length; i++) { //i: 词长-1 left_neighbors_current[i] = left_neighbors[i] = malloc(total_count * sizeof (int)); *left_neighbors_current[i] = 0; right_neighbors_current[i] = right_neighbors[i] = malloc(total_count * sizeof (int)); *right_neighbors_current[i] = 0; words_current[i] = words[i] = malloc(total_count * sizeof (word_statistics)); words_current[i]->word = sorted_index[0]; words_current[i]->count = 0; words_current[i]->left_neighbors = left_neighbors_current[i]; words_current[i]->right_neighbors = right_neighbors_current[i]; } ucs4_t *last_word = sorted_index[0]; //因为计算长度 max_length 的词的邻字时已经没有 words_current 可用了 for (int i = 0; i < total_count; i++) { //i: 字 bool different = false; for (int j = 0; j < max_length; j++) { //j: 词长-1 if (different || (*(sorted_index[i] + j) != *(words_current[j]->word + j))) { if (j != 0) { right_neighbors_current[j - 1]++; (*right_neighbors_current[j - 1]) = 1; } if (!different) { different = true; } words_current[j]++; words_current[j]->word = sorted_index[i]; words_current[j]->count = 1; //因为遍历到下一个长度的时候right_neighbors_current[j]才会++, 现在这里还是旧词的邻字, 所以要+1 words_current[j]->right_neighbors = right_neighbors_current[j]+1; } else { words_current[j]->count++; if (j != 0) { (*right_neighbors_current[j - 1])++; } } } // 长度 max_length 的词的邻字 if (different || (*(sorted_index[i] + max_length) != *(last_word + max_length))) { last_word = sorted_index[i]; right_neighbors_current[max_length - 1]++; (*right_neighbors_current[max_length - 1]) = 1; }else{ (*right_neighbors_current[max_length - 1])++; } } for (int i = 0; i < max_length; i++){ word_statistics_count[i] = words_current[i] - words[i] + 1; words_current[i] = NULL; } //左邻字 last_word = sorted_index_left[0]; for (int i = 0; i < total_count; i++) { //i: 字 bool different = false; for (int j = 0; j < max_length; j++) { //j: 词长-1 if (different || (words_current[j] == NULL) || (*(sorted_index_left[i] - j) != *(words_current[j]->word))) { if (j != 0 ) { left_neighbors_current[j - 1]++; (*left_neighbors_current[j - 1]) = 1; } if (!different) { different = true; } word word; word.start = sorted_index_left[i] - j; word.length = j+1; words_current[j] = bsearch(&word, words[j], word_statistics_count[j], sizeof(word_statistics), (int (*)(const void *, const void *))word_compare); if(words_current[j] == NULL){ //涉及到边界问题 break; } words_current[j]->left_neighbors = left_neighbors_current[j]+1; }else{ if (j != 0) { (*left_neighbors_current[j - 1])++; } } } // 长度 max_length 的词的邻字 if (different || (*(sorted_index_left[i] - max_length) != *(last_word - max_length))) { last_word = sorted_index_left[i]; left_neighbors_current[max_length - 1]++; (*left_neighbors_current[max_length - 1]) = 1; }else{ (*left_neighbors_current[max_length - 1])++; } } //words_current[i] //开始计算! uint8_t *output = malloc((max_length*utf8_max_char_length+1) * sizeof(uint8_t)); for (int i = 1; i < max_length; i++) { //i: 词长-1 for(int j=0; j<word_statistics_count[i]; j++){ //词频 if(words[i][j].count < min_frequencies){ continue; } //右邻字信息熵 double right_entropy = 0; right_neighbors_current[i] = words[i][j].right_neighbors; for(int count=words[i][j].count; count>0; right_neighbors_current[i]++){ double p = (double)*right_neighbors_current[i] / (words[i][j].count); right_entropy += -log(p) * p; count -= *right_neighbors_current[i]; } if(right_entropy < min_entropy){ continue; } //左邻字信息熵 double left_entropy = 0; left_neighbors_current[i] = words[i][j].left_neighbors; for(int count=words[i][j].count; count>0;left_neighbors_current[i]++){ double p = (double)*left_neighbors_current[i] / (words[i][j].count); left_entropy += -log(p) * p; count -= *left_neighbors_current[i]; } if(left_entropy < min_entropy){ continue; } //凝固 bool flags[i]; //true = 新开一个词; false = 连在最后一个词上 memset(flags, false, i-1); flags[i-1]=true; double best_p = 0; while(true){ //分隔词 word word = {words[i][j].word, 1}; double p = 1; for(int k = 0; k < i; k++) //k: 分隔词里的字 { if(!flags[k]){ word.length++; }else{ word_statistics *statistics = bsearch(&word, words[word.length-1], word_statistics_count[word.length-1], sizeof(word_statistics), (int (*)(const void *, const void *))word_compare); assert(statistics); p *= (double)(statistics->count) / total_count; word.start += word.length; word.length = 1; } } word_statistics *statistics = bsearch(&word, words[word.length-1], word_statistics_count[word.length-1], sizeof(word_statistics), (int (*)(const void *, const void *))word_compare); assert(statistics); p *= (double)(statistics->count) / total_count; if(p > best_p){ best_p = p; } int l = i-1; while(l >= 0) { if(flags[l] == false) // have we tried all possible status of l? { flags[l] = true; // status switch, as we only have 2 status here, I use a boolean rather than an array. break; // break to output the updated status, and further enumeration for this status change, just like a recursion } else // We have tried all possible cases for l-th number, now let's consider the previous one { flags[l] = false; // resume l to its initial status l--; // let's consider l-1 } } if(l < 0) break; // all the numbers in the set has been processed, we are done! } double cohesion = (double)(words[i][j].count) / total_count / best_p; if(cohesion < min_cohesion){ continue; } // 转换 UTF-32 到 UTF-8 size_t inbytesleft = (i+1) * sizeof(ucs4_t); size_t outbytesleft = (max_length*utf8_max_char_length+1) * sizeof(uint8_t); size_t conv_result; conv_result = iconv(iconv_output, (char**) &(words[i][j].word), &inbytesleft, (char**) &output, &outbytesleft); assert(inbytesleft == 0); words[i][j].word -= i+1; *output = '\0'; output -= (max_length*utf8_max_char_length+1) - outbytesleft / sizeof(uint8_t); printf("%s %d %g %g\n", output, words[i][j].count, cohesion, left_entropy < right_entropy ? left_entropy : right_entropy); } } return (EXIT_SUCCESS); }
C
#ifndef STACK_H #define STACK_H #include <stdlib.h> /** * Struct for Node. */ typedef struct Node { void * _data; // pointer to anything struct Node * _next; } Node; /** * Struct for stack. */ typedef struct Stack { Node * _top; size_t _elementSize; // we need that for memcpy } Stack; /** * Creates a new stack and allocates it in the memory using the given size. * @param elementSize the size of the stack to be allocated. * @return a new allocated stack. */ Stack* stackAlloc(size_t elementSize); /** * receives a pointer to a stack and frees it from the memory. * @param stack The stack to be freed. */ void freeStack(Stack** stack); /** * Pushes a given value to a given stack. * @param stack The stack were the value will be pushed. * @param data The data to be pushed to the stack. */ void push(Stack* stack, void *data); /** * Pops a value from a given stack, saves the value to a given destination and frees it from the memory. * @param stack The stack that will be popped. * @param headData The destination were the value popped value will be saved. */ void pop(Stack* stack, void *headData); /** * Checks if a given stack is empty. * @param stack The stack to be checked. * @return true if the stack is empty, false otherwise. */ int isEmptyStack(Stack* stack); #endif
C
/* JTSK-320112 a1_p2.c Zihan Qi z.qi@jacobs-university.de */ #include <stdio.h> #define DET_BIT(C) (C&1) int main(){ unsigned char c; scanf("%c",&c); printf("The decimal representation is: %d\n",c); printf("The least significant bit is: %d\n",DET_BIT(c)); return 0; }
C
/** @file * Funkcje potrzebne do implementacji funkcji addRoad. * * @author Sebastian Miller * @date 28.04.2019 */ #ifndef DROGI_ADD_ROAD_H #define DROGI_ADD_ROAD_H #include "map.h" #include <stdlib.h> /** @brief Główna część funkcji addRoad * Funkcja wywoływana w funkcji addRoad, gdy w podanych parametrach nie ma błędów. * * @param[in] map – wskaźnik na strukturę przechowującą mapę dróg; * @param[in] city1 – wskaźnik na napis reprezentujący nazwę miasta; * @param[in] city2 – wskaźnik na napis reprezentujący nazwę miasta; * @param length - długość, jaką ma mieć nowa droga; * @param builtYear - rok budowy nowej drogi; * @return Wartość @p true, jeśli dodawanie nowej drogi zakończyło się pomyślnie, * @p false, jeśli wystąpił jeden z błędów opisanych przy addRoad; */ bool initializeRoad(Map *map, const char *city1, const char *city2, unsigned length, int builtYear); /** @brief Dodaje drogę lub naprawia ją jeśli istnieje * Tworzy zadaną drogę, jeśli jest to możliwe, lub naprawia * ją. Jeśli miasta nie istnieją, to je też tworzy. * * @param map - wskaźnik na mapę; * @param city1 - wskaźnik na napis będący nazwą miasta 1; * @param city2 - wskaźnik na napis będący nazwą miasta 2; * @param length - oczekiwana długość drogi; * @param year - oczekiwany rok budowy; * @param citiesAdded - zmienna zliczająca miasta dodane w przebiegu * funkcji newRouteFromDescription * @param roadsAdded - zmienna zliczająca miasta dodane w przebiegu * funkcji newRouteFromDescription * @return Wskaźnik na stworzoną lub naprawioną drogę. NULL w przypadku błędu. */ RoadSeg* addOrRepairRoad(Map *map, const char *city1, const char *city2, unsigned length, int year, size_t* citiesAdded, size_t* roadsAdded); #endif //DROGI_ADD_ROAD_H
C
#include <stdio.h> #include <stdlib.h> int main(int argc, char** args) { unsigned int n, mask, a[16], at[16]; scanf("%x",&n); for (int i = 0;i < 16;i++){ a[i] = 0; at[i] = 0; } mask = 1; for (int i = 0;i < 16;i++){ if ((mask & n) != 0) { a[15-i] = 1; } mask *= 2; } /* for (int i = 0;i < 4;i++){ for (int j = 0;j < 4;j++){ printf("%d ", a[i*4+j]); } printf("\n"); }*/ for (int i = 0;i < 4;i++){ for (int j = 0;j < 4;j++){ at[4*i+j] = a[4*j+i]; } } /* for (int i = 0;i < 4;i++){ for (int j = 0;j < 4;j++){ printf("%d ", a[i*4+j]); } printf("\n"); }*/ for (int i = 0;i < 4;i++){ n = 0; mask = 8; for (int j = 0;j < 4;j++){ n += at[4*i+j] * mask; mask /= 2; } printf("%x", n); } // printf("\n"); printf("\n"); return 0; }
C
#include <stdio.h> #include <unistd.h> #include <sys/types.h> int main(void) { pid_t pid1, pid2, pid3; /* process id */ // printf("just one process before the fork()\n"); pid1 = fork(); // pid2 = fork(); // pid3 = fork(); if(pid1 == 0) { sleep(2); printf("Process1 ID %d\n", getpid()); } else { pid2 = fork(); if(pid2 == 0) { sleep(3); printf("Process2 ID %d\n", getpid()); } else { pid3 = fork(); if(pid3 == 0) { sleep(4); printf("Process3 ID %d\n", getpid()); } else { sleep(1); printf("\nParent Process: \n"); printf("PPID: %d\n", getpid()); printf("\nChild Processes: \n"); } } } // else if(pid > 0) // printf("I am the parent process\n"); // else // printf("The fork() has failed\n"); // printf("Process 1: %d\nProcess 2: %d\n", pid1, pid2); // printf("Process1: %d\n", pid1); sleep(5); return 0; }
C
#include "candidate.h" #include "types.h" struct candidate *alocateCandidates(int numberCan){ struct candidate *candidates = NULL; candidates = (Candidate*)malloc(numberCan * sizeof(Candidate)); for (int i = 0; i < numberCan; i++) { candidates[i].id = -1; candidates[i].n = numberCan; candidates[i].grade = -1; candidates[i].numberOfApplications = -1; candidates[i].list = NULL; } return candidates; } struct candidate *initCandidates(FILE *filePointerCan, University *universities){ int numberCan; fscanf(filePointerCan, "%d", &numberCan); // // Aloca memória para os candidates struct candidate *candidates = alocateCandidates(numberCan); int aux; for (int i = 0; i < numberCan; i++) { candidates[i].id = i; fscanf(filePointerCan, "%d", &candidates[i].numberOfApplications); fscanf(filePointerCan, "%d", &candidates[i].grade); for (int j = 0; j < candidates[i].numberOfApplications; j++) { fscanf(filePointerCan, "%d", &aux); insert(&candidates[i].list, &universities[aux-1]); } } fclose(filePointerCan); return candidates; } void printCandidate(void *ptr){ struct candidate *c = ptr; printf("struct candidate %d:\tGrade: %d\tNumber of Aplications: %d\n", c->id, c->grade, c->numberOfApplications); } void printCandidates(struct candidate *candidates){ for (int i = 0; i < candidates[0].n; i++) { printf("struct candidate %d:\tGrade: %d\tNumber of Aplications: %d\n", candidates[i].id, candidates[i].grade, candidates[i].numberOfApplications); printList(candidates[i].list, &printUniversity); } } void freeCandidates(struct candidate *candidates){ for (int i = 0; i < candidates[0].n; i++) { freeNode(candidates[i].list); } free(candidates); } int compareGrades(void *a, void *b){ struct candidate *c = a; struct candidate *d = b; if ( c->grade > d->grade ) return -1; if ( c->grade == d->grade){ if(c->id > d->id){ return -1; } else if (c->id < d->id){ return 1; } } if ( c->grade < d->grade ) return 1; }
C
#include <stdio.h> #include <stdlib.h> int* newArray(int size) { int* ret = NULL; int* auxInt; if(size>0) { auxInt = malloc(sizeof(int)*size); if(auxInt != NULL) { ret = auxInt; } } return ret; } int initArray(int* arrayInt,int limite,int valor) { int ret=-1; int i; if(arrayInt != NULL && limite > 0) { for(i=0;i<limite;i++) { *(arrayInt+i)=valor; } ret=0; } return ret; } int showArray(int* arrayInt,int limite) { int ret=-1; int i; if(arrayInt != NULL && limite > 0) { for(i=0;i<limite;i++) { printf("\n%p - [%d] - %d\n",(arrayInt+i),i,*(arrayInt+i)); } ret=0; } return ret; } int deleteArray(int* arrayInt,int size) { int ret=-1; if(arrayInt != NULL) { free(arrayInt); ret=0; } return ret; } int main() { int* arrayEnteros; arrayEnteros = newArray(100); initArray(arrayEnteros,100,1024); showArray(arrayEnteros,100); deleteArray(arrayEnteros,100); return 0; }
C
/* * Function: float Vfunc(int which, float *v1, float *v2, float *vresult, float scalar) * A Jack-of-all-trades vector function. * Input variables: * which: chooses the vector function to compute * v1,v2: input vectors: float v1[3], v2[3] * vresult: output vector, float vresult[3] * scalar: input scalar * * Note: some arguments are ignored for some functions, and so can be given the value NULL * * Assume, for documentation below, the following variables are already declared: * float a1[3], a2[3], a3[3], s; * * Functions: * * Subtracting vectors: * which == 2: vresult = v1 - v2 * Vfunc(2,a1,a2,a3,0); // a3 = a1 - a2 * * Unit vector: * which == 3: vresult = unit vector in direction of v1 * if s = Vfunc(3,a1,NULL,a3,0); // a3 = a1 / |a1| * Note: returns 0.0 if |a1| == 0, then sets a3 to the zero vector * returns 1.0 under normal circumstances * * Scalar times vector: * which == 4: vresult = s * v1 * Vfunc(4,a1,NULL,a3,s); // a3 = s * a1 * * Dot product: * which == 5: returns v1 * v2 * s = Vfunc(5,a1,a2,a3,0); // returns dot product of a1 and a2 * * Distance between two vectors (as positions): * which == 6: returns |v1-v2| * s = Vfunc(6,a1,a2,NULL,0); // s = length(a1-a2) * * Angle between 2 vectors (in degrees, not radians): * which == 8: returns angle between v1 and v2 * float angle = Vfunc(8,a1,a2,NULL,0); * * Unit vector pointing from v1 to v2: * which == 9: vresult is the unit vector pointing from position v1 toward position v2 * Vfunc(9,a1,a2,a3,0); // a3 will be the unit vector * * Rotate v1 towards v2: * which == 10: vresult is vector v1 rotated scalar degrees towards v2 * scalar degrees must be less than the angle between the two vectors * Vfunc(10,v1,v2,result,angle); * Note: returns 0 if successful, 1 if the angle is too large */ /* Copy function header: float Vfunc(int which, float *v1, float *v2, float *vresult, float scalar) { */ #define prvect(msg,p) printf("%s (%f,%f,%f)\n",msg,p[0],p[1],p[2]) int i = 0; float v3[3]; //1 and 2 are no longer needed if (which == 2) { // vresult = v1 - v2 for (; i < 3; ++i) vresult[i] = v1[i] - v2[i]; } if (which == 3) { // vresult = v1 / |v1| memcpy(vresult, v1, sizeof(float)*3); mathVecNormalize(vresult,3); } if (which == 4) { // vresult = scalar * v1 for (; i < 3; ++i) vresult[i] = scalar * v1[i]; } if (which == 6) { // returns distance between v1 and v2 Vfunc(2,v1,v2,v3,0); // v3 = v1 - v2 return mathVecMagnitude(v3,3); } if (which == 8) { // angle between two vectors return acosf(mathVecInner(v1,v2,3)/(mathVecMagnitude(v1,3)*mathVecMagnitude(v2,3))) * 180.0 / PI; } if (which == 9) { // unit vector pointing from v1 toward v2 Vfunc(2,v2,v1,v3,0); Vfunc(3,v3,NULL,vresult,0); } if (which == 10) { // rotated vector v1 towards v2 at scalar degrees float ang = scalar*PI/180.0; float u[3]; float c = cosf(ang); float s = sinf(ang); if (Vfunc(8,v3,v1,NULL,0) < Vfunc(8,v1,v2,NULL,0) && Vfunc(8,v3,v2,NULL,0) < Vfunc(8,v1,v2,NULL,0)) { c = cosf(-1*ang); s = sinf(-1*ang); } mathVecNormalize(v1,3); mathVecNormalize(v2,3); if (scalar > Vfunc(8,v1,v2,NULL,0)) { return 1; } mathVecCross(u,v1,v2); mathVecNormalize(u,3); v3[0] = (v1[0]*(c + u[0] * u[0] * (1-c)) + v1[1]*(u[0] * u[1] * (1-c) - u[2] * s) + v1[2]*(u[0] * u[2] * (1-c) + u[1] * s)); v3[1] = (v1[0]*(u[0] * u[1] * (1-c) + u[2] * s) + v1[1]*(c + u[1] * u[1] * (1-c)) + v1[2]*(u[1] * u[2] * (1-c) - u[0] * s)); v3[2] = (v1[0]*(u[0] * u[2] * (1-c) - u[1] * s) + v1[1]*(u[1] * u[2] * (1-c) + u[0] * s) + v1[2]*(c + u[2] * u[2] * (1-c))); memcpy(vresult,v3,sizeof(float)*3); } return 0; //}
C
/********************************************/ /* Trampoline functions */ /* Use these to call functions in other */ /* banks. */ /* 2015 - Danny Lousberg */ /********************************************/ #include "bankswitch.h" extern unsigned int _data; extern unsigned int _data_end; // We can't use "bankbase" here, since it hasn't been initialized yet. #define BSWITCH_0 *((volatile unsigned int*)0x6000) #define BSWITCH_4 *((volatile unsigned int*)0x6008) void init_data_section() { volatile unsigned int *src = (unsigned int*)0x6000; volatile unsigned int *dst = &_data; // Switch to bank containing initialization data BSWITCH_4 = 1; // Copy .data from ROM to higher memory expansion while (dst < &_data_end) *dst++ = *src++; // Switch back to bank 0 BSWITCH_0 = 1; }
C
/* Para ello, el programa deber dar la opcin de cambiar la clave cuando lo desee el usuario */ #include <18F4520.h> #use delay(clock=8000000) #use fast_io(B) #include "LCDeasy.c" #include "KBD2.c" //Control del teclado matricial #INT_RB char tecla; int8 i,j,a,c,Salida; const int Intro[]={50,52,49,48}; int digitos[]; int entrada[]; char f[]; int Clave(){ lcd_send_byte(0, 1); //Borra LCD lcd_send_byte(0, 2); //Posicin inicial printf(lcd_putc,"ENTER PASSWORD:\n"); for(i=0;i<=3;i++){ f=0; while (f==0) f=kbd_getc(); //printf(lcd_putc,"%u ",f); write_eeprom(i+4,f); //entrada[i]=read_eeprom printf(lcd_putc,"%c ",read_eeprom(i+4)); if(i==3){ delay_ms(200); lcd_send_byte(0, 1); //Borra LCD lcd_send_byte(0, 2); //Posicin inicial printf(lcd_putc,"Comprobacion:"); delay_ms(100); j=0; a=0; printf(lcd_putc,"\n"); while(j<4){ //printf(lcd_putc,"%u ",read_eeprom(j+4)); //if(entrada[j]==Intro[j]){ if(read_eeprom(j)==read_eeprom(j+4)){ a=a+1; } j++; } //printf(lcd_putc,"\n"); if(a==4){ printf(lcd_putc,"Clave correcta"); Salida=1; } else { printf(lcd_putc,"Clave Incorrecta"); Salida=0; } }//if }//For delay_ms(500); return Salida; } void Nueva_Clave(void){ lcd_send_byte(0, 1); //Borra LCD lcd_send_byte(0, 2); //Posicin inicial printf(lcd_putc,"Nueva Clave\n"); for(i=0;i<=3;i++){ f=0; while (f==0) f=kbd_getc(); //printf(lcd_putc,"%u ",f); write_eeprom(i,f); //entrada[i]=read_eeprom printf(lcd_putc,"%c ",read_eeprom(i)); delay_ms(200); } } void main(){ enable_interrupts(INT_RB); enable_interrupts(GLOBAL); ext_int_edge(H_to_L); lcd_init(); for(i=0;i<=3;i++){ write_eeprom(i,Intro[i]); } //printf(lcd_putc,"Clave inicial\n"); for(i=0;i<=3;i++){ digitos[i]=read_eeprom(i); //printf(lcd_putc,"%d ",digitos[i]); } //lcd_init();// printf(lcd_putc,"Pulsa teclas"); while(TRUE){ c=0; lcd_send_byte(0, 1); //Borra LCD lcd_send_byte(0, 2); //Posicin inicial do{ printf(lcd_putc,"Tecla'+'->No cambiar\nTecla'-'->Cambiar"); c=kbd_getc(); }while(c==0);; if(c==43){ //Cambiar Clave(); if (Salida==1) sleep(); } else if(c==45){ Nueva_Clave(); } else{ lcd_send_byte(0, 1); //Borra LCD lcd_send_byte(0, 2); //Posicin inicial printf(lcd_putc,"Marca una opcion\nvalida"); delay_ms(500); } } //True } //Main
C
/* ** EPITECH PROJECT, 2020 ** PSU_42sh_2019 ** File description: ** pipe.c */ #include <sys/wait.h> #include "common.h" #include "exec.h" static void redirect(int oldfd, int newfd) { if (oldfd != newfd) { if (dup2(oldfd, newfd) != -1) close(oldfd); else exit(84); } } static void child_father(int fd[2], head_t *head, int in_fd) { int status = 0; switch (fork()) { case -1: dprintf(2, "%s: %s.\n", "fork", strerror(errno)); exit(84); case 0: close(fd[0]); redirect(in_fd, STDIN_FILENO); redirect(fd[1], STDOUT_FILENO); set_exec(head, 0); exit(0); default: close(fd[1]); close(in_fd); head->cmd = head->cmd->next; exec_pipe(head, fd[0]); waitpid(in_fd, &status, 0); } } void exec_pipe(head_t *head, int in_fd) { int fd[2]; int du = dup(0); if (head->cmd->next == NULL || strcmp("|", head->cmd->sep) != 0) { redirect(in_fd, STDIN_FILENO); if (head->cmd->sep != NULL && (strcmp(head->cmd->sep, ">") == 0 || strcmp(head->cmd->sep, ">>") == 0)) { my_redirection(head, 0); head->cmd = head->cmd->next; return; } set_exec(head, 0); } else { if (pipe(fd) == -1) { dprintf(2, "%s: %s.\n", "pipe", strerror(errno)); exit(84); } child_father(fd, head, in_fd); } dup2(du, 0); }
C
#include<stdio.h> #include<stdlib.h> struct data { struct data * prev; int cylinder; struct data * next; }; int size,start,maxC; void sort(struct data*); void add(struct data**, int value); struct data* insert(struct data **,int); void delete(struct data **,struct data *); struct data* copy(struct data *); int FCFS(struct data*); int SSTF(struct data*); int SCAN(struct data*); int CSCAN(struct data*); int LOOK(struct data*); int CLOOK(struct data*); int main() { printf("Enter the total number of cylinders:"); scanf("%d",&maxC); printf("Enter the starting position of disk head:"); scanf("%d",&start); printf("Enter the size of the list:"); scanf("%d",&size); printf("Enter the cylinder values\n"); int i,value; struct data * head = NULL; for(i=0;i<size;i++) { scanf("%d",&value); add(&head,value); } struct data * fcfs = copy(head); printf("FCFS=%d",FCFS(fcfs)); sort(head); printf("\n"); struct data * sstf = copy(head); printf("SSTF=%d",SSTF(sstf)); printf("\n"); struct data * scan = copy(head); printf("SCAN=%d",SCAN(scan)); printf("\n"); struct data * cscan = copy(head); printf("CSCAN=%d",CSCAN(cscan)); printf("\n"); struct data * look = copy(head); printf("LOOK=%d",LOOK(look)); printf("\n"); struct data * clook = copy(head); printf("CLOOK=%d",CLOOK(clook)); printf("\n"); return 0; } struct data* copy(struct data *head) { struct data * new = NULL, *temp =head; int i; for(i=0;i<size;i++) { add(&new,temp->cylinder); temp=temp->next; } return new; } void add(struct data ** head, int val) { struct data* new_node = (struct data*)malloc(sizeof(struct data)); struct data* last = *head; new_node->cylinder = val; new_node->next = NULL; if (*head == NULL) { new_node->prev = NULL; *head = new_node; return; } while (last->next != NULL) last = last->next; last->next = new_node; new_node->prev = last; return; } struct data * insert(struct data ** head, int val) { struct data* new_node = (struct data*)malloc(sizeof(struct data)); new_node->cylinder = val; struct data * temp = *head; if(temp->cylinder>val) { new_node->next=temp; temp->prev=new_node; *head = new_node; return new_node; } while(temp->next!=NULL && temp->next->cylinder<val) { temp=temp->next; } new_node->next = temp->next; temp->next = new_node; new_node->prev = temp; if (new_node->next != NULL) new_node->next->prev = new_node; return new_node; } void delete(struct data ** head, struct data * del) { if (*head == NULL || del == NULL) return; if (*head == del) *head = del->next; if (del->next != NULL) del->next->prev = del->prev; if (del->prev != NULL) del->prev->next = del->next; free(del); return; } void sort(struct data * head) { struct data *ptr1, *ptr2; int i, j, temp; ptr1 = head; ptr2 = head; for (i = 0; i < size; i++) { temp = ptr1->cylinder; for (j = 0; j < i; j++) ptr2 = ptr2->next; for (j = i; j > 0 && ptr2->prev->cylinder > temp; j--) { ptr2->cylinder = ptr2->prev->cylinder; ptr2 = ptr2->prev; } ptr2->cylinder = temp; ptr2 = head; ptr1 = ptr1->next; } } int FCFS(struct data * head) { struct data * temp = head; int sum = abs(start-(head->cylinder)); while(temp->next!=NULL) { sum+=abs((temp->cylinder)-(temp->next->cylinder)); temp=temp->next; } return sum; } int SSTF(struct data * head) { struct data *temp = head; temp=insert(&temp,start); int sum=0; //code case where we are passed a list of size 1 while(temp!=NULL) { if(temp->next==NULL && temp->prev==NULL) { return sum; } else if(temp->next==NULL) { sum+=abs(temp->cylinder - temp->prev->cylinder); temp=temp->prev; delete(&head,temp->next); } else if( (temp->prev==NULL) || (abs(temp->cylinder - temp->next->cylinder) < abs(temp->cylinder - temp->prev->cylinder))) { sum+=abs(temp->cylinder - temp->next->cylinder); temp=temp->next; delete(&head,temp->prev); } else { sum+=abs(temp->cylinder - temp->prev->cylinder); temp=temp->prev; delete(&head,temp->next); } } return sum; } int SCAN(struct data* head) { struct data *temp = head,*t; //explicitly add one of two end values to list to handle SCAN because it bounces to the bounds and we have to repeat the first end value again on the bounce temp=insert(&temp,start); int sum=0; if (maxC - temp->cylinder < temp->cylinder) { t = insert(&head, maxC); while(temp!=NULL) { if(temp->next==NULL && temp->prev==NULL) { return sum; } else if(temp->next==NULL) { temp=temp->prev; sum+=abs(temp->cylinder - temp->next->cylinder); delete(&head,temp->next); } else { sum+=abs(temp->cylinder - temp->next->cylinder); temp=temp->next; delete(&head,temp->prev); } } } else { t=insert(&head,0); while(temp!=NULL) { if(temp->next==NULL && temp->prev==NULL) { return sum; } else if(temp->prev==NULL) { temp=temp->next; sum+=abs(temp->cylinder - temp->prev->cylinder); delete(&head,temp->prev); } else { sum+=abs(temp->cylinder - temp->prev->cylinder); temp=temp->prev; delete(&head,temp->next); } } } return sum; } int CSCAN(struct data* head) { struct data* temp = head,*d; temp=insert(&temp,start); int sum=0; if (maxC - temp->cylinder < temp->cylinder) { while(temp!=NULL) { if(temp->next==NULL && temp->prev==NULL) { return sum; } else if(temp->next==NULL) { sum+=abs(temp->cylinder - maxC); d=temp; while(temp->prev!=NULL) { temp=temp->prev; } delete(&head,d); sum+=temp->cylinder; } else { temp=temp->next; sum+=abs(temp->cylinder - temp->prev->cylinder); delete(&head,temp->prev); } } } else { while(temp!=NULL) { if(temp->next==NULL && temp->prev==NULL) { return sum; } else if(temp->prev==NULL) //evaluates once { sum+=abs(temp->cylinder); d=temp; while(temp->next!=NULL) { temp=temp->next; } delete(&head,d); sum+=abs(temp->cylinder - maxC); } else { temp=temp->prev; sum+=abs(temp->cylinder - temp->next->cylinder); delete(&head,temp->next); } } } return sum; } int LOOK(struct data * head) { struct data *temp = head; temp=insert(&temp,start); int sum=0; if (maxC - temp->cylinder < temp->cylinder) { while(temp!=NULL) { if(temp->next==NULL && temp->prev==NULL) { return sum; } else if(temp->prev!=NULL && temp->next == NULL) { temp=temp->prev; sum+=abs(temp->cylinder - temp->next->cylinder); delete(&head,temp->next); } else { sum+=abs(temp->cylinder - temp->next->cylinder); temp=temp->next; delete(&head,temp->prev); } } } else { while(temp!=NULL) { if(temp->next==NULL && temp->prev==NULL) { return sum; } else if(temp->next!=NULL && temp->prev == NULL) { temp=temp->next; sum+=abs(temp->cylinder - temp->prev->cylinder); delete(&head,temp->prev); } else { sum+=abs(temp->cylinder - temp->prev->cylinder); temp=temp->prev; delete(&head,temp->next); } } } return sum; } int CLOOK(struct data* head) { struct data* temp = head; temp=insert(&temp,start); int sum=0; if (maxC - temp->cylinder < temp->cylinder) { while(temp!=NULL) { if(temp->next==NULL && temp->prev==NULL) { return sum; } else if(temp->next==NULL) { temp=temp->prev; //sum+=abs(temp->cylinder - temp->next->cylinder); delete(&head,temp->next); while(temp->prev!=NULL) temp=temp->prev; } else { temp=temp->next; sum+=abs(temp->cylinder - temp->prev->cylinder); delete(&head,temp->prev); } } } else { while (temp!=NULL) { if(temp->next==NULL && temp->prev==NULL) { return sum; } else if(temp->prev==NULL) { temp=temp->next; //sum+=abs(temp->cylinder - temp->prev->cylinder); delete(&head,temp->prev); while(temp->next!=NULL) temp=temp->next; } else { temp=temp->prev; sum+=abs(temp->cylinder - temp->next->cylinder); delete(&head,temp->next); } } } return sum; }
C
#include<conio.h> #include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct { int * matrix; int sizemax; } Graph; Graph createGraph(int sizemax); void addEdge(Graph graph, int v1, int v2); int adjacent(Graph graph, int v1, int v2); int getAdjacentVertices(Graph graph, int vertex, int* output); void dropGraph(Graph graph); int main() { int i, n, output[100]; Graph g = createGraph(100); addEdge(g, 0, 1); addEdge(g, 0, 2); addEdge(g, 1, 2); addEdge(g, 1, 3); n = getAdjacentVertices (g, 1, output); if (n==0) printf("No adjacent vertices of node 1\n"); else { printf("Adjacent vertices of node 1:", n); for (i=0; i<n; i++) printf("%5d", output[i]); } dropGraph(g); getch(); } Graph createGraph(int sizemax) { Graph g; g.sizemax = sizemax; g.matrix = (int*) malloc(sizemax*sizemax*sizeof(int)); return g; } void addEdge(Graph graph, int v1, int v2) { graph.matrix[v1*graph.sizemax+v2] = 1; graph.matrix[v2*graph.sizemax+v1] = 1; } int adjacent(Graph graph, int v1, int v2) { return graph.matrix[v1*graph.sizemax+v2]; } int getAdjacentVertices (Graph graph, int v, int* output) { int total = 0, i; for (i=0; i<graph.sizemax; i++) if (adjacent(graph, v, i)) output[total++] = i; return total; } void dropGraph(Graph graph) { free(graph.matrix); graph.matrix = NULL; graph.sizemax = 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_sort_dictionary.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: raamin <raamin@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/28 10:52:55 by raamin #+# #+# */ /* Updated: 2021/03/28 21:33:10 by raamin ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft.h" #include <unistd.h> #include <fcntl.h> #include <stdlib.h> int getline(int fd, char key[99], char value[99]) { int index; char car; index = 0; while (read(fd, &car, 1) > 0) { if ('0' <= car && car <= '9') key[index++] = car; else if ('a' <= car && car <= 'z') value[index++] = car; else if (car == ':') { key[index++] = 0; index = 0; } else if (car == '\n') { value[index++] = 0; index = 0; return (1); } } return (0); } int getdictionary(char *filename, int *size, char *dictionary[99][2]) { char key[99]; char value[99]; int fd; fd = open(filename, 0); *size = 0; if (fd < 0) { ft_putstr("Error\n"); return (0); } while (getline(fd, key, value) > 0) { if (ft_strlen(key) > 0 && ft_strlen(value) > 0) { dictionary[*size][0] = ft_strdup(key); dictionary[*size][1] = ft_strdup(value); (*size)++; } else ft_putstr("Dict Error\n"); } close(fd); return (*size); } int freedictionary(int size, char *dictionary[99][2]) { int i; i = 0; while (i < size) { free(dictionary[i][0]); free(dictionary[i][1]); i++; } return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "ArrayList.h" typedef struct{ long int dni; int turno; int atendido;//0 si no se lo atendio, 1 si esta atendido int tramite;//si es 0 es regular, si es 1 es urgente int uso; }Cliente; /** \brief Comprueba si se ingreso numeros en una cadena * \param aux[] Cadena a revisar * \return 0 si contiene caracteres, 1 si contiene solo numeros */ int isnumber(char aux[]); /** \brief Recibe una estructura y carga los datos * \param Cliente array[] La cadena de estructuras a cargar los datos en los campos * \param size El largo de la cadena de estructuras * \param tramite 0 si es tramite regular, 1 si es tramite urgente */ void cargaDatosEstructura(ArrayList* pArrayList, int tramite); /** \brief Muestra en pantalla las estructuras de clientes que no fueron atendidos * \param Cliente array[] La cadena de estructuras a mostrar en pantalla si su campo atendido es igual a 0 * \param size El largo de la cadena de estructuras */ void listar(ArrayList* pList); /** \brief Muestra en pantalla la estructura del cliente que tiene que ser atendido * \param Cliente array[] La cadena de estructuras a mostrar en pantalla si su campo atendido es igual a 0 * \param size Tamao del array de estructuras */ void mostrar(Cliente array[], int size); /** \brief Muestra en pantalla todos los campos del array d Estructuras * \param Cliente array[] La cadena de estructuras a mostrar en pantalla si su campo uso es igual a 1 * \param size Tamao del array de estructuras */ void proximoTurno(ArrayList* pList); /** \brief Ordena la cadena de Estructuras. Deja adelante las estructuras con el campo tramite en 1 * \param Cliente array[] La cadena de estructuras a ordenar * \param size Tamao del array de estructuras */ void ordenarEstructura(Cliente array[], int size); /** \brief Ordena la cadena de Estructuras por DNI en forma descendente * \param Cliente array[] La cadena de estructuras a ordenar * \param size Tamao del array de estructuras */ void ordenarEstructuraDni(Cliente array[], int size); Cliente* cliente_new(void);
C
#include <stdio.h> #include <string.h> typedef struct{ char nome[30]; char endereco[50]; char matricula[10]; char curso[30]; }tAluno; tAluno gAlunos[100]; unsigned int ConsultaAlunos(char *curso){ int i, cont=0; for(i=0; curso[i] != '\0'; i++){ if(strcmp(curso, gAlunos[i].curso) == 0){ ++cont; } } return cont; } int main(){ char consulta[30]; int n, i, x; printf("Digite a quantidade de cadastros: \n"); scanf("%d", &n); for(i=0; i<n; i++){ printf("***Aluno #%d***\n" "Nome: ", i+1); scanf("%s", gAlunos[i].nome); printf("Endereco: "); scanf("%s", gAlunos[i].endereco); printf("Matricula: "); scanf("%s", gAlunos[i].matricula); printf("Curso: "); scanf("%s*c", gAlunos[i].curso); } printf("Consulte os cadastros, digite o nome do curso: "); scanf("%s", consulta); x = ConsultaAlunos(consulta); printf("Numeros de cadastros: %d\n", x); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <sys/mman.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #define BUF_SIZE 64 #define PS_PL_ADDR 0x0000 #define PS_PL_VALUE 0x0001 #define PL_PS_ADDR 0x0002 #define PL_PS_VALUE 0x0003 #define PS_PL_SCCB_REQ 0x0007 #define PS_PL_SCCB_WR 0x0008 #define PS_PL_SCCB_WDATA 0x0009 #define PL_PS_SCCB_RDATA 0x0003 #define PL_PS_SCCB_BUSY 0x0004 uint8_t readReg(const uint16_t sub_address); void writeReg(const uint16_t sub_address, const uint8_t write_data); void sendReg(const uint16_t sub_address, const uint8_t data); uint32_t *map_addr; int main(void) { int uiofd; char buf[BUF_SIZE]; char option[BUF_SIZE]; // option (write, read or quit) uint16_t sub_address; uint8_t read_data, write_data; uiofd = open("/dev/uio0", O_RDWR); if (uiofd < 0) { printf("uio open failed. \n"); return 1; } map_addr = (uint32_t *)mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, uiofd, 0); if (!map_addr) { printf("mmap failed. \n"); return 1; } while (1) { printf("> Select read ('r') or write ('w'), 'q' to quit: "); fgets(option, BUF_SIZE, stdin); if (strncmp(option, "r", 1) == 0) { // input sub_address printf("> Sub-address (4 Bytes): 0x"); fgets(buf, BUF_SIZE, stdin); // convert string to hexadecimal sub_address = strtol(buf, NULL, 16); // send SCCB data to register read_data = readReg(sub_address); printf("Sub-address: 0x%04X, Read Data: 0x%02X \n\n", sub_address, read_data); } else if (strncmp(option, "w", 1) == 0) { // input sub_address printf("> Sub-address (4 Bytes): 0x"); fgets(buf, BUF_SIZE, stdin); // convert string to hexadecimal sub_address = strtol(buf, NULL, 16); // input write_data printf("> Write Data (2 Bytes): 0x"); fgets(buf, BUF_SIZE, stdin); // convert string to hexadecimal write_data = strtol(buf, NULL, 16); // send SCCB data to register writeReg(sub_address, write_data); printf("Sub-address: 0x%04X, Write Data: 0x%02X \n\n", sub_address, write_data); } else if (strncmp(option, "q", 1) == 0) { break; } } close(uiofd); return 0; } uint8_t readReg(const uint16_t sub_address) { const uint8_t id_address = 0x79; // ID Address of OV5640 for READ const uint32_t send_data = (id_address << 24) | (sub_address << 8) | 0x0; uint8_t read_data; // send read signal to sccb_if map_addr[PS_PL_ADDR] = PS_PL_SCCB_WR; map_addr[PS_PL_VALUE] = 1; // read // set SCCB data to PL map_addr[PS_PL_ADDR] = PS_PL_SCCB_WDATA; map_addr[PS_PL_VALUE] = send_data; // wait if sccb_if module is busy map_addr[PL_PS_ADDR] = PL_PS_SCCB_BUSY; while (map_addr[PL_PS_VALUE] != 0); // send SCCB data to sccb_if module map_addr[PS_PL_ADDR] = PS_PL_SCCB_REQ; map_addr[PS_PL_VALUE] = 1; // wait if sccb_if module is busy map_addr[PL_PS_ADDR] = PL_PS_SCCB_BUSY; while (map_addr[PL_PS_VALUE] != 0); usleep(300); // get read data map_addr[PL_PS_ADDR] = PL_PS_SCCB_RDATA; read_data = map_addr[PL_PS_VALUE]; // set reqest 0 map_addr[PS_PL_ADDR] = PS_PL_SCCB_REQ; map_addr[PS_PL_VALUE] = 0; return read_data; } void writeReg(const uint16_t sub_address, const uint8_t write_data) { const uint8_t id_address = 0x78; // ID Address of OV5640 for WRITE const uint32_t send_data = (id_address << 24) | (sub_address << 8) | write_data; // send read signal to sccb_if map_addr[PS_PL_ADDR] = PS_PL_SCCB_WR; map_addr[PS_PL_VALUE] = 0; // write // set SCCB data to sccb_if module map_addr[PS_PL_ADDR] = PS_PL_SCCB_WDATA; map_addr[PS_PL_VALUE] = send_data; // wait if sccb_if module is busy map_addr[PL_PS_ADDR] = PL_PS_SCCB_BUSY; while (map_addr[PL_PS_VALUE] != 0); // send SCCB data to sccb_if module map_addr[PS_PL_ADDR] = PS_PL_SCCB_REQ; map_addr[PS_PL_VALUE] = 1; usleep(300); // set reqest 0 map_addr[PS_PL_ADDR] = PS_PL_SCCB_REQ; map_addr[PS_PL_VALUE] = 0; } void sendReg(const uint16_t sub_address, const uint8_t data) { while (data != readReg(sub_address)) { writeReg(sub_address, data); usleep(300); } }
C
#include <unistd.h> #include <unistd.h> #include <stdlib.h> void ft_putchar(char c) { write(1,&c,1); } void ft_putstr(char *str) { while(*str) { ft_putchar(*str++); } } int ft_strlen(char *str) { int len = 0; while (str[len++]){;} return (--len); } int ft_wdmatch(char *s1, char *s2) { int len_s1 = ft_strlen(s1); int len_s2 = ft_strlen(s2); int i = -1; int j; int matched_j = 0; int count = 0; while(s1[++i]) { j = matched_j; while (++j < len_s2)//iterate through s1. If s1 letter is found in s2, set the new j start index to index of matched letter. Increase count by 1. If count equals the len of s1, return 1; { if (s2[j] == s1[i]) { count++; matched_j = j; if (count == len_s1) return (1); break; } } } return 0; } int main(int argc, char **argv) { if (argc == 3) if (ft_wdmatch(argv[1], argv[2])) ft_putstr(argv[1]); ft_putchar('\n'); return (0); } // printf(count:"%d len_s1:%d\n", count, len_s1);
C
#include "Shell.h" void running(){ char *input; scanf("%s",input); struct Command a = parse(input); printf("parse finished\n"); switch (a.sequence) { case 0: return 0; break; case 1: info(); break; default: break; } } void info(){ char *out = "XJCO2211 Simplified Shell by "; struct passwd *pwd = getpwuid(getuid()); fprintf(stdout,out); printf("%s\n",pwd->pw_name); }
C
/* @(#)indino.c 1.1 */ indino(tovax,fdo,fsize,size,num,blk) int tovax,fdo,num; long fsize,blk; long *size; { /* * This recursive subroutine converts the inode indirect blocks * by swapping the two words on longs. */ /* * tovax = 1 if converting to a vax format * fdo = output file descriptor * num = current number being converted * if num = 0 single indirect block * if num = 1 double indirect block * if num = 2 tripple indirec block * blk = block address of indirect block */ #include <stdio.h> /* local data */ long buff[256]; int in,out,i; /* Define a variable for running on VAX (simplifies code generation */ #ifdef vax #define ONVAX 1 #else #define ONVAX 0 #endif /* program */ /* See if any more indirect blocks */ /* num=0 corresponds to inode address 10 */ if(num < 0 | *size > fsize) return(0); /* Add contribution of this indirect block if at level 0 */ if(num == 0) *size += (long)512*128; /* Just return if this is an empty indirect pointer */ if(blk == 0) return(0); /* read in next indirect block */ lseek(fdo,blk*512,0); in = read(fdo,buff,512); if(in <= 0) { perror("Error reading inode indirect block"); return(-1); } /* convert the inode */ for (i = 0; i < 256; i++) { /* * The following code decides whether the conversion should be * done before or after calling indino. The conversion will * be done before calling indino if conversion is to the machine * on which this program is running. */ if(ONVAX == tovax) swap(&buff[i]); if((in = indino(tovax,fdo,fsize,size,num-1,buff[i])) < 0) return(in); if(ONVAX != tovax) swap(&buff[i]); } /* write out next indirect block */ lseek(fdo,blk*512,0); out = write(fdo,buff,512); if(out != 512) { perror("Error writing inode indirect block"); return(-1); } return(0); }
C
#include<stdio.h> int main(void) { int x; scanf("%d",&x); //double amount; int amount; amount = x * 2 * 1 * 2; printf("%d",amount); return 0; }
C
#pragma once #include <inttypes.h> #include <stdint.h> #ifdef __cplusplus extern "C" { #endif /* Exact integral types */ // Signed typedef int8_t vic_int8_t; typedef int16_t vic_int16_t; typedef int32_t vic_int32_t; typedef int64_t vic_int64_t; // Unsigned typedef uint8_t vic_uint8_t; typedef uint16_t vic_uint16_t; typedef uint32_t vic_uint32_t; typedef uint64_t vic_uint64_t; /* Small types */ // Signed typedef int_least8_t vic_int_least8_t; typedef int_least16_t vic_int_least16_t; typedef int_least32_t vic_int_least32_t; typedef int_least64_t vic_int_least64_t; // Unsigned typedef uint_least8_t vic_uint_least8_t; typedef uint_least16_t vic_uint_least16_t; typedef uint_least32_t vic_uint_least32_t; typedef uint_least64_t vic_uint_least64_t; /* Fast types */ // Signed typedef int_fast8_t vic_int_fast8_t; typedef int_fast16_t vic_int_fast16_t; typedef int_fast32_t vic_int_fast32_t; typedef int_fast64_t vic_int_fast64_t; // Unsigned typedef uint_fast8_t vic_uint_fast8_t; typedef uint_fast16_t vic_uint_fast16_t; typedef uint_fast32_t vic_uint_fast32_t; typedef uint_fast64_t vic_uint_fast64_t; /* Types for `void *' pointers */ typedef intptr_t vic_intptr_t; typedef uintptr_t vic_uintptr_t; /* Largest integral types */ typedef intmax_t vic_intmax_t; typedef uintmax_t vic_uintmax_t; #ifdef __cplusplus } #endif
C
/* ** inventaire.c for in /home/querat_g/tmp/PSU_2015_zappy/src/server ** ** Made by querat_g ** Login <querat_g@epitech.net> ** ** Started on Sun Jun 26 14:45:36 2016 querat_g ** Last update Sun Jun 26 14:45:36 2016 querat_g */ #include <stdbool.h> #include <stdlib.h> #include <string.h> #include "server.h" #include "macros.h" static char *g_buffer = NULL; static off_t g_off = 0; static bool g_is_first_print = false; static bool print_to_buffer(char const *str) { int ret; ret = snprintf((g_buffer + g_off), (INVENTAIRE_BUF_SIZE - g_off), "%s", str); if (ret < 0) return (TRACE("snprintf() failed"), false); g_off += ret; return (true); } static bool print_res(t_cli *c, char const *res) { t_item *itemstack; char buf[64]; print_to_buffer(res); print_to_buffer(" "); if (!(itemstack = ht_get_entry(c->inventory, res, strlen(res)))) { print_to_buffer("0"); return (true); } snprintf(buf, sizeof(buf), "%zu", itemstack->amount); print_to_buffer(buf); return (true); } static bool print_inv(t_cli *c) { print_res(c, "nourriture"); print_to_buffer(", "); print_res(c, "linemate"); print_to_buffer(", "); print_res(c, "deraumere"); print_to_buffer(", "); print_res(c, "sibur"); print_to_buffer(", "); print_res(c, "mendiane"); print_to_buffer(", "); print_res(c, "phiras"); print_to_buffer(", "); print_res(c, "thystame"); return (true); } bool inventaire(t_cli *c, t_msg UNUSED(*msg)) { ERR(PINK"[%s], client %d from team '%s'\n"WHITE, __func__, c->sock.fd, c->team->name); g_buffer = malloc(INVENTAIRE_BUF_SIZE); g_off = 0; g_is_first_print = true; if (!g_buffer) return (perror("malloc()"), false); print_to_buffer("{"); print_inv(c); print_to_buffer("}\n"); enqueue_msg(c, g_buffer); free(g_buffer); return (true); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <pthread.h> struct sockaddr_in addr; int success = 0; int failed = 0; int failed_conn = 0; char request[] = "GET / HTTP/1.1\r\nHost: 127.0.0.1:8080\r\n\r\n"; void* thread_func(void *arg) { int sockfd = socket(AF_INET, SOCK_STREAM, 0); if ( sockfd <= 0 ) { perror("socket error.\n"); exit(-1); } int connect_result = connect(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)); if ( connect_result < 0 ) { goto FAILED_CONN; } write(sockfd, &request, sizeof(request)); char str[13] = {0}; read(sockfd, &str, 13); if (0 == strncmp(str, "HTTP/1.1 200", 12)) { goto SUCCESS; } else { goto FAILED; } SUCCESS: success++; close(sockfd); return (void *)NULL; FAILED: failed++; close(sockfd); return (void *)NULL; FAILED_CONN: failed_conn++; close(sockfd); return (void *)NULL; } int main(int argc, char * argv[]) { memset(&addr, 0, sizeof(struct sockaddr_in)); addr.sin_family = AF_INET; if ( 1!= inet_pton(AF_INET, (const char*)argv[1], &addr.sin_addr) ) { printf("address error!\n"); exit(-1); } addr.sin_port = htons(8080); int n = 0; for ( int i = 0; argv[2][i] != '\0'; ++i ) { n *= 10; n += argv[2][i] - '0'; } pthread_t * tid = malloc(sizeof(pthread_t) * n); for ( int i = 0; i < n; ++i ) { pthread_create(&tid[i], NULL, thread_func, NULL); } sleep(1); for ( int i = 0; i < n; ++i ) { void * ret; pthread_join(tid[i], &ret); } printf("\n\n"); printf("success : %d\n", success); printf("failed_conn : %d\n", failed_conn); printf("failed : %d\n", failed); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main() { int a, b; a = 0; b = a++ * 2 + 1; printf("After postincrement\n"); printf("A: %d\n", a); printf("B: %d\n", b); printf("\n"); a = 0; b = ++a * 2 + 1; printf("After preincrement\n"); printf("A: %d\n", a); printf("B: %d\n", b); printf("\n\n=== ByteGarage ===\n\n"); return EXIT_SUCCESS; }
C
#include "adj_list.c" int main() { al_graph *graph = al_graph_create(18, true); al_graph_insert_edge(graph, 0, 2); al_graph_insert_edge(graph, 0, 14); al_graph_insert_edge(graph, 1, 4); al_graph_insert_edge(graph, 1, 5); al_graph_insert_edge(graph, 2, 1); al_graph_insert_edge(graph, 2, 5); al_graph_insert_edge(graph, 2, 6); al_graph_insert_edge(graph, 3, 2); al_graph_insert_edge(graph, 3, 17); al_graph_insert_edge(graph, 4, 1); al_graph_insert_edge(graph, 4, 7); al_graph_insert_edge(graph, 5, 2); al_graph_insert_edge(graph, 5, 4); al_graph_insert_edge(graph, 5, 8); al_graph_insert_edge(graph, 5, 9); al_graph_insert_edge(graph, 6, 2); al_graph_insert_edge(graph, 6, 3); al_graph_insert_edge(graph, 8, 5); al_graph_insert_edge(graph, 8, 7); al_graph_insert_edge(graph, 8, 12); al_graph_insert_edge(graph, 9, 5); al_graph_insert_edge(graph, 9, 10); al_graph_insert_edge(graph, 10, 17); al_graph_insert_edge(graph, 11, 8); al_graph_insert_edge(graph, 12, 9); al_graph_insert_edge(graph, 13, 9); al_graph_insert_edge(graph, 13, 10); al_graph_insert_edge(graph, 13, 16); al_graph_insert_edge(graph, 14, 7); al_graph_insert_edge(graph, 15, 12); al_graph_insert_edge(graph, 15, 17); al_graph_insert_edge(graph, 16, 12); al_graph_insert_edge(graph, 17, 13); al_graph_insert_edge(graph, 17, 16); DEBUG_PRINT(("Starting from vertex 0\n")); al_queue *tq = al_graph_dfs(graph, 0); int popped; int expected[18] = {14, 7, 2, 6, 3, 17, 16, 12, 9, 10, 5, 8, 4, 1 , 13}; int i = 0; while(!al_queue_is_empty(tq)) { popped = al_queue_pop(tq); assert(popped == expected[i++]); } al_queue_free(tq); DEBUG_PRINT(("\n\nStarting from vertex 9\n")); tq = al_graph_dfs(graph, 9); int expectedNext[18] = {10, 17, 16, 12, 9, 5, 8, 7, 4, 1, 2, 6, 3, 13}; i = 0; while(!al_queue_is_empty(tq)) { popped = al_queue_pop(tq); assert(popped == expectedNext[i++]); } al_queue_free(tq); al_graph_free(graph); return 0; }
C
/* * @file : myStack.h * @author : Marcelo Fernandez * @date : 25/06/2021 * @brief : declaración de funciones y estructura para mi stack y sus nodos, tarea 1 ELO320 */ #define NLEN 30 typedef struct NODO { char nombre[NLEN]; char apellido[NLEN]; int nota; struct NODO* previous; struct NODO* next; }Nodo; typedef struct Stack { unsigned capacidad_stack; // capacidad o total de nodos int num_nodos;// indicar cuantos nodos hay en la struct struct NODO* header; // header }Stack; /** * @brief : funcion que revisa si el stack esta lleno * @param head_nodo : nodo cabecera que puedo trabajar y contiene mi info * @return : retorna 0 si eta lleno y 1 si no lo esta */ int isFull (struct Stack* head_nodo) ;// /** * @brief : funcion que revisa si el stack esta vacío * @param head_nodo : nodo cabecera que puedo trabajar y contiene mi info * @return : retorna 1 si esta vacio y 0 si no esta vacio */ int isEmpty(struct Stack* head_nodo) ;// indica si el stack está vacío /** * @brief : crea un nuevo stack * @param capacidad_deseada : capacidad que deseo tenga el nuevo stack * @return : retorna un puntero a mi stack */ Stack *getNewStack (unsigned capacidad_deseada) ;// genera un nuevo stack /** * @brief : eslimina el stack y sus nodos * @param stack : recibe el stack que deseo eliminar * @return : no retorna */ void stackDelete(Stack* stack) ;// elimina el stack y libera la memoria reservada /** * @brief : agrega nuevo elemento al stack * @param stack : stack al que deseo agregar un elemento * @param nodo : nodo con a informacion que quiero agregar * @return : me retorna la cabecera siempre */ Stack *push(Stack* stack, Nodo* nodo);// agrega un elemento al stack /** * @brief : crea un nodo nuevo * @param nombreee : nombre a asignar * @param apellidooo : apellido a asignar * * @param notaaa : nota correspondiente a la persona del nodo * @return : me retonra el puntero al nodo creado */ struct NODO* crear_nodo(char* nombreee,char* apellidooo,int notaaa); //crea un nodo /** * @brief : quita el elemento que este como cabecera * @param head_nodo : nodo que voy a elliminar * @return : me retorna la nueva cabecera */ struct HOJAS *pop(Stack* head_nodo);// quita el primero elemento del stack /** * @brief : imprime todo mi stack en orden de elementos * @param mi_stack : stack que tengo que imprimir * @param table : tabla para imprimir nombres desencriptados * @return : me retorna la nueva cabecera */ struct HOJAS* imprimir_stack(Stack* mi_stack,char table[3][26]); /** * @brief : desencripta un nombre o apellido * @param token : palabra que debo desencriptar * @param table : tabla para imprimir nombres desencriptados * @return : retorna la palabra desencriptada */ char* decrypt(char* token, char table[3][26]); /** * @brief : rellena mi tabla de encriptación con las letras aleatorias * @param table : tabla a la que le debo agregar los valores aleatorios * @return : retorna 0 cuando se complete la tabla */ int initEncryptionTable(char table[3][26]); /** * @brief : encripta los nombres y apellidos * @param token : palabra que deseo encriptar * @param table : tabla para imprimir nombres desencriptados * @return : retorna mi palabra encriptada */ char* encrypt(char* token, char table[3][26]);
C
#include"link.h" #pragma warning(disable:4996) Contact sta; void menu(void) { printf("**************************************\n"); printf("***********1.ϵ***************\n"); printf("***********2.ɾָϵ***********\n"); printf("***********3.ָϵ***********\n"); printf("***********4.޸ָϵ***********\n"); printf("***********5.ʾϵ***********\n"); printf("***********6.ϵ***********\n"); printf("***********7.ϵ*****\n"); printf("***********0.˳*****************\n"); printf("**************************************\n"); } void test(void) { char ch; sta.sz = 0; char input = 0; /*inint_link(&sta);*/ do { menu(); printf("ҪеIJ:>"); scanf("%c", &input); /*printf("%d\n"); while (1);*/ while('\n'!=(ch=getchar())); if (input >= '0' && input <= '7') { switch (input-'0') { case ADD: Add_link(&sta); break; case DEL: Dele_link(&sta); break; case FIND: Find_link(&sta); break; case MOD: Mod_link(&sta); break; case SHOW: Show_link(&sta); break; case EMPTY: Empty_link(&sta); break; case SORT: Sort_link(&sta); break; case EXIT: break; default: printf("\n"); break; } } else { printf(",\n"); } } while(input); } int main() { test(); system("pause"); return 0; }
C
// to execute // gcc midpointellipse.c -lgraph -o a // ./a // enter point a and b #include<graphics.h> #include<stdio.h> int main() { double a,b; printf("enter a and b"); scanf("%lf%lf",&a,&b); int gd=DETECT,gm; initgraph(&gd,&gm,NULL); double x=0,y=b; double fx=0,fy=2*(a*a*b); double p=(b*b)-(a*a*b)+((a*a)/4); double c=300; while(fx<=fy) { putpixel(x+c,y+c,RED); putpixel(-x+c,y+c,RED); putpixel(x+c,-y+c,RED); putpixel(-x+c,-y+c,RED); x++; fx=fx+2*b*b; if(p<0) p=p+fx+b*b; else { y--; fy=fy-2*a*a; p=p+fx+b*b-fy; } delay(50); } putpixel(x+c,y+c,RED); p=b*b*((x+0.5)*(x+0.5))+a*a*((y-1)*(y-1))-(a*a*b*b); while(y>0) { y--; fy=fy-2*a*a; if(p>0) p=p-fy+a*a; else { x++; fx=fx+2*b*b; p=p+fx-fy+a*a; } putpixel(x+c,y+c,RED); putpixel(-x+c,y+c,RED); putpixel(x+c,-y+c,RED); putpixel(-x+c,-y+c,RED); delay(50); } getch(); }
C
#include <stdio.h> #include <stdlib.h> int compare(const void *a, const void *b); int main(void) { int a[100] = {0, 2, 3, 4, 5, 0, 1, 1}; qsort(&a[50], 50, sizeof(a[0]), compare); return 0; } int compare(const void *a, const void *b) { if(*((int*) a) < *((int*) b)) return -1; else if(*((int*) a) > *((int*) b)) return 1; return 0; }
C
#include <stdio.h> #include <conio.h> #include <stdlib.h> int main() { FILE *fp; char name[20]; int age,salary; char another = 'y'; fp = fopen("d:/data/employee.exe","w"); if(fp==NULL){ printf("cannot open file"); exit(1); } while(another=='y'){ printf("enter name,age ans salary\n"); // gets(name); scanf("%s%d%d",name,&age,&salary); fprintf(fp,"%s %d %d\n",name,age,salary); printf("do you want to enter another?/n"); fflush(stdin); another = getchar(); } fclose(fp); return 0; }
C
#include<stdio.h> int main() { char dig_word[][10]={"zero","one","two","three","four","five","six","seven","eight","nine"}; char ten_word[][10]={"zero","ten","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"}; int n,flag=0; scanf("%d",&n); if(n > 100 && n%100 > 0) flag = 1; if(n/1000 > 0) { printf("%s thousand ",dig_word[n/1000]); } n %= 1000; if(n/100 > 0) { printf("%s hundered ",dig_word[n/100]); } n %= 100; if(flag) printf("and "); if(n/10 > 0) { printf("%s ",ten_word[n/10]); } n %= 10; if(n > 0) { printf("%s ",dig_word[n]); } return 0; }
C
#include<stdlib.h> #include<stdio.h> #include<graphics.h> void ff4(int x, int y, int oc, int nc){ if(getpixel(x,y) == oc){ putpixel(x,y,nc); ff4(x, y+1, oc, nc); ff4(x-1, y, oc, nc); ff4(x, y-1, oc, nc); ff4(x+1, y, oc, nc); } return; } void ff8(int x, int y, int oc, int nc){ if(getpixel(x,y) == oc){ putpixel(x,y,nc); ff8(x, y+1, oc, nc); ff8(x-1, y, oc, nc); ff8(x, y-1, oc, nc); ff8(x+1, y, oc, nc); ff8(x-1, y+1, oc, nc); ff8(x-1, y-1, oc, nc); ff8(x+1, y-1, oc, nc); ff8(x+1, y+1, oc, nc); } return; } void main(){ int gd=DETECT, gm; initgraph(&gd, &gm, NULL); int oc = getpixel(120,120); rectangle(100,100,200,200); ff8(120, 120, oc, 15); printf("Flood Fill 8 Neighbouring Pixels"); getch(); closegraph(); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int rock = 1, scissors = 2, paper = 3; int computer, me; int draw = 0, win = 0; srand((int)time(NULL)); computer = rand() % 3 + 1; while (1) { printf("r: 1, s: 2, p: 3 your choice: "); scanf("%d\n", &me); printf("You: %d, Computer: %d ", me, computer); if ((computer - me) == 0) { printf("draw!\n"); draw++; } else if ((computer - me) == -1 || (computer - me) == 2) { printf("You lose...\n"); break ; } else if ((computer - me) == 1 || (computer - me) == -2) { printf("You win!\n"); win++; } } printf("\nwin: %d, draw: %d", win, draw); return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include "h264_stream.h" h264_stream_t *h264_stream_new(uint8_t *data, int size) { h264_stream_t *s = malloc(sizeof(h264_stream_t)); s->data = data; s->size = size; s->bit_pos = 7; s->byte_pos = 0; return s; } h264_stream_t *h264_stream_from_file(char *path) { FILE *fp; long file_size; uint8_t *buffer; size_t result; fp = fopen(path, "rb"); if (fp == NULL) { return NULL; } fseek(fp , 0 , SEEK_END); file_size = ftell(fp); rewind(fp); buffer = (uint8_t *)malloc(file_size); assert(buffer); result = fread(buffer, 1, file_size, fp); assert(result == file_size); fclose (fp); return h264_stream_new(buffer, file_size); } void h264_stream_free(h264_stream_t *s) { free(s->data); s->size = 0; s->bit_pos = 7; s->byte_pos = 0; } uint32_t h264_stream_read_bits(h264_stream_t *s, uint32_t n) { uint32_t ret = 0; if (n == 0) { return 0; } int i; for (i = 0; i < n; ++i) { if (h264_stream_bits_remaining(s) == 0) { ret <<= n - i - 1; } uint8_t b = s->data[s->byte_pos]; if (n - i <= 32) { ret = ret << 1 | BITAT(b, s->bit_pos); } if (s->bit_pos == 0) { s->bit_pos = 7; s->byte_pos++; } else { s->bit_pos--; } } return ret; } uint32_t h264_stream_peek_bits(h264_stream_t *s, uint32_t n) { int prev_bit_pos = s->bit_pos; int prev_byte_pos = s->byte_pos; uint32_t ret = h264_stream_read_bits(s, n); s->bit_pos = prev_bit_pos; s->byte_pos = prev_byte_pos; return ret; } uint32_t h264_stream_read_bytes(h264_stream_t *s, uint32_t n) { uint32_t ret = 0; if (n == 0) { return 0; } int i; for (i = 0; i < n; ++i) { if (h264_stream_bytes_remaining(s) == 0) { ret <<= (n - i - 1) * 8; break; } if (n - i <= 4) { ret = ret << 8 | s->data[s->byte_pos]; } s->byte_pos++; } return ret; } uint32_t h264_stream_peek_bytes(h264_stream_t *s, uint32_t n) { int prev_byte_pos = s->byte_pos; uint32_t ret = h264_stream_read_bytes(s, n); s->byte_pos = prev_byte_pos; return ret; } int h264_stream_bits_remaining(h264_stream_t *s) { return (s->size - s->byte_pos) * 8 + s->bit_pos; } int h264_stream_bytes_remaining(h264_stream_t *s) { return s->size - s->byte_pos; }
C
#include <utility.h> #include <userint.h> #include <ansi_c.h> #include "util.h" #include "list.h" #include "listu.h" #define TRUE 1 #define FALSE 0 struct listStruct listG; void list_Init (listPtr list); nodePtr list_GetNode (listType list, int i); int list_FindItem (listType list, void *item); int list_AddItem (listPtr list, void *item); void list_RemoveItem (listPtr list, int i, int trashitem); void list_RemoveAllItems (listPtr list, int trashitems); void list_MoveUp (listType list, int i); void list_MoveDown (listType list, int i); void listG_Init(void); void list_InitPanel (char *header, char *button); void listG_Init(void) { util_ChangeInitMessage ("List Utilities..."); listG.p = 0; } void list_Init (listPtr list) { list->first = NULL; list->last = NULL; list->nItems = 0; } nodePtr list_GetNode (listType list, int i) { nodePtr p; int cnt; cnt = 0; p = list.first; while (cnt < i) {if(p && p->next){ p = p->next; cnt++;}else return NULL;} return p; } int list_FindItem (listType list, void *item) { int i, cnt = 0; nodePtr p; i = 0; p = list.first; while (p && ((p->item != item) && (p->next))) { p = p->next; i++;} if (!p || (p->item != item)) { while (cnt < 20) {cnt++;} i = NOT_IN_LIST; } return i; } int list_AddItem (listPtr list, void *item) { nodePtr newnode; newnode = malloc (sizeof(nodeType)); if (!newnode) {util_OutofMemory("List Add Item"); return FALSE;} newnode->next = NULL; newnode->prev = NULL; newnode->item = item; if (list->nItems == 0) list->first = newnode; else { list->last->next = newnode; newnode->prev = list->last; } list->last = newnode; list->nItems++; return TRUE; } void list_RemoveItem (listPtr list, int i, int trashitem) { nodePtr trash; trash = list_GetNode (*list, i); if (trashitem) free (trash->item); if (list->nItems == 1) { list->first = NULL; list->last = NULL; } else { if (list->first == trash) { list->first = list->first->next; list->first->prev = NULL; } else if (list->last == trash) { list->last = list->last->prev; list->last->next = NULL; } else { trash->next->prev = trash->prev; trash->prev->next = trash->next; } } free (trash); list->nItems--; } void list_RemoveAllItems (listPtr list, int trashitems) { while (list->first) list_RemoveItem (list, 0, trashitems); } void list_MoveUp (listType list, int i) { nodePtr p; void *temp; if (i != 0) { p = list_GetNode (list, i); temp = p->prev->item; p->prev->item = p->item; p->item = temp; } } void list_MoveDown (listType list, int i) { nodePtr p; void *temp; if (i != (list.nItems-1)) { p = list_GetNode (list, i); temp = p->next->item; p->next->item = p->item; p->item = temp; } } void list_InitPanel (char *header, char *button) { listG.p = LoadPanel (0, "listu.uir", LIST); SetPanelPos (listG.p, VAL_AUTO_CENTER, VAL_AUTO_CENTER); util_InitClose (listG.p, LIST_CANCEL, TRUE); SetPanelAttribute (listG.p, ATTR_TITLE, header); SetCtrlAttribute (listG.p, LIST_CONT, ATTR_LABEL_TEXT, button); } int ListSelectAllCallback(int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { int i, n, checked; if (event == EVENT_COMMIT) { GetCtrlVal (panel, control, &checked); GetNumListItems (panel, LIST_ITEMS, &n); for (i = 0; i < n; i++) CheckListItem (panel, LIST_ITEMS, i, checked); } return 0; }
C
#include <stdio.h> #include <stdlib.h> int main(void){ char * ascii; ascii = "ab"; printf("%d\n", ascii); ascii = "ac"; printf("%d\n", ascii); return 0; }
C
#include<stdio.h> #include<sys/types.h> #include<unistd.h> #include<fcntl.h> #include<sys/wait.h> int index = 0; void StartSignal(int n) { printf("Process %d catch signal %d \n",getpid(),n); index++; } int main() { int a1, a2; double e2 = 0, pi = 0, f, qw; char argum[10]; int fd1[2], fd2[2]; printf("Start make the canals....\n"); pipe(fd1); pipe(fd2); printf("Finish make the canals....\n"); //make 1 child process; switch (a1 = fork()) { case -1: printf("Error to child process 1.\n");exit(1); case 0: printf("Enter to 1 child process(pi)....\n"); signal(10,StartSignal); //catch signal from parents; while (index == 0) sleep(1); sprintf(argum,"%d",fd1[1]); //Put int fd1[1] to string; execl("./pod1","pod1",argum,0); //Change programm in pod1; break; } printf("Parents cries to 1 child...\n"); sleep(1); kill(a1,10); //Call son-process a1; sleep(1); //Wait execution son-process 1; //make 2 child process; switch (a2 = fork()) { case -1: printf("Error to child process 2.\n"); case 0: printf("Enter to 2 child process(e2)....\n"); signal(20,StartSignal); //Catch signal from parents; while (index == 0) sleep(1); sprintf(argum,"%d",fd2[1]); //Put int fd2[1] to string; execl("./pod2","pod2",argum,0); //Chang program in pod2; break; } printf("Parents cries to 2 child....\n"); sleep(1); kill(a2,20); //Call son-process 2; wait(&qw); //Wait execution son-process 2; printf("Parents process begining read....\n"); read(fd1[0],&pi,sizeof(double)); //reading result from canals; read(fd2[0],&e2,sizeof(double)); printf("Parents was read....\n"); //output result; f = 1. / (pi* (1. + e2)); printf("F= %f\n",f); return 0; }
C
// ̾ #ifdef _WIN32 #pragma warning(disable:4996) // c io #pragma warning(disable:6031) // ȯ #pragma warning(disable:4018) // unsigned int ȯ #endif #include <cstdio> int to_num(char c) { if (c < 'S') return (c - 'A') / 3 + 2; else if (c == 'S') return 7; else if (c < 'W') return 8; else return 9; } int main() { char c; int t = 0; while ((c = getchar()) != '\n') { t += to_num(c) + 1; } printf("%d\n", t); }