language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* * C Program to Implement a strpbrk() Function */ #include <stdio.h> char* strpbrk(char *, char *); int main() { char string1[50], string2[50]; char *pos; printf("Enter the String: "); scanf(" %[^ ]s", string1); printf(" Enter the Character Set: "); scanf(" %[^ ]s", string2); pos=strpbrk(string1, string2); printf("%s", pos); } /* Locates First occurrence in string s1 of any character in string s2, * If a character from string s2 is found , * a pointer to the character in string s1 is returned, * otherwise, a NULL pointer is returned. */ char* strpbrk(char *string1, char *string2) { int i, j, pos, flag = 0; for (i = 0; string1[i] != ''; i++); pos = i; for (i = 0; string2[i] != ''; i++) { for (j = 0; string1[j] != ''; j++) { if (string2[i] == string1[j]) { if ( j <= p1) { pos = j; flag = 1; } } } } if (flag == 1) { return &string1[pos]; } else { return NULL; } } Enter the String: C programming Class Enter the Character Set: mp programming Class
C
#include <string.h> #include <stdlib.h> #include <stdio.h> #include "cpu.h" #define DATA_LEN 6 /** * Load the binary bytes from a .ls8 source file into a RAM array */ void cpu_load(struct cpu *cpu, char *filename) { //open file FILE *fptr = fopen(filename, "r"); if (fptr == NULL) { printf("File %s is not recognized.\n", filename); exit(2); } //read line by line until returns null, ignore blank lines and comments char line[1000]; int address = 0; while(fgets(line, sizeof line, fptr) != NULL) { //convert string to a number. if get an error char *endpointer; unsigned char value = strtoul(line, &endpointer, 2); //needs pointer to a pointer so need & as address of pointer //ignore lines where no numbers read if (endpointer == line) { continue; } //save data into ram, have to convert binary strings to int values to store in ram with strtoul //cpu_ram_write(cpu, address++, value); cpu->ram[address++] = value; } fclose(fptr); //original hard code we're refactoring // char data[DATA_LEN] = { // // From print8.ls8 // 0b10000010, // LDI R0,8 // 0b00000000, // 0b00001000, // 0b01000111, // PRN R0 // 0b00000000, // 0b00000001 // HLT // }; // int address = 0; // for (int i = 0; i < DATA_LEN; i++) { // cpu->ram[address++] = data[i]; // } // TODO: Replace this with something less hard-coded } /** * ALU */ void alu(struct cpu *cpu, enum alu_op op, unsigned char regA, unsigned char regB) { unsigned char valA = cpu->reg[regA]; unsigned char valB = cpu->reg[regB]; unsigned char flag; switch (op) { case ALU_MUL: // TODO cpu->reg[regA] = cpu->reg[regA]*cpu->reg[regB]; //reg[regA] *= valB?? break; // TODO: implement more ALU ops case ALU_ADD: cpu->reg[regA] = cpu->reg[regA]+cpu->reg[regB]; break; case ALU_CMP: //compare values in two registers w limited subtraction. if (valA < valB) //if less than flag to 1 { flag = 0b00000100; } else if (valA > valB) //if greater than flag to 1 { flag = 0b00000010; } else if (valA == valB) //if equal flag to 1 { flag = 0b00000001; } cpu->fl = flag; break; } } unsigned char cpu_ram_read(struct cpu *cpu, unsigned char mar) { return cpu->ram[mar]; } //mar is index in ram so set to new value void cpu_ram_write(struct cpu *cpu, unsigned char mar, unsigned char mdr) { cpu->ram[mar] = mdr; } void push(struct cpu *cpu, unsigned char val) { //push the value in the given register to top of the stack //decrement the sp cpu->reg[7]--; //copy the value in the given register to the address pointed to by the sp //another variable? add sp to struct? cpu_ram_write(cpu, cpu->reg[7], val); } unsigned char pop(struct cpu *cpu) { //pop the value at the top of the stack into given register //copy the value from the address pointed to by sp to given register //put value in register take it out of ram (by reading) get address reg7 and store it in given register //unsigned char pop_val = cpu_ram_read(cpu, cpu->reg[7]); unsigned char val = cpu->ram[cpu->reg[7]]; //increment sp cpu->reg[7]++; return val; } void call(struct cpu *cpu, unsigned char registerAddress) { //push address of instruction on to stack so we can return to where we left off after subroutine executes unsigned char address = cpu->reg[registerAddress]; push(cpu, cpu->pc+2); //set program counter to location of subroutine cpu->pc = address; //pc is set to address stored in given register. jump to that location and execute the instruction in the subroutine. } void ret(struct cpu *cpu) { //return from subroutine. pop value from top of stack and store in pc. cpu->pc = pop(cpu); } /** * Run the CPU */ void cpu_run(struct cpu *cpu) { int running = 1; // True until we get a HLT instruction while (running) { // TODO // 1. Get the value of the current instruction (in address PC). unsigned char IR = cpu_ram_read(cpu, cpu->pc); // 2. Figure out how many operands this next instruction requires // 3. Get the appropriate value(s) of the operands following this instruction unsigned char operandA = cpu_ram_read(cpu, cpu->pc+1); unsigned char operandB = cpu_ram_read(cpu, cpu->pc+2); printf("TRACE: %02X %02X: %02X %02X %02X\n", cpu->fl, cpu->pc, IR, operandA, operandB); // 4. switch() over it to decide on a course of action. // 5. Do whatever the instruction should do according to the spec. //int instruction_set_pc = (IR >> 4); switch(IR) { case LDI: //sets value in given register to value specified cpu->reg[operandA] = operandB; //increment by 3 since 3 arguments (CP+2) cpu->pc += 3; break; case PRN: //print out numerically in given register printf("%d\n", cpu->reg[operandA]); cpu->pc += 2; break; case MUL: alu(cpu, ALU_MUL, operandA, operandB); cpu->pc += 3; break; case ADD: alu(cpu, ALU_ADD, operandA, operandB); cpu->pc += 3; break; case PUSH: push(cpu, cpu->reg[operandA]); cpu->pc += 2; break; case POP: cpu->reg[operandA] = pop(cpu); cpu->pc += 2; break; case CALL: //call(cpu, operandA); push(cpu, cpu->pc + 2); cpu->pc = cpu->reg[operandA]; //printf("TRACE: 0x%02X\n", cpu->pc); break; case RET: //ret(cpu); cpu->pc = pop(cpu); break; case CMP: alu(cpu, ALU_CMP, operandA, operandB); cpu->pc +=3; break; case JMP: //jump to address stored in given register. set pc to address stored in given register. cpu->pc = cpu->reg[operandA]; break; case JEQ: //if equal flag set to true jump to address stored at given register. if (cpu->fl & 0b00000001) { cpu->pc = cpu->reg[operandA]; } //if not skip jump else { cpu->pc += 2; } break; case JNE: //if equal flag is clear/false/0 jump to address stored at given register. if ((cpu->fl & 0b00000001) == 0) { cpu->pc = cpu->reg[operandA]; } else { cpu->pc += 2; } break; case HLT: running = 0; //set running to false break; default: //program stops if gets instruction it doesnt know printf("unexpected instruction: 0x%0X2 at 0x%0X2 \n", IR, cpu->pc); exit(1); } // 6. Move the PC to the next instruction. // if (!instruction_set_pc) // { // cpu->pc+= ((IR >> 6) & 0x3) + 1; // } } } /** * Initialize a CPU struct */ void cpu_init(struct cpu *cpu) { // TODO: Initialize the PC and other special registers cpu->fl = 0; cpu->pc = 0; memset(cpu->reg, 0, sizeof cpu->reg); //R7?????? cpu->reg[7] = 0xf4; memset(cpu->ram, 0, sizeof cpu->ram); } // When the LS-8 is booted, the following steps occur: // * `R0`-`R6` are cleared to `0`. // * `R7` is set to `0xF4`. // * `PC` and `FL` registers are cleared to `0`. // * RAM is cleared to `0`.
C
#include<stdio.h> #include<conio.h> void main() { char choice,answer='y'; printf("Enter a number : \n"); fflush(stdin); scanf("%c",&choice); do { if(choice=='a') { printf("Lower case \n"); } else if(choice=='A') { printf("Upper case\n"); } else if(choice==1) { printf("Number\n"); } else { printf("Special Symbol\n"); } printf("Wheather you want to enter a another character : \n"); fflush(stdin); scanf("%d",&answer); }while(answer=='y'); getch(); }
C
/* * This is Linux ONLY code * Do not compile on windows * compile this file using the command * g++ -fopenmp loadtest.C -o loadtest * once compilation is successful run the test using * ./loadtest * Ctrl C to stop the test */ #include <iostream> #include <fstream> #include <cmath> #include <unistd.h> #include <omp.h> #include <cstdlib> using namespace std; void sleep_ms(int milliseconds); int main(int argc, char **argv) { srand(time(NULL)); ofstream fptr; if (argc != 2) { cout << "useage: loadtest N" << endl; cout << "where N is the number of concurrent users from 0-100" << endl; exit(1); } int nthreads = atoi(argv[1]); int tid; fptr.open("synthetic.dat", ios::trunc); omp_set_num_threads(nthreads); omp_lock_t writelock; omp_init_lock(&writelock); #pragma omp parallel private(tid) { tid = omp_get_thread_num(); #pragma omp parallel for for (int t = 0; t < 10; t++) { for (;;) { for (int i = 0; i < 1000000; i++) { double t = rand() % 8273 + 1; double tt = sqrt(t); } time_t t = time(0); struct tm *now = localtime(&t); omp_set_lock(&writelock); fptr << (now->tm_year + 1900) << '-' << (now->tm_mon + 1) << '-' << now->tm_mday << '-' << (now->tm_hour) << '-' << (now->tm_min) << '-' << (now->tm_sec) << " UserID [" << tid << "]" << " Transaction Complete " << endl; omp_unset_lock(&writelock); sleep_ms(100); } } } fptr.close(); return 0; } void sleep_ms(int milliseconds) { struct timespec ts; ts.tv_sec = milliseconds / 1000; ts.tv_nsec = (milliseconds % 1000) * 1000000; nanosleep(&ts, NULL); usleep(milliseconds * 1000); }
C
/* Copyright (c) 2002, 2004, Christopher Clark All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the original author; nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include <string.h> #include "pet_hashtable.h" struct hash_entry { uintptr_t key; uintptr_t value; uint32_t hash; struct hash_entry * next; }; struct pet_hashtable { struct hash_entry ** table; uint32_t table_length; uint32_t entry_count; uint32_t load_limit; uint32_t prime_index; uint32_t (*hash_fn) (uintptr_t key); int (*eq_fn) (uintptr_t key1, uintptr_t key2); void (*val_free_fn)(uintptr_t val); void (*key_free_fn)(uintptr_t key); }; #define HTABLE_FREE(x) free(x) #define HTABLE_CALLOC(cnt, size) calloc(cnt, size) /* HASH FUNCTIONS */ static inline uint32_t do_hash(struct pet_hashtable * htable, uintptr_t key) { /* Aim to protect against poor hash functions by adding logic here * - logic taken from java 1.4 hashtable source */ uint32_t i = htable->hash_fn(key); i += ~(i << 9); i ^= ((i >> 14) | (i << 18)); /* >>> */ i += (i << 4); i ^= ((i >> 10) | (i << 22)); /* >>> */ return i; } #define GOLDEN_RATIO_PRIME_32 0x9e370001UL #define GOLDEN_RATIO_PRIME_64 0x9e37fffffffc0001ULL uint32_t pet_hash_u32(uintptr_t val) { uint32_t hash = val; hash *= GOLDEN_RATIO_PRIME_32; return hash; } uint32_t pet_hash_ptr(uintptr_t val) { uintptr_t hash = val; uintptr_t n = hash; /* Sigh, gcc can't optimise this alone like it does for 32 bits. */ n <<= 18; hash -= n; n <<= 33; hash -= n; n <<= 3; hash += n; n <<= 3; hash -= n; n <<= 4; hash += n; n <<= 2; hash += n; /* High bits are more random, so use them. */ return (uint32_t)(hash >> 32); } int pet_cmp_ptr(uintptr_t val1, uintptr_t val2) { return (val1 == val2); } /* HASH GENERIC MEMORY BUFFER */ /* ELF HEADER HASH FUNCTION */ uint32_t pet_hash_buffer(uint8_t * msg, uint32_t length) { uint32_t hash = 0; uint32_t temp = 0; uint32_t i; for (i = 0; i < length; i++) { hash = (hash << 4) + *(msg + i) + i; if ((temp = (hash & 0xF0000000))) { hash ^= (temp >> 24); } hash &= ~temp; } return hash; } /* indexFor */ static inline uint32_t indexFor(uint32_t table_length, uint32_t hash_value) { return (hash_value % table_length); }; /* Credit for primes table: Aaron Krowne http://br.endernet.org/~akrowne/ http://planetmath.org/encyclopedia/GoodHashTablePrimes.html */ static const uint32_t primes[] = { 53, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469, 12582917, 25165843, 50331653, 100663319, 201326611, 402653189, 805306457, 1610612741 }; // this assumes that the max load factor is .65 static const uint32_t load_factors[] = { 35, 64, 126, 253, 500, 1003, 2002, 3999, 7988, 15986, 31953, 63907, 127799, 255607, 511182, 1022365, 2044731, 4089455, 8178897, 16357798, 32715575, 65431158, 130862298, 261724573, 523449198, 1046898282 }; const uint32_t prime_table_len = sizeof(primes) / sizeof(primes[0]); struct pet_hashtable * pet_create_htable(uint32_t min_size, uint32_t (*hash_fn) (uintptr_t), int (*eq_fn) (uintptr_t, uintptr_t), void (*val_free_fn)(uintptr_t), void (*key_free_fn)(uintptr_t)) { struct pet_hashtable * htable = NULL; uint32_t prime_index = 0; uint32_t size = primes[0]; /* Check requested hashtable isn't too large */ if (min_size > (1u << 30)) { return NULL; } /* Enforce size as prime */ for (prime_index = 0; prime_index < prime_table_len; prime_index++) { if (primes[prime_index] > min_size) { size = primes[prime_index]; break; } } htable = (struct pet_hashtable *)HTABLE_CALLOC(1, sizeof(struct pet_hashtable)); if (htable == NULL) { return NULL; /*oom*/ } htable->table = (struct hash_entry **)HTABLE_CALLOC(1, sizeof(struct hash_entry *) * size); if (htable->table == NULL) { HTABLE_FREE(htable); return NULL; /*oom*/ } htable->table_length = size; htable->prime_index = prime_index; htable->entry_count = 0; htable->hash_fn = hash_fn; htable->eq_fn = eq_fn; htable->val_free_fn = val_free_fn; htable->key_free_fn = key_free_fn; htable->load_limit = load_factors[prime_index]; return htable; } static int hashtable_expand(struct pet_hashtable * htable) { /* Double the size of the table to accomodate more entries */ struct hash_entry ** new_table = NULL; struct hash_entry ** entry_ptr = NULL; struct hash_entry * tmp_entry = NULL; uint32_t new_size = 0; uint32_t index = 0; uint32_t i = 0; /* Check we're not hitting max capacity */ if (htable->prime_index == (prime_table_len - 1)) { return -1; } new_size = primes[++(htable->prime_index)]; new_table = (struct hash_entry **)HTABLE_CALLOC(1, sizeof(struct hash_entry *) * new_size); if (new_table != NULL) { /* This algorithm is not 'stable'. ie. it reverses the list * when it transfers entries between the tables */ for (i = 0; i < htable->table_length; i++) { while ((tmp_entry = htable->table[i]) != NULL) { htable->table[i] = tmp_entry->next; index = indexFor(new_size, tmp_entry->hash); tmp_entry->next = new_table[index]; new_table[index] = tmp_entry; } } HTABLE_FREE(htable->table); htable->table = new_table; } else { /* Plan B: realloc instead */ new_table = (struct hash_entry **)realloc(htable->table, new_size * sizeof(struct hash_entry *)); if (new_table == NULL) { (htable->prime_index)--; return -1; } htable->table = new_table; memset(new_table[htable->table_length], 0, new_size - htable->table_length); for (i = 0; i < htable->table_length; i++) { entry_ptr = &(new_table[i]); for (tmp_entry = *entry_ptr; tmp_entry != NULL; tmp_entry = *entry_ptr) { index = indexFor(new_size, tmp_entry->hash); if (i == index) { entry_ptr = &(tmp_entry->next); } else { *entry_ptr = tmp_entry->next; tmp_entry->next = new_table[index]; new_table[index] = tmp_entry; } } } } htable->table_length = new_size; htable->load_limit = load_factors[htable->prime_index]; return 0; } uint32_t pet_htable_count(struct pet_hashtable * htable) { return htable->entry_count; } int pet_htable_insert(struct pet_hashtable * htable, uintptr_t key, uintptr_t value) { /* This method allows duplicate keys - but they shouldn't be used */ struct hash_entry * new_entry = NULL; uint32_t index = 0; if (++(htable->entry_count) > htable->load_limit) { /* Ignore the return value. If expand fails, we should * still try cramming just this value into the existing table * -- we may not have memory for a larger table, but one more * element may be ok. Next time we insert, we'll try expanding again.*/ hashtable_expand(htable); } new_entry = (struct hash_entry *)HTABLE_CALLOC(1, sizeof(struct hash_entry)); if (new_entry == NULL) { (htable->entry_count)--; return -1; /*oom*/ } new_entry->hash = do_hash(htable, key); index = indexFor(htable->table_length, new_entry->hash); new_entry->key = key; new_entry->value = value; new_entry->next = htable->table[index]; htable->table[index] = new_entry; return 0; } int pet_htable_change(struct pet_hashtable * htable, uintptr_t key, uintptr_t value) { struct hash_entry * tmp_entry = NULL; uint32_t hash_value = 0; uint32_t index = 0; hash_value = do_hash(htable, key); index = indexFor(htable->table_length, hash_value); tmp_entry = htable->table[index]; while (tmp_entry != NULL) { /* Check hash value to short circuit heavier comparison */ if ((hash_value == tmp_entry->hash) && (htable->eq_fn(key, tmp_entry->key))) { if (htable->val_free_fn) { htable->val_free_fn(tmp_entry->value); } tmp_entry->value = value; return 0; } tmp_entry = tmp_entry->next; } return -1; } int pet_htable_inc(struct pet_hashtable * htable, uintptr_t key, uintptr_t value) { struct hash_entry * tmp_entry = NULL; uint32_t hash_value = 0; uint32_t index = 0; hash_value = do_hash(htable, key); index = indexFor(htable->table_length, hash_value); tmp_entry = htable->table[index]; while (tmp_entry != NULL) { /* Check hash value to short circuit heavier comparison */ if ((hash_value == tmp_entry->hash) && (htable->eq_fn(key, tmp_entry->key))) { tmp_entry->value += value; return 0; } tmp_entry = tmp_entry->next; } return -1; } int pet_htable_dec(struct pet_hashtable * htable, uintptr_t key, uintptr_t value) { struct hash_entry * tmp_entry = NULL; uint32_t hash_value = 0; uint32_t index = 0; hash_value = do_hash(htable, key); index = indexFor(htable->table_length, hash_value); tmp_entry = htable->table[index]; while (tmp_entry != NULL) { /* Check hash value to short circuit heavier comparison */ if ((hash_value == tmp_entry->hash) && (htable->eq_fn(key, tmp_entry->key))) { tmp_entry->value -= value; return 0; } tmp_entry = tmp_entry->next; } return -1; } /* returns value associated with key */ void * pet_htable_search(struct pet_hashtable * htable, uintptr_t key) { struct hash_entry * cursor = NULL; uint32_t hash_value = 0; uint32_t index = 0; hash_value = do_hash(htable, key); index = indexFor(htable->table_length, hash_value); cursor = htable->table[index]; while (cursor != NULL) { /* Check hash value to short circuit heavier comparison */ if ((hash_value == cursor->hash) && (htable->eq_fn(key, cursor->key))) { return (void *)cursor->value; } cursor = cursor->next; } return NULL; } /* returns value associated with key */ uintptr_t pet_htable_cond_remove(struct pet_hashtable * htable, uintptr_t key, bool (*cond_func)(uintptr_t value)) { /* TODO: consider compacting the table when the load factor drops enough, * or provide a 'compact' method. */ struct hash_entry * cursor = NULL; struct hash_entry ** entry_ptr = NULL; uintptr_t value = 0; uint32_t hash_value = 0; uint32_t index = 0; hash_value = do_hash(htable, key); index = indexFor(htable->table_length, hash_value); entry_ptr = &(htable->table[index]); cursor = *entry_ptr; while (cursor != NULL) { /* Check hash value to short circuit heavier comparison */ if ((hash_value == cursor->hash) && (htable->eq_fn(key, cursor->key))) { if (cond_func != NULL && cond_func(cursor->value) != true) { return (uintptr_t)NULL; } *entry_ptr = cursor->next; htable->entry_count -= 1; value = cursor->value; if (htable->key_free_fn) { htable->key_free_fn(cursor->key); } HTABLE_FREE(cursor); return value; } entry_ptr = &(cursor->next); cursor = cursor->next; } return (uintptr_t)NULL; } uintptr_t pet_htable_remove(struct pet_hashtable * htable, uintptr_t key) { return pet_htable_cond_remove(htable, key, NULL); } /* destroy */ void pet_free_htable(struct pet_hashtable * htable) { struct hash_entry * cursor = NULL; struct hash_entry * tmp = NULL; struct hash_entry ** table = htable->table; uint32_t i = 0; for (i = 0; i < htable->table_length; i++) { cursor = table[i]; while (cursor != NULL) { tmp = cursor; cursor = cursor->next; if (htable->key_free_fn) { htable->key_free_fn(tmp->key); } if (htable->val_free_fn) { htable->val_free_fn(tmp->value); } HTABLE_FREE(tmp); } } HTABLE_FREE(htable->table); HTABLE_FREE(htable); } /* HASH TABLE ITERATORS */ struct pet_hashtable_iter * pet_htable_create_iter(struct pet_hashtable * htable) { // uint32_t i = 0; uint32_t table_length = 0; struct pet_hashtable_iter * iter = (struct pet_hashtable_iter *)HTABLE_CALLOC(sizeof(struct pet_hashtable_iter), 1); if (iter == NULL) { return NULL; } iter->htable = htable; iter->entry = NULL; iter->parent = NULL; table_length = htable->table_length; iter->index = table_length; /* if (htable->entry_count == 0) { return iter; } for (i = 0; i < table_length; i++) { if (htable->table[i] != NULL) { iter->entry = htable->table[i]; iter->index = i; break; } } */ return iter; } void pet_htable_free_iter(struct pet_hashtable_iter * iter) { HTABLE_FREE(iter); } uintptr_t pet_htable_get_iter_key(struct pet_hashtable_iter * iter) { return iter->entry->key; } uintptr_t pet_htable_get_iter_value(struct pet_hashtable_iter * iter) { return iter->entry->value; } /* advance - advance the iterator to the first/next element * returns zero if advanced to end of table */ int pet_htable_iter_advance(struct pet_hashtable_iter * iter) { uint32_t i = 0; uint32_t j = 0; uint32_t table_length = iter->htable->table_length;; struct hash_entry ** table = NULL; struct hash_entry * next = NULL; if (iter->entry == NULL) { for (i = 0; i < table_length; i++) { if (iter->htable->table[i] != NULL) { iter->entry = iter->htable->table[i]; iter->index = i; break; } } return (iter->entry != NULL); } next = iter->entry->next; if (next != NULL) { iter->parent = iter->entry; iter->entry = next; return 1; } iter->parent = NULL; if (table_length <= (j = ++(iter->index))) { iter->entry = NULL; return 0; } table = iter->htable->table; while ((next = table[j]) == NULL) { if (++j >= table_length) { iter->index = table_length; iter->entry = NULL; return 0; } } iter->index = j; iter->entry = next; return 1; } /* remove - remove the entry at the current iterator position * and advance the iterator, if there is a successive * element. * If you want the value, read it before you remove: * beware memory leaks if you don't. * Returns zero if end of iteration. */ int pet_htable_iter_remove(struct pet_hashtable_iter * iter) { struct hash_entry * remember_entry = NULL; struct hash_entry * remember_parent = NULL; int ret; /* Do the removal */ if ((iter->parent) == NULL) { iter->htable->table[iter->index] = iter->entry->next; /* element is head of a chain */ } else { iter->parent->next = iter->entry->next; /* element is mid-chain */ } /* itr->e is now outside the hashtable */ remember_entry = iter->entry; iter->htable->entry_count -= 1; if (iter->htable->key_free_fn) { iter->htable->key_free_fn(remember_entry->key); } /* Advance the iterator, correcting the parent */ remember_parent = iter->parent; ret = pet_htable_iter_advance(iter); if (iter->parent == remember_entry) { iter->parent = remember_parent; } HTABLE_FREE(remember_entry); return ret; } /* returns zero if not found */ int pet_htable_iter_search(struct pet_hashtable_iter * iter, struct pet_hashtable * htable, uintptr_t key) { struct hash_entry * entry = NULL; struct hash_entry * parent = NULL; uint32_t hash_value = 0; uint32_t index = 0; hash_value = do_hash(htable, key); index = indexFor(htable->table_length, hash_value); entry = htable->table[index]; parent = NULL; while (entry != NULL) { /* Check hash value to short circuit heavier comparison */ if ((hash_value == entry->hash) && (htable->eq_fn(key, entry->key))) { iter->index = index; iter->entry = entry; iter->parent = parent; iter->htable = htable; return 1; } parent = entry; entry = entry->next; } return 0; }
C
#include <stdio.h> int main() { int i,j,tam; printf("\n entre com o tamanho do quadrado [4-80]"); scanf("%d",&tam); for(i=1;i<=tam;i++) { for(j=1;j<=tam;j++) { if(i==1||i==tam) printf("#"); else if(j==1||j==tam) printf("#"); else printf(" "); } printf("\n"); } system("pause"); return 0; }
C
#ifndef PARSER_H #define PARSER_H #include <stdlib.h> #include "value.h" #include "talloc.h" /* * Takes a linked list of tokens from a Scheme program (as in * the output of your tokenizer), and it should return a pointer * to a parse tree representing that program. */ Value *parse(Value *tokens); /* * display a parse tree to the screen, using parentheses to denote * tree structure. (In other words, the output of printTree should * visually look identical to legal Scheme code.) */ void printTree(Value *tree); #endif
C
#include <stdio.h> #include <stdlib.h> typedef struct neighbor{ int num; struct neighbor *next; } AS_neighbor; /* * Estrutura que guarda o ASN e os vizinhos */ typedef struct asnode{ AS_neighbor *customers; AS_neighbor *peers; AS_neighbor *providers; } AS_node; typedef struct astopnode{ int asn; AS_neighbor *start; struct astopnode *next; } AS_topnode; void new_link(int asn, int neighborn, int rel, AS_node ** hash_table); AS_neighbor * AS_neighbor_new(int num); AS_node * AS_node_new(void); void print_AS_table(AS_node ** AS_table); int best_est_possible(int * counts); AS_neighbor * remove_node(AS_neighbor * remove, AS_neighbor * parent, AS_neighbor * set_to_visit); int elected_route(int origin, int dest, AS_node ** AS_table); AS_neighbor * Sort_List(AS_neighbor *pList, int asn, AS_neighbor **start); int IsConnected(AS_node **AS_table); AS_topnode * AS_topnode_new(int asn, AS_neighbor *start, AS_topnode *next);
C
#ifndef _A01b_H #define _A01b_H #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <math.h> #include <string.h> #include <sys/time.h> typedef struct{ size_t sizeX, sizeY, number; double *element; } matrix; void init_(matrix *TARGET) { TARGET->sizeX = 0; TARGET->sizeY = 0; TARGET->element = malloc(1); } void clear_(matrix *TARGET) { free(TARGET->element); } void inits (matrix *TARGET, size_t size) { for(int i = 0; i < size; i++) init_ (&TARGET[i]); } void clears(matrix *TARGET, size_t size) { for(int i = 0; i < size; i++) clear_(&TARGET[i]); } void init(matrix *TARGET, ...) { va_list list; va_start(list, TARGET); while(TARGET != 0) { init_((matrix *) TARGET); TARGET = va_arg(list, matrix *); } va_end(list); } void clear(matrix *TARGET, ...) { va_list list; va_start(list, TARGET); while(TARGET != 0) { clear_((matrix *) TARGET); TARGET = va_arg(list, matrix *); } va_end(list); } void printm(matrix INPUT, char *text, double threshold) { printf("\n\x1B[38;5;7m%s %dx%d\n", text, INPUT.sizeX, INPUT.sizeY); double buff; for(int i = 0; i < INPUT.sizeX * INPUT.sizeY; i++) { (INPUT.element[i] >= threshold)? printf("\x1B[38;5;2m"): printf("\x1B[38;5;1m"); buff = INPUT.element[i]; if(buff >= 0) printf(" %.2f ", buff); else printf("%.2f ", buff); if ( (i + 1) % INPUT.sizeY == 0 ) printf("\n"); } } void MOD_random(matrix *TARGET, size_t sizeX, size_t sizeY) { TARGET->sizeX = sizeX; TARGET->sizeY = sizeY; TARGET->element = realloc(TARGET->element, sizeof(double) * sizeX *sizeY); struct timeval tme; gettimeofday(&tme, 0); srand((unsigned) tme.tv_usec); double buff; for(int i = 0; i < sizeX * sizeY; i++) { buff = (double)rand() / (double)(RAND_MAX); TARGET->element[i] = rand() % 2 == 0? buff: -buff; } } #define sigmoid(x) 1 / (1 + exp(-x)) #define sigmoid_dx(x) x * (1 - x) void sigmoid_matrix(matrix *TARGET, matrix INPUT) { size_t size = INPUT.sizeX * INPUT.sizeY, i = 0; TARGET->sizeX = INPUT.sizeX; TARGET->sizeY = INPUT.sizeY; TARGET->element = realloc(TARGET->element, sizeof(double) * size); for(; i < size; i++) TARGET->element[i] = sigmoid(INPUT.element[i]); } void sigmoid_dx_matrix(matrix *TARGET, matrix INPUT) { size_t size = INPUT.sizeX * INPUT.sizeY, i = 0; TARGET->sizeX = INPUT.sizeX; TARGET->sizeY = INPUT.sizeY; TARGET->element = realloc(TARGET->element, sizeof(double) * size); for(; i < size; i++) TARGET->element[i] = sigmoid_dx(INPUT.element[i]); } void add_matrix(matrix *TARGET, matrix A, matrix B) { size_t size = A.sizeX * A.sizeY, i = 0; TARGET->sizeX = A.sizeX; TARGET->sizeY = A.sizeY; TARGET->element = realloc(TARGET->element, sizeof(double) * size); for(; i < size; i++) TARGET->element[i] = A.element[i] + B.element[i]; } void mul_matrix_alt(matrix *TARGET, matrix A, matrix B) { size_t size = A.sizeX * A.sizeY, i = 0; TARGET->sizeX = A.sizeX; TARGET->sizeY = A.sizeY; TARGET->element = realloc(TARGET->element, sizeof(double) * size); for(; i < size; i++) TARGET->element[i] = A.element[i] * B.element[i]; } void sub_matrix(matrix *TARGET, matrix A, matrix B) { size_t size = A.sizeX * A.sizeY, i = 0; TARGET->sizeX = A.sizeX; TARGET->sizeY = A.sizeY; TARGET->element = realloc(TARGET->element, sizeof(double) * size); for(; i < size; i++) TARGET->element[i] = A.element[i] - B.element[i]; } void mul_matrix(matrix *TARGET, matrix A, matrix B) { double MA[A.sizeX * A.sizeY], *MA_ptr = MA, MB[B.sizeX * B.sizeY], *MB_ptr = MB; int i; for(i = 0; i < A.sizeX * A.sizeY; i++) MA[i] = A.element[i]; for(i = 0; i < B.sizeX * B.sizeY; i++) MB[i] = B.element[i]; TARGET->sizeX = A.sizeX; TARGET->sizeY = B.sizeY; TARGET->element = realloc(TARGET->element, sizeof(double) * A.sizeX * B.sizeY); double *TARGET_ptr = TARGET->element, buffer[A.sizeX][B.sizeY]; for(int IAx = 0; IAx < A.sizeX; IAx++) { for(int IBy = 0; IBy < B.sizeY; IBy++) { buffer[IAx][IBy] = 0; for(int IAy = 0; IAy < A.sizeY; IAy++) { buffer[IAx][IBy] += *MA_ptr++ * *MB_ptr; MB_ptr += B.sizeY; } MA_ptr -= A.sizeY; MB_ptr -= A.sizeY * B.sizeY - 1; *TARGET_ptr++ = buffer[IAx][IBy]; } MA_ptr += A.sizeY; MB_ptr -= B.sizeY; } } void mirror_matrix(matrix *TARGET, matrix INPUT) { double buff[INPUT.sizeY][INPUT.sizeX], *INPUT_ptr = INPUT.element; int ix, iy; for(ix = 0; ix < INPUT.sizeX; ix++) for(iy = 0; iy < INPUT.sizeY; iy++) buff[iy][ix] = *INPUT_ptr++; TARGET->sizeX = INPUT.sizeY; TARGET->sizeY = INPUT.sizeX; TARGET->element = realloc(TARGET->element, sizeof(double) * INPUT.sizeX * INPUT.sizeY); double *TARGET_ptr = TARGET->element; for(iy = 0; iy < INPUT.sizeY; iy++) for(ix = 0; ix < INPUT.sizeX; ix++) *TARGET_ptr++ = buff[iy][ix]; } double dot_array(double *A, double *B, size_t size) { double buff = 0; for (int i = 0; i < size; i++) buff += A[i] * B[i]; return buff; } void MOD_dot_matrix(matrix *TARGET, matrix A, matrix B) { double A_buff[A.sizeX][A.sizeY], B_buff[B.sizeX][B.sizeY], *A_ptr = A.element, *B_ptr = B.element; int iA, iB, iY; for(iA = 0; iA < A.sizeX; iA++) for(iY = 0; iY < A.sizeY; iY++) A_buff[iA][iY] = *A_ptr++; for(iB = 0; iB < B.sizeX; iB++) for(iY = 0; iY < B.sizeY; iY++) B_buff[iB][iY] = *B_ptr++; TARGET->sizeX = A.sizeX; TARGET->sizeY = B.sizeX; TARGET->element = realloc(TARGET->element, sizeof(double) * A.sizeX * B.sizeX); double *TARGET_ptr = TARGET->element; for(iA = 0; iA < A.sizeX; iA++) for(iB = 0; iB < B.sizeX; iB++) *TARGET_ptr++ = dot_array(A_buff[iA], B_buff[iB], A.sizeY); } void read_matrix(matrix *TARGET, char *filename) { FILE *INfile = fopen(filename, "r"); char *buff = malloc(sizeof(char) * 255); int sizeX = 1, sizeY = 0; while(buff[0] != ';') { fscanf(INfile, "%s", buff); if(buff[0] == ',') sizeX++; else if(sizeX == 1) sizeY++; } TARGET->sizeX = sizeX; TARGET->sizeY = sizeY; TARGET->element = realloc(TARGET->element, sizeof(double) * sizeX * sizeY); double *TARGET_ptr = TARGET->element; rewind(INfile); buff[0] = 'N'; while(buff[0] != ';') { fscanf(INfile, "%s", buff); if(buff[0] != ',') *TARGET_ptr++ = atof(buff); } free(buff); fclose(INfile); } void read_matrixs(matrix **TARGET, char *filename) { FILE *INfile = fopen(filename, "r"); char *buff = malloc(sizeof(char) * 255); int matrix_amount = 0; while(strcmp(buff, "END")) { fscanf(INfile, "%s", buff); if(buff[0] == ';') matrix_amount++; } rewind(INfile); *TARGET = realloc(*TARGET, sizeof(matrix) * matrix_amount); inits(*TARGET, matrix_amount); TARGET[0]->number = matrix_amount; int X[matrix_amount], Y[matrix_amount], i = 0; for(; i < matrix_amount; i++) { X[i] = 1; Y[i] = 0; for(; buff[0] != ';';) { fscanf(INfile, "%s", buff); if(buff[0] == ',') X[i]++; else if(X[i] == 1) Y[i]++; } buff[0] = 'N'; } rewind(INfile); double *TARGET_ptr; for(i = 0; i < matrix_amount; i++) { TARGET[0]->sizeX = X[i]; TARGET[0]->sizeY = Y[i]; TARGET[0]->element = realloc(TARGET[0]->element, sizeof(double) * X[i] * Y[i]); TARGET_ptr = TARGET[0]->element; TARGET[0]++; for(; buff[0] != ';';) { fscanf(INfile, "%s", buff); if(buff[0] != ',') *TARGET_ptr++ = atof(buff); } buff[0] = 'N'; } TARGET[0] -= matrix_amount; free(buff); fclose(INfile); } void write_matrix(matrix meta, char *filename) { FILE *file = fopen(filename, "w+"); char write_buff[4096] , buff[512]; for(int i = 0; i < meta.sizeX * meta.sizeY; i++) { if(meta.element[i] >= 0) sprintf(buff, " %.2f\t", meta.element[i]); else sprintf(buff, "%.2f\t", meta.element[i]); strcat(write_buff, buff); if((i + 1) % (meta.sizeX * meta.sizeY) == 0) strcat(write_buff, ";\n"); else if((i + 1) % meta.sizeY == 0) strcat(write_buff, ",\n"); } fputs(write_buff, file); fclose(file); } void write_matrixs(matrix *meta, char *filename) { int write_size = 0, meta_num = 0; for(; meta_num++ < meta[0].number; write_size += sizeof(char *) * meta[meta_num].sizeX * meta[meta_num].sizeY * 8) ; FILE *file = fopen(filename, "w"); char write_buff[write_size], buff[512]; for(meta_num = 0; meta_num < meta[0].number; meta_num++) for(int position = 0; position < meta[meta_num].sizeX * meta[meta_num].sizeY; position++) { if(meta[meta_num].element[position] >= 0) sprintf(buff, " %.2f\t", meta[meta_num].element[position]); else sprintf(buff, "%.2f\t", meta[meta_num].element[position]); strcat(write_buff, buff); if((position + 1) % (meta[meta_num].sizeX * meta[meta_num].sizeY) == 0) strcat(write_buff, ";\n"); else if((position + 1) % meta[meta_num].sizeY == 0) strcat(write_buff, ",\n"); } strcat(write_buff, "END"); fputs(write_buff, file); fclose(file); } #endif
C
// // Created by Anirudh on 30/03/21. // #ifndef PS5_NODE_H #define PS5_NODE_H enum type_of_value{ OPERATOR, NUMBER }; enum type_of_operation{ LEFT_BRACKET, RIGHT_BRACKET, ADDITION, SUBTRACTION, MULTIPLICATION, DIVISION, EXPONENTIATION }; typedef struct node{ union{ double value; char operator; } contents; int type; int precedence; struct node *next; }node; struct node* createNode(int type, char *token); #endif //PS5_NODE_H
C
#include<stdio.h> #include<math.h> void round_money(double *val) { *val =((int)(*val * 100 + .5) / 100.0); } void chargers(double h,double *charge,double *avg) { if(h<=10) *charge=7.99; else { double h1=ceil(h); *charge=7.99+(1.99*(h1-10)); } *avg=*charge/h; round_money(charge); round_money(avg); } int main() { double d,yr,h,charge,avg; int id; FILE *inp=fopen("usage.txt","r"); FILE *out=fopen("chargers.txt","w"); fscanf(inp,"%d%d",&d,&yr); fprintf(out,"Charges for %d/%d\n",d,yr); fprintf(out,"customers Hours used Charge per hour Avg. cost\n"); while(fscanf(inp,"%d",&id)!=EOF) { fscanf(inp,"%lf",&h); fprintf(out,"%d%15.2lf",id,h); chargers(h,&charge,&avg); fprintf(out,"%15.2lf%15.2lf\n",charge,avg); } fclose(inp); fclose(out); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main(int argc, char const *argv[]) { char c[1000]; FILE *restrict fptr; if ((fptr = fopen("singcl.txt", "r")) == NULL) { printf("Error,! opening file"); exit(1); } fscanf(fptr, "%[^\n]", c); printf("The string: \n%s", c); fclose(fptr); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_parser.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mrahmani <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/05 11:58:55 by mrahmani #+# #+# */ /* Updated: 2021/01/05 12:05:36 by mrahmani ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/ft_printf.h" void parse_flags(int *i, char *str, t_format *parser) { if (str[*i] == '\0') return ; if (str[*i] == '-') { parser->flag = '-'; *i = *i + 1; } else if (str[*i] == '0') { parser->flag = '0'; *i = *i + 1; if (str[*i] == '-') { parser->flag = '-'; *i = *i + 1; } } } void parse_width(int *i, char *str, t_format *parser) { int count; char *width; count = 0; if (str[*i] == '\0') return ; if (str[*i] == '*') { parser->is_dynamic_wdith = 1; *i = *i + 1; return ; } while (ft_isdigit(str[*i])) { *i = *i + 1; count++; } if (count == 0) return ; width = ft_substr(str, *i - count, count + 1); parser->width = ft_atoi(width); free(width); } void ft_check_str(char *str, int *i, t_format *parser) { int count; char *result; count = 0; if (ft_isdigit(str[*i]) == 1) { while (ft_isdigit(str[*i])) { *i = *i + 1; count++; } result = ft_substr(str, *i - count, count); parser->precision = ft_atoi(result); free(result); } else if (is_valid_specifier(str[*i])) parser->precision = 0; else if (!ft_isdigit(str[*i]) && !is_valid_specifier(str[*i])) { while (!ft_isdigit(str[*i]) && !is_valid_specifier(str[*i])) *i = *i + 1; } } void parse_precision(int *i, char *str, t_format *parser) { if (str[*i] == '\0') return ; if (str[*i] != '.') return ; *i = *i + 1; if (str[*i] == '*') { parser->is_dynamic_precision = 1; *i = *i + 1; } else ft_check_str(str, i, parser); } void parse_specifier(int *i, char *str, t_format *parser) { if (str[*i] == '\0') return ; if (is_valid_specifier(str[*i]) || str[*i] == '%') { parser->specifier = str[*i]; *i = *i + 1; } else if (is_valid_specifier(str[*i]) == 0) { *i = *i + 1; if (is_valid_specifier(str[*i])) { parser->specifier = str[*i]; *i = *i + 1; } } }
C
#include <stdio.h> #include <stdarg.h> void printlns(char *fst, ...) { char *str; va_list vl; str = fst; va_start(vl, fst); do { printf("%s\n", str); str = va_arg(vl, char*); } while (str != NULL); va_end(vl); } int main(int argc, char *argv[]) { printlns("First", "Second", "Third", NULL); return 0; }
C
#include<stdio.h> #include<string.h> int main(void) { char a[100]; int i,b,count=0; gets(a); b=strlen(a); for(i=0;i<=b;i++) { if(((a[i]>=27 && a[i]<=47) && a[i]!=32)||(a[i]>=58 && a[i]<=64)||(a[i]>=91 && a[i]<=96) ||(a[i]>=123 && a[i]<=126)) { count++; } } printf("%d",count); return 0; }
C
#include <unistd.h> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <string.h> void eatMem(int time,int block_num) { int block = block_num; int i =0; int j = 0; int cell = 0.1 * 1024 * 1024; char * pMem[block]; for(i = 0; i < block; i++) { pMem[i] = (char*)malloc(cell); if(NULL == pMem[i]) { printf("Insufficient memory avalible ,Cell %d Failure\n", i); break; } memset(pMem[i], 0, cell); printf("[%d]%d Bytes.\n", i, cell); fflush(stdout); } sleep(time); printf("Done! Start to release memory.\n"); //释放内存 for(i = 0; i < block; i++) { printf("free[%d]\n", i); if(NULL != pMem[i]) { free(pMem[i]); pMem[i] = NULL; } fflush(stdout); } printf("Operation successfully!\n"); fflush(stdout); } int main(int argc,char * args[]) { eatMem(atoi(args[1]),atoi(args[2])); }
C
#include <stdlib.h> #include <stdio.h> #define BLOCK 128 #define MAX 1000000 int main(void){ int i = 0; int j = 0; FILE *fp; // A buffer for the filename. char file1[BLOCK]; char buffer[MAX]; printf("Please enter file to be read:\n"); printf("\nWarning: Your file will only be read in increments of 128 byte blocks\n"); gets(file1); if((fp = fopen(file1, "r+")) == NULL){ fprintf(stderr, "Error opening file"); exit(1); }else while(!feof(fp)) { if(fread(buffer, sizeof(char), BLOCK, fp)!= BLOCK) { printf("\n abbherant Block %d",i); printf("\n HEX: %x", buffer); printf("\n\n\t%s", buffer); i++; }else{ printf("\n Block : %d", j); printf("\n HEX: %x", buffer); printf("\n\n\t%s", buffer); j++; } } fclose(fp); //printf("\n%s", buffer); //printf("\n%x", buffer); }
C
#include "libft.h" char *ft_substr(char const *s, unsigned int start, size_t len) { char *sub; char *str; unsigned int i; unsigned int sub_size; if (!s) return (NULL); if (start >= ft_strlen(s)) return (ft_strdup("")); if (start + len <= ft_strlen(s)) sub_size = len; else sub_size = ft_strlen(s) - start; sub = ft_calloc(sub_size + 1, sizeof(char)); str = (char *)s; i = 0; while (i < sub_size && str[start + i] != '\0') { sub[i] = str[start + i]; i++; } return (sub); }
C
//369Problem //A number is said to be a 369 number if //The count of 3s is equal to count of 6s and the count of 6s is equal to count of 9s. The count of 3s is at least 1. For Example 12369, 383676989, 396 all are 369 numbers whereas 213, 342143, 111 are not. //Given A and B find how many 369 numbers are there in the interval [A, B] #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int c3 = 0, c6 = 0, c9 = 0, count = 0; int i, r, j; int a, b; scanf ("%d", &a); scanf ("%d", &b); for (i = a; i <= b; i++) { c3=0;c6=0;c9=0; for (j = i; j > 0; j = j / 10) { r = j % 10; if (r == 3) { c3++; } if (r == 6) { c6++; } if (r == 9) { c9++; } } if (c3 == c6 && c3 == c9) { if(c3!=0) { count++; } } } printf ("%d", count); return 0; }
C
/********************************************************************************/ /*PURPOSE: Gets radius and calculates area, diameter, and circumference. */ /*IMPLEMENTED BY: DAG */ /*DATE: 12/7/15 */ /*USER INFORMATION: The user puts inputs radius. */ /*IMPLEMENTATION METHOD: The program gets a radius from user and calculates the */ /* area, diameter, and circumference of a circle. */ /*OVERVIEW OF SUBPARTS: The program consist of the main function and subparts. */ /********************************************************************************/ #include <iostream> using namespace std; class circle//initialize circle class { private://only functions in circle can call privite double radius; double pi; public://functions to interact with circle object circle();//constructor circle(double r);//constructor with given radius void setRadius(double newR);//Set a new radius double getRadius();//returns object's radius double getArea();//returns object's Area double getDiameter();//returns object's diameter double getCircumference();//returns object's circumference }; //Constructs a circle object with no given parameters circle::circle() { radius = 0.0;//Radius of new circle object pi = 3.14; } //Constructs a circle with a given radius circle::circle(double r) { radius = r;//Radius of new circle given by parameter pi = 3.14; } //Changes a circle object's radius with that of the parameters void circle::setRadius(double newR) { radius = newR; } //Returns a circle object's radius double circle::getRadius() { return radius; } //Returns a circle object's Area double circle::getArea() {//calculate area with object's radius and pi return pi*radius*radius; } //Returns a circle object's diameter double circle::getDiameter() {//calculate diameter with object's radius return radius*2; } double circle::getCircumference() {//Calculate circumference w/ objects radius and pi return pi*radius*2; } int main() { circle c1; //Construct a circle object with no given parameters double ans; cout << "Enter a radius: "; cin >> ans; c1.setRadius(ans);//set new radius to given input //Display the circle object's properties cout << "Circle's radius: " << c1.getRadius() << endl; cout << "Circles's area: " << c1.getArea() << endl; cout << "Circle's diameter: " << c1.getDiameter() << endl; cout << "Circle's circumference: " << c1.getCircumference() << endl; return 0; }
C
#include <iostream> #include<string.h> #include<string> using namespace std; char * bubblesort(char *,int); int main() { int n,l,gp=0; cin>>n; string s[n]; char s1[100]; char *s2; for(int i=0;i<n;i++) { cin>>s1; l=strlen(s1); s2=bubblesort(s1,l); s[i]=s2; } for(int i=0;i<n-1;i++) { string temp; for(int j=0;j<n-1;j++) { if(s[j].compare(s[j+1])>0) { temp=s[j]; s[j]=s[j+1]; s[j+1]=temp; } } } for(int j=0;j<n;j++) { int count=0; for(int k=j+1;k<n;k++) { if(s[j].compare(s[k])==0) { count++; j++; } //j=j+count; //yes i figured out....this is resulting into segmentation fault } if(count) { gp++; } } cout<<gp; } char *bubblesort(char *x,int l1) { char temp; for(int j=0;j<l1-1;j++) { for(int k=0;k<l1-1;k++) { if(x[k]>x[k+1]) { temp=x[k]; x[k]=x[k+1]; x[k+1]=temp; } } } return x; }
C
/* * FILENAME: otp_enc_d.c * DESCRIPTION: otp_enc_d serves as a sever to encrpyt messages * Jared Tence */ #include "otp_tools.h" // Error function used for reporting issues void parseInput(char *, char *); //runs the server int main(int argc, char *argv[]) { //initalizes values later to be used int listenSocketFD, establishedConnectionFD, portNumber, charsRead; socklen_t sizeOfClientInfo; struct sockaddr_in serverAddress, clientAddress; //checks if there are not enough arguments if (argc < 2) { fprintf(stderr, "USAGE: %s port\n", argv[0]); exit(1); } // Check usage & args // Set up the address struct for this process (the server) memset((char *)&serverAddress, '\0', sizeof(serverAddress)); // Clear out the address struct portNumber = atoi(argv[1]); // Get the port number, convert to an integer from a string serverAddress.sin_family = AF_INET; // Create a network-capable socket serverAddress.sin_port = htons(portNumber); // Store the port number serverAddress.sin_addr.s_addr = INADDR_ANY; // Any address is allowed for connection to this process // Set up the socket listenSocketFD = socket(AF_INET, SOCK_STREAM, 0); // Create the socket if (listenSocketFD < 0) error("ERROR opening socket"); // Enable the socket to begin listening if (bind(listenSocketFD, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0) // Connect socket to port error("ERROR on binding"); listen(listenSocketFD, 5); // Flip the socket on - it can now receive up to 5 connections //runs forever int con = 1; while(con){ // Accept a connection, blocking if one is not available until one connects sizeOfClientInfo = sizeof(clientAddress); // Get the size of the address for the client that will connect establishedConnectionFD = accept(listenSocketFD, (struct sockaddr *)&clientAddress, &sizeOfClientInfo); // Accept //when an established connection is made it forks the process to deal with it int spawnPid = fork(); switch (spawnPid) { //breaks if fork errors case -1: fprintf(stderr, "ERROR creating fork\n"); exit(1); case 0: if (establishedConnectionFD < 0) error("ERROR on accept"); // Get the message from the client char rawInput[MAX_BUFFER], encryptString[MAX_BUFFER]; memset(rawInput, '\0', MAX_BUFFER); memset(encryptString, '\0', MAX_BUFFER); getInput(establishedConnectionFD, rawInput, MAX_BUFFER - 1); //set values so it has correct terminates and if it recieves a vlue //from otp_dec then it sends back a blank message if(rawInput[strlen(rawInput) - 1] == '%'){ encryptString[0] = '@'; encryptString[1] = '\0'; }else{ parseInput(rawInput, encryptString); encryptString[strlen(encryptString)] = '@'; encryptString[strlen(encryptString)] = '\0'; } // Send a encrpyted message back to the client sendMessage(establishedConnectionFD, encryptString); close(establishedConnectionFD); // Close the existing socket which is connected to the client } //KILL THOSE ZOMBIE CHILDREN waitpid((pid_t)(-1), 0, WNOHANG); } close(listenSocketFD); // Close the listening socket return 0; } //parses raw input and encrpyts to be sent out void parseInput(char * rawInput, char * encryptString){ strcpy(encryptString, strtok(rawInput,"&")); char * key = strtok(NULL,"&"); encrypt(encryptString, key); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_pwd.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: getrembl <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/05/18 14:25:20 by getrembl #+# #+# */ /* Updated: 2015/05/18 16:15:57 by getrembl ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell_1.h" char **ft_pwd(char **envp) { int i[2]; char *pwd; char *oldpwd; pwd = ft_strnew(BUFFERSIZE); pwd = getcwd(pwd, BUFFERSIZE); i[0] = -1; while (envp[++i[0]]) if (ft_strncmp(envp[i[0]], "PWD=", 4) == 0) { oldpwd = ft_strdup(envp[i[0]]); oldpwd = ft_strrchr(oldpwd, '='); oldpwd++; i[1] = -1; while (envp[++i[1]]) if (ft_strncmp(envp[i[1]], "OLDPWD=", 7) == 0) { envp[i[1]] = ft_strnew(ft_strlen(oldpwd) + 15); envp[i[1]] = ft_strcpy(envp[i[1]], "OLDPWD="); envp[i[1]] = ft_strcat(envp[i[1]], oldpwd); } } i[0] = -1; while (envp[++i[0]]) if (ft_strncmp(envp[i[0]], "PWD=", 4) == 0) { envp[i[0]] = ft_strnew(BUFFERSIZE); envp[i[0]] = ft_strcpy(envp[i[0]], "PWD="); envp[i[0]] = ft_strcat(envp[i[0]], pwd); } return (envp); }
C
#include<stdio.h> #include<math.h> int main() { int t,i; double x,y; char str[1000]; scanf("%d",&t); while(t--) { scanf(" %s",str); x=y=0.0; for(i=0;str[i];i++) { switch(str[i]) { case 'A':x+=1; y+=0; break; case 'B':x+=0.5; y+=sqrt(3)/2; break; case 'C':x+=-0.5; y+=sqrt(3)/2; break; case 'D':x+=-1; y+=0; break; case 'E':x+=-0.5; y+=-sqrt(3)/2; break; case 'F':x+=0.5; y+=-sqrt(3)/2; break; } } printf("%0.10f ",sqrt(x*x+y*y)); } return 0; }
C
#ifdef __cplusplus #include <cmath> #else #include <math.h> #endif #ifndef M_PI /* pi */ #define M_PI 3.14159265358979323846264338327950288 #endif #ifndef M_PIf /* pi (float) */ #define M_PIf 3.14159265358979323846264338327950288f #endif #ifndef M_PI_2 /* pi/2 */ #define M_PI_2 1.57079632679489661923132169163975144 #endif
C
#include <stdlib.h> #include <stdio.h> #include "world.h" void AddEntity(EntityNode **head, Entity *newEntity) { EntityNode *currNode = *head; EntityNode *newNode = newEntityNode(newEntity); if (currNode) { while (currNode->next) { currNode = currNode->next; } currNode->next = newNode; } else { *head = newNode; } } EntityNode *newEntityNode(Entity *entity) { EntityNode *newNode = (EntityNode *) malloc(sizeof(EntityNode)); if (newNode) { newNode->entity = entity; newNode->next = 0; } else { printf("Could not allocate memory (newEntityNode)\n"); exit(-1); } return (newNode); } Entity *newEntity(void *object, EntityKind kind) { Entity *new = (Entity *) malloc(sizeof(Entity)); if (new) { new->object = object; new->kind = kind; } else { printf("Could not allocate memory (newEntity)\n"); exit(-1); } return (new); } Player *GetPlayer(EntityNode *head) { EntityNode *currNode = head; while (currNode) { if (currNode->entity->kind == PLAYER) return ((Player *)currNode->entity->object); currNode = currNode->next; } return (0); }
C
/* * activity.h * banker * * Created by Yeison Rodriguez on 12/14/09. * Copyright 2009 New York University. All rights reserved. * */ /* An activity is a struct, which contains all of the information from one typical "line" of input. It also contains a next pointer, so that activity nodes may be arranged in a linked list. The linked list will be used as a queue. This way we can maintain task activities in the appropriate order.*/ #ifndef bankers_activity_h #define bankers_activity_h typedef struct activity activity; struct activity { int taskNumber; int delay; int type; int resourceType; int resourceAmount; int currentState; activity *next; }; // Create an activity node (an action to be performed on a task) activity* makeActivityNode(); // Create queues of actions(activities) for each task void makeActivityQueues(activity *taskTable[], activity *taskTableTails[]); // Retrieve the integer value for the string type int getActivityTypeValue(char *type); // Retrieve string-value for the activity type char* getActivityType(int activityTypeValue); #define NOT_INITIATED 0 #define TERMINATE 1 #define INITIATE 2 #define REQUEST 3 #define RELEASE 4 #define GRANTED 6 #define WAITING 7 #define DELAYED 8 #define DENIED 9 #define MAX_STRING_LENGTH 10 #endif
C
/* ** my_strcat_dyn.c for strcat dyn in /lib/ ** ** Made by Frederic ODDOU ** Login oddou_f <[email protected]> ** ** Started on Mon Mar 14 17:52:04 2016 Frederic ODDOU ** Last update Thu Apr 14 09:20:38 2016 Mizibi */ #include <stdlib.h> #include "my.h" char *my_strcat_fusion(char *dest, char *src) { unsigned int id; unsigned int is; char *new; id = 0; is = 0; if (dest == NULL || src == NULL) return (NULL); if ((new = malloc(my_strlen(dest) + my_strlen(src) + 1)) == NULL) { my_putstr(ERROR_MALLOC); return (NULL); } while (dest[id] != '\0') { new[id] = dest[id]; id++; } while (src[is] != '\0') new[id++] = src[is++]; new[id] = '\0'; return (new); } char *my_strcat_dyn(char *dest, char *src) { unsigned int id; unsigned int is; char *new; id = 0; is = 0; if (dest == NULL || src == NULL) return (NULL); if ((new = malloc(my_strlen(dest) + my_strlen(src) + 1)) == NULL) { my_putstr(ERROR_MALLOC); return (NULL); } while (dest[id] != '\0') { new[id] = dest[id]; id++; } while (src[is] != '\0') new[id++] = src[is++]; new[id] = '\0'; free(dest); return (new); } char *my_strcat_dyn_char(char *dest, char src) { unsigned int id; char *new; id = 0; if (dest == NULL) return (NULL); if ((new = malloc(my_strlen(dest) * sizeof(char) + 2)) == NULL) { my_putstr(ERROR_MALLOC); return (NULL); } while (dest[id] != '\0') { new[id] = dest[id]; id++; } new[id++] = src; new[id] = '\0'; free(dest); return (new); }
C
#include <stdio.h> #include <cs50.h> int main (void) { int x = get_int("n: "); int y = get_int("\ny: "); if (x > y) printf("\n\nx is greater than y\n"); else if (x < y) printf("\n\nx is less than y\n"); else printf("\n\nx is equals to y\n"); }
C
#ifndef SNMP_PARSE_ARGS_H #define SNMP_PARSE_ARGS_H /** * @file snmp_parse_args.h * * Support for initializing variables of type netsnmp_session from command * line arguments */ #ifdef __cplusplus extern "C" { #endif /** Don't enable any logging even if there is no -L argument */ #define NETSNMP_PARSE_ARGS_NOLOGGING 0x0001 /** Don't zero out sensitive arguments as they are not on the command line * anyway, typically used when the function is called from an internal * config-line handler */ #define NETSNMP_PARSE_ARGS_NOZERO 0x0002 /** * Parsing of command line arguments succeeded and application is expected * to continue with normal operation. */ #define NETSNMP_PARSE_ARGS_SUCCESS 0 /** * Parsing of command line arguments succeeded, but the application is expected * to exit with zero exit code. For example, '-V' parameter has been found. */ #define NETSNMP_PARSE_ARGS_SUCCESS_EXIT -2 /** * Parsing of command line arguments failed and application is expected to show * usage (i.e. list of parameters) and exit with nozero exit code. */ #define NETSNMP_PARSE_ARGS_ERROR_USAGE -1 /** * Parsing of command line arguments failed and application is expected to exit * with nozero exit code. netsnmp_parse_args() has already printed what went * wrong. */ #define NETSNMP_PARSE_ARGS_ERROR -3 /** * Parse an argument list and initialize netsnmp_session from it. * @param argc Number of elements in argv * @param argv string array of at least argc elements * @param session * @param localOpts Additional option characters to accept * @param proc function pointer used to process any unhandled arguments * @param flags flags directing how to handle the string * * @retval 0 (= #NETSNMP_PARSE_ARGS_SUCCESS) on success * @retval #NETSNMP_PARSE_ARGS_SUCCESS_EXIT when the application is expected * to exit with zero exit code (e.g. '-V' option was found) * @retval #NETSNMP_PARSE_ARGS_ERROR_USAGE when the function failed to parse * the command line and the application is expected to show it's usage * @retval #NETSNMP_PARSE_ARGS_ERROR when the function failed to parse * the command line and it has already printed enough information for the user * and no other output is needed * * The proc function is called with argc, argv and the currently processed * option as arguments */ NETSNMP_IMPORT int netsnmp_parse_args(int argc, char **argv, netsnmp_session *session, const char *localOpts, void (*proc)(int, char *const *, int), int flags); /** * Calls \link netsnmp_parse_args() * netsnmp_parse_args(argc, argv, session, localOpts, proc, 0)\endlink */ NETSNMP_IMPORT int snmp_parse_args(int argc, char **argv, netsnmp_session *session, const char *localOpts, void (*proc)(int, char *const *, int)); NETSNMP_IMPORT void snmp_parse_args_descriptions(FILE *); NETSNMP_IMPORT void snmp_parse_args_usage(FILE *); #ifdef __cplusplus } #endif #endif
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include "prog2Utils.h" // Structs do Programa // Cliente struct clients{ int id; char name[51]; char address[51]; char phone[20]; float debt; }; typedef struct clients clients; // Produto struct product{ int id; char name[31]; float price; int amount; }; typedef struct product product; // Vendas struct sales{ int id; int idCliente; int dataVenda[3]; int amount; float value; }; typedef struct sales sales; /* Função: newClient * ---------------- * Identifica qual ação será executada */ int readOption(){ // Recebe o valor referente a opção a ser executada int value = 0; // Imprime as opções disponiveis printf("____________Opções:____________\n"); printf("[1] Cadastrar Cliente:_________\n"); printf("[2] Cadastrar Produto:_________\n"); printf("[3] Alterar Produto:___________\n"); printf("[4] Realizar venda:____________\n"); printf("[5] Listar Clientes/Devedores:_\n"); printf("[6] Listar Vendas Feitas Hoje:_\n"); printf("[7] Fechar Caixa:______________\n"); printf("Opção: "); scanf("%d", &value); return value; } /* Função: newClient * ---------------- * Registra um novo cliente no sistema */ void newClient(){ clients cliente; // Recebendo as informações printf("Digite as informações do cliente: \n"); printf("Digite o id do cliente: "); scanf("%d", &cliente.id); printf("Nome: "); getchar(); fgets(cliente.name, sizeof(cliente.name), stdin); printf("Endereço: "); fgets(cliente.address, sizeof(cliente.address), stdin); printf("Telefone: "); fgets(cliente.phone, sizeof(cliente.phone), stdin); cliente.debt = 0.0; // Removendo a quebra de linha da string strtok(cliente.name, "\n"); strtok(cliente.address, "\n"); strtok(cliente.phone, "\n"); // Verifica se as informações estão corretas printf("%d,%s,%s,%s,%.2f\n", cliente.id, cliente.name, cliente.address, cliente.phone, cliente.debt); // Escaneando o arquivo FILE *client = fopen(":cliente.txt", "r"); if(client == NULL){ printf("Arquivo não encontrado!"); exit(0); } // Gravando as informações do cliente no arquivo client = fopen(":cliente.txt", "a"); if(client == NULL){ printf("Arquivo não encontrado!"); exit(0); } fprintf(client,"%d,%s,%s,%s,%.2f\n", cliente.id, cliente.name, cliente.address, cliente.phone, cliente.debt); fclose(client); } /* Função newFile * -------------- * Cria um novo arquivo ".txt" * fileName: Nome do arquivo * action: Comando de execução do arquivo */ void newFile(char fileName[], char action[]){ FILE *myFile = fopen(fileName, action); if(myFile == NULL){ printf("Arquivo não encontrado."); exit(0); } } /* Função: newProduct * ---------------- * Registra um novo produto no sistema */ void newProduct(){ product produto; // Variavel para produto // Recebendo as informações printf("Digite as informações do produto: \n"); printf("Digite o id do produto: "); scanf("%d", &produto.id); printf("Nome: "); getchar(); fgets(produto.name, 51, stdin); printf("Preço: "); scanf("%f", &produto.price); printf("Quantidade: "); scanf("%d", &produto.amount); // Remove a quebra de linha strtok(produto.name, "\n"); // Adicionando o produto no arquivo FILE *product = fopen(":produto.txt", "a"); if(product == NULL){ printf("Arquivo não encontrado!"); exit(0); } fprintf(product,"%d,%s,%.2f,%d\n", produto.id, produto.name, produto.price, produto.amount); fclose(product); } /* Função: verifyFile * ---------------- * Verifica se o arquivo existe * myFile: parametro que o nome do arquivo */ int verifyFile(char myFile[]){ FILE *fileToVerify = fopen(myFile, "r"); if(fileToVerify) return 1; else return 0; } /* Função: updateFile * ---------------- * Atualiza as informações do arquivo */ void updateFile(){ FILE *fileToUpdate = fopen(":produto.txt", "r"); if(fileToUpdate == NULL){ printf("Arquivo não encontrado!"); exit(0); } // Armazena as informações do produto a ser alterado product alter; char *token = calloc(2, sizeof(char)); char *s = calloc(2, sizeof(char)); // Lista todas as informações armazenadas no arquivo printf("Lista de produtos em estoque: \n"); while (!feof(fileToUpdate)){ char *line = calloc(100, sizeof(char)); char *result; result = fgets(line, 100+1, fileToUpdate); if (result) token = strtok(result, s); while( token != NULL ){ printf( "%s", token ); token = strtok(NULL, s); } } printf("\n"); s = ","; int position; int id; // Identifica o produto a ser alterado printf("digite o id do produto a ser alterado: "); scanf("%d", &id); // Identifica qual posição vai ser alterada printf("O deseja alterar: "); printf("[1] nome "); printf("[2] preço "); printf("[3] Quantidade: "); scanf("%d", &position); if(position == 1){ // Muda o nome do produto printf("Digite o novo nome: "); getchar(); fgets(alter.name, 100+1, stdin); strtok(alter.name, s); strtok(alter.name, "\n"); editFile(":produto.txt", s, id, position, alter.name); fclose(fileToUpdate); }else if(position == 2){ // Muda o preço do produto char *productPrice = calloc(10, sizeof(char)); printf("Digite o novo preço: "); getchar(); fgets(productPrice, 6, stdin); strtok(productPrice, s); strtok(productPrice, "\n"); editFile(":produto.txt", s, id, position, productPrice); fclose(fileToUpdate); }else if(position == 3){ // Atualiza o estoque do produto char productAmount[6]; printf("Produto atualize o estoque: "); getchar(); fgets(productAmount, 6, stdin); strtok(productAmount, s); strtok(productAmount, "\n"); editFile(":produto.txt", s, id, position, productAmount); fclose(fileToUpdate); }else if(position < 1 || position > 3){ printf("Opção invalida!"); fclose(fileToUpdate); exit(0); } } /* Função: gerarPvf * ---------------- * Cria o nome do arquivo que armazena todas as vendas ralizadas na data * fileName: parametro da variavel que será alterada */ void gerarPvf(char fileName[]){ int dia, mes, ano; // Recebendo as informações de data do sistema getToday(&dia, &mes, &ano); // Convertendo data de inteiro para caractere char day[3], month[3], year[5]; sprintf(day, "%d", dia); sprintf(month, "%d", mes); sprintf(year, "%d", ano); // Concatenando as informações para gerar o nome do arquivo strcat(fileName, ":"); strcat(fileName, day); strcat(fileName, month); strcat(fileName, year); strcat(fileName, ".pvf"); strtok(fileName, "\n"); } /* Função: sell * ---------------- * Realiza uma venda fiada ou avista * venda: parametro que recebe um vetor de extrutras */ void sell(sales *venda){ #define MAX 300 // Valor máximo de vendas que podem ser realiazadas char day[3]; char month[3]; char year[5]; char linha[200]; int verifica; int tipoVenda; int idCliente; int dia = 0; int mes = 0; int ano = 0; // Recebendo as informações de data do sistema getToday(&dia, &mes, &ano); // Identificando quel tipo de venda deve ser realizada printf("Venda avista ou fiado? [1]Avista [0]Fiado: "); scanf("%d", &tipoVenda); sprintf(day, "%d", dia); sprintf(month, "%d", mes); sprintf(year, "%d", ano); if(!tipoVenda){ printf("Cliente cadastrado? [1]Sim [0]Não: "); scanf("%d", &verifica); if(!verifica){ newClient(); } printf("Digite o código do cliente: "); scanf("%d", &idCliente); } else if(tipoVenda){ // Zero é o id usado para todos os clientes que compram a vista idCliente = 0; } // Escaneando o arquivo FILE *fp = fopen(":produto.txt","r"); if(fp == NULL){ printf("Arquivo não encontrado"); exit(0); } int idVenda = 0; int indice = 0; for (int i = 0; i < 300; i++){ if (venda[i].id != 0 || venda[i].amount != 0){ indice++; } } idVenda = indice + 1; venda[indice].id = idVenda; char strtmp[10]; int i = 0; int idProduto; int quantidade; int codigo; int finalizar = 1; float precoVenda = 0.0; float troco = 0.0; float valorPago = 0.0; // Adicionando um produto a venda while(codigo != -1){ // Aqui é lido o código do produto afim de adicioná-lo a venda printf("Codigo do produto [Digite -1 para sair]: "); scanf("%d", &codigo); float valor = 0.0; while(fscanf(fp, "%d,%*s,%f,%d", &idProduto, &valor, &quantidade) != EOF){ if(idProduto == codigo){ printf("%d,%.2f,%d\n", idProduto, valor, quantidade); // Soma o valor do produto a venda precoVenda += valor; quantidade--; printf("%d,%.2f,%d\n", idProduto, valor, quantidade); } } } // Armazenando as informações da venda sprintf(strtmp, "%d", quantidade); editFile(":produto.txt", ",", idProduto, 3, strtmp); venda[indice].dataVenda[0] = dia; venda[indice].dataVenda[1] = mes; venda[indice].dataVenda[2] = ano; char data[15]; strcat(data, day); strcat(data, "/"); strcat(data, month); strcat(data, "/"); strcat(data, year); printf("Preço: %.2f\n", precoVenda ); // Caso a venda seja fiada, o programa retornará ao main if(!tipoVenda){ return; } // Caso seja a vista, receberá o valor pago pelo cliente e informará o troco que será dado a mesmo printf("Valor Pago: "); scanf("%f", &valorPago); troco = valorPago - precoVenda; printf("Troco: %.2f\n", troco); printf("Tecle 0 para sair: "); scanf("%d", &finalizar); fclose(fp); } /* Função: quitarDivida * ---------------- * Diminui ou zera o saldo do cliente que pagar suas dividas */ void quitarDivida(){ FILE *fp = fopen(":cliente.txt","r"); if(fp == NULL){ printf("Arquivo não encontrado!"); exit(0); } char valorPagoChar[10]; int id; int idValidacao; float debito; float pagamento = 0.0; float valorPago = 0.0; printf("Digite o id do cliente: "); scanf("%d", &idValidacao); printf("Digite o total a ser pago: "); scanf("%f", &pagamento); while(fscanf(fp,"%d,%*s,%*s,%*s,%f", &id, &debito) != EOF){ if(idValidacao == id && debito > 0.0){ valorPago = debito - pagamento; sprintf(valorPagoChar, "%.2f", valorPago); editFile(":cliete.txt", ",", idValidacao, 4, valorPagoChar); } } fclose(fp); } /* Função: listSales * ---------------- * Lista todas as vendas realizadas na data */ void listSales(){ char path[20]; gerarPvf(path); char infoVenda[100]; FILE *fpBin = fopen(path,"rb"); fread(infoVenda, 100, 5, fpBin); while(fread(infoVenda, 100, 5, fpBin) != EOF){ printf("%s\n", infoVenda); } fclose (fpBin); } /* Função: verifyDebt * ---------------- * Lista todos os clientes que estão em debito ativo e realiza o pagamento da divida caso o cliente queira * path: parametro que recebe o caminho do arquivo de clientes */ void verifyDebt(char *path){ FILE *fp = fopen(path,"r"); if(fp == NULL){ printf("Arquivo não encontrado!"); exit(0); } char nome[25]; int id = 0; float debito = 0.0; // Listando os devedores printf("Devedores: \n"); while(fscanf(fp,"%d,%s,%*s,%*s,%f", &id, nome, &debito) != EOF){ if(debito > 0.0){ printf("id: %d | nome: %s | divida: %.2f", id, nome, debito); } } // Invocando a função quitarDivida int opcao; printf("Quitar divida? [1]Sim [0]Não: "); scanf("%d", &opcao); if(opcao){ quitarDivida(); } fclose(fp); } /* Função: saveSales * ---------------- * Salva as vendas realizadas na data * salesDate: parametro que recebe um vetor de extruturas */ void saveSales(sales *salesDate){ char path[20]; // Criando um arquivo binário gerarPvf(path); FILE *fpBin = fopen(path,"wb"); if(fpBin == NULL){ printf("Arquivo não encontrado!"); exit(0); } // Criando um vetor de strings e armazenando no arquivo char infoVenda[100]; snprintf (infoVenda, 100,"%d %d %.2d/%.2d/%d", salesDate[0].idCliente, salesDate[0].amount, salesDate[0].dataVenda[0], salesDate[0].dataVenda[1], salesDate[0].dataVenda[2]); printf ("%s", infoVenda); fwrite(infoVenda, 100, 6, fpBin); fclose(fpBin); }
C
#include <stdio.h> #include <stdlib.h> #include "sddapi.h" int main(int argc, char** argv) { // set up vtree and manager SddLiteral var_count = 4; SddLiteral var_order[4] = {2,1,4,3}; const char* type = "balanced"; Vtree* vtree = sdd_vtree_new_with_var_order(var_count,var_order,type); SddManager* manager = sdd_manager_new(vtree); // construct a formula (A^B)v(B^C)v(C^D) printf("constructing SDD ... "); SddNode* f_a = sdd_manager_literal(1,manager); SddNode* f_b = sdd_manager_literal(2,manager); SddNode* f_c = sdd_manager_literal(3,manager); SddNode* f_d = sdd_manager_literal(4,manager); SddNode* alpha = sdd_manager_false(manager); SddNode* beta; beta = sdd_conjoin(f_a,f_b,manager); alpha = sdd_disjoin(alpha,beta,manager); beta = sdd_conjoin(f_b,f_c,manager); alpha = sdd_disjoin(alpha,beta,manager); beta = sdd_conjoin(f_c,f_d,manager); alpha = sdd_disjoin(alpha,beta,manager); printf("done\n"); printf("saving sdd and vtree ... "); sdd_save_as_dot("output/sdd.dot",alpha); sdd_vtree_save_as_dot("output/vtree.dot",vtree); printf("done\n"); sdd_vtree_free(vtree); sdd_manager_free(manager); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <locale.h> #include <string.h> #include <stdbool.h> #define MAX_LEN 128 // Leitura maxima para imprimir a Logo #define TAM_SEMANA 7 // Quantidades de dias na semana de Domingo a Sabado // Cores para o console em ANSII #define COR_VERMELHA "\033[1;31m" #define COR_ROXA "\033[0;35m" #define COR_AZUL "\033[1;94m" #define COR_VERDE "\033[1;32m" #define COR_BRANCA "\033[1;97m" // Structs typedef struct { int inicioHora; int inicioMinuto; int fimHora; int fimMinuto; } Horario; typedef struct { char nomeAtividade[50]; int grau; char descricao[100]; Horario horario; struct AtividadesDia *prox; } AtividadesDia; typedef struct { AtividadesDia *semana[TAM_SEMANA]; } agendaSemanal; typedef struct { char nomeAtividade[50]; Horario horario; char descricao[100]; int grau; } DadosAtividade; typedef struct { char nomeAtividade[50]; int inicioHora; int inicioMinuto; int fimHora; int fimMinuto; char descricao[100]; int grau; int dia; } ArquivoDados; // Variaveis Globais agendaSemanal agendasemanal; DadosAtividade dadosAtividade; char diaSemana[TAM_SEMANA][10] = { "Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado" }; // Funções void print_image(FILE *fptr) { char read_string[MAX_LEN]; while(fgets(read_string,sizeof(read_string),fptr) != NULL) printf("%s",read_string); printf("\n"); } void logo() { char *filename = "BD/logo.txt"; FILE *fptr = NULL; if((fptr = fopen(filename,"r")) == NULL) { fprintf(stderr,"error opening %s\n",filename); } print_image(fptr); fclose(fptr); } // Diz a cor de determinado grau escolhido! void grauCor(int n) { switch(n) { case 1: printf(COR_BRANCA); break; case 2: printf(COR_AZUL); break; case 3: printf(COR_ROXA); break; case 4: printf(COR_VERDE); break; case 5: printf(COR_VERMELHA); break; } } // Diz o dia semana dado o Index(n) e diz qual o dia exato // Ex: 0 -> Domingo void printDiaSemana(int n) { switch(n) { case 1: printf("Dia da semana: Segunda"); break; case 2: printf("Dia da semana: Terça"); break; case 3: printf("Dia da semana: Quarta"); break; case 4: printf("Dia da semana: Quinta"); break; case 5: printf("Dia da semana: Sexta"); break; case 6: printf("Dia da semana: Sabado"); break; case 0: printf("Dia da semana: Domingo"); break; } } //Serve de debug para ver se o arquivo //está abrindo normalmentte void lerArquivo() { ArquivoDados dados; FILE *f = fopen("BD/semana.bin", "rb"); if(!f) { printf("erro ao tentar ler o arquivo :("); } while(fread(&dados, sizeof(ArquivoDados), 1, f)) { grauCor(dados.grau); printDiaSemana(dados.dia); printf("Nome Atividade: %s",dados.nomeAtividade); printf("Descrição: %s",dados.descricao); printf("Horario: \nDas %d:%d até as %d:%d", dados.inicioHora, dados.inicioMinuto, dados.fimHora, dados.fimMinuto); printf("\n--------------------------------\n"); } } //Salva definitivamente nos arquivos void salvarArquivos(AtividadesDia *no, int index) { ArquivoDados dados; FILE *f = fopen("BD/semana.bin", "ab"); strcpy(dados.nomeAtividade, no->nomeAtividade); strcpy(dados.descricao, no->descricao); dados.dia = index; dados.inicioHora = no->horario.inicioHora; dados.inicioMinuto = no->horario.inicioMinuto; dados.fimHora = no->horario.fimHora; dados.fimMinuto = no->horario.fimMinuto; dados.grau = no->grau; fwrite(&dados, sizeof(ArquivoDados), 1, f); fclose(f); } // Tem o objetivo de salvar em qualquer tipo de Arquivo ou banco de dados void salvar(AtividadesDia *inicio, int index) { AtividadesDia *atividades = inicio; while(atividades!=NULL) { salvarArquivos(atividades, index); atividades = (AtividadesDia *)atividades->prox; } } //Troca valores do tipo AtividadeDia void trocarValoresAtividade(AtividadesDia *primeiro, AtividadesDia *segundo) { char nomeAux[50]; char descricaoAux[100]; int aux; strcpy(nomeAux, primeiro->nomeAtividade); strcpy(primeiro->nomeAtividade, segundo->nomeAtividade); strcpy(segundo->nomeAtividade, nomeAux); strcpy(descricaoAux, primeiro->descricao); strcpy(primeiro->descricao, segundo->descricao); strcpy(segundo->descricao, descricaoAux); aux = primeiro->grau; primeiro->grau = segundo->grau; segundo->grau = aux; aux = primeiro->horario.inicioHora; primeiro->horario.inicioHora = segundo->horario.inicioHora; segundo->horario.inicioHora = aux; aux = primeiro->horario.inicioMinuto; primeiro->horario.inicioMinuto = segundo->horario.inicioMinuto; segundo->horario.inicioMinuto = aux; aux = primeiro->horario.fimHora; primeiro->horario.fimHora = segundo->horario.fimHora; segundo->horario.fimHora = aux; aux = primeiro->horario.fimMinuto; primeiro->horario.fimMinuto = segundo->horario.fimMinuto; segundo->horario.fimMinuto = aux; } //Essa função organiza a lista por horário //chamando a função trocarValoresAtividade void organizarLista(AtividadesDia *inicio) { AtividadesDia *i = inicio; AtividadesDia *j = inicio; while (i != NULL) { while (j != NULL) { if(i->horario.inicioHora > j->horario.inicioHora) { trocarValoresAtividade(i, j); break; } if(i->horario.inicioHora == j->horario.inicioHora) { if(i->horario.inicioMinuto > j->horario.inicioMinuto) { trocarValoresAtividade(i, j); } } j =(AtividadesDia *) j->prox; } i = (AtividadesDia *) i->prox; j = i; } } void listaAtividades(AtividadesDia *inicio) { system("clear"); logo(); AtividadesDia *atividades = inicio; while(atividades!=NULL) { grauCor(atividades->grau); printf("Nome Atividade: %s",atividades->nomeAtividade); printf("Descrição: %s",atividades->descricao); printf("Horario: \nDas %d:%d até as %d:%d", atividades->horario.inicioHora, atividades->horario.inicioMinuto, atividades->horario.fimHora, atividades->horario.fimMinuto); printf("\n--------------------------------\n"); atividades = (AtividadesDia *)atividades->prox; } printf(COR_BRANCA); } AtividadesDia * inserirAtividade(AtividadesDia *inicio, DadosAtividade *dados) { // alocando o novo nó AtividadesDia *atividade; atividade = (AtividadesDia *) malloc(sizeof(AtividadesDia)); // dados da atividade strcpy(atividade->nomeAtividade, dados->nomeAtividade); strcpy(atividade->descricao, dados->descricao); // horario da atividade atividade->horario.inicioHora = dados->horario.inicioHora; atividade->horario.fimHora = dados->horario.fimHora; atividade->horario.inicioMinuto = dados->horario.inicioMinuto; atividade->horario.fimMinuto = dados->horario.fimMinuto; atividade->grau = dados->grau; atividade->prox = NULL; // está inserindo ao final da lista! if(inicio == NULL) { return atividade; } else { AtividadesDia *p = inicio; while(p->prox != NULL) { p = (AtividadesDia *) p->prox ; } p->prox = (struct AtividadesDia *) atividade; organizarLista(inicio); return inicio; } } AtividadesDia * criar_atividades_dia(void) { return NULL; } // Obtém todas as atividades do arquivo // e adiciona nas devidas listas void carregarDadosArquivo() { ArquivoDados dados; DadosAtividade dadosArquivo; FILE *f = fopen("BD/semana.bin", "rb"); if(!f) { printf("erro ao tentar ler o arquivo :("); } while(fread(&dados, sizeof(ArquivoDados), 1, f)) { strcpy(dadosArquivo.nomeAtividade, dados.nomeAtividade); strcpy(dadosArquivo.descricao, dados.descricao); dadosArquivo.grau = dados.grau; dadosArquivo.horario.inicioHora = dados.inicioHora; dadosArquivo.horario.inicioMinuto = dados.inicioMinuto; dadosArquivo.horario.fimHora = dados.fimHora; dadosArquivo.horario.fimMinuto = dados.fimMinuto; agendasemanal.semana[dados.dia] = inserirAtividade(agendasemanal.semana[dados.dia], &dadosArquivo); } fclose(f); } //Configuração necessária para configurar cada lista void config(AtividadesDia *semana[], int tam) { for(int i = 0; i < tam; i++){ semana[i] = criar_atividades_dia(); } } //Filtragem de index de dia da Semana int indexDiaSemana() { int op; printf("\n"); for(int i = 0; i < TAM_SEMANA; i++) { printf("%d-%s\n", i + 1, diaSemana[i]); } printf("Digite o numero correspondente ao dia: "); scanf("%d", &op); while(op <= 0 || op > TAM_SEMANA) { printf(COR_VERMELHA "Ops... você digitou um número invalido\n" COR_BRANCA); printf("Digite o numero correspondente ao dia: "); scanf("%d", &op); } return op - 1; } void cadastrarAtividade() { // int opDeAtribuicaoOuCriacao; printf("Qual o nome da atividade? "); setbuf(stdin, NULL); fgets(dadosAtividade.nomeAtividade, sizeof(dadosAtividade.nomeAtividade), stdin); printf("Que horas começa a atividade?"); printf("\nHora/Minutos: "); scanf("%d", &dadosAtividade.horario.inicioHora); scanf("%d", &dadosAtividade.horario.inicioMinuto); printf("---------------------------------\n"); printf("Que horas termina a atividade?"); printf("\nHora/Minutos: "); scanf("%d", &dadosAtividade.horario.fimHora); scanf("%d", &dadosAtividade.horario.fimMinuto); printf("---------------------------------\n"); printf("Descrição:\n"); setbuf(stdin, NULL); fgets(dadosAtividade.descricao, sizeof(dadosAtividade.descricao), stdin); printf("\nQual o Grau de importância(1 a 5)?\n"); scanf("%i", &dadosAtividade.grau); if (dadosAtividade.grau > 5){ printf("O grau de importancia esta maior que o limite!\n"); printf("Escolha o grau de importancia novamente: "); scanf("%i", &dadosAtividade.grau); printf("\n"); } int index = indexDiaSemana(); agendasemanal.semana[index] = inserirAtividade(agendasemanal.semana[index], &dadosAtividade); } bool existiAtividade(AtividadesDia *inicio, char nomeAtividade[]) { bool existir = false; AtividadesDia *p = inicio; while(p != NULL) { if(strcmp(p->nomeAtividade, nomeAtividade) == 0) { existir = true; return existir; } p =(AtividadesDia *) p->prox; } return existir; } void buscarAtividade(AtividadesDia *inicio, char nomeAtividade[], int index) { AtividadesDia *p = inicio; while(p != NULL) { if(strcmp(p->nomeAtividade, nomeAtividade) == 0) { grauCor(p->grau); printDiaSemana(index); printf("\n"); printf("Nome Atividade: %s",p->nomeAtividade); printf("Descrição: %s",p->descricao); printf("Horario: \nDas %d:%d até as %d:%d", p->horario.inicioHora, p->horario.inicioMinuto, p->horario.fimHora, p->horario.fimMinuto); printf("\n--------------------------------\n"); } p =(AtividadesDia *) p->prox; } } void atualizarAtividade(AtividadesDia *inicio, char nomeAtividade[], DadosAtividade *dados) { AtividadesDia *p = inicio; bool existir = false; while(p != NULL) { if(strcmp(p->nomeAtividade, nomeAtividade) == 0) { existir = true; p->grau = dados->grau; p->horario.inicioHora = dados->horario.inicioHora; p->horario.inicioMinuto = dados->horario.inicioMinuto; p->horario.fimHora = dados->horario.fimHora; p->horario.fimMinuto = dados->horario.fimMinuto; strcpy(p->nomeAtividade, dados->nomeAtividade); strcpy(p->descricao, dados->descricao); } p =(AtividadesDia *) p->prox; } if(existir == false) { printf("Ops... nenhuma atividade encontrada com esse nome\n"); } } //Valida se a atividade existe e altera a atividade existente //Chamando a função de organizar a lista para manter em ordem void alterarAtividade(int index,char nomeAtividade[] ) { bool existir = false; for(int i= 0; i < TAM_SEMANA; i++) { if(existiAtividade(agendasemanal.semana[i], nomeAtividade)) { existir = true; break; } } if(existir == false) { printf("Ops... não foi encontrado essa atividade :("); return; } printf("novo nome da atividade? "); setbuf(stdin, NULL); fgets(dadosAtividade.nomeAtividade, sizeof(dadosAtividade.nomeAtividade), stdin); printf("Que horas começa a atividade?"); printf("\nHora/Minutos: "); scanf("%d", &dadosAtividade.horario.inicioHora); scanf("%d", &dadosAtividade.horario.inicioMinuto); printf("---------------------------------\n"); printf("Que horas termina a atividade?"); printf("\nHora/Minutos: "); scanf("%d", &dadosAtividade.horario.fimHora); scanf("%d", &dadosAtividade.horario.fimMinuto); printf("---------------------------------\n"); printf("Nova Descrição:\n"); setbuf(stdin, NULL); fgets(dadosAtividade.descricao, sizeof(dadosAtividade.descricao), stdin); printf("\nQual novo Grau de importância(1 a 5)?\n"); scanf("%i", &dadosAtividade.grau); if (dadosAtividade.grau > 5){ printf("O grau de importancia esta maior que o limite!\n"); printf("Escolha o grau de importancia novamente: "); scanf("%i", &dadosAtividade.grau); printf("\n"); } atualizarAtividade(agendasemanal.semana[index], nomeAtividade, &dadosAtividade); organizarLista(agendasemanal.semana[index]); } //Deletar atividades escolhidas AtividadesDia * deletarAtividade(AtividadesDia *inicio, char nomeAtividade[]){ AtividadesDia *p = inicio; AtividadesDia *a = NULL; if(!existiAtividade(p, nomeAtividade)) { printf("Ops... nenhuma atividade encontrada com esse nome\n"); return inicio; } while (p != NULL && strcmp(p->nomeAtividade, nomeAtividade) != 0 ) { a = p; p = (AtividadesDia *)p->prox; } if(p == NULL) { printf(COR_VERMELHA "\nAtividade não encontrado!\n" COR_BRANCA); return inicio; }else if( a == NULL) { printf(COR_VERDE "\nAtividade %sremovido!\n" COR_BRANCA, inicio->nomeAtividade); inicio =(AtividadesDia *) p->prox; free(p); return inicio; }else { printf( COR_VERDE "\nAtividade %sremovido!\n" COR_BRANCA, p->nomeAtividade); a->prox = p->prox; free(p); return inicio; } } int contadorAtividadePorGrau(int grau) { int contador = 0; ArquivoDados dados; FILE *f = fopen("BD/semana.bin", "rb"); if(!f) { printf("erro ao tentar ler o arquivo :("); } while(fread(&dados, sizeof(ArquivoDados), 1, f)) { if(dados.grau == grau) { contador ++; } } fclose(f); return contador; } int contadorAtividadePorDia(int indexDia) { int contador = 0; ArquivoDados dados; FILE *f = fopen("BD/semana.bin", "rb"); if(!f) { printf("erro ao tentar ler o arquivo :("); } while(fread(&dados, sizeof(ArquivoDados), 1, f)) { if(dados.dia == indexDia) { contador ++; } } fclose(f); return contador; } void relatorioSemanal() { system("clear"); logo(); int contadorAtividadesGrau[5], contadorAtividadeDia[TAM_SEMANA], totalDeAtividades = 0; printf(COR_AZUL); printf("\n------- Quantidade de atividades --------"); for (int i = 0; i < TAM_SEMANA; i++) { printf("\n"); contadorAtividadeDia[i] = contadorAtividadePorDia(i); printDiaSemana(i); printf("\nQuantidade: %d\n", contadorAtividadeDia[i]); totalDeAtividades += contadorAtividadeDia[i]; } printf(COR_BRANCA); printf("\n------- Quantidade de atividades por Grau --------"); for (int i = 1; i <= 5; i++) { contadorAtividadesGrau[i] = contadorAtividadePorGrau(i); printf("\nAtividades com Grau %d: %d", i, contadorAtividadesGrau[i]); } printf("\n"); printf(COR_VERDE); printf("\n------- Atividades Semanal --------\n"); printf("O total de atividades é: %d\n", totalDeAtividades); printf(COR_BRANCA); } // Main int main() { setlocale(LC_ALL, "Portuguese"); config(agendasemanal.semana, TAM_SEMANA); int op, index; char nomeAtividade[50]; carregarDadosArquivo(); logo(); do { // começo do menu do programa printf("\nEscolha uma das opções abaixo:"); printf("\n1 - Cadastrar atividade"); printf("\n2 - Buscar atividade"); printf("\n3 - Alterar atividade"); printf("\n4 - Deletar atividade"); printf("\n5 - Mostrar Relatório Semanal"); printf("\n6 - Mostrar Agenda Semanal"); printf("\n0 - Sair"); printf("\nDigite a opção:\n"); scanf("%d", &op); switch (op) { case 0: printf(COR_AZUL "Até mais\n" COR_BRANCA); break; case 1: cadastrarAtividade(); printf("\n"); printf(COR_BRANCA); remove("BD/semana.bin"); for(int i= 0; i < TAM_SEMANA; i++) { salvar(agendasemanal.semana[i], i); } break; case 2: printf("Digite a atividade: "); setbuf(stdin, NULL); fgets(nomeAtividade, sizeof(nomeAtividade), stdin); for(int i= 0; i < TAM_SEMANA; i++) { buscarAtividade(agendasemanal.semana[i], nomeAtividade, i); } printf("\n"); printf(COR_BRANCA); break; case 3: printf("Digite a atividade: "); setbuf(stdin, NULL); fgets(nomeAtividade, sizeof(nomeAtividade), stdin); index = indexDiaSemana(); alterarAtividade(index, nomeAtividade); remove("BD/semana.bin"); for(int i= 0; i < TAM_SEMANA; i++) { salvar(agendasemanal.semana[i], i); } break; case 4: printf("Digite a atividade: "); setbuf(stdin, NULL); fgets(nomeAtividade, sizeof(nomeAtividade), stdin); index = indexDiaSemana(); agendasemanal.semana[index] = deletarAtividade(agendasemanal.semana[index], nomeAtividade); remove("BD/semana.bin"); for(int i= 0; i < TAM_SEMANA; i++) { salvar(agendasemanal.semana[i], i); } break; case 5: relatorioSemanal(); break; case 6: index = indexDiaSemana(); listaAtividades(agendasemanal.semana[index]); break; default: printf("\n************************"); printf(COR_VERMELHA "\nDigite uma opção valida!" COR_BRANCA); printf("\n************************\n"); break; } } while (op != 0); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <windows.h> #define BRWSR "chrome" #define NBRWSR "iexplorer" int main() { char str[30]; char browser[20]; printf("-------------------------------\n"); printf("| WebsiteVisit |\n"); printf("| |\n"); printf("| by AlpeRoot |\n"); printf("| |\n"); printf("-------------------------------\n"); printf("\n"); printf("\n"); printf("\n"); printf("Please enter the link you want to open : "); scanf("%s" , str); printf("\nPlease choose your web browser. Type chrome or iexplorer \n"); scanf("%s" , browser); if(strcmp(browser, BRWSR) == 0) { ShellExecute(NULL,"open","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", str,NULL,SW_SHOWNORMAL); } if(strcmp(browser, NBRWSR) == 0) { ShellExecute(NULL,"open","C:\\Program Files\\Internet Explorer\\iexplore.exe", str,NULL,SW_SHOWNORMAL); } /* Unused Chrome Direct Function ShellExecute(NULL,"open","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", str,NULL,SW_SHOWNORMAL); */ return 0; }
C
#include "philo_one.h" void print_output(t_philo *philo, char *output) { printf("%ld %d %s\n", philo->action_time, philo->name, output); } void philo_take_forks(t_philo *philo) { pthread_mutex_lock(&(philo->permission)); pthread_mutex_lock(&(philo->general_info->forks[philo->left_index])); pthread_mutex_lock(&(philo->general_info->output)); philo->action_time = get_time() - philo->general_info->start_time; print_output(philo, "took a fork"); pthread_mutex_unlock(&(philo->general_info->output)); pthread_mutex_lock(&(philo->general_info->forks[philo->right_index])); pthread_mutex_lock(&(philo->general_info->output)); philo->action_time = get_time() - philo->general_info->start_time; print_output(philo, "took a fork"); pthread_mutex_unlock(&(philo->general_info->output)); } void philo_eat(t_philo *philo) { pthread_mutex_lock(&(philo->dead)); pthread_mutex_lock(&(philo->general_info->output)); philo->next_death_time = get_time() + philo->general_info->time_to_die; philo->action_time = get_time() - philo->general_info->start_time; print_output(philo, "is eating"); pthread_mutex_unlock(&(philo->resume)); pthread_mutex_unlock(&(philo->general_info->output)); pthread_mutex_unlock(&(philo->dead)); usleep(philo->general_info->time_to_eat * 1000); (philo->finished_meals)++; pthread_mutex_unlock(&(philo->general_info->forks[philo->left_index])); pthread_mutex_unlock(&(philo->general_info->forks[philo->right_index])); } void philo_sleep(t_philo *philo) { pthread_mutex_lock(&(philo->general_info->output)); philo->action_time = get_time() - philo->general_info->start_time; print_output(philo, "is sleeping"); pthread_mutex_unlock(&(philo->general_info->output)); usleep(philo->general_info->time_to_sleep * 1000); }
C
#include"headers.h" extern queue[]; extern int rear; extern int front; void dequeue(void) { if((rear==-1)||(front==MAX-1)||(front==rear)) { printf("QUEUE IS EMPTY\n"); } else { front++; printf("DELETED DATA IS %d\n",queue[front]); } }
C
#include <stdio.h> #include <stdlib.h> /** * \brief Solicita un nmero al usuario y devuelve el resultado * \param mensaje Es el mensaje a ser mostrado * \return El nmero ingresado por el usuario * */ float getFloat(char mensaje[]) { float auxiliar; printf("%s",mensaje); scanf("%f",&auxiliar); return auxiliar; } /** * \brief Muestra el pantalla el Menu de opciones para el usuario * \param 1er operando * \param 2do operando * */ void CargarMenu(float val1,float val2) { system("cls"); printf("1- Ingresar 1er operando (A = %.2f )\n",val1); printf("2- Ingresar 2do operando (B = %.2f )\n",val2); printf("3- Calcular la suma (%.2f + %.2f)\n",val1,val2); printf("4- Calcular la resta (%.2f - %.2f)\n",val1,val2); printf("5- Calcular la division (%.2f / %.2f)\n",val1,val2); printf("6- Calcular la multiplicacion (%.2f * %.2f)\n",val1,val2); printf("7- Calcular el factorial (%.2f!)\n",val1); printf("8- Calcular todas las operacione\n"); printf("9- Salir\n"); } /** * \brief Muestra el pantalla la descripcion del resultado de la operacion * \param mensaje Es el mensaje a ser mostrado * \param resultado de la operacion * */ void MostrarResultado(char mensaje[],float resultado) { printf("%s %.2f\n\n",mensaje,resultado); system("PAUSE"); } /** * \brief valido que el divisor no sea 0 * \param valor operando 1 * \param valor operando 2 * \return Flat para seguir o no */ int ValidoCeros(float val) { int result = 1; if(val <= 0) { printf("El sistema no opera con valores en cero\n\n"); system("PAUSE"); result = 0; } return result; }
C
#include<stdio.h> #include<stdlib.h> struct cqueue { int size; int f,r; int *arr; }; int isfull(struct cqueue *q) { if((q->r+1)%q->size==q->f) return 1; return 0; } void enqueue(struct cqueue *q,int val) { if(isfull(q)) printf("Circular Queue is Full.\n"); else { q->r=(q->r+1)%q->size; q->arr[q->r]=val; printf("Enqueue value : %d\n",val); } } int isempty(struct cqueue *q) { if(q->f==q->r) return 1; return 0; } int dequeue(struct cqueue *q) { int a=-1; if(isempty(q)) printf("Circular Queue is Empty.\n"); else { q->f=(q->f+1)%q->size; a=q->arr[q->f]; } return a; } void main() { struct cqueue q; q.size=4; q.f=q.r=0; q.arr=(int *)malloc(q.size*sizeof(int)); enqueue(&q,20); enqueue(&q,30); enqueue(&q,40); printf("Deleting value : %d \n",dequeue(&q)); printf("Deleting value : %d \n",dequeue(&q)); printf("Deleting value : %d \n",dequeue(&q)); enqueue(&q,50); enqueue(&q,60); enqueue(&q,70); enqueue(&q,80); enqueue(&q,90); enqueue(&q,10); if(isempty(&q)) { printf("Queue is Empty \n"); } if(isfull(&q)) { printf("Queue is Full \n"); } }
C
#include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> int main() { int i, children_number = 5; pid_t fork_pid; printf("Moj PID = %d\n", getpid()); for (i = 0; i < children_number; i++) { fork_pid = fork(); if (fork_pid == -1) { fprintf(stderr, "Blad w fork\n"); return EXIT_FAILURE; } else if (fork_pid == 0) { printf("Jestem procesem potomnym. PID = %d fork() = %d\n", getpid(), fork_pid); break; } else { printf("Jestem procesem macierzystym. PID = %d fork() = %d\n", getpid(), fork_pid); } } if (fork_pid != 0 && wait(0) == -1) { fprintf(stderr, "Blad w wait\n"); return EXIT_FAILURE; } if (fork_pid == 0) { sleep(60); } return EXIT_SUCCESS; }
C
// // Created by 민지우 on 2019-04-10. // #include <stdlib.h> #include <memory.h> #include <sys/msg.h> #include "mq.h" #include "../../devices/dot/dot.h" #include "../../services/log/log.h" static int MQ_ID = -1; /** * 메세지 큐 생성 * @return 생성 성공 여부 */ int create_message_queue () { if (MQ_ID != -1) return MQ_ID; MQ_ID = msgget((key_t)MESSAGE_KEY, IPC_CREAT|0666); if (MQ_ID == MQ_ERROR) LOG_ERROR("Fail:: create MQ"); else LOG_INFO("Success:: create MQ"); return MQ_ID == MQ_ERROR ? MQ_ERROR : MQ_SUCCESS; } /** * 메세지를 생성 * @param device_type: target device # * @param callback_num: target callback # * @param data: arguments of callback func * @return address of msgbuf */ msgbuf* create_message(int device_type, int callback_num, int cnt, unsigned char* data) { msgbuf* msg = (msgbuf *) malloc(sizeof(msgbuf)); msg->mtype = 1; msg->data.device_type = device_type; msg->data.callback_num = callback_num; msg->data.arg_cnt = cnt; if (data != NULL) memcpy(msg->data.data, data, sizeof(msg->data.data)); return msg; } /** * message queue에 있는 message를 msg에 옮기는 함수 * @param msg * @return */ int get_message (msgbuf * msg) { int sz; if (MQ_ID == MQ_ERROR) { LOG_ERROR("No Message queue"); return MQ_ERROR; } sz = msgrcv(MQ_ID, msg, sizeof(msgbuf), 0, 0); if (sz == -1) { LOG_ERROR("Fail to get message"); return MQ_ERROR; } LOG_INFO("Success to get message:: size: %d", sz); return MQ_SUCCESS; } int send_message (msgbuf* msg) { int sz; if (MQ_ID == MQ_ERROR) { LOG_ERROR("No Message queue"); return MQ_ERROR; } sz = msgsnd(MQ_ID,(void *)msg, sizeof(MESSAGE), 0); if(sz == -1) { LOG_ERROR("Fail to send message"); return MQ_ERROR; } LOG_INFO("Success to send message"); return MQ_SUCCESS; } int remove_message_queue () { LOG_INFO("main:: remove message queue"); return msgctl(MQ_ID, IPC_RMID, NULL); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> struct employeeRank { // representation of ranks employees can have int level; float salary; }; struct employee { // representation of employee information int id; char name[20]; int JoinYear; struct employeeRank rank; }; //function declarations int SearchEmployee (struct employee EmployeeArray[], int N, struct employee key); int CountEmployee_Salary (struct employee EmployeeArray[], int N, float S1, float S2); int main(){ // employees in database struct employee Bia = {3452, "Bia", 2014, {3, 45000}}; struct employee Chris = {6109, "Chris", 2016, {2, 30000}}; struct employee Brian = {5421, "Brian", 2013, {4, 55000}}; struct employee Kevin = { 7390, "Kevin", 2016, { 1 , 20000}}; // make the database and a vairable to represent it's size struct employee Employees[] = {Bia,Chris,Brian,Kevin}; int EmployeesSize = 4; int menuOption = 1; // used to store which option is chosen while ( menuOption) { printf("Access Employee Database:\n 0.Exit\n 1.Search for employee\n 2.Count employees in Salary Range\n"); // menu prompt scanf("%d", &menuOption); //store menu option if( menuOption == 1){ // if they are searching for an employee struct employee key; // used to store the information of the employee being searched for //prompt to get information for search printf("Enter employee id\n"); scanf("%d", &key.id); printf("Enter employee name\n"); scanf("%s", key.name); printf("Enter year employee was hired\n"); scanf("%d", &key.JoinYear); printf("Enter employee's rank level\n"); scanf("%d", &key.rank.level); printf("Enter employee salary\n"); scanf("%f", &key.rank.salary); // get where the employee is in the database int indexOfEmployee = SearchEmployee(Employees, EmployeesSize, key); // print the index of where the employee is printf( "Employee is located at index: %d\n\n", indexOfEmployee); } else if( menuOption == 2){ // if they are counting employees within a salary range float salaryLower; // store lower bound float salaryUpper; //store upper bound // get bounds from user printf( "Enter lower bound of salary range.\n"); scanf("%f", &salaryLower); printf("Enter upper bound of salary range\n"); scanf("%f", &salaryUpper); // count employees in the range int numInRange = CountEmployee_Salary ( Employees, EmployeesSize, salaryLower, salaryUpper); //print what was found printf("There are %d employees in the salary range\n\n", numInRange); } } } int SearchEmployee (struct employee EmployeeArray[], int N, struct employee key){ for ( int i = 0 ; i < N ; i ++){ //loop through the array // if all the data from the current emploee in EmployeeArray equals the data in the key if( EmployeeArray[i].id == key.id && strcmp(EmployeeArray[i].name, key.name) == 0 && EmployeeArray[i].JoinYear == key.JoinYear && EmployeeArray[i].rank.level == key.rank.level && EmployeeArray[i].rank.salary == key.rank.salary) { return i; // return the current index } } return -1; // else return -1 } int CountEmployee_Salary (struct employee EmployeeArray[], int N, float S1, float S2){ int count = 0; // store counter for ( int i = 0 ; i < N ; i ++){ // loop through array float salary = EmployeeArray[i].rank.salary; //get current employee's salary if( salary > S1 && salary < S2 ){ // if the salary is in the range count++; // increment counter; } } return count; // return the counter }
C
/* * AnalogInputThread.c * * Created on: Mar 11, 2015 * Author: Brian */ #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <pthread.h> // pthread_create/exit #include <errno.h> // defines EOK #include <sys/neutrino.h> //MsgReceive and MsgReply #include "AnalogInputThread.h" #include "GeneralUtils.h" #include "ThreadMsg.h" #include "ADC.h" //for adc mapping and reading void AnalogInputThread(void *arguments) { int rcvid; ThreadMessage message; AnalogInputThreadArgs *args = (AnalogInputThreadArgs *) arguments; int chid = args->ch_id; int threadId = args->thread_id; printf("AnalogInputThread %d created\n", threadId); //TODO init ADC if ( ! GetRootAccess() ){ SetupAtoD(); //run until message signals to exit while( 1 ){ rcvid = MsgReceive(chid, &message, sizeof(message), NULL); if( message.exit != 1 ){ //TODO read analog input message.value = MeasureVoltageOnChannel( 1 ); //digital reading from ADC on ch 1 message.value =((float)message.value / AD_SCALE) * INPUT_RANGE; //convert to volts MsgReply( rcvid, EOK, &message, sizeof(message) ); } else { printf("AnalogInputThread %d exiting\n", threadId); MsgReply( rcvid, EOK, &message, sizeof(message) ); break; } } }else { printf("AnalogInputThread::Couldn't get root access for mapping ADC\n"); } printf("AnalogInputThread %d finished\n", threadId); pthread_exit(0); return; } pthread_t *initAnalogInputThread(int chid, int threadId) { AnalogInputThreadArgs *args; args = malloc(sizeof(AnalogInputThreadArgs)); args->ch_id = chid; args->thread_id = threadId; return initThread( 0, (void *)AnalogInputThread, (void *)args); }
C
#include<stdio.h> #include<pthread.h> int x = 0; //a normal Global Variable, NOt a Mutex Variable /* Hence there might be a chance that Thread-swirching might happen inbetween and the OP might be 5 or 25 sometimes. */ void *thread_func (void * arg) { while(1) { x=5; x+=10; printf("x is %d\n",x); // printf("thread is %lu\n",pthread_self()); } } int main() { pthread_t tid1; pthread_t tid2; pthread_create(&tid1, NULL, &thread_func, NULL); pthread_create(&tid2, NULL, &thread_func, NULL); pthread_join(tid1, NULL); pthread_join(tid2, NULL); } /* ./a.out | grep -v 15 prints the out other than 15 op might be 5, 25 depend on the cores in the CPU. for virtual box 1 core would be assigned hence it diff to see the op. */
C
#include "libdstr/libdstr.h" derr_type_t utf8_encode_quiet( uint32_t codepoint, derr_type_t (*foreach)(char, void*), void *data ){ derr_type_t etype = E_NONE; unsigned char byte; char *c = (char*)&byte; if(codepoint < 0x80){ // 1-byte encoding byte = (unsigned char)codepoint; return foreach(*c, data); }else if(codepoint < 0x800){ // 2-byte encoding byte = (unsigned char)(0xC0 | ((codepoint >> 6) & 0x1F)); etype = foreach(*c, data); if(etype) return etype; byte = (unsigned char)(0x80 | ((codepoint >> 0) & 0x3F)); return foreach(*c, data); }else if(codepoint < 0x10000){ if(codepoint >= 0xD800 && codepoint <= 0xDFFF){ LOG_DEBUG("unicode code point in utf16 reserved range\n"); return E_PARAM; } // 3-byte encoding byte = (unsigned char)(0xE0 | ((codepoint >> 12) & 0x0F)); etype = foreach(*c, data); if(etype) return etype; byte = (unsigned char)(0x80 | ((codepoint >> 6) & 0x3F)); etype = foreach(*c, data); if(etype) return etype; byte = (unsigned char)(0x80 | ((codepoint >> 0) & 0x3F)); return foreach(*c, data); }else if(codepoint < 0x110000){ // 4-byte encoding byte = (unsigned char)(0xF0 | ((codepoint >> 18) & 0x07)); etype = foreach(*c, data); if(etype) return etype; byte = (unsigned char)(0x80 | ((codepoint >> 12) & 0x3F)); etype = foreach(*c, data); if(etype) return etype; byte = (unsigned char)(0x80 | ((codepoint >> 6) & 0x3F)); etype = foreach(*c, data); if(etype) return etype; byte = (unsigned char)(0x80 | ((codepoint >> 0) & 0x3F)); return foreach(*c, data); } LOG_DEBUG("unicode code point too high\n"); return E_PARAM; } derr_type_t utf16_encode_quiet( uint32_t codepoint, derr_type_t (*foreach)(uint16_t, void*), void *data ){ derr_type_t etype = E_NONE; if(codepoint < 0x10000){ if(codepoint >= 0xD800 && codepoint <= 0xDFFF){ return E_PARAM; } etype = foreach((uint16_t)codepoint, data); if(etype) return etype; return E_NONE; } codepoint -= 0x10000; uint32_t w1 = 0xD800 | ((codepoint >> 10) & 0x3FF); uint32_t w2 = 0xDC00 | ((codepoint >> 0) & 0x3FF); etype = foreach((uint16_t)w1, data); if(etype) return etype; etype = foreach((uint16_t)w2, data); if(etype) return etype; return E_NONE; } derr_type_t utf8_decode_stream( const char *in, size_t len, derr_type_t (*foreach)(uint32_t, void*), void *data, uint32_t *codepointp, size_t *tailp ){ derr_type_t etype = E_NONE; uint32_t codepoint = *codepointp; size_t tail = *tailp; *tailp = 0; size_t i = 0; const unsigned char *udata = (const unsigned char*)in; unsigned char u; // possibly skip into loop if(tail) goto process_tail; // unroll for loop into gotos, for easy loop resuming loop_start: if(i >= len) return E_NONE; u = udata[i++]; if((u & 0x80) == 0){ // 1-byte encoding // 0xxxxxxx etype = foreach(u, data); if(etype) return etype; goto loop_start; } if((u & 0xE0) == 0xC0){ // 2-byte encoding // 110xxxxx 10xxxxxx tail = 1; codepoint = (u & 0x1F); }else if((u & 0xF0) == 0xE0){ // 3-byte encoding // 1110xxxx 10xxxxxx 10xxxxxx tail = 2; codepoint = (u & 0x0F); }else if((u & 0xF8) == 0xF0){ // 4-byte encoding // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx tail = 3; codepoint = (u & 0x0F); }else{ LOG_DEBUG("invalid utf8 start byte\n"); return E_PARAM; } process_tail: while(tail){ if(i == len){ // unterminated sequence *tailp = tail; *codepointp = codepoint; return E_NONE; } u = udata[i++]; tail--; if((u & 0xC0) != 0x80){ LOG_DEBUG("invalid utf8 secondary byte\n"); return E_PARAM; } codepoint = (codepoint << 6) | (u & 0x3F); } if(codepoint >= 0xD800 && codepoint <= 0xDFFF){ LOG_DEBUG("utf8 value in utf16 reserved range\n"); return E_PARAM; } etype = foreach(codepoint, data); if(etype) return etype; goto loop_start; } derr_type_t utf8_decode_quiet( const char *in, size_t len, derr_type_t (*foreach)(uint32_t, void*), void *data ){ uint32_t codepoint = 0; size_t tail = 0; derr_type_t etype; etype = utf8_decode_stream(in, len, foreach, data, &codepoint, &tail); if(etype) return etype; // this function does not allow incomplete utf8 sequences if(tail){ LOG_DEBUG("incomplete utf8 sequence\n"); return E_PARAM; } return E_NONE; }
C
/* Kenneth Adair K&R pg. 117 As far as I can tell this program lets you enter some text in the commandline. After entering text in the initial commandline then whenever you type text that matches the text you just entered it will echo it back out. */ #include <stdio.h> #include <string.h> #define MAXLINE 1000 int getaline(char line[], int max); int main(int argc, char *argv[]) { char line[MAXLINE]; long lineno = 0; int c, except = 0, number = 0, found = 0; while(--argc > 0 && (*++argv)[0] == '-') while((c = *++argv[0])) switch(c){ case 'x': except = 1; break; case 'n': number = 1; break; default: printf("find: illegal option %c\n", c); argc = 0; found = -1; break; } if(argc != 1) printf("Usage: find -x -n pattern\n"); else while(getaline(line, MAXLINE) > 0){ lineno++; if((strstr(line, *argv) != NULL) != except){ if(number) printf("%ld:", lineno); printf("%s", line); found++; } } return 0; } //K&R pg. 69 /*getaline: get line ito s, return length */ int getaline(char s[], int lim) { int c, i; i = 0; while(--lim > 0 && (c=getchar()) != EOF && c != '\n') s[i++] = c; if(c == '\n') s[i++] = c; s[i] = '\0'; return i; }
C
#include <stdio.h> int main() { double data,data1,data2; char op; scanf("%lf%c%lf",&data1,&op,&data2); switch(op) {case '+':data=data1+data2;break; case '-':data=data1-data2;break; case '*':data=data1*data2;break; case '/':if(data2!=0)data=data1/data2; else{printf("Ϊ0");} return 0; } printf("%g%c%g=%g\n",data1,op,data2,data); return 0; }
C
/* ID: flsnnx1 LANG: C TASK: namenum */ #include <stdio.h> #include <string.h> char mapping[10][3] = {0,0,0,0,0,0,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','R','S','T','U','V','W','X','Y'},dict[5000][13],word[13]; int num[13],words,found = 0; FILE *fdict,*fin,*fout; int count = 0; int search(int len) { int i; for(i = 0;i < words;i++) { if(len == 0 && strcmp(word,dict[i]) == 0) return 1; else if(len != 0 && strncmp(word,dict[i],len) == 0) return 1; } return 0; } void work(int len,int now) { int i; if(now > 0 && search(now) == 0) return; if(now == len && search(0) == 1) { fprintf(fout,"%s\n",word); count++; return; } if(now < len) for(i = 0;i < 3;i++) { word[now] = mapping[num[now]][i]; if(!found) work(len,now + 1); } } int main() { int i = 0,tmp,len = 0; fdict = fopen("dict.txt","r"); fin = fopen("namenum.in","r"); fout = fopen("namenum.out","w"); while(fscanf(fdict,"%s",dict[i]) != EOF) i++; words = i; char ch; while(fscanf(fin,"%c",&ch) != EOF && ch != '\n') { num[len] = ch - '0'; len++; } work(len,0); if(count == 0) fprintf(fout,"NONE\n"); fclose(fdict); fclose(fin); fclose(fout); return 0; }
C
//Gets random floats from a normal distribution with mean=0 and std, //and then integrates (cumsum) to generate the brown noise. //This uses modified code from PCG randoms minimal C library, //but remains stand-alone (no install of PCG required). //I use the textbook cos and sin formulae to make Gaussian. //Since numerical overflow is very possible for long signals //I use a sign reversal of the current random float //to prevent this (only if the resulting sum would overflow). //Brown noise is also called "Brownian" noise (as in Brownian motion), //"random-walk" noise (since generated by a random-walk process), //and "red" noise (since pink is between white and red). #include <stdio.h> #include <stdint.h> #include <float.h> #include <math.h> #include <time.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifdef __cplusplus namespace codee { extern "C" { #endif int brown_s (float *Y, const size_t N, const float std, const int zmn); int brown_d (double *Y, const size_t N, const double std, const int zmn); int brown_c (float *Y, const size_t N, const float std, const int zmn); int brown_z (double *Y, const size_t N, const double std, const int zmn); int brown_s (float *Y, const size_t N, const float std, const int zmn) { if (std<0.0f) { fprintf(stderr, "error in brown_s: std must be nonnegative\n"); return 1; } if (N==0u) {} else if (std<FLT_EPSILON) { for (size_t n=N; n>0u; --n, ++Y) { *Y = 0.0f; } } else { const float M_2PI = (float)(2.0*M_PI); float u1, u2, R, sm = 0.0f; uint32_t r, xorshifted, rot; uint64_t state = 0u; const uint64_t mul = 6364136223846793005u; const uint64_t inc = ((uint64_t)(&state) << 1u) | 1u; struct timespec ts; //Init random num generator if (timespec_get(&ts,TIME_UTC)==0) { fprintf(stderr, "error in brown_s: timespec_get.\n"); perror("timespec_get"); return 1; } state = (uint64_t)(ts.tv_nsec^ts.tv_sec) + inc; //Generate if (std==1.0f) { for (size_t n=N-1u; n>0u; n-=2u) { state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u1 = ldexp((float)r,-32); state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u2 = ldexp((float)r,-32); R = sqrtf(-2.0f*logf(1.0f-u1)); //sm += R * cosf(M_2PI*u2); *Y++ = sm; //sm += R * sinf(M_2PI*u2); *Y++ = sm; //Idea to fix overflow sm += R * cosf(M_2PI*u2); if (isnan(sm) || !isfinite(sm)) { sm = *(Y-1) - R*cosf(M_2PI*u2); } *Y++ = sm; sm += R * sinf(M_2PI*u2); if (isnan(sm) || !isfinite(sm)) { sm = *(Y-1) - R*sinf(M_2PI*u2); } *Y++ = sm; } if (N%2u==1u) { state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u1 = ldexp((float)r,-32); state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u2 = ldexp((float)r,-32); R = sqrtf(-2.0f*logf(1.0f-u1)); //sm += R * cosf(M_2PI*u2); *Y++ = sm; //Idea to fix overflow sm += R * cosf(M_2PI*u2); if (isnan(sm) || !isfinite(sm)) { sm = *(Y-1) - R*cosf(M_2PI*u2); } *Y++ = sm; } } else { for (size_t n=N-1u; n>0u; n-=2u) { state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u1 = ldexp((float)r,-32); state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u2 = ldexp((float)r,-32); R = std * sqrtf(-2.0f*logf(1.0f-u1)); //sm += R * cosf(M_2PI*u2); *Y++ = sm; //sm += R * sinf(M_2PI*u2); *Y++ = sm; //Idea to fix overflow sm += R * cosf(M_2PI*u2); if (isnan(sm) || !isfinite(sm)) { sm = *(Y-1) - R*cosf(M_2PI*u2); } *Y++ = sm; sm += R * sinf(M_2PI*u2); if (isnan(sm) || !isfinite(sm)) { sm = *(Y-1) - R*sinf(M_2PI*u2); } *Y++ = sm; } if (N%2u==1u) { state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u1 = ldexp((float)r,-32); state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u2 = ldexp((float)r,-32); R = std * sqrtf(-2.0f*logf(1.0f-u1)); //sm += R * cosf(M_2PI*u2); *Y++ = sm; //Idea to fix overflow sm += R * cosf(M_2PI*u2); if (isnan(sm) || !isfinite(sm)) { sm = *(Y-1) - R*cosf(M_2PI*u2); } *Y++ = sm; } } if (zmn) { sm = 0.0f; for (size_t n=N; n>0u; --n) { sm += *--Y; } sm /= (float)N; for (size_t n=N; n>0u; --n, ++Y) { *Y -= sm; } } } return 0; } int brown_d (double *Y, const size_t N, const double std, const int zmn) { if (std<0.0) { fprintf(stderr, "error in brown_d: std must be nonnegative\n"); return 1; } if (N==0u) {} else if (std<DBL_EPSILON) { for (size_t n=N; n>0u; --n, ++Y) { *Y = 0.0; } } else { const double M_2PI = 2.0*M_PI; double u1, u2, R, sm = 0.0; uint32_t r, xorshifted, rot; uint64_t state = 0u; const uint64_t mul = 6364136223846793005u; const uint64_t inc = ((uint64_t)(&state) << 1u) | 1u; struct timespec ts; //Init random num generator if (timespec_get(&ts,TIME_UTC)==0) { fprintf(stderr, "error in brown_d: timespec_get.\n"); perror("timespec_get"); return 1; } state = (uint64_t)(ts.tv_nsec^ts.tv_sec) + inc; //Generate if (std==1.0) { for (size_t n=N-1u; n>0u; n-=2u) { state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u1 = ldexp((double)r,-32); state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u2 = ldexp((double)r,-32); R = sqrt(-2.0*log(1.0-u1)); //sm += R * cos(M_2PI*u2); *Y++ = sm; //sm += R * sin(M_2PI*u2); *Y++ = sm; //Idea to fix overflow sm += R * cos(M_2PI*u2); if (isnan(sm) || !isfinite(sm)) { sm = *(Y-1) - R*cos(M_2PI*u2); } *Y++ = sm; sm += R * sin(M_2PI*u2); if (isnan(sm) || !isfinite(sm)) { sm = *(Y-1) - R*sin(M_2PI*u2); } *Y++ = sm; } if (N%2u==1u) { state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u1 = ldexp((double)r,-32); state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u2 = ldexp((double)r,-32); R = sqrt(-2.0*log(1.0-u1)); //sm += R * cos(M_2PI*u2); *Y++ = sm; //Idea to fix overflow sm += R * cos(M_2PI*u2); if (isnan(sm) || !isfinite(sm)) { sm = *(Y-1) - R*cos(M_2PI*u2); } *Y++ = sm; } } else { for (size_t n=N-1u; n>0u; n-=2u) { state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u1 = ldexp((double)r,-32); state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u2 = ldexp((double)r,-32); R = std * sqrt(-2.0*log(1.0-u1)); //sm += R * cos(M_2PI*u2); *Y++ = sm; //sm += R * sin(M_2PI*u2); *Y++ = sm; //Idea to fix overflow sm += R * cos(M_2PI*u2); if (isnan(sm) || !isfinite(sm)) { sm = *(Y-1) - R*cos(M_2PI*u2); } *Y++ = sm; sm += R * sin(M_2PI*u2); if (isnan(sm) || !isfinite(sm)) { sm = *(Y-1) - R*sin(M_2PI*u2); } *Y++ = sm; } if (N%2u==1u) { state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u1 = ldexp((double)r,-32); state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u2 = ldexp((double)r,-32); R = std * sqrt(-2.0*log(1.0-u1)); //sm += R * cos(M_2PI*u2); *Y++ = sm; //Idea to fix overflow sm += R * cos(M_2PI*u2); if (isnan(sm) || !isfinite(sm)) { sm = *(Y-1) - R*cos(M_2PI*u2); } *Y++ = sm; } } if (zmn) { sm = 0.0; for (size_t n=N; n>0u; --n) { sm += *--Y; } sm /= (double)N; for (size_t n=N; n>0u; --n, ++Y) { *Y -= sm; } } } return 0; } int brown_c (float *Y, const size_t N, const float std, const int zmn) { if (std<0.0f) { fprintf(stderr, "error in brown_c: std must be nonnegative\n"); return 1; } if (N==0u) {} else if (std<FLT_EPSILON) { for (size_t n=2u*N; n>0u; --n, ++Y) { *Y = 0.0f; } } else { const float M_2PI = (float)(2.0*M_PI); float u1, u2, R, smr=0.0f, smi=0.0f; uint32_t r, xorshifted, rot; uint64_t state = 0u; const uint64_t mul = 6364136223846793005u; const uint64_t inc = ((uint64_t)(&state) << 1u) | 1u; struct timespec ts; //Init random num generator if (timespec_get(&ts,TIME_UTC)==0) { fprintf(stderr, "error in brown_c: timespec_get.\n"); perror("timespec_get"); return 1; } state = (uint64_t)(ts.tv_nsec^ts.tv_sec) + inc; //Generate if (std==1.0f) { for (size_t n=N; n>0u; --n) { state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u1 = ldexp((float)r,-32); state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u2 = ldexp((float)r,-32); R = sqrtf(-2.0f*logf(1.0f-u1)); //smr += R * cosf(M_2PI*u2); *Y++ = smr; //smi += R * sinf(M_2PI*u2); *Y++ = smi; //Idea to fix overflow smr += R * cosf(M_2PI*u2); if (isnan(smr) || !isfinite(smr)) { smr = *(Y-1) - R*cosf(M_2PI*u2); } *Y++ = smr; smi += R * sinf(M_2PI*u2); if (isnan(smi) || !isfinite(smi)) { smi = *(Y-1) - R*sinf(M_2PI*u2); } *Y++ = smi; } } else { for (size_t n=N; n>0u; --n) { state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u1 = ldexp((float)r,-32); state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u2 = ldexp((float)r,-32); R = std * sqrtf(-2.0f*logf(1.0f-u1)); //smr += R * cosf(M_2PI*u2); *Y++ = smr; //smi += R * sinf(M_2PI*u2); *Y++ = smi; //Idea to fix overflow smr += R * cosf(M_2PI*u2); if (isnan(smr) || !isfinite(smr)) { smr = *(Y-1) - R*cosf(M_2PI*u2); } *Y++ = smr; smi += R * sinf(M_2PI*u2); if (isnan(smi) || !isfinite(smi)) { smi = *(Y-1) - R*sinf(M_2PI*u2); } *Y++ = smi; } } if (zmn) { smr = smi = 0.0f; for (size_t n=N; n>0u; --n) { smi += *--Y; smr += *--Y; } smr /= (float)N; smi /= (float)N; for (size_t n=N; n>0u; --n) { *Y++ -= smr; *Y++ -= smi; } } } return 0; } int brown_z (double *Y, const size_t N, const double std, const int zmn) { if (std<0.0) { fprintf(stderr, "error in brown_z: std must be nonnegative\n"); return 1; } if (N==0u) {} else if (std<DBL_EPSILON) { for (size_t n=2u*N; n>0u; --n, ++Y) { *Y = 0.0; } } else { const double M_2PI = 2.0*M_PI; double u1, u2, R, smr=0.0, smi=0.0; uint32_t r, xorshifted, rot; uint64_t state = 0u; const uint64_t mul = 6364136223846793005u; const uint64_t inc = ((uint64_t)(&state) << 1u) | 1u; struct timespec ts; //Init random num generator if (timespec_get(&ts,TIME_UTC)==0) { fprintf(stderr, "error in brown_z: timespec_get.\n"); perror("timespec_get"); return 1; } state = (uint64_t)(ts.tv_nsec^ts.tv_sec) + inc; //Generate if (std==1.0) { for (size_t n=N; n>0u; --n) { state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u1 = ldexp((double)r,-32); state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u2 = ldexp((double)r,-32); R = sqrt(-2.0*log(1.0-u1)); //smr += R * cos(M_2PI*u2); *Y++ = smr; //smi += R * sin(M_2PI*u2); *Y++ = smi; //Idea to fix overflow smr += R * cos(M_2PI*u2); if (isnan(smr) || !isfinite(smr)) { smr = *(Y-1) - R*cos(M_2PI*u2); } *Y++ = smr; smi += R * sin(M_2PI*u2); if (isnan(smi) || !isfinite(smi)) { smi = *(Y-1) - R*sin(M_2PI*u2); } *Y++ = smi; } } else { for (size_t n=N; n>0u; --n) { state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u1 = ldexp((double)r,-32); state = state*mul + inc; xorshifted = (uint32_t)(((state >> 18u) ^ state) >> 27u); rot = state >> 59u; r = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); u2 = ldexp((double)r,-32); R = std * sqrt(-2.0*log(1.0-u1)); //smr += R * cos(M_2PI*u2); *Y++ = smr; //smi += R * sin(M_2PI*u2); *Y++ = smi; //Idea to fix overflow smr += R * cos(M_2PI*u2); if (isnan(smr) || !isfinite(smr)) { smr = *(Y-1) - R*cos(M_2PI*u2); } *Y++ = smr; smi += R * sin(M_2PI*u2); if (isnan(smi) || !isfinite(smi)) { smi = *(Y-1) - R*sin(M_2PI*u2); } *Y++ = smi; } } if (zmn) { smr = smi = 0.0; for (size_t n=N; n>0u; --n) { smi += *--Y; smr += *--Y; } smr /= (double)N; smi /= (double)N; for (size_t n=N; n>0u; --n) { *Y++ -= smr; *Y++ -= smi; } } } return 0; } #ifdef __cplusplus } } #endif
C
#include <stdio.h> int len; void printArray(int arr[]) { for (int i = 0; i < len; i++) { printf("%d ", arr[i]); } } void mergeSort(int arr[], int low, int high) { if (high - low <= 1) return; if (high - low == 2) { if (arr[low] > arr[high - 1]) { int t = arr[low]; arr[low] = arr[high - 1]; arr[high - 1] = t; } return; } int mid = (low + high) / 2; mergeSort(arr, low, mid); mergeSort(arr, mid, high); int t[high - low]; int i = low; int j = mid; int p = 0; while (1) { if (i == mid) { t[p++] = arr[j++]; } else if (j == high) { t[p++] = arr[i++]; } else if (arr[i] > arr[j]) { t[p++] = arr[j++]; } else if (arr[i] <= arr[j]) { t[p++] = arr[i++]; } if (p >= high - low) break; } for (int k = 0; k < high - low; k++) { arr[low + k] = t[k]; } } int main(int argc, char *argv[]) { int arr[] = {6, 8, 5, 4, 9, 2, 7, 3, 1, 0}; len = sizeof(arr) / sizeof(int); mergeSort(arr, 0, len); printArray(arr); }
C
/* * This program will be used to generate random matrices and write them to file. * Sample usage : ./x.out <size_of_matrix> <output file for A> <output file for B> */ #include <stdio.h> void writeMatrix(FILE *wptr, int x){ //initialize variables for looping int i, j; for(i = 0; i<x; i++){ for(j = 0; j<x; j++){ //make sure that the random number generated is less than 2000 int val = rand() % 2000; //write to file fprintf(wptr, "%d ", val); } } } void main(int argc, char *argv[]){ FILE *wptrA; FILE *wptrB; //get the size of matrix from arguments int x = atoi(argv[1]); //open file for matrix A from arguments wptrA = fopen(argv[2], "wb"); //open file for matrix B from arguments wptrB = fopen(argv[3], "wb"); //seed the rand function with current time srand(time(NULL)); //write matrix A writeMatrix(wptrA, x); //write matrix B writeMatrix(wptrB, x); //close file pointers fclose(wptrA); fclose(wptrB); }
C
/* 8-8ݺӦꡢ¡աҪ͵úmonth_day ( year, yeardy, *pmonth, *pday)year꣬yearday*pmonth*pdayǼóºա磬2000612000-3-12000ĵ6131ա */ /* ʹָΪضֵʾ */ # include <stdio.h> int main (void) { int day, month, year, yearday; /* ա¡ı*/ void month_day(int year,int yearday, int *pmonth,int *pday);/*¡յĺ*/ printf("input year and yearday: "); /* ʾݣ */ scanf ("%d%d", &year, &yearday ); month_day (year, yearday, &month, &day ); /* ü¡պ */ printf ("%d-%d-%d \n", year, month, day ); return 0; } void month_day ( int year, int yearday, int * pmonth, int * pday) { int k, leap; int tab [2][13]= { {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, }; /* ŷÿµ */ leap=year%4==0 && year% 100!= 0 || year%400==0; /* бleap */ /* leap1ʾΪ꣬tab[1][k]ȡkµΪ */ for ( k=1; yearday>tab[leap][k]; k++) yearday -= tab [leap][k]; * pmonth = k; *pday = yearday; }
C
// ColorTemperatureController bool onColorTemperature(const String &deviceId, int &colorTemperature) { Serial.printf("Device %s colorTemperature is set to %i\r\n", deviceId.c_str(), colorTemperature); return true; // request handled properly } bool onIncreaseColorTemperature(const String &deviceId, int &colorTemperature) { globalColorTemperature += 1000; // increase globalColorTemperature about 1000; Serial.printf("Device %s colorTemperature changed to %i\r\n", deviceId.c_str(), colorTemperature); colorTemperature = globalColorTemperature; // return new colorTemperature return true; // request handled properly } bool onDecreaseColorTemperature(const String &deviceId, int &colorTemperature) { globalColorTemperature -= 1000; // decrease globalColorTemperature about 1000; Serial.printf("Device %s colorTemperature changed %i\r\n", deviceId.c_str(), colorTemperature); colorTemperature = globalColorTemperature; // return new colorTemperature return true; // request handled properly }
C
/* https://projecteuler.net/problem=4 Largest palindrome product Problem 4 A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. */ #include <stdio.h> int reverseNumber (int n) { // Function to know thw reverse of a number int reverse = 0, i=1; // Let's initialize (int reverse) as 0 and (int i) as 1 int nl = n; // (int nl) will work as an helper to find (int i) while (nl>10) { // while (int nl) it's bigger than 10 i=i*10; // (int i) it's equal to (int i) * 10 nl=nl/10; // and (nl) it's equal to (nl)/10 // ... So, in this case, (int i) it's now 100 } while(i>0){ // While (int i) it's bigger than 0 reverse = reverse + (i*(n%10)); // (reverse) it's equal at reverse plus (int i) times (n%10) n=n/10; // (n) it's equal to (n)/10 i=i/10; // (i) it's equal to (i)/10 } return reverse; // ... and that's how we discover the reverse } int palindromic(int n){ // Function to find the largest palindrome made from the product of two 3-digit numbers int p=0; // let's initialize (int p) as 0 for(n; n>99; n--){ // Now, let's initialize a cicle 'for' that takes (int n '999'), and will decrement till n>99 for(int m=n; m>99; m--){ // (int m) it's equal to (int n) and we will do the same thing if((m*n)==reverseNumber(m*n)){ // If the product of m&n it's equal to the reverse number of n&m... if((m*n)>p){ // ... and if the producto of n&m it's bigger than (int p)... p=(m*n); // (int p) it's now (m*n) } } } } return p; // After the two cicles 'for', return the value of p } void main () { printf("This is the largest palindrome made from the product of two 3-digit numbers: %d\n", palindromic(999)); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_ping.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mcanal <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/11/29 13:23:15 by mcanal #+# #+# */ /* Updated: 2018/09/06 16:46:21 by vm ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef FT_PING_H # define FT_PING_H # include <stdlib.h> # include <unistd.h> # include <stdio.h> # include <signal.h> # include <sys/types.h> # include <sys/socket.h> # include <sys/time.h> # include <arpa/inet.h> # include <netinet/ip.h> # include <netinet/ip_icmp.h> # include <netdb.h> /* If ping does not receive any reply packets at all it will exit with code 1. */ /* If a packet count and deadline are both specified, and fewer than */ /* count packets are received by the time the deadline has arrived, it will */ /* also exit with code 1. On other error it exits with code 2. Otherwise */ /* it exits with code 0. This makes it possible to use the exit code to see */ /* if a host is alive or not. */ # define PING_SUCCESS 0 # define PING_FAILURE 1 # define PING_ERROR 2 /* ** bool handling */ # ifndef TRUE # define TRUE 1 # define FALSE 0 # endif //TRUE typedef int t_bool; /* ** limits */ # ifndef INT_MAX # define SHRT_MAX 32767 # define SHRT_MIN (-SHRT_MAX - 1) # define USHRT_MAX (2 * SHRT_MAX + 1) # define INT_MAX 2147483647 # define INT_MIN (-INT_MAX - 1) # define UINT_MAX (2 * INT_MAX + 1) # define LONG_MAX 9223372036854775807 # define LONG_MIN (-LONG_MAX - 1) # define ULONG_MAX (2 * LONG_MAX + 1) # endif /* ** some types for memory handling */ typedef unsigned char t_byte; typedef unsigned short t_word; typedef unsigned int t_dword; /* ** this is always useful */ # ifndef MIN # define MIN(a, b) ((a) < (b) ? (a) : (b)) # endif # ifndef MAX # define MAX(a, b) ((a) > (b) ? (a) : (b)) # endif # ifndef ABS # define ABS(x) ((x) < 0 ? -(x) : (x)) # endif # define TOLERANCE 1e-4 // precision needed for square root computing /* ** time helper */ # define SEC_TO_USEC(x) (t_dword)((x) * 1e6) # define USEC_TO_SEC(x) ((double)(x) / 1e6) /* ** error handling */ enum e_error { USAGE, ROOT, INET_NTOP, ADDRINFO, SOCKET, IPV6, TIMER, SEND }; /* ** some colors for pretty printing */ # define CLR_BLACK "\033[30;01m" # define CLR_RED "\033[31;01m" # define CLR_GREEN "\033[32;01m" # define CLR_YELLOW "\033[33;01m" # define CLR_BLUE "\033[34;01m" # define CLR_MAGENTA "\033[35;01m" # define CLR_CYAN "\033[36;01m" # define CLR_WHITE "\033[37;01m" # define CLR_RESET "\033[0m" /* ** packet struct */ #define PACKET_DATA_SIZE 40 typedef struct s_packet t_packet; struct s_packet { struct icmphdr header; struct timeval timestamp; t_byte data[PACKET_DATA_SIZE]; }; # define IOV_BUF_SIZE (sizeof(t_packet)) /* ** packet stats struct */ typedef struct s_packet_stats t_packet_stats; struct s_packet_stats { t_word n_sent; t_word n_received; long double trip_time_sum; long double trip_time_sum_squared; double max_trip_time; double min_trip_time; t_word n_errors; }; /* ** command line flags */ # define NO_FLAG 0 # define FLAG_V (1 << 1) # define FLAG_Q (1 << 2) # define FLAG_C (1 << 3) # define FLAG_T (1 << 4) # define FLAG_I (1 << 5) # define FLAG_W (1 << 6) # define FLAG_F (1 << 7) # define FLAG_D (1 << 8) # define NEXT_ARG 2 /* ** command line options struct */ typedef struct s_options t_options; struct s_options { char *host; t_dword flags; int ttl; int n_packets; int interval; //ms int deadline; //s }; /* ** env struct */ typedef struct s_env t_env; struct s_env { struct addrinfo addr_info; char addr_str[INET6_ADDRSTRLEN]; t_options opt; int sock; t_packet_stats stats; struct timeval start_time; }; /* ** GLOBAD */ extern t_env g_env; /* ** -error.c */ void error(enum e_error e, char *msg); /* ** -signal.c */ void sig_init(t_dword usec_interval); void interupt_handler(int i); /* ** -util.c */ void *ft_memcpy(void *dest, const void *src, size_t n); int ft_memcmp(const void *s1, const void *s2, size_t n); int ft_atoi(char *str); double ft_sqrtl(double x); t_dword time_diff(struct timeval *since, struct timeval *now); /* ** -ping.c */ int ping(void); /* ** -socket.c */ int get_sock(void); /* ** -packet.c */ int send_packet(void); int recv_packet(void); #endif //FT_PING_H
C
/* * _| _|_|_|_| _| * _| _|_| _| _| _| _| _|_|_| _|_|_|_| * _| _| _| _| _| _| _|_|_| _| _| _| * _| _| _| _| _| _| _| _| _| _| _| * _|_|_|_| _|_| _| _| _| _|_|_| _|_| * * Gregory J. Duck. * * Copyright (c) 2017 The National University of Singapore. * All rights reserved. * * This file is distributed under the University of Illinois Open Source * License. See the LICENSE file for details. */ #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "usage: %s length\n", argv[0]); exit(1); } size_t size = (size_t)atoi(argv[1]); char *buf = (char *)malloc(size); printf("malloc(%zu) = %p\n", size, buf); printf("Enter a string: "); fflush(stdout); int i; for (i = 0; (buf[i] = getchar()) != '\n'; i++) ; buf[i] = '\0'; printf("String = \"%s\"\n", buf); return 0; }
C
#include<stdio.h> #include<sys/time.h> int delay(int time) { int i,j; for(i=0; i<time; i++) for(j=0; j<5000; j++) ; } int main() { struct timeval start; struct timeval end; double msdiff, usdiff; gettimeofday(&start, NULL); delay(10); gettimeofday(&end, NULL); msdiff = 1000.0*(end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec)/1000.0; usdiff = 1000000.0*(end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec)/1.0; printf("time passed is %lf ms\n", msdiff); printf("time passed is %lf us\n", usdiff); return 0; }
C
/* ** ** һx, еҺΪx ** 27, Ϊ2~7, 8~10, 13~14 */ #define _CRT_SECURE_NO_WARNINGS #include "stdio.h" #include "stdlib.h" int main() { int number = 0; int sum = 0; int result = 0; int j = 1; int temp = 0; printf("һ: \n"); scanf("%d", &number); for (int i = j; i <= number / 2 + 2;) { temp = number - sum; if (temp > 0) { sum = sum + i++; } if (temp < 0) { sum = sum - j++; } if (temp == 0) { for (int k = j; k < i; ++k) { printf("%-4d", k); } sum = sum + i++; ++result; printf("\n"); } } printf("%dΪ%d!\n", result, number); system("pause"); return 0; }
C
#include "queue.h" struct s_queue_elem { struct s_queue_elem *next; void *content; }; struct s_queue { int nb_elem; struct s_queue_elem *rear; }; t_queue queue_create() { t_queue result; result = malloc(sizeof(struct s_queue)); result->nb_elem = 0; result->rear = NULL; return result; } void queue_enqueue(void *elem, t_queue queue) { struct s_queue_elem *new_elem; new_elem = malloc(sizeof(struct s_queue_elem)); new_elem->content = elem; if (queue->nb_elem == 0) { queue->rear = new_elem; queue->rear->next = queue->rear; queue->nb_elem = 1; } else { new_elem->next = queue->rear->next; queue->rear->next = new_elem; queue->rear = new_elem; queue->nb_elem++; } } void *queue_dequeue(t_queue queue) { void *result; if (queue->nb_elem == 0) { result = NULL; } else { struct s_queue_elem *head_save; head_save = queue->rear->next; result = head_save->content; queue->rear->next = head_save->next; free(head_save); queue->nb_elem--; } return result; } int queue_isempty(const t_queue queue) { return (queue->nb_elem == 0); } int queue_nbelement(const t_queue queue) { return queue->nb_elem; } void queue_destroy(t_queue queue) { while (!queue_isempty(queue)) { queue_dequeue(queue); } free(queue); }
C
// Simple command-line kernel monitor useful for // controlling the kernel and exploring the system interactively. #include <inc/stdio.h> #include <inc/string.h> #include <inc/memlayout.h> #include <inc/assert.h> #include <inc/x86.h> #include <kern/console.h> #include <kern/monitor.h> #include <kern/trap.h> #include <kern/kdebug.h> #include <kern/pmap.h> #define CMDBUF_SIZE 80 // enough for one VGA text line struct Command { const char *name; const char *desc; // return -1 to force monitor to exit int (*func)(int argc, char** argv, struct Trapframe* tf); }; //str -> num based also can use strtol ? int StrToNum(char *str,int base){ int i,sum = 0; for(i=0;str[i]!='\0';i++){ if(base != 10&&i<2) continue; sum *= base; if(str[i]>='0'&&str[i]<='9') sum += (str[i]-'0'); else if(str[i]>='a'&&str[i]<='f') sum += (str[i]+10-'a'); else {cprintf("wrong input num ! \n");return 0;} } //cprintf(" set to be %d\n",sum); return sum; } // static struct Command commands[] = { { "help", "Display this list of commands", mon_help }, { "kerninfo", "Display information about the kernel", mon_kerninfo }, { "setcolor", "set the back color of the Os, Remember to add '0x'", mon_setcolor }, { "add", "add all num followed", mon_add }, { "produce", "mul all num followed", mon_mul }, { "backtrace", "show the function in the stack", mon_backtrace}, { "showmappings", "Display in a useful format all of the physical page mappings", mon_showmappings}, { "setmappings", " contents of memory given either a virtual or physical address", mon_setmappings} }; #define NCOMMANDS (sizeof(commands)/sizeof(commands[0])) unsigned read_eip(); int mon_add(int argc, char **argv, struct Trapframe *tf){ int sum = 0; int i; for(i=1;i<argc;i++){ sum += StrToNum(argv[i],10); } cprintf("the sum is %d\n",sum); return 0; } int mon_mul(int argc, char **argv, struct Trapframe *tf){ int sum = 1; int i; for(i=1;i<argc;i++){ sum *= StrToNum(argv[i],10); } cprintf("the produce is %d\n",sum); return 0; } int mon_setcolor(int argc, char **argv, struct Trapframe *tf){ if(argc<2||argc>2) cprintf("the argc wrong!\n"); else { cprintf("set color to %s\n",argv[1]); SetBackColor(StrToNum(argv[1],16));//test for strtol(argv,0,0) } return 0; } void showmappings(int32_t lva, int32_t hva){ pte_t *pte; while(lva < hva){ pte = pgdir_walk(boot_pgdir, (void *)lva, 0); cprintf("va : 0x%x -- 0x%x : ",lva, lva + PGSIZE); if(pte == NULL||!(*pte & PTE_P)) cprintf("Not Mapped\n"); else{ cprintf("pa: 0x%x ",PTE_ADDR(*pte)); if(*pte & PTE_U) cprintf("User "); else cprintf("Kernel "); if(*pte & PTE_W) cprintf("Read/Write"); else cprintf("Read Only"); cprintf("\n"); } lva += PGSIZE; } } int mon_showmappings(int argc, char **argv, struct Trapframe *tf){ if(argc != 3){ cprintf("Hit: showmappings [LOWER_ADDR] [HIGHER_ADDER]\n"); return 0; } uint32_t lva = strtol(argv[1], 0, 0); uint32_t hva = strtol(argv[2], 0, 0); if(lva != ROUNDUP(lva, PGSIZE)|| hva != ROUNDUP(hva, PGSIZE)|| lva > hva){ cprintf("showmappings : Invalid address\n"); cprintf("Both address must be aligned in 4KB\n"); return 0; } showmappings(lva, hva); return 0; } void setmappings(uint32_t va, uint32_t memsize, uint32_t pa, int perm){ uint32_t offset; for(offset = 0; offset < memsize; offset += PGSIZE){ page_insert(boot_pgdir, pa2page(pa + offset), (void *)va + offset, perm); } } int mon_setmappings(int argc, char **argv, struct Trapframe *tf){ if (argc != 5) { cprintf ("Usage: setmappings [VIRTUAL_ADDR] [PAGE_NUM] [PHYSICAL_ADDR] [PERMISSION]\n"); cprintf ("Both virtual address and physical address must be aligned in 4KB\n"); cprintf ("Permission is one of 4 options ('ur', 'uw', 'kr', 'kw')\n"); cprintf ("u stands for user mode, k for kernel mode\n"); cprintf ("\nMake sure that the physical memory space has already been mounted before\n"); return 0; } uint32_t va = strtol(argv[1], 0, 0); uint32_t pa = strtol(argv[3], 0, 0); uint32_t perm = 0; uint32_t memsize = strtol(argv[2], 0, 0) * PGSIZE; if(va != ROUNDUP(va, PGSIZE)|| pa != ROUNDUP(pa, PGSIZE)|| va > ~0 - memsize ){ cprintf("argc error\n"); return 0; } uint32_t offset; struct Page *pp; for(offset = 0;offset < memsize; offset += PGSIZE){ pp = pa2page(pa + offset); if(pp->pp_ref == 0){ cprintf("unmounted physical page: %x - %x\n",pa + offset, pa + offset + PGSIZE); return 0; } } if(argv[4][0] == 'u'){ perm |= PTE_U; } if(argv[4][1] == 'w'){ perm |= PTE_W; } setmappings(va, memsize, pa, perm); cprintf("set memory mapping ok\n"); showmappings(va, va + memsize); return 0; } /***** Implementations of basic kernel monitor commands *****/ int mon_help(int argc, char **argv, struct Trapframe *tf) { int i; for (i = 0; i < NCOMMANDS; i++) cprintf("%s - %s\n", commands[i].name, commands[i].desc); return 0; } int mon_kerninfo(int argc, char **argv, struct Trapframe *tf) { extern char _start[], etext[], edata[], end[]; cprintf("Special kernel symbols:\n"); cprintf(" _start %08x (virt) %08x (phys)\n", _start, _start - KERNBASE); cprintf(" etext %08x (virt) %08x (phys)\n", etext, etext - KERNBASE); cprintf(" edata %08x (virt) %08x (phys)\n", edata, edata - KERNBASE); cprintf(" end %08x (virt) %08x (phys)\n", end, end - KERNBASE); cprintf("Kernel executable memory footprint: %dKB\n", (end-_start+1023)/1024); return 0; } int mon_backtrace(int argc, char **argv, struct Trapframe *tf) { // Your code here. uint32_t ebp = read_ebp(), *p, eip, i; struct Eipdebuginfo bug; while (ebp > 0) { p = (uint32_t *)ebp; eip = p[1]; cprintf("ebp %x ,eip %x args", ebp, eip); for (i = 2; i < 6; i++) { cprintf(" %08x, ", p[i]); } debuginfo_eip(eip, &bug); cprintf("\n\t%s : %d : ", bug.eip_file, bug.eip_line); for (i = 0; i < bug.eip_fn_namelen; i++) cputchar(bug.eip_fn_name[i]);//the same to the name //cprintf(" %s ",bug.eip_fn_name); cprintf("+%d\n", eip - bug.eip_fn_addr); ebp = *p; } return 0; } /***** Kernel monitor command interpreter *****/ #define WHITESPACE "\t\r\n " #define MAXARGS 16 static int runcmd(char *buf, struct Trapframe *tf) { int argc; char *argv[MAXARGS]; int i; // Parse the command buffer into whitespace-separated arguments argc = 0; argv[argc] = 0; while (1) { // gobble whitespace while (*buf && strchr(WHITESPACE, *buf)) *buf++ = 0; if (*buf == 0) break; // save and scan past next arg if (argc == MAXARGS-1) { cprintf("Too many arguments (max %d)\n", MAXARGS); return 0; } argv[argc++] = buf; while (*buf && !strchr(WHITESPACE, *buf)) buf++; } argv[argc] = 0; // Lookup and invoke the command if (argc == 0) return 0; for (i = 0; i < NCOMMANDS; i++) { if (strcmp(argv[0], commands[i].name) == 0) return commands[i].func(argc, argv, tf); } cprintf("Unknown command '%s'\n", argv[0]); return 0; } void monitor(struct Trapframe *tf) { char *buf; //cprintf("Welcome to the JOS kernel monitor!\n"); cprintf("%CredWelcome %Cwhtto %Cgrnthe %CorgJOS %Cgrykernel %Cpurmonitor!\n"); //cprintf("%x %CredWelcome\n",BackColor); //cprintf("%x %Cwhtto\n",BackColor); //cprintf("%x %Cgrnthe\n",BackColor); //cprintf("%x %CorgJOS\n",BackColor); cprintf("%CwhtType 'help' for a list of commands.\n"); if (tf != NULL) print_trapframe(tf); while (1) { buf = readline("K> "); if (buf != NULL) if (runcmd(buf, tf) < 0) break; } } // return EIP of caller. // does not work if inlined. // putting at the end of the file seems to prevent inlining. unsigned read_eip() { uint32_t callerpc; __asm __volatile("movl 4(%%ebp), %0" : "=r" (callerpc)); return callerpc; }
C
#include <stdio.h> #include "list.h" #include <stdlib.h> #include <assert.h> struct node_struct * newNode(int v){ struct node_struct *n = (struct node_struct*) malloc(sizeof(struct node_struct)); assert(n != NULL); (*n).value = v; n->value = v; n->next = NULL; return n; } void deleteNode(struct node_struct *n){ free(n); } //funcion que calcula la longitud de una lista de manera recursiva int get_long(struct node_struct *l){ //Base: si el siguiente del nodo que recibimos es null devolvemos 1 if(l ==NULL) return 0; if(l->next == NULL) return 1; else //Llamada recursiva return 1+get_long(l->next); } int get_long_iter(struct node_struct *l){ int iterador=0; while(l!= NULL){ iterador+=1; l = l->next; } return iterador; } void print_list(struct node_struct* l){ printf("["); for(; l != NULL; l= l->next){ printf("%d%c ", l->value, l->next != NULL ? ',': ']'); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "3-calc.h" /** * get_op_func - gets the operator * @s: string * Return: a pointer to a function */ int (*get_op_func(char *s))(int, int) { op_t ops[] = { {"*", op_mul}, {"+", op_add}, {"-", op_sub}, {"*", op_mul}, {"/", op_div}, {"%", op_mod}, {'\0', '\0'} }; int k = 0; while (ops[k].op != '\0') { if (strcmp(s, ops[k].op) == 0) break; k++; } return (ops[k].f); }
C
#include <stdio.h> int x, y, z; int xadd, yadd, zadd; int main(void){ int line; int i; scanf("%d", &line); for(i = 0; i < line; i++){ scanf("%d %d %d", &x, &y, &z); xadd += x; yadd += y; zadd += z; } if(xadd == 0 && yadd == 0 && zadd == 0){ printf("YES\n"); } else{ printf("NO\n"); } }
C
/* * Copyright (c) 2005 Jan Schaumann * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/stat.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> void check_dir(void); int do_split(FILE *); void usage(void); #define MAX_LINE_LENGTH 1024 #define NAME "splitmbox" #define VERSION "0.1" int mcount; char *dir; /* Split mbox input into individual mail files. */ int main(int argc, char **argv) { extern char *optarg; extern int optind; FILE *f; int ch, ret, cnt, num; dir = "."; mcount = 0; while ((ch = getopt(argc, argv, "d:hv")) != -1) { switch(ch) { case 'd': dir = optarg; break; case 'h': case '?': usage(); exit(EXIT_SUCCESS); /* NOTREACHED */ break; case 'v': (void)printf("%s: Version %s\n", NAME, VERSION); exit(EXIT_SUCCESS); /* NOTREACHED */ break; default: usage(); exit(EXIT_FAILURE); /* NOTREACHED */ } } argc -= optind; argv += optind; cnt = argc; ret = 0; check_dir(); if (cnt == 0) { return do_split(stdin); } else { for (num = 0; num < argc; num++) { char *file; file = argv[num]; if (strcmp(file, "-") == 0) ret += do_split(stdin); else if ((f = fopen(file, "r")) == NULL) { (void)fprintf(stderr, "%s: %s: %s\n", NAME, file, strerror(errno)); } else { ret += do_split(f); fclose(f); } } } return ret; } void check_dir() { struct stat sb; if (stat(dir, &sb) == -1) { if (mkdir(dir, S_IRUSR|S_IWUSR|S_IXUSR) == -1) { (void)fprintf(stderr, "%s: Unable to create directory %s: %s\n", NAME, dir, strerror(errno)); exit(EXIT_FAILURE); /* NOTREACHED */ } return; } if (!(sb.st_mode & S_IFDIR)) { (void)fprintf(stderr, "%s: %s is not a directory!\n", NAME, dir); exit(EXIT_FAILURE); /* NOTREACHED */ } } void usage() { (void)printf("Usage: %s [-d dir] [-h] [-v] [file ...]\n", NAME); (void)printf("Split mbox input into individual mail files.\n"); (void)printf("Supported options:\n"); (void)printf("\t-d dir \tspecify directory to create output in\n"); (void)printf("\t-h \tdisplay this message and exit\n"); (void)printf("\t-v \tdisplay version information and exit\n"); } /* performs the actual splitting, returning 0 on success, 1 on error */ int do_split(FILE *rfile) { char buf[MAX_LINE_LENGTH]; char out[PATH_MAX]; int retval; int i, wrflg, wfd; retval = wrflg = 0; wfd = -1; memset(&buf, '\0', MAX_LINE_LENGTH); memset(&out, '\0', PATH_MAX); while (fgets(buf, MAX_LINE_LENGTH, rfile) != NULL) { if ((i = strncmp(buf, "From ", 5)) == 0) { mcount++; if (wfd != -1) { (void)close(wfd); memset(&out, '\0', PATH_MAX); wfd = -1; } wrflg= 1; if (snprintf(out, PATH_MAX, "%s/%06d", dir, mcount) == -1) { (void)fprintf(stderr, "%s: Unable to create filename: %s\n", NAME, strerror(errno)); retval = 1; continue; } } if (wfd == -1) { if ((wfd = open(out, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR)) == -1) { (void)fprintf(stderr, "%s: Unable to create file %s: %s\n", NAME, out, strerror(errno)); retval = 1; continue; } } if (wrflg) { int written; int len = strlen(buf); while ((written = write(wfd, buf, len)) != -1 && written != len) { len = len - written; } if (written == -1) { (void)fprintf(stderr, "%s: Unable to write to %s: %s\n", NAME, out, strerror(errno)); retval = 1; continue; } } } (void)close(wfd); return retval; }
C
/* The purpose of this program is to provide a C Language implementation to read in the state of the switches into the MSP430 and to output a conditional string that describes the state of the switches to HyperTerminal. */ //--------------------------------------------------------------- // Console I/O through the on board UART for MSP 430X4XXX //--------------------------------------------------------------- void Init_UART(void); void OUTA_UART(unsigned char A); unsigned char INCHAR_UART(void); void printStr(char *str); void toggleLED(); void displaySW(); #include "msp430fg4618.h" #include "stdio.h" #include "string.h" int main(void){ volatile unsigned char a; volatile unsigned int i; // volatile to prevent optimization WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer Init_UART(); // Make green and yellow outputs P2DIR |= 0x06; // Set P1.0 to output direction // Use The LED as an indicator P2OUT = 0x00; //Start with Green and Yellow LEDs off for (;;) { displaySW(); i = 1000; while (i > 0) i--;//Delay } } void displaySW() { int SW1_Val, SW2_Val; char buffer[100]; SW1_Val = (P1IN & 0x01); SW2_Val = (P1IN & 0x02); sprintf(buffer, "SW1 = %d, SW2 = %d", SW1_Val != 1, SW2_Val != 2); printStr(buffer); } void toogleLED(){ char a; a = INCHAR_UART(); //Receive from user OUTA_UART(a); //Echo character to the hyper terminal if ( a == 'G') //If user enters G then toggle the green LED P2OUT ^= 0x04; else if ( a == 'Y') //If user enters Y then toggle the yellow LED P2OUT ^= 0x02; else ;//Stay the same } void printStr(char *str) { if (str == NULL) return; //Print each character until null character is seen while (*str != '\0') { OUTA_UART(*str); //print character to Terminal str++; //move to next character } OUTA_UART(0x0D); //Print Newline to Terminal } void OUTA_UART(unsigned char A){ //--------------------------------------------------------------- //*************************************************************** //--------------------------------------------------------------- // IFG2 register (1) = 1 transmit buffer is empty, // UCA0TXBUF 8 bit transmit buffer // wait for the transmit buffer to be empty before sending the // data out do{ }while ((IFG2&0x02)==0); // send the data to the transmit buffer UCA0TXBUF =A; } unsigned char INCHAR_UART(void){ //--------------------------------------------------------------- //*************************************************************** //--------------------------------------------------------------- // IFG2 register (0) = 1 receive buffer is full, // UCA0RXBUF 8 bit receive buffer // wait for the receive buffer is full before getting the data do{ }while ((IFG2&0x01)==0); // go get the char from the receive buffer return (UCA0RXBUF); } void Init_UART(void){ //--------------------------------------------------------------- // Initialization code to set up the uart on the experimenter // board to 8 data, // 1 stop, no parity, and 9600 baud, polling operation //--------------------------------------------------------------- P2SEL=0x30; // transmit and receive to port 2 b its 4 and 5 // Bits p2.4 transmit and p2.5 receive UCA0CTL0=0; // 8 data, no parity 1 stop, uart, async // (7)=1 (parity), (6)=1 Even, (5)= 0 lsb first, // (4)= 0 8 data / 1 7 data, // (3) 0 1 stop 1 / 2 stop, (2-1) -- UART mode, // (0) 0 = async UCA0CTL1= 0x41; // select ALK 32768 and put in // software reset the UART // (7-6) 00 UCLK, 01 ACLK (32768 hz), 10 SMCLK, // 11 SMCLK // (0) = 1 reset UCA0BR1=0; // upper byte of divider clock word UCA0BR0=3; // clock divide from a clock to bit clock 32768/9600 // = 3.413 // UCA0BR1:UCA0BR0 two 8 bit reg to from 16 bit // clock divider // for the baud rate UCA0MCTL=0x06; // low frequency mode module 3 modulation pater // used for the bit clock UCA0STAT=0; // do not loop the transmitter back to the // receiver for echoing // (7) = 1 echo back trans to rec // (6) = 1 framing, (5) = 1 overrun, (4) =1 Parity, // (3) = 1 break // (0) = 2 transmitting or receiving data UCA0CTL1=0x40; // take UART out of reset IE2=0; // turn transmit interrupts off //--------------------------------------------------------------- //*************************************************************** //--------------------------------------------------------------- // IFG2 register (0) = 1 receiver buffer is full, // UCA0RXIFG // IFG2 register (1) = 1 transmit buffer is empty, // UCA0RXIFG // UCA0RXBUF 8 bit receiver buffer // UCA0TXBUF 8 bit transmit buffer }
C
/* * Demo PIC16F15376 Curiosity Nano + RDM6300 RFID reader * Output on LCD 16x2 * This is a demo: no checksum checked, no valid tag checked. Only reading * * (c)2020 Bernardo Giovanni * https://www.settorezero.com * */ /* Connections: * RD3 : LCD RS * RC0 : LCD EN * RB5 : LCD RW * RD4 : LCD D4 * RD5 : LCD D5 * RD6 : LCD D6 * RD7 : LCD D7 * RA0 : BUZZER (through a mosfet) * RE0 : LED0 on board * RE2 : SW0 on board * RC7 : EUSART1 RX (to module TX) * */ #include "mcc_generated_files/mcc.h" #include "hd44780sz.h" #pragma warning disable 520 // suppress "function not used" warnings uint8_t receive_status=0; #define RECSTA_IDLE 0 // uart ready #define RECSTA_BUSY 1 // uart is receiving #define RECSTA_END 2 // tag received #define MAX_TAG_LEN 12 // tag max bytes (without blank chars) char rx_buffer[MAX_TAG_LEN]; // called on RCIF void RFID_rx(void) { char rx_byte=RC1REG; // received byte if (receive_status==RECSTA_END) return; // exit if not in receive mode static uint8_t buffer_pointer=0; // rx buffer pointer // overrun error if(RC1STAbits.OERR) { // restart usart RC1STAbits.CREN = 0; RC1STAbits.CREN = 1; } // received byte value switch (rx_byte) { case 0x02: // STX - start transmission LED0_SetLow(); // turn on the led buffer_pointer=0; // pointer reset receive_status=RECSTA_BUSY; // I'm busy break; case 0x03: // ETX - end transmission LED0_SetHigh(); // turn off the led // if we're in receive mode if (receive_status==RECSTA_BUSY) { rx_buffer[buffer_pointer]='\0'; // close the buffer receive_status=RECSTA_END; // receive end } break; // do nothing for those chars case 0x00: // null case 0x0D: // <CR> case 0x0A: // <LF> break; default: // any byte other than previous ones => store if (receive_status==RECSTA_BUSY) { rx_buffer[buffer_pointer++]=rx_byte; } break; } // received bytes are too much if (buffer_pointer>MAX_TAG_LEN) { buffer_pointer=0; // pointer reset receive_status=RECSTA_IDLE; } } void main(void) { // initialize the device SYSTEM_Initialize(); // set the interrupt handler for uart receive EUSART1_SetRxInterruptHandler(*RFID_rx); // Enable the Global Interrupts INTERRUPT_GlobalInterruptEnable(); // Enable the Peripheral Interrupts INTERRUPT_PeripheralInterruptEnable(); LCDInit(); LCDGoto(1,1); LCDPuts("RFID Reader"); LCDGoto(2,1); LCDPuts("BernardoGiovanni"); while (1) { // receive complete if (receive_status==RECSTA_END) { BUZZER_SetHigh(); LCDGoto(2,1); uint8_t i=0; while(rx_buffer[i]) { // remembder: last two chars are the checksum! LCDPutch(rx_buffer[i++]); } LCDPuts(" "); __delay_ms(100); BUZZER_SetLow(); // wait 2 seconds uint8_t q=20; while (q--) { __delay_ms(100); } LCDGoto(2,1); LCDPuts(" "); // delete disply row receive_status=RECSTA_IDLE; // ready to receive again } } }
C
/* ** EPITECH PROJECT, 2018 ** PSU_42sh_2017 ** File description: ** Add new path in pipe structure */ #include <stdlib.h> #include "instruction.h" #include "globbing.h" #include "shell.h" static int realloc_pipe_args(args_list_t *list, pipe_t *pipe, int size) { args_list_t *tmp = list; free_array_string(pipe->args); pipe->args = NULL; pipe->args = malloc(sizeof(char *) * (size + 1)); if (!pipe->args) return (FAILURE); for (int i = 0; i < size; i += 1, tmp = tmp->next) pipe->args[i] = strdup(tmp->arg); pipe->args[size] = NULL; return (SUCCESS); } int add_path_in_pipe(args_list_t *list, pipe_t *pipe) { args_list_t *tmp = list; int size = 0; while (tmp != NULL) { size += 1; tmp = tmp->next; } if (realloc_pipe_args(list, pipe, size) == FAILURE) return (FAILURE); return (SUCCESS); }
C
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define SIZE 3 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t queue_not_empty = PTHREAD_COND_INITIALIZER; pthread_cond_t queue_free_places = PTHREAD_COND_INITIALIZER; int queue[SIZE]; int qlen = 0; void *producer( void *p) { int r; while(1) { r = rand() % 10; //sleep(1); printf( "generated: %d\n", r); pthread_mutex_lock( &mutex); while(qlen == SIZE) { pthread_cond_wait( &queue_free_places, &mutex); } queue[qlen] = r; qlen++; pthread_cond_broadcast( &queue_not_empty); pthread_mutex_unlock(&mutex); } return 0; } int do_something_complex(int r) { sleep(1); printf( "square of %d is %d\n", r, r*r); } void *consumer( void *p) { int r; while(1) { pthread_mutex_lock( &mutex); while( qlen == 0) { pthread_cond_wait( &queue_not_empty, &mutex); } r = queue[0]; qlen--; if( qlen) memmove(queue, queue+1, qlen*sizeof(int)); printf( "received: %d\n", r); pthread_cond_broadcast(&queue_free_places); pthread_mutex_unlock(&mutex); do_something_complex(r); } return 0; } int main() { pthread_t t1, t2, t3; pthread_create( &t1, 0, producer, 0); pthread_create( &t2, 0, consumer, 0); pthread_create( &t3, 0, consumer, 0); pthread_create( &t3, 0, consumer, 0); pthread_create( &t3, 0, consumer, 0); pthread_create( &t3, 0, consumer, 0); pthread_create( &t3, 0, consumer, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); return 0; }
C
#include <stdio.h> int main(){ FILE *fp; int num,i; fp=fopen("numeric.dat","w"); for(i=0;i<5;i++){ printf("Ͽ %d :",i+1); scanf("%d",&num); fwrite(&num,sizeof(int),1,fp); } fclose(fp); fp=fopen("numeric.dat","r"); for(i=0;i<5;i++){ printf("%d° Է :",i+1); fread(&num,sizeof(int),1,fp); printf("%d\n",num); } fclose(fp); }
C
#include <stdio.h> #include "stack.h" linklist link_create(){ linklist p; p = (linklist) malloc(sizeof(linknode)); if (p == NULL){ puts("error!"); return 0; } p->data = 0; p->next = NULL; return p; } int push(linklist h, datatype value){ linklist q; q = (linklist)malloc(sizeof(linknode)); if(q == NULL){ puts("error!"); return -1; } q->data = value; q->next = h->next; h->next = q; return 0; } int pop(linklist h){ if(h->next == NULL) puts("stack is empty!\n"); return -1; } datatype num; linklist p = h->next; num = p->data; h->next = p->next; free(p); return num; } void link_show(linklist p){ linklist q; q = p->next; while(q != NULL){ printf("%d ", q->data); q = q->next; } putchar(10); }
C
#include <stdio.h> int main() { int num; printf("Please enter a number:"); scanf("%d", &num); int quotient = num / 2; int remainder = num - 2 * quotient; if ( remainder == 0 ) { printf("%d is an even number.", num); } else { printf("%d is an odd number.", num); } return 0; }
C
#include "debugger/commands.h" #include "debugger/debugger.h" #include <ctype.h> #include <string.h> int command_load_register(debugger_state_t *state, int argc, char **argv) { if (argc != 3) { state->print(state, "%s - Load a register with a specified value. Supports hex (i.e. 0x0000) and base-10 (i.e. 12)\n", argv[0]); return 0; } #define REGISTER(num, len, print) \ if (strncasecmp(argv[1], print, len) == 0) {\ state->asic->cpu->registers. num = parse_expression_z80e(state, argv[2]); \ }\ REGISTER(IXH, 3, "IXH"); REGISTER(IXL, 3, "IXL"); REGISTER(IYH, 3, "IYH"); REGISTER(IYL, 3, "IYL"); REGISTER(_BC, 3, "BC'"); REGISTER(_DE, 3, "DE'"); REGISTER(_HL, 3, "HL'"); REGISTER(_AF, 3, "AF'"); REGISTER(IX, 2, "IX"); REGISTER(IY, 2, "IY"); REGISTER(AF, 2, "AF"); REGISTER(BC, 2, "BC"); REGISTER(DE, 2, "DE"); REGISTER(HL, 2, "HL"); REGISTER(PC, 2, "PC"); REGISTER(SP, 2, "SP"); REGISTER(A, 1, "A"); REGISTER(B, 1, "B"); REGISTER(C, 1, "C"); REGISTER(D, 1, "D"); REGISTER(E, 1, "E"); REGISTER(F, 1, "F"); REGISTER(H, 1, "H"); REGISTER(L, 1, "L"); REGISTER(I, 1, "I"); REGISTER(R, 1, "R"); return 0; }
C
/* * Utilizing leetcode test cases for One Edit Distance to verify the FileDescriptor API on-the-fly problem * https://leetcode.com/problems/one-edit-distance/ */ class FileDescriptor{ string fd; int idx; public: FileDescriptor(string v){ fd = v; idx=0; } bool hasNext(){ return idx<fd.size(); } int next(){ return fd[idx++]; } }; class Solution { public: bool isOneEditDistance(string s, string t) { FileDescriptor a(s); FileDescriptor b(t); return isOneOrLessEditDistance(a, b); } bool isOneOrLessEditDistance(FileDescriptor &a, FileDescriptor &b){ vector<vector<int>> dp(2, vector<int>(2, 0)); vector<int> aPrev, bPrev; while(a.hasNext() && b.hasNext()){ int aCur = a.next(), bCur = b.next(); if(aPrev.empty() || aPrev[0]!=bCur){ dp[1][0] = min(dp[1][0], dp[1][1]) + 1; }//else aPrev[0]==bCur, dp[1][0] stay the same if(bPrev.empty() || bPrev[0]!=aCur){ dp[0][1] = min(dp[0][1], dp[1][1]) + 1; }//else stay the same if(aCur!=bCur){ dp[1][1] = min(dp[1][1], min(dp[0][1], dp[1][0])) + 1 ; } if(min(dp[1][1], min(dp[0][1], dp[1][0])) > 1) return false; if(aPrev.empty()) aPrev.push_back(aCur); else aPrev[0]=aCur; if(bPrev.empty()) bPrev.push_back(bCur); else bPrev[0]=bCur; } if(a.hasNext()){ int aCur = a.next(); if((bPrev.empty() || bPrev[0]!=aCur)){ dp[0][1] = min(dp[0][1], dp[1][1]) + 1 ; } return dp[0][1]==1 && !a.hasNext(); } if(b.hasNext()){ int bCur = b.next(); if(aPrev.empty() || aPrev[0]!=bCur){ dp[1][0] = min(dp[1][0], dp[1][1]) + 1 ; } return dp[1][0]==1 && !b.hasNext(); } return dp[1][1]==1; } };
C
#include <SDL2/SDL.h> #include <math.h> #include <stdio.h> #include "raycast.h" #include "graphics/graphics.h" #include "map/map.h" #include "map/tile.h" #include "math/vec2.h" #include "util/util.h" #define MAX_RECURSION 3 void cast(ray_t* r, hit_t* hit, map_t* map); void raystep(ray_t* r, map_t* map); // render a map void raycast_render(SDL_Surface* sf, camera_t* cam, map_t* map) { vec2_t plane = {cam->dir.y*0.66, -cam->dir.x*0.66}; vec2_normalize(&plane, &plane); for (int x=0; x<sf->w; x++) { double cx = 2*x/(double) sf->w - 1; ray_t r; r.orig = cam->pos; r.startdir = (vec2_t){cam->dir.x + plane.x * cx, cam->dir.y + plane.y * cx}; r.distance = 0; raycast_column(sf, &r, map, x, cx, 0); } } void raycast_column(SDL_Surface* sf, ray_t* r, map_t* map, int x, double cx, int rec) { if (rec >= MAX_RECURSION) return; hit_t hit; cast(r, &hit, map); if (!hit.hit) return; double dist = hit.distance / sqrt(1+cx*cx); int lineh = (int)(sf->h / dist); tile_t* tile = map_getTileAt(map, r->mapX, r->mapY); if (tile && tile_isVisible(tile) && tile->render) { tileRenderData_t rd; rd.x = x; rd.h = lineh; rd.cx = cx; rd.hit = &hit; rd.rec = rec+1; rd.dir = &r->startdir; rd.map = map; rd.distance = r->distance; tile->render(sf, tile, &rd); } } // travels the camera a distance void raycast_travel(camera_t* cam, double distance, map_t* map) { ray_t r; r.orig = cam->pos; r.startdir = cam->dir; r.distance = 0; r.mapX = (int) r.orig.x; r.mapY = (int) r.orig.y; tile_t* t; while (distance > 0) { raystep(&r, map); t = map_getTileAt(map, (int) cam->pos.x, (int) cam->pos.y); vec2_t s = t? t->space : (vec2_t){1,1}; vec2_t oldpos = cam->pos; vec2_mul(&s, &cam->dir, &s); if (distance - r.distance < 0) vec2_addScale(&cam->pos, &s, distance, &cam->pos); else vec2_addScale(&cam->pos, &s, r.distance*1.0001, &cam->pos); distance -= r.distance; r.distance = 0; t = map_getTileAt(map, (int) cam->pos.x, (int) cam->pos.y); if (t && tile_isCollidable(t)) { cam->pos = oldpos; break; } } } void cast(ray_t* r, hit_t* hit, map_t* map) { hit->hit = 0; r->mapX = (int) r->orig.x; r->mapY = (int) r->orig.y; for (int _=0; _<100; _++) { raystep(r, map); tile_t* ht = map_getTileAt(map, r->mapX, r->mapY); if (ht && tile_isVisible(ht)) { hit->distance = r->distance; hit->side = r->side; hit->hit = 1; hit->point = r->orig; return; } } } // get next block hit. void raystep(ray_t* r, map_t* map) { tile_t* t = map_getTileAt(map, r->mapX, r->mapY); vec2_t s = t? t->space : (vec2_t){1,1}; r->dir = r->startdir; vec2_mul(&r->dir, &s, &r->dir); vec2_normalize(&r->dir, &r->dir); double deltaDistX = sqrt(1 + (r->dir.y * r->dir.y) / (r->dir.x * r->dir.x)); double deltaDistY = sqrt(1 + (r->dir.x * r->dir.x) / (r->dir.y * r->dir.y)); int stepX = sign(r->dir.x); int stepY = sign(r->dir.y); double sideDistX = (stepX < 0 ? (r->orig.x - r->mapX) : (r->mapX + 1.0 - r->orig.x)) * deltaDistX; double sideDistY = (stepY < 0 ? (r->orig.y - r->mapY) : (r->mapY + 1.0 - r->orig.y)) * deltaDistY; vec2_t d = {0,0}; if (sideDistX < sideDistY) { vec2_scale(&r->dir, sideDistX, &d); r->mapX += stepX; } else { vec2_scale(&r->dir, sideDistY, &d); r->mapY += stepY; } vec2_add(&r->orig, &d, &r->orig); vec2_div(&d, &s, &d); r->distance += sqrt(d.x*d.x + d.y*d.y); r->side = sideDistX < sideDistY ? stepX < 0 ? SIDE_EAST : SIDE_WEST: stepY < 0 ? SIDE_NORTH : SIDE_SOUTH; } void raycast_getSideNormal(int side, vec2_t* out) { switch(side) { case SIDE_NORTH: out->x = 0; out->y = 1; break; case SIDE_EAST: out->x = 1; out->y = 0; break; case SIDE_SOUTH: out->x = 0; out->y = -1; break; case SIDE_WEST: out->x = -1; out->y = 0; break; } }
C
#include <stdio.h> /** * main - Entry point * * Return: Always 0 (Success) */ int main(void) { int num = 0; int div, mod, aux; while (num < 100) { div = num / 10; mod = num % 10; aux = mod * 10 + div; if (num != aux && num < aux) { putchar((num / 10) + '0'); putchar((num % 10) + '0'); if (num != 89) { putchar(','); putchar(' '); } } num++; } putchar('\n'); return (0); }
C
// // syssched.c // // // Created by Neil Singh on 8/31/17. // // #include <sys/stat.h> #include <sys/types.h> #include <sys/fcntl.h> #include <sys/errno.h> #include <sys/time.h> #include <unistd.h> #include <sched.h> extern unsigned int sys_nanosleep(struct timespec* req, struct timespec* rem); extern unsigned int sys_sched_yield(); unsigned int nanosleep(struct timespec* req, struct timespec* rem) { if (req->tv_sec < 0 || req->tv_nsec < 0 || req->tv_nsec > 999999999) { errno = EINVAL; return -1; } int ret = sys_nanosleep(req, rem); if (ret < 0) { errno = -ret; return -1; } return ret; } int sched_yield() { int ret = sys_sched_yield(); if (ret < 0) { errno = -ret; return -1; } return ret; }
C
#include <stdio.h> void main(); { int i; for (i = 0; i < 256; i++) { printf("%d = %c", i, i); } return 0; }
C
#include "allowexec.h" #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <inttypes.h> #include <string.h> #include <sys/mman.h> #include <sys/resource.h> void check_system_call(int r, const char* syscall) { if (r == -1) { fprintf(stderr, "%s: %s\n", syscall, strerror(errno)); exit(1); } } #define PAGE_SIZE 4096 void allow_execute(const void* ptr, size_t size) { uintptr_t address = (uintptr_t) ptr; uintptr_t end_address = address + size; address = address & ~(uintptr_t) (PAGE_SIZE - 1); end_address = (end_address | (PAGE_SIZE - 1)) + 1; int r = mprotect((void*) address, end_address - address, PROT_READ | PROT_WRITE | PROT_EXEC); check_system_call(r, "mprotect"); } void limit_stack_size(size_t size) { struct rlimit rlim; int r = getrlimit(RLIMIT_STACK, &rlim); check_system_call(r, "getrlimit"); if (rlim.rlim_cur > size) { rlim.rlim_cur = size; r = setrlimit(RLIMIT_STACK, &rlim); check_system_call(r, "setrlimit"); } } // Test if `s` is a number (a string completely parseable by `strtol`). int strisnumber(const char* s) { char* ends; (void) strtol(s, &ends, 0); return s != ends && *ends == 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "cgraph/cgraph.h" #include "cgraph/cgen/s2i.h" #include "cgraph/cgen/svector.h" typedef struct _congdan { char ten[60]; char cmnd[20]; char sdt[20]; }congdan; bn_tree_t s2i = NULL; vector_t i2s = NULL; int g_id = 0; int get_save_id(char *key) { int res = s2i_value(s2i, key); //search if(res != k_s2i_invalid) { //Nếu tìm thấy -> return return res; } s2i_insert(s2i, key, g_id); //Nếu không tìm thấy -> insert svec_push_back(&i2s, key); res = g_id; ++g_id; return res; } int main() { s2i = rb_create_node(); //String to int i2s = gtv_create(); //Int to string //Doc file .txt FILE *tiepxuc=fopen("TIEPXUC.txt","r"); FILE *dancu=fopen("DANCU.txt","r"); if(tiepxuc == NULL||dancu==NULL) { printf("Loi doc file !!!"); return 0; } int n; fscanf(dancu,"%d",&n); congdan *dscongdan=(congdan*)calloc(100,sizeof(congdan)); for(int i=0;i<n;i++) { fscanf(dancu,"%s %s %s",dscongdan[i].cmnd,dscongdan[i].sdt,dscongdan[i].ten); get_save_id(dscongdan[i].cmnd); } cgraph_ivec_t edges = cgraph_ivec_create(); cgraph_ivec_t dsthoigian = cgraph_rvec_create(); int m; fscanf(tiepxuc,"%d",&m); char tx1[20],tx2[20],thoigian[20]; for(int i=0;i<m;i++) { fscanf(tiepxuc,"%s %s %s",tx1,tx2,thoigian); int id1=get_save_id(tx1); int id2=get_save_id(tx2); int idthoigian=get_save_id(thoigian); cgraph_ivec_push_back(&edges, id1); cgraph_ivec_push_back(&edges, id2); cgraph_ivec_push_back(&dsthoigian, idthoigian); } cgraph_t g = cgraph_create(edges, 0, CGRAPH_UNDIRECTED); printf("Tong so dinh cua do thi: %d\n",cgraph_vcount(g)); printf("Tong so canh cua do thi: %d\n",cgraph_ecount(g)); //menu int lenh=0; do { printf("==Menu chuong trinh\n"); printf("1. Dang ky cong dan moi\n2. Ghi nhan tiep xuc\n3. Tra cuu cong dan\n4. Tra cuu thong tin tiep xuc\n5. Tra cuu mang luoi tiep xuc\n6. Thoat\n"); scanf("%d",&lenh); if(lenh<1||lenh>6) printf("LENH SAI! NHAP LAI!\n"); else if(lenh==1) { //task1 char cmnd[20]; printf("CMND: ");getc(stdin);scanf("%s",cmnd); int kiemtra=0; for(int i=0;i<n;i++) { if(strcmp(dscongdan[i].cmnd,cmnd)==0) { printf("Cap nhat thong tin\n"); printf("Ten: ");getc(stdin);scanf("%s",dscongdan[i].ten); printf("Sdt: ");getc(stdin);scanf("%s",dscongdan[i].sdt); kiemtra++; } } if(kiemtra==0) { printf("Them cong dan\n"); printf("Ten: ");getc(stdin);scanf("%s",dscongdan[n].ten); printf("Sdt: ");getc(stdin);scanf("%s",dscongdan[n].sdt); n++; } } else if(lenh==2) { //task2 char cmnd1[20],cmnd2[20]; while(1) { printf("Nhap cmnd nguoi 1: ");getc(stdin);scanf("%s",cmnd1); int kiemtra = s2i_value(s2i, cmnd1); if(kiemtra != k_s2i_invalid) break; printf("CMND khong ton tai!NHAP LAI\n"); } while(1) { printf("Nhap cmnd nguoi 2: ");getc(stdin);scanf("%s",cmnd2); int kiemtra = s2i_value(s2i, cmnd2); if(kiemtra != k_s2i_invalid) break; printf("CMND khong ton tai!NHAP LAI\n"); } int eid; cgraph_get_eid(g, &eid,get_save_id(cmnd1), get_save_id(cmnd2),CGRAPH_UNDIRECTED); if(eid<0) { printf("Them tiep xuc\n"); cgraph_ivec_t newedges = cgraph_ivec_create(); cgraph_ivec_push_back(&newedges, get_save_id(cmnd1)); cgraph_ivec_push_back(&newedges, get_save_id(cmnd2)); cgraph_add_edges(g, newedges); char newtg[20]; printf("Nhap thoi gian: ");getc(stdin);scanf("%s",newtg); cgraph_ivec_push_back(&dsthoigian, get_save_id(newtg)); }else { printf("Cap nhat tiep xuc"); char newtg[20]; printf("Nhap thoi gian: ");getc(stdin);scanf("%s",newtg); dsthoigian[eid]=get_save_id(newtg); } printf("Tong so tiep xuc: %d\n",cgraph_ecount(g)); } else if(lenh==3) { //task 3 char cmndfind[20]; printf("Nhap cmnd: ");getc(stdin);scanf("%s",cmndfind); int kiemtra = s2i_value(s2i, cmndfind); if(kiemtra == k_s2i_invalid) printf("CMND khong ton tai!\n"); else if(kiemtra != k_s2i_invalid) { for(int i=0;i<n;i++) { if(strcmp(dscongdan[i].cmnd,cmndfind)==0) { printf("Ten: %s\n",dscongdan[i].ten); printf("Sdt: %s\n",dscongdan[i].sdt); } } } } else if(lenh==4) { //task4 char cmndfind[20]; printf("Nhap cmnd: ");getc(stdin);scanf("%s",cmndfind); int kiemtra = s2i_value(s2i, cmndfind); if(kiemtra == k_s2i_invalid) printf("CMND khong ton tai!\n"); else { cgraph_ivec_t neis = cgraph_ivec_create(); cgraph_neighbors(g,&neis,get_save_id(cmndfind),CGRAPH_ALL); printf("Danh sach tiep xuc: \n"); if (cgraph_ivec_size(neis)==0) printf("Khong co tiep xuc\n"); else { for(int j=0; j<cgraph_ivec_size(neis);j++) { printf("%s ",i2s[neis[j]]); } printf("\n"); } } } else if(lenh==5) { //task5 char cmndfind[20]; printf("Nhap cmnd: ");getc(stdin);scanf("%s",cmndfind); int kiemtra = s2i_value(s2i, cmndfind); cgraph_ivec_t giantiep = cgraph_ivec_create(); if(kiemtra == k_s2i_invalid) printf("CMND khong ton tai!\n"); else { cgraph_ivec_t neis = cgraph_ivec_create(); cgraph_neighbors(g,&neis,get_save_id(cmndfind),CGRAPH_ALL); printf("Danh sach tiep xuc truc tiep: \n"); if (cgraph_ivec_size(neis)==0) printf("Khong co tiep xuc\n"); else { for(int j=0; j<cgraph_ivec_size(neis);j++) { printf("%s \n",i2s[neis[j]]); cgraph_ivec_t neis1 = cgraph_ivec_create(); cgraph_neighbors(g,&neis1,neis[j],CGRAPH_ALL); printf("Danh sach tiep xuc gian tiep: \n"); for(int i=0;i<cgraph_ivec_size(neis1);i++) { int check2=0; for(int z=0;z<cgraph_ivec_size(neis);z++) { if(neis1[i]==neis[z]||neis1[i]==get_save_id(cmndfind)) check2++; } if(check2==0) printf("%s ",i2s[neis1[i]]); } printf("\n"); } printf("\n"); } } } }while(lenh!=6); cgraph_destroy(&g); fclose(dancu);fclose(tiepxuc); return 0; }
C
#include <stdio.h> int main(int argc, char** argv) { int n, fatorial = 1; printf("Digite o valor a ser fatorado:\n"); scanf("%d", &n); if (n < 0){ printf("Valor absurdo\n"); } else if (n == 0){ printf("Fatorial: 1\n"); } else{ for ( ; n>0; n--){ fatorial *= n; } printf("Fatorial: %d\n", fatorial); } return 0; }
C
#include <unistd.h> #include <sys/types.h> #include <errno.h> #include <stdio.h> #include <sys/wait.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <math.h> //AQUI TEM A STRING DE REFERENCIA DOS ESLAIDES int teste[20] = {7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0,1,7,0,1}; int teste2[11] = {6, 6 ,3, 0, 4, 8, 2, 3, 3,9, 0}; void FIFOFunction(int tamSR); void LRUFunction(int tamSR); void CLOCKFunction(int tamSR); void CLOCKBFunction(int tamSR); typedef struct Fila { struct Frame* first; struct Frame* last; struct Frame* it; int pageIn; int pageOut; int qtPag; } FILA; typedef struct Frame { int pag; int bitRef; int bitMod; struct Frame *next; struct Frame *prev; }FRAME; FILA* criaFila() { FILA* fila = (FILA*) malloc(sizeof(FILA)); fila->first = NULL; fila->last = NULL; fila->it = NULL; fila->pageIn = 0; fila->pageOut = 0; fila->qtPag = 0; return fila; } FRAME* criaFreeFrame() { FRAME* novo = (FRAME*) malloc(sizeof(FRAME)); novo->pag = -1; novo->bitRef = 0; novo->bitMod = 0; novo->prev = NULL; novo->next = NULL; return novo; } void appendLast(FILA* fila, FRAME *nodo) { FRAME *aux; aux = fila->last; if(aux == NULL) { fila->first = nodo; fila->last = nodo; fila->it = nodo; } else { aux->next = nodo; nodo->prev = aux; nodo->next = NULL; fila->last = nodo; } } void appendFirst(FILA* fila, FRAME *nodo) { FRAME *aux; aux = fila->first; if(aux == NULL) { fila->first = nodo; fila->last = nodo; fila->it = nodo; return; } aux->prev = nodo; nodo->next = aux; fila->first = nodo; return; } FRAME* DeleteAtIterator(FILA *fila){ FRAME *deleted = fila->it; if(fila == NULL) return NULL; if(fila->it == fila->first) { fila->first = fila->it->next; fila->first->prev = NULL; return deleted; } if(fila->it == fila->last){ fila->last = fila->it->prev; fila->last->next = NULL; return deleted; } deleted->prev->next = deleted->next; deleted->next->prev = deleted->prev; return deleted; } void FirstFila(FILA *fila){ fila->it = fila->first; } void LastFila(FILA *fila){ fila->it = fila->last; } //Seta o iterador no primeiro frame livre encontrado. Retorna 1 se acha e 0 se n'ao acha int setIteratorFreeFrame(FILA *fila) { FRAME *aux; for(aux = fila->first; aux != NULL; aux = aux->next){ if(aux->pag < 0){ fila->it = aux; return 1; } } return 0; } int procuraMemoria(FILA *fila, int pag){ FRAME* aux; for(aux = fila->first; aux != NULL; aux = aux->next){ if(aux->pag == pag){ fila->it = aux; return 1; } } return 0; } int procuraProxClock(FILA *fila, FRAME* stopped) { FRAME *aux; for(aux = stopped; aux != NULL; aux = aux->next){ if(aux->bitRef == 0){ fila->it = aux; return 1; } aux->bitRef = 0; } for(aux = fila->first; aux != stopped; aux = aux->next){ if(aux->bitRef == 0){ fila->it = aux; return 1; } aux->bitRef = 0; } FirstFila(fila); return 1; } int procuraProxClockA(FILA *fila, FRAME* stopped) { FRAME *aux; for(aux = stopped; aux != NULL; aux = aux->next){ if(aux->bitRef == 0){ fila->it = aux; return 1; } } for(aux = fila->first; aux != stopped; aux = aux->next){ if(aux->bitRef == 0){ fila->it = aux; return 1; } } return 0; } int procuraProxClockB(FILA *fila, FRAME* stopped) { FRAME *aux; for(aux = stopped; aux != NULL; aux = aux->next){ if(aux->bitMod == 0){ fila->it = aux; return 1; } aux->bitRef = 0; } for(aux = fila->first; aux != stopped; aux = aux->next){ if(aux->bitMod == 0){ fila->it = aux; return 1; } aux->bitRef = 0; } return 1; } int *SR, *bitMod; FILA *FIFO, *LRU, *CLOCK, *CLOCKB; FRAME* itClock; int main (int argc, char *argv[]) { int i; int pag = 1024; int frame = 256; int string = 5000; for (i = 1; i < argc; i++) { if(strcmp(argv[i], "-v") == 0) pag = atoi(argv[i+1]); else if (strcmp(argv[i], "-f") == 0) frame = atoi(argv[i+1]); else if (strcmp(argv[i], "-s") == 0) string = atoi(argv[i+1]); } srand(time(NULL)); // printf("String de referência: "); //Allocando espaço para a string de referencia SR = (int*) malloc(string*sizeof(int)); bitMod = (int*) malloc(string*sizeof(int)); for(i = 0; i < string; i++) { *(SR+i) = rand() % pag; if(*(SR+i) % 16 < 13) *(bitMod+i) = 0; else *(bitMod+i) = 1; } //Cria as filas FIFO = criaFila(); LRU = criaFila(); CLOCK = criaFila(); CLOCKB = criaFila(); //Cria os frames passados pelo usuario, ou não for(i = 0; i < frame; i++){ appendLast(FIFO, criaFreeFrame()); appendLast(LRU, criaFreeFrame()); appendLast(CLOCK, criaFreeFrame()); appendLast(CLOCKB, criaFreeFrame()); } FIFOFunction(string); printf("%d,%d,%d\n",FIFO->pageIn,FIFO->pageOut,FIFO->qtPag); LRUFunction(string); printf("%d,%d,%d\n",LRU->pageIn,LRU->pageOut,LRU->qtPag); CLOCKFunction(string); printf("%d,%d,%d\n",CLOCK->pageIn,CLOCK->pageOut,CLOCK->qtPag); CLOCKBFunction(string); printf("%d,%d,%d\n",CLOCKB->pageIn,CLOCKB->pageOut,CLOCKB->qtPag); } void FIFOFunction(int tamSR){ int i,j,pagAtual; FRAME *aux, *aux2; for(i = 0; i < tamSR; i++){ //Se a página não está na memória if(!procuraMemoria(FIFO, *(SR+i))){ FIFO->qtPag++; //Mas há frames livres if(setIteratorFreeFrame(FIFO)){ aux = DeleteAtIterator(FIFO); aux->pag = *(SR+i); FIFO->pageIn++; appendLast(FIFO, aux); } //Se não há frames livres, pega o primeiro e o atualiza else { FirstFila(FIFO); aux = DeleteAtIterator(FIFO); aux->pag = *(SR+i); FIFO->pageIn++; FIFO->pageOut++; appendLast(FIFO, aux); } } //Pedaço de código que mostra o estado da memória a cada iteração. Bem legal :) /*aux2 = FIFO->first; printf("Como está o estado da memória \n"); for(j = 0; j < 3; j++){ printf("%d ", aux2->pag); aux2 = aux2->next; } printf("\n");*/ } } void LRUFunction(int tamSR){ int i, j, pagAtual; FRAME *aux, *aux2; for(i = 0; i < tamSR; i++){ //Se a página não está na memória if(!procuraMemoria(LRU, *(SR+i))){ LRU->qtPag++; //Mas há frames livres if(setIteratorFreeFrame(LRU)){ aux = DeleteAtIterator(LRU); aux->pag = *(SR+i); LRU->pageIn++; appendFirst(LRU, aux); } //Se não há frames livres, pega o primeiro e o atualiza else { LastFila(LRU); aux = DeleteAtIterator(LRU); aux->pag = *(SR+i); LRU->pageIn++; LRU->pageOut++; appendFirst(LRU, aux); } } else { aux = DeleteAtIterator(LRU); appendFirst(LRU, aux); } //Pedaço de código que mostra o estado da memória a cada iteração. Bem legal :) /*aux2 = LRU->first; printf("Como está o estado da memória \n"); for(j = 0; j < 3; j++){ printf("%d ", aux2->pag); aux2 = aux2->next; } printf("\n"); */ } } void CLOCKFunction(int tamSR) { int i,j; FRAME *aux, *aux2; itClock = CLOCK->first; for (i = 0; i < tamSR; i++){ if(!procuraMemoria(CLOCK, *(SR+i))){ CLOCK->qtPag++; if(setIteratorFreeFrame(CLOCK)){ aux = CLOCK->it; aux->pag = *(SR+i); CLOCK->pageIn++; aux->bitRef = 1; } else { CLOCK->pageOut++; procuraProxClock(CLOCK, itClock); aux = CLOCK->it; aux->pag = *(SR+i); aux->bitRef = 1; CLOCK->pageIn++; } } else{ CLOCK->it->bitRef = 1; } itClock = aux->next; /*aux2 = CLOCK->first; printf("Como está o estado da memória \n"); for(j = 0; j < 3; j++){ printf("( %d, %d ) ", aux2->pag, aux2->bitRef); aux2 = aux2->next; } printf("\n");*/ } } void CLOCKBFunction(int tamSR) { int i,j; FRAME *aux, *aux2; itClock = CLOCKB->first; for (i = 0; i < tamSR; i++){ if(!procuraMemoria(CLOCKB, *(SR+i))){ CLOCKB->qtPag++; if(setIteratorFreeFrame(CLOCKB)){ aux = CLOCKB->it; aux->pag = *(SR+i); CLOCKB->pageIn++; aux->bitRef = 1; aux->bitMod = *(bitMod+i); } else { if(procuraProxClockA(CLOCKB, itClock)){ aux = CLOCKB->it; aux->pag = *(SR+i); aux->bitRef = 1; aux->bitMod = *(bitMod+i); CLOCKB->pageIn++; } else{ procuraProxClockB(CLOCKB, itClock); aux = CLOCKB->it; aux->pag = *(SR+i); aux->bitRef = 1; aux->bitMod = *(bitMod+i); CLOCKB->pageIn++; CLOCKB->pageOut++; } } } else CLOCKB->it->bitRef = 1; itClock = aux->next; /*aux2 = CLOCKB->first; printf("Como está o estado da memória \n"); for(j = 0; j < 4; j++){ printf("( %d, %d, %d) ", aux2->pag, aux2->bitRef, aux2->bitMod); aux2 = aux2->next; } printf("\n"); */ } }
C
#include "generateText.c" #ifndef GENERATETEXT_H #define GENERATETEXT_H //Fungsi Free List /* Mengosongkan isi linked list yang sudah tidak diakses */ /* Input: head dari linked list, jumlah node pada linked list */ /* Hasil: memori linked list dihapus */ void freeList(node** head, int n); //Fungsi Search Value /* Mencari value dari key pada linked list */ /* Input: node dari linked list text, queue key, jumlah kata pada teks */ /* Hasil: value di print, key digeser satu kata */ void searchValue(node **text, queue **key, int textLength); //Fungsi Generate Text /* Mencetak string text baru */ /* Input: node dari linked list teks, jumlah kata yg akan dicetak, jumlah n-gram */ /* Hasil: teks random */ void generateText(node*text, int textLength, int word_count, int n_grams); #endif
C
#include <stdio.h> void casillas (char *argv[]); int main(int argc, char *argv[]) { // short int a; //short int b; //short int c; //short int d; if (argc==1) { printf("Debes ingresar mas parametros...\n"); return 1; } // else // { // scanf(" %hd", &a); //} if (argc==2) { printf("Debes ingresar mas parametros...\n"); } //else //{ // scanf (" &d", &b); //} if (argc==3) { printf("Debes ingresar mas parametros...\n"); } //else //{ // scanf (" %hd", &c); //} if (argc==4) { printf("Debes ingresar mas parametros...\n"); } //else //{ // scanf (" %hd", &d); //} casillas(argv); } void casillas (char *argv[]) { int op; printf("Del 1 al 4, que casilla quieres?(por favor, poner del 1 al 4)\n\n"); scanf(" %d", &op); if (op==1) { printf ("el numero que corresponde a la casilla uno es %s\n", argv[1]); } if (op==2) { printf ("el numero que corresponde a la casilla uno es %s\n", argv[2]); } if (op==3) { printf ("el numero que corresponde a la casilla uno es %s\n", argv[3]); } if (op==4) { printf ("el numero que corresponde a la casilla uno es %s\n", argv[4]); } casillas(argv); }
C
/* Example- Entire structure as function arguments */ # include<stdio.h> struct book { char name[20]; char author[10]; int pages; }; void display(struct book tech_book) { printf("Name :%s\n Author :%s\nPages :%d\n", tech_book.name, tech_book.author,tech_book.pages); } void main(void) { void display(struct book);//it can be outside struct book tech_book={"Programming in C","Stephen", 300}; display(tech_book); getch(); return 0; }
C
/*==================================================== * Copyright (C) 2018 All rights reserved. * * 文件名称:fifo_read.c * 创 建 者:cqb [email protected] * 创建日期:2018年01月10日 * 描 述: ================================================================*/ #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int main(int argc, char *argv[]) { //int fd = open("./fifo",O_RDONLY); int fd = open("./fifo",O_RDONLY|O_NONBLOCK); if(fd < 0) { perror("open fifo"); return -1; } char buff[128] ={0}; int ret = read(fd,buff,sizeof(buff)); if(ret > 0) { printf("read buff = %s \n",buff); } else { perror("read fifo"); } close(fd); return 0; }
C
#ifndef __STACK_H #define __STACK_H typedef void* Stack; typedef void* InfoStack; /* Cria uma stack POS: retoan a stack */ Stack createStack(); /* Verifica se a stack está vazia PRE: stack POS: 0 se não está vazio e 1 se está */ int isEmptyStack(Stack stack); /* Retorna o tamanho da stack PRE: stack POS: numero de elementos */ int sizeStack(Stack stack); /* Retorna o primeiro elemento da stack PRE: stack POS: elemento */ InfoStack topStack(Stack stack); /* Insere um novo elemento na stack PRE: stack e elemento */ void pushStack(Stack stack, InfoStack info); /* Retira o último elemento da stack PRE: stack e flag: 1 = desaloca info e 0 = não desaloca */ void popStack(Stack stack, int flag); /* Desaloca stack PRE: stack e flag: 1 = desaloca info e 0 = não desaloca */ void removeStack(Stack stack, int flag); #endif
C
/* mpchash.c */ /* This library implements multi-probe consistent hashing */ #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include "mpchash.h" uint64_t siphash(uint64_t k0, uint64_t k1, const unsigned char *m, size_t len); struct bucket_t { uint64_t point; size_t node_idx; } bucket_t; struct mpchash_t { struct bucket_t *blist; size_t nbuckets; char **node_names; size_t *name_lens; size_t num_names; size_t probes; uint64_t seeds[2]; } mpchash_t; static int cmpbucket(const void *a, const void *b) { struct bucket_t *b1 = (struct bucket_t *) a; struct bucket_t *b2 = (struct bucket_t *) b; if (b1->point < b2->point) { return -1; } if (b1->point > b2->point) { return 1; } return 0; } struct mpchash_t *mpchash_create(const char **node_names, size_t * name_lens, size_t num_names, size_t probes, uint64_t seed1, uint64_t seed2) { struct mpchash_t *mpchash; struct bucket_t *blist = (struct bucket_t *) malloc(sizeof(bucket_t) * num_names); char **nlist = (char **) malloc(sizeof(char *) * num_names); size_t *lens = (size_t *) malloc(sizeof(size_t) * num_names); size_t n, bidx = 0; for (n = 0; n < num_names; n++) { nlist[n] = (char *) malloc(sizeof(char) * name_lens[n]); lens[n] = name_lens[n]; memcpy(nlist[n], node_names[n], lens[n]); blist[bidx].node_idx = n; blist[bidx].point = siphash(0, 0, (const unsigned char *) nlist[n], lens[n]); bidx++; } qsort(blist, bidx, sizeof(struct bucket_t), cmpbucket); mpchash = malloc(sizeof(mpchash_t)); mpchash->blist = blist; mpchash->nbuckets = bidx; mpchash->node_names = nlist; mpchash->name_lens = lens; mpchash->num_names = num_names; mpchash->probes = probes; mpchash->seeds[0] = seed1; mpchash->seeds[1] = seed2; return mpchash; } void mpchash_lookup(struct mpchash_t *mpchash, const char *key, size_t len, const char **node_name, size_t * name_len) { size_t k; uint64_t distance; uint64_t min_distance = 0xffffffffffffffff; size_t min_node; uint64_t h1; uint64_t h2; h1 = siphash(mpchash->seeds[0], 0, (const unsigned char *) key, len); h2 = siphash(mpchash->seeds[1], 0, (const unsigned char *) key, len); for (k = 0; k < mpchash->probes; k++) { uint64_t point = h1 + k * h2; uint32_t low = 0, high = mpchash->nbuckets; /* binary search through blist */ while (low < high) { uint32_t mid = low + (high - low) / 2; if (mpchash->blist[mid].point > point) { high = mid; } else { low = mid + 1; } } if (low >= mpchash->nbuckets) { low = 0; } distance = mpchash->blist[low].point - point; if (distance < min_distance) { min_distance = distance; min_node = mpchash->blist[low].node_idx; } } *node_name = mpchash->node_names[min_node]; *name_len = mpchash->name_lens[min_node]; } void mpchash_free(struct mpchash_t *mpchash) { size_t i; for (i = 0; i < mpchash->num_names; i++) { free(mpchash->node_names[i]); } free(mpchash->node_names); free(mpchash->name_lens); free(mpchash->blist); free(mpchash); } /* Floodyberry's public-domain siphash: https://github.com/floodyberry/siphash */ static uint64_t U8TO64_LE(const unsigned char *p) { return *(const uint64_t *) p; } #define ROTL64(a,b) (((a)<<(b))|((a)>>(64-b))) uint64_t siphash(uint64_t k0, uint64_t k1, const unsigned char *m, size_t len) { uint64_t v0, v1, v2, v3; uint64_t mi; uint64_t last7; size_t i, blocks; v0 = k0 ^ 0x736f6d6570736575ull; v1 = k1 ^ 0x646f72616e646f6dull; v2 = k0 ^ 0x6c7967656e657261ull; v3 = k1 ^ 0x7465646279746573ull; last7 = (uint64_t) (len & 0xff) << 56; #define sipcompress() \ v0 += v1; v2 += v3; \ v1 = ROTL64(v1,13); v3 = ROTL64(v3,16); \ v1 ^= v0; v3 ^= v2; \ v0 = ROTL64(v0,32); \ v2 += v1; v0 += v3; \ v1 = ROTL64(v1,17); v3 = ROTL64(v3,21); \ v1 ^= v2; v3 ^= v0; \ v2 = ROTL64(v2,32); for (i = 0, blocks = (len & ~7); i < blocks; i += 8) { mi = U8TO64_LE(m + i); v3 ^= mi; sipcompress() sipcompress() v0 ^= mi; } switch (len - blocks) { case 7: last7 |= (uint64_t) m[i + 6] << 48; case 6: last7 |= (uint64_t) m[i + 5] << 40; case 5: last7 |= (uint64_t) m[i + 4] << 32; case 4: last7 |= (uint64_t) m[i + 3] << 24; case 3: last7 |= (uint64_t) m[i + 2] << 16; case 2: last7 |= (uint64_t) m[i + 1] << 8; case 1: last7 |= (uint64_t) m[i + 0]; case 0: default:; }; v3 ^= last7; sipcompress() sipcompress() v0 ^= last7; v2 ^= 0xff; sipcompress() sipcompress() sipcompress() sipcompress() return v0 ^ v1 ^ v2 ^ v3; }
C
/* Written by Kaelen Carling and Max Weiss */ #include "interpol.h" float interpol(float x1,float x2,float y1,float y2,float x) { // calculates slope from given coordinates float slope = (y2 - y1)/(x2-x1); // inerpolates the next y coordinate from the // given coordinates using slope intercept form float y = (slope)*x - (slope)*x2+y2; // returns the interpolated value return y; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_4__ TYPE_1__ ; /* Type definitions */ typedef int /*<<< orphan*/ uint8_t ; struct TYPE_4__ {size_t len_; int eos_; size_t pos_; int /*<<< orphan*/ * buf_; } ; typedef TYPE_1__ VP8LBitReader ; /* Variables and functions */ scalar_t__ VP8LIsEndOfStream (TYPE_1__* const) ; int /*<<< orphan*/ assert (int) ; void VP8LBitReaderSetBuffer(VP8LBitReader* const br, const uint8_t* const buf, size_t len) { assert(br != NULL); assert(buf != NULL); assert(len < 0xfffffff8u); // can't happen with a RIFF chunk. br->buf_ = buf; br->len_ = len; // pos_ > len_ should be considered a param error. br->eos_ = (br->pos_ > br->len_) || VP8LIsEndOfStream(br); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> /* * \brief Solicita un numero al usuario y devuelve el resultado. * \param mensaje Es el mensaje a mostrar. * \return El número ingresado por el usuario. * */ float getFloat(char mensaje[]){ float auxiliar; printf("%s", mensaje); scanf("%f", &auxiliar); return auxiliar; } int getInt(char mensaje[]){ int auxiliar; printf("%s", mensaje); printf("%s", mensaje); scanf("%d", &auxiliar); return auxiliar; } char getChar(char mensaje[]){ char auxiliar; printf("%s", mensaje); fflush(stdin); scanf("%c", &auxiliar); return auxiliar; } /* * \brief Genera un numero aleatorio. * \param desde Número aleatorio mínimo. * \param hasta Número aleatorio máximo. * \param iniciar Indica si se trata del primer número solicitado 1 indica que sí. * \return retorna el número aleatorio generado. * */ char getNumeroAleatorio(int desde,int hasta,int iniciar){ if(iniciar){ srand(time(NULL)); } return desde + (rand() % (hasta +1 - desde)); } /* * \brief Verifica si el valor recibido es numérico * \param str Array con la cadena a ser analizada * \return 1 si es numérico y 0 si no lo es. * */ int esNumerico(char str[]){ int i=0; while(str[i] != '\0'){ if(str[i]<'0' || str[i]>'9'){ return 0; } i++; } return 1; } /* * \brief Verifica si el valor recibido contiene solo letras * \param str Array con la cadena a se analizada * \return 1 si contien solo ' ' y letras y 0 so no es así. * */ int esSoloLetras(char str[]){ int i=0; while(str[i] != '\0'){ if((str[i] !=' ') && (str[i]<'a' || str[i]>'z') && (str[i]<'A' || str[i]>'Z')){ return 0; } i++; } return 1; } /* * \brief Verifica si el valor recibido contiene solo letras y números. * \param str Array con la cadena a ser analizada. * \return 1 Si contiene solo espacio o letras y números, o 0 si no es así. * */ int esAlfaNumerico(char str[]){ int i=0; while(str[i] != '\0'){ if((str[i] != ' ') && (str[i]<'a' || str[i]>'z') && (str[i]<'A' || str[i]>'Z')){ return 0; } i++; } return 1; } /* * \brief Verifica si el valor recibido contiene solo números, + y -. * \param str Array con la cadena a ser analizada. * \return 1 Si contiene solo números, espacios y un guión. * */ int esTelefono(char str[]){ int i=0; int contadorGuiones=0; while(str[i] != '\0'){ if((str[i] !=' ') && (str[i]!='-') && (str[i]<'0' || str[i]>'9')){ return 0; } if(str[i]=='-'){ contadorGuiones++; } i++; } if(contadorGuiones==1){ return 1; } return 0; }
C
#include <stdio.h> #include <stdlib.h> float * selectionSort(float array[ ], int size) { int pass,item,position,temp; /* Selection-sort the values read in. */ for(pass=0; pass<size-1; pass++){ position = pass; for(item=pass+1; item<size; item++) if (array[position] < array[item]) position = item; if(pass != position){ temp = array[pass]; array[pass] = array[position]; array[position] = temp; } } return array; } float * printArray(float a[ ], int s) { int i; for(i=0; i<s; i++) /* display values in array */ printf("%f\n", a[i]); return a; } float * readArray(float a[ ], int s) { int i; /* Read score values into array */ for(i=0; i<s; i++) { printf("Enter value %d of %d: ", i+1, s); scanf("%f", &a[i]); } return a; }
C
#include <stdio.h> #define N 5 float invmat(float *a, int n) { float aux; int i, j, k; for (i = 0; i < n; i++) { aux = *(a + n * i + i); for (j = 0; j < n; j++) *(a + n * i + j) /= aux; *(a + n * i + i) = 1.0 / aux; for (k = 0; k < n; k++) if (k != i) { aux = *(a + n * k + i); for (j = 0; j < n; j++) *(a + n * k + j) -= aux * *(a + n * i + j); *(a + n * k + i) = -aux * *(a + n * i + i); } } } void decomp_LU(float *a, int n) { int i, j, k; float aux, aux2; for (i = 0; i < n - 1; i++) { aux = *(a + i * n + i); for (k = i + 1; k < n; k++) *(a + i * n + k) /= aux; for (k = i + 1; k < n; k++) { aux2 = *(a + k * n + i); for (j = i + 1; j < n; j++) *(a + k * n + j) -= aux2 * *(a + i * n + j); } } } void get_LU(float *a, float *L, float *U, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { *(L + i * n + j) = *(a + i * n + j); } for (int j = i; j <= i; j++) { *(U + i * n + j) = 1; } for (int j = i + 1; j < n; j++) { *(U + i * n + j) = *(a + i * n + j); } } } void print_matrix(float *a, int n) { for (int i = 0; i < n * n; i++) { printf("%.2f\t", a[i]); if ((i + 1) % n == 0) printf("\n"); } printf("\n"); } void prodmatmat(float *a, float *b, float *p, int n) { float *p1, *p2, *p3, *pa, *pb; for (p1 = a, p3 = p; p1 < a + n * n; p1 += n) { for (p2 = b; p2 < b + n; p2++, p3++) { *p3 = 0; for (pa = p1, pb = p2; pa < p1 + n; pa++, pb += n) { *p3 += *pa * *pb; } } } } float invlinf(float *l, int n) { float aux; int i, j, k; for (i = 1; i < n; i++) { aux = *(l + n * i + i); *(l + n * i + i) = 1 / aux; for (j = 0; j < i; j++) { *(l + n * i + j) /= aux; *(l + n * i + j) = -*(l + n * i + j) * *(l + n * j + j); for (k = j + 1; k < i; k++) *(l + n * i + j) -= *(l + n * i + k) * *(l + n * k + j) / aux; } } } float invusup(float *u, int n) { int i, j, k; for (i = n - 1; i >= 0; i--) { for (j = n - 1; j > i; j--) { *(u + n * i + j) = -*(u + n * i + j); for (k = j - 1; k > i; k--) { *(u + i * n + j) -= *(u + n * k + j) * *(u + i * n + k); } } } } int max(int a, int b) { if (a > b) return a; return b; } float invLU(float *a, float *r, int n) { int i, j, k; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { for (k = n - 1; k >= max(i, j); k--) { if (i == k) *(r + n * i + j) += *(a + n * k + j); else *(r + n * i + j) += *(a + n * i + k) * *(a + n * k + j); } } } } int main(void) { /* test inv */ /* // float test[3 * 3] = {2, 3, -1, 4, 4, -3, -2, 3, -1}; // invmat(test, 3); */ float a[N * N] = {1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, -1, 1, -1, 1, 1, -2, 4, -8, 16, 1, -3, 9, -27, 81}; decomp_LU(a, N); print_matrix(a, N); /* test LU */ // float L[N * N] = {0}, U[N * N] = {0}; float res[N * N] = {0}; // get_LU(a, L, U, N); // invmat(L, N); // invmat(U, N); // print_matrix(L, N); // print_matrix(U, N); // prodmatmat(L, U, res, N); // print_matrix(res, N); invusup(a, N); invlinf(a, N); print_matrix(a, N); invLU(a, res, N); print_matrix(res, N); return 0; } /* inverse de a 0.00 1.00 -0.00 0.00 -0.00 0.25 0.83 -1.50 0.50 -0.08 0.46 -0.83 0.25 0.17 -0.04 0.25 -0.83 1.00 -0.50 0.08 0.04 -0.17 0.25 -0.17 0.04 */
C
#pragma once typedef int bool; #define false 0 #define true 1 typedef unsigned char uint8; /* == 8 bits */ typedef unsigned short uint16; /* == 16 bits */ typedef unsigned int uint32; /* == 32 bits */
C
/**************************************/ /*Author : PERUMAL R */ /*Date : 14-03-2019 */ /*Filename : header_lib.h */ /*Description: Prototypes */ /**************************************/ #include "headr_make.h" int a,b; int main() { printf("Enter the input\n"); scanf("%d %d",&a,&b); addition(a,b); subtration(a,b); return 0; }
C
#define GLFW_DLL 1 #define PI 3.14159265358979323846 #define WINDOW_WIDTH 500 #define WINDOW_HEIGHT 500 #define GL_GLEXT_PROTOTYPES #include <GLES2/gl2.h> #include <GLFW/glfw3.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <assert.h> //data type to store pixel rgb values typedef struct Pixel { unsigned char r, g, b; } Pixel; FILE* inputfp; int width, height, maxcv; //global variables to store header information GLFWwindow* window; //data type to store vertex data typedef struct { float position[3]; float color[4]; float textcoord[2]; } Vertex; //list of vertexes to store triangle information Vertex Vertices[] = { {{1, -1, 0}, {1, 0, 0, 1}, {0.99999,0.99999}}, {{1, 1, 0}, {0, 1, 0, 1}, {0.99999,0}}, {{-1, 1, 0}, {0, 0, 1, 1}, {0,0}}, {{-1, -1, 0}, {0, 0, 0, 1}, {0,0.99999}} }; //mapping vertexes into two triangles const GLubyte Indices[] = { 0, 1, 2, 2, 3, 0 }; char* vertex_shader_src = "attribute vec4 Position;\n" "attribute vec4 SourceColor;\n" "\n" "attribute vec2 TexCoordIn;\n" "varying lowp vec2 TexCoordOut;\n" "\n" "varying lowp vec4 DestinationColor;\n" "\n" "void main(void) {\n" " TexCoordOut = TexCoordIn;\n" " DestinationColor = SourceColor;\n" " gl_Position = Position;\n" "}\n"; char* fragment_shader_src = "varying lowp vec4 DestinationColor;\n" "\n" "varying lowp vec2 TexCoordOut;\n" "uniform sampler2D Texture;\n" "\n" "void main(void) {\n" " gl_FragColor = texture2D(Texture, TexCoordOut);\n" "}\n"; //simple_shader compiles an input shader and returns that shader's id if compilation was successful GLint simple_shader(GLint shader_type, char* shader_src) { GLint compile_success = 0; int shader_id = glCreateShader(shader_type); glShaderSource(shader_id, 1, &shader_src, 0); glCompileShader(shader_id); glGetShaderiv(shader_id, GL_COMPILE_STATUS, &compile_success); if (compile_success == GL_FALSE) { GLchar message[256]; glGetShaderInfoLog(shader_id, sizeof(message), 0, &message[0]); printf("glCompileShader Error: %s %s\n", shader_src, message); exit(1); } return shader_id; } //This function reads the header data of the input file and stores the crucial parts into global variables for future use int read_header(char input) //take in the p type (3 or 6) as a char { int i, line, endOfHeader, x; char a, b; char widthB[32], heightB[32], maxcvB[32]; //buffers to temporarily store the width, height, and max color value char comment[64]; //buffer to store the comment a = fgetc(inputfp); //get the first two chars of the file (P#) b = fgetc(inputfp); if(a != 'P' || b != input) //check to see if the input number matches the function input and if the P is there { fprintf(stderr, "Error: Improper header filetype.\n", 005); exit(1); //exit if the header is incorrect } a = fgetc(inputfp); //move past newline a = fgetc(inputfp); //get the comment # OR the first digit of the width if(a == '#') //if there is a comment, move past it { while(a != '\n') //move past comment with this loop { a = fgetc(inputfp); } a = fgetc(inputfp); //get the first digit of the width if there was a comment } i = 0; while(a != ' ') //get the rest of the width { widthB[i] = a; //store it in a buffer a = fgetc(inputfp); i++; } width = atoi(widthB); //convert the buffer to an integer and store it a = fgetc(inputfp); //get the first char of the height i = 0; while(a != '\n') //get the rest of the height { heightB[i] = a; //store it in a buffer a = fgetc(inputfp); i++; } height = atoi(heightB); //convert the buffer to an integer and store it a = fgetc(inputfp); //get the first char of the max color value i = 0; while(a != '\n') //get the rest of the max color value { maxcvB[i] = a; //store it in a buffer a = fgetc(inputfp); i++; } maxcv = atoi(maxcvB); //convert the buffer to an integer and store it if(maxcv != 255) //check to see if the max color value is not 8 bits per channel { fprintf(stderr, "Error: Color value exceeds limit.\n", 007); exit(1); //exit the program if there isn't 8 bits per channel } return 1; } //This function reads p3 data from an input file and stores it in dynamically allocated memory, a pointer to which is passed into the function. int read_p3(Pixel* image) { int i; unsigned char check; char number[5]; for(i=0; i < width*height; i++) //for as many pixels in the image { fgets(number, 10, inputfp); //get the red value check = (char)atoi(number); //store it in an intermediate variable if(check > maxcv) //check to see if the color value is compliant with the max color value { fprintf(stderr, "Error: Color value exceeds limit.\n", 006); exit(1); //exit the program if the image's pixels don't comply with the max color value } image[i].r = check; fgets(number, 10, inputfp); //get the green value check = (char)atoi(number); //store it in an intermediate variable if(check > maxcv) //check to see if the color value is compliant with the max color value { fprintf(stderr, "Error: Color value exceeds limit.\n", 006); exit(1); //exit the program if the image's pixels don't comply with the max color value } image[i].g = check; fgets(number, 10, inputfp); //get the blue value check = (char)atoi(number); //store it in an intermediate variable if(check > maxcv) //check to see if the color value is compliant with the max color value { fprintf(stderr, "Error: Color value exceeds limit.\n", 006); exit(1); //exit the program if the image's pixels don't comply with the max color value } image[i].b = check; } return 1; } //simple_program attempts to link the shaders to the program and returns the program id if successful int simple_program() { GLint link_success = 0; GLint program_id = glCreateProgram(); GLint vertex_shader = simple_shader(GL_VERTEX_SHADER, vertex_shader_src); GLint fragment_shader = simple_shader(GL_FRAGMENT_SHADER, fragment_shader_src); glAttachShader(program_id, vertex_shader); glAttachShader(program_id, fragment_shader); glLinkProgram(program_id); glGetProgramiv(program_id, GL_LINK_STATUS, &link_success); if (link_success == GL_FALSE) { GLchar message[256]; glGetProgramInfoLog(program_id, sizeof(message), 0, &message[0]); printf("glLinkProgram Error: %s\n", message); exit(1); } return program_id; } //error_callback static void error_callback(int error, const char* description) { fputs(description, stderr); } //the pan function pans the textured triangles based on an input to decide which direction to pan in void pan(int direction) { switch(direction) { case 0: printf("You pressed right arrow key.\n"); Vertices[0].position[0] += 0.1; Vertices[1].position[0] += 0.1; Vertices[2].position[0] += 0.1; Vertices[3].position[0] += 0.1; break; case 1: printf("You pressed left arrow key.\n"); Vertices[0].position[0] -= 0.1; Vertices[1].position[0] -= 0.1; Vertices[2].position[0] -= 0.1; Vertices[3].position[0] -= 0.1; break; case 2: printf("You pressed up arrow key.\n"); Vertices[0].position[1] += 0.1; Vertices[1].position[1] += 0.1; Vertices[2].position[1] += 0.1; Vertices[3].position[1] += 0.1; break; case 3: printf("You pressed down arrow key.\n"); Vertices[0].position[1] -= 0.1; Vertices[1].position[1] -= 0.1; Vertices[2].position[1] -= 0.1; Vertices[3].position[1] -= 0.1; break; default: printf("Something went wrong when trying to pan.\n"); break; } } //the 3-dimensional float vector V3 is necessary for the dot operation inline function typedef float* V3; //the dot operation inline function is necessary for rotation calculation. //it calculates the dot product of two input vectors and returns it. static inline float v3_dot(V3 a, V3 b) { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]; } //rotateImage rotates the textured triangles by 22.5 degrees per keypress //in the direction specified in the input parameter. void rotateImage(int direction) { float theta = 22.5*(PI/180); //convert degrees to radians and store the computed value float x, y; //temporary variables to prevent premature modification of vertex positions float rotationMatrixColA[3] = {cos(theta), sin(theta), 0}; //column A of the rotation matrix about the z-axis float rotationMatrixColB[3] = {-sin(theta), cos(theta), 0}; //column B of the rotation matrix about the z-axis switch(direction) { case 0: printf("You pressed W key.\n"); x = v3_dot(Vertices[0].position, rotationMatrixColA); //store the new x-value from the dot product of the existing position and rotation matrix y = v3_dot(Vertices[0].position, rotationMatrixColB); //store the new y-value Vertices[0].position[0] = x; //assign the new x value to the proper vertex x-position Vertices[0].position[1] = y; //assign the new y value to the proper vertex y-position x = v3_dot(Vertices[1].position, rotationMatrixColA); y = v3_dot(Vertices[1].position, rotationMatrixColB); Vertices[1].position[0] = x; Vertices[1].position[1] = y; x = v3_dot(Vertices[2].position, rotationMatrixColA); y = v3_dot(Vertices[2].position, rotationMatrixColB); Vertices[2].position[0] = x; Vertices[2].position[1] = y; x = v3_dot(Vertices[3].position, rotationMatrixColA); y = v3_dot(Vertices[3].position, rotationMatrixColB); Vertices[3].position[0] = x; Vertices[3].position[1] = y; break; case 1: printf("You pressed Q key.\n"); theta = -theta; //a negative theta is required for rotations in the opposite direction rotationMatrixColA[0] = cos(theta); //recalculate the values of the rotation matrices rotationMatrixColA[1] = sin(theta); rotationMatrixColB[0] = -sin(theta); rotationMatrixColB[1] = cos(theta); x = v3_dot(Vertices[0].position, rotationMatrixColA); //repeat the same process as earlier to rotate the vertices y = v3_dot(Vertices[0].position, rotationMatrixColB); Vertices[0].position[0] = x; Vertices[0].position[1] = y; x = v3_dot(Vertices[1].position, rotationMatrixColA); y = v3_dot(Vertices[1].position, rotationMatrixColB); Vertices[1].position[0] = x; Vertices[1].position[1] = y; x = v3_dot(Vertices[2].position, rotationMatrixColA); y = v3_dot(Vertices[2].position, rotationMatrixColB); Vertices[2].position[0] = x; Vertices[2].position[1] = y; x = v3_dot(Vertices[3].position, rotationMatrixColA); y = v3_dot(Vertices[3].position, rotationMatrixColB); Vertices[3].position[0] = x; Vertices[3].position[1] = y; break; default: printf("Something went wrong when trying to rotate.\n"); break; } } //scaleImage scales the textured polygons uniformly by 10% with each keypress. //scaling up or down is determined by the input parameter. void scaleImage(int direction) { switch(direction) { case 0: printf("You pressed A key.\n"); Vertices[0].position[0] *= 1.1; Vertices[0].position[1] *= 1.1; Vertices[1].position[0] *= 1.1; Vertices[1].position[1] *= 1.1; Vertices[2].position[0] *= 1.1; Vertices[2].position[1] *= 1.1; Vertices[3].position[0] *= 1.1; Vertices[3].position[1] *= 1.1; break; case 1: printf("You pressed S key.\n"); Vertices[0].position[0] *= 1/1.1; Vertices[0].position[1] *= 1/1.1; Vertices[1].position[0] *= 1/1.1; Vertices[1].position[1] *= 1/1.1; Vertices[2].position[0] *= 1/1.1; Vertices[2].position[1] *= 1/1.1; Vertices[3].position[0] *= 1/1.1; Vertices[3].position[1] *= 1/1.1; break; default: printf("Something went wrong when trying to scale.\n"); break; } } //shearImage shears the textured polygons left and right in accordance with //the top of the original orientation of the vertices. //Whether the textured polygons are sheared left or right is determined by the input parameter. void shearImage(int direction) { switch(direction) { case 0: printf("You pressed X key.\n"); Vertices[2].position[0] += 0.1; Vertices[1].position[0] += 0.1; break; case 1: printf("You pressed Z key.\n"); Vertices[2].position[0] -= 0.1; Vertices[1].position[0] -= 0.1; break; default: printf("Something went wrong when trying to shear.\n"); break; } } //the function key_callback checks to see if a key was pressed that triggers the calling //of a particular function and which direction that function should transform the image in. void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_RIGHT && action == GLFW_PRESS) pan(0); else if (key == GLFW_KEY_LEFT && action == GLFW_PRESS) pan(1); else if (key == GLFW_KEY_UP && action == GLFW_PRESS) pan(2); else if (key == GLFW_KEY_DOWN && action == GLFW_PRESS) pan(3); else if (key == GLFW_KEY_Q && action == GLFW_PRESS) rotateImage(1); else if (key == GLFW_KEY_W && action == GLFW_PRESS) rotateImage(0); else if (key == GLFW_KEY_A && action == GLFW_PRESS) scaleImage(0); else if (key == GLFW_KEY_S && action == GLFW_PRESS) scaleImage(1); else if (key == GLFW_KEY_Z && action == GLFW_PRESS) shearImage(0); else if (key == GLFW_KEY_X && action == GLFW_PRESS) shearImage(1); else if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) //escape exits the program { printf("closing..."); glfwTerminate(); exit(EXIT_SUCCESS); } else if (key == GLFW_KEY_SPACE && action == GLFW_PRESS) //spacebar resets the vertices { printf("Resetting vertices...\n"); Vertices[0].position[0] = 1; Vertices[0].position[1] = -1; Vertices[1].position[0] = 1; Vertices[1].position[1] = 1; Vertices[2].position[0] = -1; Vertices[2].position[1] = 1; Vertices[3].position[0] = -1; Vertices[3].position[1] = -1; } } int main(int argc, char* argv[]) { if(argc != 2) { fprintf(stderr, "Error: Incorrect parameter amount.\nProper input: input_filename\n\n"); exit(1); //exit the program if there are insufficient arguments } inputfp = fopen(argv[1], "r"); //open input to read if (inputfp == 0) { fprintf(stderr, "Error: Input file \"%s\" could not be opened.\n", argv[1]); exit(1); //if the file cannot be opened, exit the program } read_header('3'); //read the header of a P3 file Pixel* data = calloc(width*height, sizeof(Pixel*)); //allocate memory to hold all of the pixel data printf("width: %d\nheight: %d\n", width, height); read_p3(&data[0]); printf("over \n"); GLint program_id, position_slot, color_slot; GLuint vertex_buffer; GLuint index_buffer; glfwSetErrorCallback(error_callback); // Initialize GLFW library if (!glfwInit()) return -1; glfwDefaultWindowHints(); glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_EGL_CONTEXT_API); glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); // Create and open a window window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Mitchell Hewitt Project 5", NULL, NULL); if (!window) { glfwTerminate(); printf("glfwCreateWindow Error\n"); exit(1); } glfwMakeContextCurrent(window); //generate the texture, bind it, define its mipmap filtering, and store the p3 image data in the texture GLuint myTexture; glGenTextures(1, &myTexture); glBindTexture(GL_TEXTURE_2D, myTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); program_id = simple_program(); glUseProgram(program_id); //put the position and sourcecolor attributes into slots and ensure this was successful position_slot = glGetAttribLocation(program_id, "Position"); color_slot = glGetAttribLocation(program_id, "SourceColor"); assert(position_slot != -1); assert(color_slot != -1); glEnableVertexAttribArray(position_slot); glEnableVertexAttribArray(color_slot); //put the texture coordinates and texture into slots and ensure this was successful GLint texCoordSlot = glGetAttribLocation(program_id, "TexCoordIn"); assert(texCoordSlot != -1); glEnableVertexAttribArray(texCoordSlot); GLint textureUniform = glGetUniformLocation(program_id, "Texture"); assert(textureUniform != -1); // Create Buffer glGenBuffers(1, &vertex_buffer); // Map GL_ARRAY_BUFFER to this buffer glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); // Send the data glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW); glGenBuffers(1, &index_buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Indices), Indices, GL_STATIC_DRAW); // Repeat for as long as the program should stay open while (!glfwWindowShouldClose(window)) { glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW); //background of the program defaults to hot pink glClearColor(255.0/255.0, 20.0/255.0, 147.0/255.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); //set the viewport width and height glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); glVertexAttribPointer(position_slot, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); glVertexAttribPointer(color_slot, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*) (sizeof(float) * 3)); glVertexAttribPointer(texCoordSlot, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), sizeof(float)*7); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, myTexture); glUniform1i(textureUniform, 0); glDrawElements(GL_TRIANGLES, sizeof(Indices) / sizeof(GLubyte), GL_UNSIGNED_BYTE, 0); //swap the buffers of what to show on screen, check for keypresses, and poll events glfwSwapBuffers(window); glfwSetKeyCallback(window, key_callback); glfwPollEvents(); } //end the program glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); }
C
/* * bitops.c -- bit manipulation operations. * * by Christopher Adam Telfer * * Copyright 2003-2012 See accompanying license * */ #include <cat/bitops.h> char num_bits_array[256] = { 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5, 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8, }; char num_leading_zeros_array[256] = { 8,7,6,6,5,5,5,5,4,4,4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; uint32_t rup2_32(uint32_t x, uint lg2p) { uint32_t p2 = ((uint32_t)1 << lg2p) - 1; return (lg2p > 31) ? 0 : (x + p2) & ~p2; } uint32_t rdp2_32(uint32_t x, uint lg2p) { return (lg2p > 31) ? 0 : (x & ~(((uint32_t)1 << lg2p) - 1)); } #if CAT_64BIT uint64_t rup2_64(uint64_t x, uint lg2p) { uint64_t p2 = ((uint64_t)1 << lg2p) - 1; return (lg2p > 63) ? 0 : (x + p2) & ~p2; } uint64_t rdp2_64(uint64_t x, uint lg2p) { return (lg2p > 63) ? 0 : (x & ~(((uint64_t)1 << lg2p) - 1)); } #endif /* CAT_64BIT */ uint32_t compress_l32(uint32_t x, uint32_t m) { uint32_t t, mp, mv, mk; int i; x &= m; mk = ~m >> 1; for ( i = 0; i < 5; ++i ) { mp = mk ^ (mk >> 1); mp = mp ^ (mp >> 2); mp = mp ^ (mp >> 4); mp = mp ^ (mp >> 8); mp = mp ^ (mp >> 16); mv = m & mp; m = (m ^ mv) | (mv << ((uint32_t)1 << i)); t = x & mv; x = (x ^ t) | (t << ((uint32_t)1 << i)); mk = mk & ~mp; } return x; } /* HD p. 119 */ uint32_t compress_r32(uint32_t x, uint32_t m) { uint32_t t, mp, mv, mk; int i; x &= m; mk = ~m << 1; for ( i = 0; i < 5; ++i ) { mp = mk ^ (mk << 1); mp = mp ^ (mp << 2); mp = mp ^ (mp << 4); mp = mp ^ (mp << 8); mp = mp ^ (mp << 16); mv = m & mp; m = (m ^ mv) | (mv >> ((uint32_t)1 << i)); t = x & mv; x = (x ^ t) | (t >> ((uint32_t)1 << i)); mk = mk & ~mp; } return x; } #if CAT_64BIT uint64_t compress_l64(uint64_t x, uint64_t m) { uint64_t t, mp, mv, mk; int i; x &= m; mk = ~m >> 1; for ( i = 0; i < 6; ++i ) { mp = mk ^ (mk >> 1); mp = mp ^ (mp >> 2); mp = mp ^ (mp >> 4); mp = mp ^ (mp >> 8); mp = mp ^ (mp >> 16); mp = mp ^ (mp >> 32); mv = m & mp; m = (m ^ mv) | (mv << ((uint64_t)1 << i)); t = x & mv; x = (x ^ t) | (t << ((uint64_t)1 << i)); mk = mk & ~mp; } return x; } uint64_t compress_r64(uint64_t x, uint64_t m) { uint64_t t, mp, mv, mk; int i; x &= m; mk = ~m << 1; for ( i = 0; i < 6; ++i ) { mp = mk ^ (mk << 1); mp = mp ^ (mp << 2); mp = mp ^ (mp << 4); mp = mp ^ (mp << 8); mp = mp ^ (mp << 16); mp = mp ^ (mp << 32); mv = m & mp; m = (m ^ mv) | (mv >> ((uint64_t)1 << i)); t = x & mv; x = (x ^ t) | (t >> ((uint64_t)1 << i)); mk = mk & ~mp; } return x; } #endif /* CAT_64BIT */ uint32_t SAG32(uint32_t x, uint32_t mask) { return compress_l32(x, mask) | compress_r32(x, ~mask); } #if CAT_64BIT uint64_t SAG64(uint64_t x, uint64_t mask) { return compress_l64(x, mask) | compress_r64(x, ~mask); } #endif /* CAT_64BIT */ /* converts an array of bit positions to a permutation vector used to permute */ /* the bits of a 32-bit word usinv the permute32() function */ int arr_to_SAG_permvec32(uint8_t arr[32], uint32_t pv[5]) { int i, j; uint32_t t = 0, bit; /* ensures that arr[] represents a real permutation */ for ( i = 0; i < 32; ++i ) { if ( arr[i] & ~0x1f ) return -1; bit = (uint32_t)1 << arr[i]; if ( t & bit ) return -1; t |= bit; } /* Each bit k (low order bit is 0) in pv[i] contains the ith bit */ /* of k's position in the final permutation. */ for ( i = 0; i < 5; ++i ) { pv[i] = 0; for ( j = 0; j < 32; ++j ) pv[i] |= ((arr[j] >> i) & 1) << j; } /* now permute each bit of p[x] for x > 1 so it lines up with */ /* the permuted bit during shuffle x */ pv[1] = SAG32(pv[1], pv[0]); pv[2] = SAG32(SAG32(pv[2], pv[0]), pv[1]); pv[3] = SAG32(SAG32(SAG32(pv[3], pv[0]), pv[1]), pv[2]); pv[4] = SAG32(SAG32(SAG32(SAG32(pv[4], pv[0]), pv[1]), pv[2]), pv[3]); return 0; } /* Performs a stable base-2 radix sort of the bits in "bits" ascribing a */ /* value to each bit position equal its final position (as a number). */ /* The SAG32() operation does the actual moving of bits */ uint32_t permute32_SAG(uint32_t bits, uint32_t pv[5]) { bits = SAG32(bits, pv[0]); bits = SAG32(bits, pv[1]); bits = SAG32(bits, pv[2]); bits = SAG32(bits, pv[3]); bits = SAG32(bits, pv[4]); return bits; } #if CAT_64BIT /* converts an array of bit positions to a permutation vector used to permute */ /* the bits of a 64-bit word usinv the permute64() function */ int arr_to_SAG_permvec64(uint8_t arr[64], uint64_t pv[6]) { int i, j; uint64_t t = 0, bit; /* ensures that arr[] represents a real permutation */ for ( i = 0; i < 64; ++i ) { if ( arr[i] & ~0x3f ) return -1; bit = (uint64_t)1 << arr[i]; if ( t & bit ) return -1; t |= bit; } /* Each bit k (low order bit is 0) in pv[i] contains the ith bit */ /* of k's position in the final permutation. */ for ( i = 0; i < 6; ++i ) { pv[i] = 0; for ( j = 0; j < 64; ++j ) pv[i] |= (uint64_t)((arr[j] >> i) & 1) << j; } /* now permute each bit of p[x] for x > 1 so it lines up with */ /* the permuted bit during shuffle x */ pv[1] = SAG64(pv[1], pv[0]); pv[2] = SAG64(SAG64(pv[2], pv[0]), pv[1]); pv[3] = SAG64(SAG64(SAG64(pv[3], pv[0]), pv[1]), pv[2]); pv[4] = SAG64(SAG64(SAG64(SAG64(pv[4], pv[0]), pv[1]), pv[2]), pv[3]); pv[5] = SAG64(SAG64(SAG64(SAG64(SAG64(pv[5], pv[0]), pv[1]), pv[2]), pv[3]), pv[4]); return 0; } /* Performs a stable base-2 radix sort of the bits in "bits" ascribing a */ /* value to each bit position equal its final position (as a number). */ /* The SAG64() operation does the actual moving of bits. */ uint64_t permute64_SAG(uint64_t bits, uint64_t pv[6]) { bits = SAG64(bits, pv[0]); bits = SAG64(bits, pv[1]); bits = SAG64(bits, pv[2]); bits = SAG64(bits, pv[3]); bits = SAG64(bits, pv[4]); bits = SAG64(bits, pv[5]); return bits; } #endif /* CAT_64BIT */ uint32_t bitgather32(uint32_t bits, uint8_t pos[32]) { int i; uint32_t x = 0; for ( i = 0; i < 32; ++i ) x |= ((bits >> (pos[i] & 0x1f)) & 1) << i; return x; } #if CAT_64BIT uint64_t bitgather64(uint64_t bits, uint8_t pos[64]) { int i; uint64_t x = 0; for ( i = 0; i < 64; ++i ) x |= ((bits >> (pos[i] & 0x3f)) & 1) << i; return x; } #endif /* CAT_64BIT */
C
#include <gmodule.h> #include <stdio.h> #include "pqueue.h" struct pqueue { unsigned int size; pq_pri_t *lowest_pri; pq_pricmp_fun pricmp; GTree *tree; }; static int update_min(pq_pri_t *pri, pq_val_t *val, pqueue_t *pq) { pq_pri_t *prev_lowest = pq->lowest_pri; if(pq->pricmp(pri, pq->lowest_pri) > 0) pq->lowest_pri = pri; return (pq->pricmp(pq->lowest_pri, prev_lowest) != 0) ? 1 : 0; } pqueue_t *pqueue_init(pq_pricmp_fun pricmp) { pqueue_t *pq = malloc(sizeof(pqueue_t)); pq->size = 0; pq->lowest_pri = NULL; pq->pricmp = pricmp; pq->tree = g_tree_new((GCompareFunc) pricmp); return pq; } int pqueue_free(pqueue_t *pq) { g_tree_destroy(pq->tree); free(pq); return 0; } int pqueue_push(pqueue_t *pq, pq_val_t *val, pq_pri_t *pri) { /* if(g_tree_lookup(pq->tree, pri) != NULL) return -1; */ if(pq->lowest_pri == NULL || pq->pricmp(pri, pq->lowest_pri) <= 0) pq->lowest_pri = pri; g_tree_insert(pq->tree, pri, val); pq->size += 1; return 0; } int pqueue_remove(pqueue_t *pq, pq_pri_t *pri) { /* if(pq->lowest_pri == NULL) puts("ERROR: trying to remove from empty pqueue"); */ if(pq->pricmp(pri, pq->lowest_pri) == 0) { pq_val_t *poped = pqueue_pop(pq); return (poped != NULL) ? 1 : 0; } int ret = g_tree_remove(pq->tree, pri); pq->size -= ret; return ret; } /* pq_val_t *pqueue_peek(pqueue_t *pq) { pq_val_t *val = NULL; pq_pri_t *pri = NULL; if (pq->lowest_pri != NULL) if(!g_tree_lookup_extended(pq->tree, pq->lowest_pri, &pri, &val)) puts("ERROR: lowest_pri not found in pqueue but pq->lowest_pri not NULL"); if (pq->lowest_pri != NULL && !(pri != NULL && pq->pricmp(pri, pq->lowest_pri) == 0 && val != NULL)) { printf("ERROR: pqueue still has a lowest pri and size %u," " but can not be found in underlying tree of size %u\n", pq->size, g_tree_nnodes(pq->tree)); //exit(EXIT_FAILURE); } return val; } */ pq_val_t *pqueue_peek(pqueue_t *pq) { return (pq->lowest_pri != NULL) ? g_tree_lookup(pq->tree, pq->lowest_pri) : NULL; } pq_pri_t *pqueue_lowest_priority(pqueue_t *pq) { return pq->lowest_pri; } pq_val_t *pqueue_pop(pqueue_t *pq) { /* if(pq->lowest_pri == NULL) puts("ERROR: trying to pop from empty pqueue"); */ pq_val_t *min = pqueue_peek(pq); if(!g_tree_remove(pq->tree, pq->lowest_pri)) min = NULL; if(min != NULL) { pq->size -= 1; if(pq->size == 0) { pq->lowest_pri = NULL; } else { //Because it iterates in order, it stops after the first iteration g_tree_foreach(pq->tree, (GTraverseFunc) update_min, (void*) pq); } } return min; } unsigned int pqueue_size(pqueue_t *pq) { return pq->size; } void pqueue_foreach(pqueue_t *pq, pq_traverse_fun cb, void *cb_arg) { g_tree_foreach(pq->tree, (GTraverseFunc) cb, cb_arg); }
C
// gcc ~/c/hexdump.c -o ~/c/hexdump // /usr/local/gcc-3.4.5-glibc-2.3.6/arm-linux/bin/arm-linux-gcc ~/c/hexdump.c -o ~/c/hexdump_arm // ~/c/hexdump 0 10 // ~/c/hexdump 0xc0353c30 0x50 // /home/jc235005/c/hexdump_arm 0xc0353c30 0x50 // [jc235005@brocadh fconfig]$ nm /usr/local/OLO/Intel_CE_2110-1.5.354/linux-2.6.16.16/vmlinux |grep c0353|sort |less //c0353c30 B mtd_table //c0353c70 b proc_mtd //c0353c74 b mtd_class #include <stdio.h> #include <stdlib.h> void hexdump(char *msg, char *buf, long offset, int len) { long i; char c; char str[0x11]; if (msg != NULL) printf("%s: %s\n", __func__, msg); i=0; while(i<len){ if (i%0x10 == 0) printf("%08x: ",i+offset); c = *(buf+i); printf("%02x", (int)c); str[i%0x10] = '.'; if (c >= 32 && c<=120) str[i%0x10] = c; if (i%2 == 0) printf(" "); if (i%0x10 == 0xf) { str[i%0x10+1] = 0; printf(" %s\n",str); } i++; } if (i%0x10 != 0xf) { str[i%0x10+1] = 0; printf(" %s\n",str); } } int a_glob; int main(int argc, char **argv) { char *ptr = 0; int len=0x10; // argv[1] = address argv[2] = length if (argc>=2) ptr = (char*)strtoul(argv[1],NULL,16); if (argc>=3) len = (int)strtoul(argv[2],NULL,16); printf("glob %p %lx, stack %p %lx\n", &a_glob, &a_glob, &len, &len); printf("hexdump %lx, %x,\n",(long)ptr,len); hexdump(NULL,ptr,(long)ptr,len); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include <string.h> #define MAX_PRODUCTS 60 // 저장할 수 있는 레코드 최대 갯수 // 회원 정보 레코드의 데이터 타입을 정의함 typedef struct st_watch{ char name[20]; // 시계 이름 char brname[20]; // 브랜드 이름 char size[20]; // 시계 사이즈 char gender[10];// 남성용,여성용 float price; // 시계 가격 int stock; // 재고 수 int sale; //세일율 } W_Record; // 라이브러리 함수 원형을 선언함 int w_is_available(); // 현재 추가할 수 있는 데이터 공간이 있는가?/ 공간이 있으면 1 없으면 0을 리턴 int w_first_available(); // 추가할 수 있는 가장 빠른 포인터 배열의 인덱스 찾기/ 포인터 배열의 인덱스를 리턴하거나 없으면 -1을 리턴 int w_count(); // 현재 저장된 시계 레코드의 개수 가져오기/ 레코드의 개수를 리턴 void w_create(char* n, char* bn, char *s, char *g, float pr, int st); // 새로운 신규 시계 레코드 추가 /파라메터-> 시계이름,브랜드,시계크기,가격,재고 수 W_Record* w_search_by_name(char* n); // 이름이 일치하는 시계 레코드 포인터 찾기/파라메터-> 이름 /이름이 일치하는 시계 레코드 포인터를 리턴 void w_update(W_Record* p, char* bn, char *s, char *g, float pr, int st); // 특정 시계 레코드의 정보 업데이트/파라메터-> 특정 시계의 구조체 포인터,브랜드,시계크기,가격,재고 수 void w_delete(W_Record* p); // 특정 시계 레코드의 상세정보 제거/파라메터->특정 시계의 구조체 포인터 void w_get_all(W_Record* a[]); // 시계정보가 들어있는 모든 레코드 포인터의 배열을 만들기/파라메터-> 시계 정보를 저장할 구조체 포인터 배열 int w_get_all_brand(W_Record* a[],char* bn); // 시계정보가 들어있는 특정 브랜드별 레코드 포인터의 배열을 만들기/파라메터->특정 브랜드별 레코드 포인터를 저장할 구조체 포인터 배열, 브랜드이름/저장된 특정브랜드의 시계의 정보 개수를 리턴 int w_get_all_gender(W_Record* a[],char *g); // 시계정보가 들어있는 특정 성별별 레코드 포인터의 배열을 만들기/파라메터->특정 성별 별 레코드 포인터를 저장할 구조체 포인터 배열, 성별/저장된 특정 성별의 시계의 정보 개수를 리턴 void w_save_file(char *t); // 작성한 레코드 저장하기//파라메터-> 저장할 파일의 이름 int w_recall_file(char *t,int ch); //파일 불러오기//파라메터->불러올 파일의 이름//파일로드에 성공하면 1을 리턴하고 실패하면 0을 리턴한다. void w_stock_update(W_Record *p, int s); //재고 업데이트하기//파라메터-> 특정시계의 레코드 포인터, 바꿀 재고의 수 void w_order_by_name(); //이름별로 정리하기 void w_record_op(); //레코드 최적화 시키기 void w_apply_sale(W_Record *p,int sa); //할인율 적용하기//파라메터->특정시계의 레코드 포인터, 적용할 할인율 char* w_getname(W_Record* p); // 특정 시계 정보 레코드의 시계이름 가져오기//파라메터-> 특정시계의 레코드포인터//특정 시계의 이름을 문자열로 리턴 char* w_getbrname(W_Record* p); // 특정 시계 정보의 브랜드이름 가져오기//파라메터-> 특정시계의 레코드포인터//특정 시계의 브랜드를 문자열로 리턴 char* w_getsize(W_Record* p);// 특정 시계 정보 레코드의 사이즈 가져오기//파라메터-> 특정시계의 레코드포인터//특정 시계의 사이즈를 문자열로 리턴 char* w_getgender(W_Record* p); // 특정 시계 정보 레코드의 gender 가져오기//파라메터-> 특정시계의 레코드포인터//특정 시계의 gender를 문자열로 리턴 float w_getprice(W_Record* p); // 특정 시계 정보 레코드의 가격 가져오기//파라메터-> 특정시계의 레코드포인터//특정 시계의 가격을 리턴 int w_getstock(W_Record* p); // 특정 시계 정보 레코드의 재고 가져오기//파라메터-> 특정시계의 레코드포인터//저장 할 특정 시계의 재고를 리턴 int w_getsale(W_Record *p); //특정 시계 세일율 가져오기//파라메터-> 특정시계의 레코드포인터//저장 할 특정 시계의 세일율을 리턴
C
#include <stdio.h> #include <stdlib.h> #include <math.h> /** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */ int* findDisappearedNumbers(int* nums, int numsSize, int* returnSize) { int* ret = (int *)malloc(sizeof(int) * numsSize); int index = 0; for(int i = 0; i < numsSize; i++) { int val = abs(*(nums+i)) - 1; if(*(nums+val) > 0) { *(nums+val) = -*(nums+val); } } for(int i = 0; i < numsSize; i++) { if(*(nums+i) > 0) { ret[index] = i + 1; index++; } } *returnSize = index; return ret; } void main() { int numsSize = 8; int input[] = {4, 3, 2, 7, 8, 2, 3, 1}; int* p = input; int* size = (int *)malloc(sizeof(int)); int* ret = findDisappearedNumbers(p, numsSize, size); printf("the output array size is: %d\nthe array is: \n", *size); for(int i = 0; i < *size; i++) { printf(" %d", *(ret+i)); } printf("\n"); free(size); free(ret); }
C
/* tanimate.c: animate several strings using threads, curses, usleep() * * bigidea one thread for each animated string * one thread for keyboard contol * shared variables for communication * compile cc tanimate.c -lcurses -lpthread -o tanimate * to do needs locks for shared variables * nice to put screen handling in its own thread */ #include <stdio.h> #include <curses.h> #include <pthread.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <termios.h> #define MAXMSG 10 /* limit to number of strings */ #define TUNIT 20000 /* timeunits in microseconds */ struct propset { char *str; /* the message */ int row; /* the row */ int delay; /* delay in time units */ int dir; /* +1 or -1 */ }; //Todo pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER; void set_cr_noecho_mode(void); int setup( int, char *[], struct propset []); void* animate(void* arg); int main(int ac, char *av[]) { int c; /* user input */ //Todo pthread_t thrds[MAXMSG]; // the threads struct propset props[MAXMSG]; // properties of string int num_msg; /* number of strings */ int i; if( ac == 1) { printf("usage: tanimate string..\n"); exit(1); } //todo num_msg = setup(ac - 1, av + 1, props); /* create all the threads */ //todo for(i=0;i<num_msg;i++) if (pthread_create(&thrds[i], NULL, animate, &props[i])) { fprintf(stderr, "error creating thread"); endwin(); exit(0); } /* process user input */ while(1) { //todo c = getchar(); if (c == 'Q') break; if (c == ' ') for (i = 0; i < num_msg; i++) props[i].dir = -props[i].dir; if (c >= '0' && c <= '9') { i = c - '0'; if (i < num_msg) props[i].dir = -props[i].dir; } } /* cancel all the threads */ //todo pthread_mutex_lock(&mx); for (i = 0; i < num_msg; i++) pthread_cancel(thrds[i]); endwin(); return 0; } int setup( int nstrings, char * strings[], struct propset props[]) { int num_msg = ( nstrings > MAXMSG ? MAXMSG : nstrings ); int i; /* assign rows and velocities to each string */ srand( getpid ()); //todo for (i = 0; i < num_msg; i++) { props[i].str = strings[i]; // the message props[i].row = i; // the row props[i].delay = 1 + (rand() % 15); // a speed props[i].dir = ((rand() % 2) ? 1 : -1); // +1 or -1 } /* set up curses */ initscr(); set_cr_noecho_mode();//gsjung clear(); mvprintw(LINES-1, 0, "'Q' to quit, '0'..'%d' to bounce", num_msg-1); return num_msg; } /* the code that runds in each thread */ void *animate(void *arg) { struct propset *info = arg; /* point to info block */ int len = strlen(info->str)+2; /* +2 for padding */ int col = rand()%(COLS-len-3); /* space for padding */ while( 1 ) { //todo usleep(info->delay * TUNIT); pthread_mutex_lock(&mx); // only one thread move(info->row, col); // can call curses addch(' '); // at the same time addstr(info->str); // Since I doubt it is addch(' '); // reentrant move(LINES - 1, COLS - 1); // park cursor refresh(); // and show it pthread_mutex_unlock(&mx); // done with curses /* move item to next column and check for bouncing */ col += info->dir; if (col <= 0 && info->dir == -1) info->dir = 1; else if (col + len >= COLS && info->dir == 1) info->dir = -1; } } void set_cr_noecho_mode(void) /* * purpose: put file descriptor 0 into chr-by-chr mode and noecho mode * method: use bits in termios */ { struct termios ttystate; tcgetattr( 0, &ttystate); /* read curr. setting */ ttystate.c_lflag &= ~ICANON; /* no buffering */ ttystate.c_lflag &= ~ECHO; /* no echo either */ ttystate.c_cc[VMIN] = 1; /* get 1 char at a time */ tcsetattr( 0, TCSANOW, &ttystate); /* install settings */ }