language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <ruby.h> #include "ast.h" VALUE rb_cVar; VALUE rb_cAnd; VALUE rb_cOr; VALUE rb_cNot; VALUE rb_eParseError; /** * Transforms the C AST to a Ruby AST. */ static VALUE transform(Node *node) { switch (node->type) { case eVAR: return rb_funcall(rb_cVar, rb_intern("new"), 1, rb_str_new2(((Var*)node)->value)); case eAND: return rb_funcall(rb_cAnd, rb_intern("new"), 2, transform(((Binary*)node)->left), transform(((Binary*)node)->right)); case eOR: return rb_funcall(rb_cOr, rb_intern("new"), 2, transform(((Binary*)node)->left), transform(((Binary*)node)->right)); case eNOT: return rb_funcall(rb_cNot, rb_intern("new"), 1, transform(((Unary*)node)->refnode)); default: rb_raise(rb_eArgError, "Should never happen"); return 0; } } static VALUE Bool_parse(VALUE klass, VALUE r_expr) { Node* ast; char* expr; if(NIL_P(klass)) { rb_raise(rb_eRuntimeError, "Bool klass was nil"); } // TODO: Verify that r_expr is a String expr = RSTRING_PTR(r_expr); ast = parse_ast(expr); if(ast != NULL) { VALUE result = transform(ast); free_ast(ast); return result; } else { rb_raise(rb_eParseError, "%s", last_error_msg); } } void Init_bool_ext() { VALUE rb_mBool; VALUE rb_eStandardError; VALUE rb_cBinary; VALUE rb_cUnary; rb_eStandardError = rb_const_get(rb_cObject, rb_intern("StandardError")); rb_mBool = rb_define_module("Bool"); rb_eParseError = rb_define_class_under(rb_mBool, "ParseError", rb_eStandardError); rb_cBinary = rb_define_class_under(rb_mBool, "Binary", rb_cObject); rb_cUnary = rb_define_class_under(rb_mBool, "Unary", rb_cObject); rb_cVar = rb_define_class_under(rb_mBool, "Var", rb_cObject); rb_cAnd = rb_define_class_under(rb_mBool, "And", rb_cBinary); rb_cOr = rb_define_class_under(rb_mBool, "Or", rb_cBinary); rb_cNot = rb_define_class_under(rb_mBool, "Not", rb_cUnary); rb_define_singleton_method(rb_mBool, "parse", Bool_parse, 1); }
C
#include "hwinfo_config_ini_parser.h" #include "ini_builder.h" #include "ini_parser.h" #include "ini_builder_list.h" #include "dlist.h" #include "iterator.h" #include "dlist_iterator.h" #include "hwinfo.h" #include <string.h> #include <stdio.h> #define COMMENT_CHAR '#' #define DELIM_CHAR '=' typedef struct { INIBuilder* ini_builder; INIParser* ini_parser; } PrivInfo; static Ret hwinfo_ini_parser_parser(HwinfoParser* thiz, const char* filename, DList** items_list) { return_val_if_fail(thiz != NULL && filename != NULL && *items_list != NULL, RET_INVALID_PARAMS); PrivInfo* priv = (PrivInfo*)thiz->priv; DList* lists = NULL; return_val_if_fail(ini_parser_load_from_file(priv->ini_parser, filename, COMMENT_CHAR, DELIM_CHAR) == RET_OK, RET_FAIL); lists = ini_builder_get_list(priv->ini_builder); if (dlist_length(lists) == 0) { printf("config file is empty\n"); return RET_INVALID_PARAMS; } Iterator* forward = dlist_iterator_create(lists); do { HwinfoItem* forward_item; HwinfoItem* item; iterator_get(forward, (void**)&forward_item); item = (HwinfoItem*)malloc(sizeof(HwinfoItem)); item->mainkey = strdup(forward_item->mainkey); item->subkey = strdup(forward_item->subkey); item->value = strdup(forward_item->value); dlist_append(*items_list, item); } while (iterator_next(forward) == RET_OK); iterator_destroy(forward); return RET_OK; } static void hwinfo_ini_parser_destroy(HwinfoParser* thiz) { return_if_fail(thiz != NULL); PrivInfo* priv = (PrivInfo*)thiz->priv; ini_builder_destroy(priv->ini_builder); ini_parser_destroy(priv->ini_parser); free(thiz); return; } HwinfoParser* hwinfo_ini_parser_create() { HwinfoParser* thiz = (HwinfoParser*)malloc(sizeof(HwinfoParser) + sizeof(PrivInfo)); if (thiz != NULL) { PrivInfo* priv = (PrivInfo*)thiz->priv; thiz->parser = hwinfo_ini_parser_parser; thiz->destroy = hwinfo_ini_parser_destroy; priv->ini_parser = ini_parser_create(); priv->ini_builder = ini_builder_list_create(); ini_parser_set_builder(priv->ini_parser, priv->ini_builder); } return thiz; } #ifdef HWINFO_CONFIG_INI_PARSER_TEST #include "dlist.h" static Ret data_visit_func(void* ctx, void* data) { return_val_if_fail(data != NULL, RET_FAIL); HwinfoItem* item = (HwinfoItem*)data; printf("[mainkey]: %s\n\t [subkey]: %s\n\t [value]: %s\n", item->mainkey, item->subkey, item->value); return RET_OK; } static void hwinfo_data_destroy(void* ctx, void* data) { return_if_fail(data != NULL); HwinfoItem* item = (HwinfoItem*)data; SAFE_FREE(item->mainkey); SAFE_FREE(item->subkey); SAFE_FREE(item->value); free(item); return; } int main(int argc, char* argv[]) { DList* items_list = dlist_create(hwinfo_data_destroy, NULL); HwinfoParser* hwinfo_ini_parser = hwinfo_ini_parser_create(); hwinfo_parser_config(hwinfo_ini_parser, "./main.conf", &items_list); dlist_foreach(items_list, data_visit_func, NULL); hwinfo_parser_destroy(hwinfo_ini_parser); dlist_destroy(items_list); return 0; } #endif // HWINFO_CONFIG_INI_PARSER_TEST
C
#include <stdio.h> #include <stdlib.h> long int power(long int x,long int m){ if(m!=1){ return x*power(x,(m-1)); } } int main(void){ int t,i; long int x,m,n,sum=0; scanf("%d",&t); while(t){ t--; scanf("%ld %ld %ld",&x,&m,&n); for(i=1; i<=m; i++){ sum += power(x,i); } sum++; sum = sum%n; printf("%ld\n",sum); } return 0; }
C
/* ================================================== Workshop #6 (Part-1): ================================================== Name :Justin Hoang ID :021569132 Email :jhoang11@myseneca.ca Section:NCC */ #define MAX_PRODUCT 3 #define SUGGESTED_SERVING 64 // ---------------------------------------------------------------------------- // structures struct CatFoodInfo { int sku; double productPrice; int caloriesPerServing; double productWeight; }; // ---------------------------------------------------------------------------- // function prototypes // 1. Get user input of int type and validate for a positive non-zero number // (return the number while also assigning it to the pointer argument) int getIntPositive(int* positiveInt); // 2. Get user input of double type and validate for a positive non-zero number // (return the number while also assigning it to the pointer argument) double getDoublePositive(double* positiveDouble); // 3. Opening Message (include the number of products that need entering) void openingMessage(void); // 4. Get user input for the details of cat food product // 5. Display the formatted table header void displayCatFoodHeader(void); // 6. Display a formatted record of cat food data // 7. Logic entry point
C
#include<stdio.h> #include<conio.h> void main(int argc, char const *argv[]) { char ch; printf("Enter any alphabet"); scanf(" %c",&ch); if (ch=='a' ||ch=='A' || ch=='e' ||ch=='E' || ch=='i' || ch=='I'|| ch=='o' ||ch=='O'|| ch=='u' ||ch=='U') { printf("%c is a vowel", ch); } else { printf("%c is a consonant",ch); /* code */ } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw_fractol.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: amelikia <amelikia@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/21 14:01:09 by amelikia #+# #+# */ /* Updated: 2019/06/21 14:02:29 by amelikia ### ########.fr */ /* */ /* ************************************************************************** */ #include "fractol.h" t_color define_color(int depth, t_fractol *fractol) { t_color color; if (fractol->psychedelic == 1) { color.blue = fractol->psychedelic_palette[depth % 10]->blue; color.green = fractol->psychedelic_palette[depth % 10]->green; color.red = fractol->psychedelic_palette[depth % 10]->red; } else { color.blue = fractol->palette->color->blue + (depth * 2.62); color.green = fractol->palette->color->green + (depth * 2.62); color.red = fractol->palette->color->red + (depth * 2.62); } return (color); } void draw_fractal(t_fractol *fractol, int FUNCTION) { t_point pixel; t_color color; int depth; int pos; pixel.y = 0; while (pixel.y < WIN_HEIGHT) { pixel.x = 0; while (pixel.x < WIN_WIDTH) { pixel.x += fractol->offset.x; pixel.y += fractol->offset.y; depth = define_fractal_pixel(pixel, fractol); pixel.x -= fractol->offset.x; pixel.y -= fractol->offset.y; pos = pixel.x * 4 + 4 * WIN_WIDTH * pixel.y; color = define_color(depth, fractol); fractol->image.data[pos] = color.blue; fractol->image.data[pos + 1] = color.green; fractol->image.data[pos + 2] = color.red; ++pixel.x; } ++pixel.y; } } void load_fractal(t_fractol *fractol) { if (fractol->type == 1) draw_fractal(fractol, mandelbrot); else if (fractol->type == 2) draw_fractal(fractol, julia); else if (fractol->type == 3) draw_fractal(fractol, newton); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> int locating(char * location){ int i, result=0; char station[50]; char *cmp[100] = {'\0'}; char p[20]={'\0',}; FILE *f; strcpy(station,location); /* printf("station : "); gets(station); */ strcat(station, "\n"); f=fopen("getsstation.txt","r"); for(i=0; i<96; i++) { fgets(p, sizeof(p), f); cmp[i] = (char*)malloc(strlen(p)+1); strcpy(cmp[i],p); } for(i=0; i<96; i++) if(strcmp(station, cmp[i])==0) result = 1; fclose(f); if(result==1) return 1; else return 0; }
C
#include<stdio.h> #include<string.h> void bubblesortstring(char arr[][100],int n) { char temp[20]; for(int i=0;i<n-1;i++) { for(int j=0;j<n-i-1;j++) { if(strcmp(arr[j],arr[j+1])>0) { strcpy(temp, arr[j+1]); strcpy(arr[j+1],arr[j]); strcpy(arr[j], temp); } } } } int main() { char arr[10][100]; int n; printf("Enter n : "); scanf("%d",&n); printf("\n"); printf("Enter strings: "); for(int i=0;i<=n;i++) { gets(arr[i]); printf("\n"); } bubblesortstring(arr,n+1); printf("Array after bubble sort is : \n"); for(int i=0;i<=n;i++) { puts(arr[i]); printf("\n"); } return(0); }
C
#include "../../../lv_examples.h" #if LV_USE_ARC /** * An `lv_task` to call periodically to set the angles of the arc * @param t */ static void arc_loader(lv_task_t * t) { static int16_t a = 270; a+=5; lv_arc_set_end_angle(t->user_data, a); if(a >= 270 + 360) { lv_task_del(t); return; } } /** * Create an arc which acts as a loader. */ void lv_ex_arc_2(void) { /*Create an Arc*/ lv_obj_t * arc = lv_arc_create(lv_scr_act(), NULL); lv_arc_set_bg_angles(arc, 0, 360); lv_arc_set_angles(arc, 270, 270); lv_obj_align(arc, NULL, LV_ALIGN_CENTER, 0, 0); /* Create an `lv_task` to update the arc. * Store the `arc` in the user data*/ lv_task_create(arc_loader, 20, LV_TASK_PRIO_LOWEST, arc); } #endif
C
#define _BSD_SOURCE #include <stdio.h> #include <stdlib.h> #include <err.h> #include <math.h> #include <limits.h> #include <unistd.h> #include <sys/syscall.h> #include <sys/types.h> #include <signal.h> #include "tools/vectors.h" #include "tools/color.h" #include "shapes/material.h" #include "ray/ray.h" #include "shapes/3Dshapes/cube.h" extern int coreNB; double min_dist_cube(double d1, double d2, int face, int nt, struct cube *c) { if (d1 < d2 || d2 < 0) return d1; else { c->inter[nt] = face; return d2; } } struct cube *new_cube(double x, double y, double z, double size) { struct cube *c = malloc(sizeof(struct cube)); c->pos = new_vector(x, y, z); c->size = size; c->c1 = new_vector(x + size / 2, y + size / 2, z - size / 2); c->c2 = new_vector(x + size / 2, y + size / 2, z + size / 2); c->c3 = new_vector(x + size / 2, y - size / 2, z + size / 2); c->c4 = new_vector(x + size / 2, y - size / 2, z - size / 2); c->c5 = new_vector(x - size / 2, y - size / 2, z - size / 2); c->c6 = new_vector(x - size / 2, y + size / 2, z - size / 2); c->c7 = new_vector(x - size / 2, y + size / 2, z + size / 2); c->c8 = new_vector(x - size / 2, y - size / 2, z + size / 2); c->inter = calloc(coreNB, sizeof(char)); return c; } double intersect_face(struct vector *c1, struct vector *c2, struct vector *c3, struct ray *r) { struct vector *u = vector_from_points(c1, c2); struct vector *v = vector_from_points(c1, c3); struct vector *w = new_vector(r->pos->x - c1->x, r->pos->y - c1->y, r->pos->z - c1->z); struct vector *tmp1 = cross_product(u, v); struct vector *tmp2 = cross_product(w, v); struct vector *tmp3 = cross_product(u, w); double a = dot_product(tmp2, r->dir) / dot_product(tmp1, r->dir); double b = dot_product(tmp3, r->dir) / dot_product(tmp1, r->dir); double result; if (a >= 0 && b >= 0 && a <= 1 && b <= 1) result = -(dot_product(tmp1, w) / dot_product(tmp1, r->dir)); else result = INT_MAX; free_vector(u); free_vector(v); free_vector(w); free_vector(tmp1); free_vector(tmp2); free_vector(tmp3); return result; } double intersect_cube(void *cube, struct ray *r, int i) { struct cube *c = (struct cube *)cube; double dist = INT_MAX; dist = min_dist_cube(dist, intersect_face(c->c1, c->c2, c->c4, r), 1, i, c); dist = min_dist_cube(dist, intersect_face(c->c6, c->c7, c->c5, r), 2, i, c); dist = min_dist_cube(dist, intersect_face(c->c1, c->c6, c->c2, r), 3, i, c); dist = min_dist_cube(dist, intersect_face(c->c2, c->c7, c->c3, r), 4, i, c); dist = min_dist_cube(dist, intersect_face(c->c3, c->c8, c->c4, r), 5, i, c); dist = min_dist_cube(dist, intersect_face(c->c4, c->c5, c->c1, r), 6, i, c); return dist; } struct vector *get_normal_face(struct vector *c1, struct vector *c2, struct vector *c3, struct vector *inter_pos) { if (inter_pos == NULL) return NULL; struct vector *u = vector_from_points(c1, c2); struct vector *v = vector_from_points(c1, c3); struct vector *w = cross_product(u, v); struct vector *x = add_vector(w, inter_pos); struct vector *wn = normal_vector(x); free_vector(u); free_vector(v); free_vector(w); free_vector(x); return wn; } struct vector *get_normal_cube(struct vector *inter_pos, void *cube, int i) { struct cube *c = (struct cube *)cube; struct vector *v; switch (c->inter[i]) { case 1: v = get_normal_face(c->c1, c->c2, c->c4, inter_pos); break; case 2: v = get_normal_face(c->c6, c->c7, c->c5, inter_pos); break; case 3: v = get_normal_face(c->c1, c->c6, c->c2, inter_pos); break; case 4: v = get_normal_face(c->c2, c->c7, c->c3, inter_pos); break; case 5: v = get_normal_face(c->c3, c->c8, c->c4, inter_pos); break; case 6: v = get_normal_face(c->c4, c->c5, c->c1, inter_pos); break; default: v = NULL; break; } c->inter[i] = 0; return v; } struct cube *read_cube(FILE *f, unsigned *line, struct material *m) { double x, y, z, s, r, g, b; if (fscanf(f, "%lg %lg %lg %lg %lg %lg %lg\n", &x, &y, &z, &s, &r, &g, &b) != 7) errx(3, "Error while parsing input file: line %u\n", *line); ++(*line); m->diffuse->r = r; m->diffuse->g = g; m->diffuse->b = b; read_material(f, line, m); return new_cube(x, y, z, s); } void free_cube(void *cube) { struct cube *c = (struct cube *)cube; free_vector(c->pos); free_vector(c->c1); free_vector(c->c2); free_vector(c->c3); free_vector(c->c4); free_vector(c->c5); free_vector(c->c6); free_vector(c->c7); free_vector(c->c8); free(c->inter); free(c); }
C
/** @file Main.c * Display light patterns on the leds. * @author Adrien RICCIARDI */ #include <system.h> //-------------------------------------------------------------------------------------------------- // Microcontroller configuration //-------------------------------------------------------------------------------------------------- #pragma DATA _CONFIG, _CPD_OFF & _CP_OFF & _BODEN_ON & _MCLRE_OFF & _PWRTE_ON & _WDT_OFF & _INTRC_OSC_NOCLKOUT // Disable EEPROM protection, disable code protection, enable brown-out detection, disable /MCLR pin to use GP3 as a GPIO, enable the power-up timer, disable the watchdog timer, select the internal oscillator and keep all pins as GPIOs // The clock frequency is needed by software delay functions #pragma CLOCK_FREQ 4000000 //-------------------------------------------------------------------------------------------------- // Private types //-------------------------------------------------------------------------------------------------- /** All available leds. */ typedef enum { LED_ID_1_RED, //!< Connected to GP0 pin. LED_ID_2_YELLOW, //!< Connected to GP1 pin. LED_ID_3_AMBER, //!< Connected to GP2 pin. LED_ID_4_GREEN, //!< Connected to GP4 pin. LED_ID_5_RED, //!< Connected to GP5 pin. LED_IDS_COUNT } TLedID; //-------------------------------------------------------------------------------------------------- // Private variables //-------------------------------------------------------------------------------------------------- /** A latch containing the expected GPIO state (could not directly read from GPIO register due to its read-modify-write working way). */ static unsigned char GPIOs_State = 0; //-------------------------------------------------------------------------------------------------- // Private functions //-------------------------------------------------------------------------------------------------- /** Turn a led on. * @param Led_ID The led to light. */ static void LedOn(unsigned char Led_ID) { // Adjust the led ID to use it as shift value if (Led_ID >= LED_ID_4_GREEN) Led_ID++; // Bypass unconnected GP3 pin // Turn led on GPIOs_State |= 1 << Led_ID; gpio = GPIOs_State; } /** Turn a led off. * @param Led_ID The led to turn off. */ static void LedOff(unsigned char Led_ID) { // Adjust the led ID to use it as shift value if (Led_ID >= LED_ID_4_GREEN) Led_ID++; // Bypass unconnected GP3 pin // Turn led off GPIOs_State &= ~(1 << Led_ID); gpio = GPIOs_State; } /** Turn all leds on. */ inline void LedAllOn(void) { GPIOs_State = 0x37; gpio = 0x37; } /** Turn all leds off. */ inline void LedAllOff(void) { GPIOs_State = 0; gpio = 0; } //-------------------------------------------------------------------------------------------------- // Entry point //-------------------------------------------------------------------------------------------------- void main(void) { unsigned char i; // Turn off all leds gpio = 0; // Set all pins as output trisio = 0; while (1) { // 1-2-3 LedOn(LED_ID_1_RED); LedOn(LED_ID_3_AMBER); LedOn(LED_ID_5_RED); delay_s(1); // 2-4 LedAllOff(); LedOn(LED_ID_2_YELLOW); LedOn(LED_ID_4_GREEN); delay_s(1); // 1 -> 2 -> 3 -> 4 -> 5 LedAllOff(); for (i = 0; i < LED_IDS_COUNT; i++) { LedOn(i); delay_s(1); LedOff(i); } // 4 -> 3 -> 2 -> 1 for (i = LED_IDS_COUNT - 2; i != 255; i--) { LedOn(i); delay_s(1); LedOff(i); } // All leds lighted LedAllOn(); delay_s(1); LedAllOff(); delay_s(1); // 5 -> 4 -> 3 -> 2 -> 1 for (i = LED_IDS_COUNT - 1; i != 255; i--) { LedOn(i); delay_s(1); LedOff(i); } // 2 -> 3 -> 4 -> 5 for (i = 1; i < LED_IDS_COUNT; i++) { LedOn(i); delay_s(1); LedOff(i); } // All leds lighted LedAllOn(); delay_s(1); LedAllOff(); delay_s(1); // 1 -> 1-2 -> 1-2-3 -> 1-2-3-4 -> 1-2-3-4-5 for (i = 0; i < LED_IDS_COUNT; i++) { LedOn(i); delay_s(1); } // 1-2-3-4-5 -> 1-2-3-4 -> 1-2-3 -> 1-2 -> 1 for (i = LED_IDS_COUNT - 1; i != 255; i--) { LedOff(i); delay_s(1); } // 5 -> 4-5 -> 3-4-5 -> 2-3-4-5 -> 1-2-3-4-5 for (i = LED_IDS_COUNT - 1; i != 255; i--) { LedOn(i); delay_s(1); } // 1-2-3-4-5 -> 2-3-4-5 -> 3-4-5 -> 4-5 -> 5 for (i = 0; i < LED_IDS_COUNT; i++) { LedOff(i); delay_s(1); } } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <conio.h> #include "../lib.h" void copy_element(HEAD* head) { if (head->first != NULL) { HEAD* new_head = NULL; new_head = malloc(sizeof(head)); new_head->count = 0; new_head->first = NULL; new_head->last = NULL; NODE* new_ptr = NULL; new_ptr = malloc(sizeof(NODE)); int n=1, count, i; int* num; char s1[10], n1[1000]; printf("\033[0d\033[2J"); output(head); printf("\nEntre the number of numbers to copy: "); fgets(s1, 100, stdin); count = atoi(s1); if (count <= head->count) { num = malloc(count * sizeof(int)); printf("Entre number elements:\n"); for (i = 0; i < count; i++) { scanf("%d", &num[i]); if (num[i] > head->count) n = 0; } if (n) { bubbleSort(num, count); for (i = 0; i < count; i++) { new_ptr = select_id(head, num[i]); add_last_node(new_head, new_ptr); } } if (n) { output(new_head); file_print(new_head); } else error(); } else error(); } else error(); }
C
// Implements a dictionary's functionality #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "dictionary.h" #define CHAR_TO_INDEX(c) ((int)c - (int)'a') // Represents number of children for each node in a trie #define N 27 // const int CASE = 'a'; // Represents a node in a trie typedef struct trieNode { bool is_word; struct trieNode *children[N]; // struct node* next is single list, struct node* children is the way to do the same thing for the trie int value; struct trieNode *next; int occurrences; // probably will be misspellings later } trieNode; // Represents a trie ******* is this needed trieNode *root; // trieNode *nav // trieNode *parent = NULL; int occurrences = 0; // probably will be misspellings later // Loads dictionary into memory, returning true if successful else false bool load(const char *dictionary) { // Initialize trie root = malloc(sizeof(trieNode)); // assign a traveller to the root trieNode *trav = root; if (root == NULL) { return false; } // set the is_word boolean to false for all the childern of the node root->is_word = false; // create 27 children pointers of [N] for (int i = 0; i < N; i++) { // all set to NULL root->children[i] = NULL; } // Open dictionary FILE *file = fopen(dictionary, "r"); // printf("dictionary is here\n"); if (file == NULL) { unload(); return false; } printf("\nfile %s\n", dictionary); // Buffer for a word // // this is where the words are held char word[LENGTH + 1]; // Insert words into trie // for each word in dictionary iterate through the trie while (fscanf(file, "%s", word) != EOF) // while the dictionary has words in it get words { printf("\nthe word is %s\n\n", word); // printf("get a letter from the word %s\n", word); // TODO int letterPosition; int wordLength = strlen(word); int alphaPointer = 0; // create a variable to create new nodes called newNode // trieNode *navig = root; // trieNode* newNode = (trieNode*)malloc(sizeof(trieNode)); // for the first node in the trie, // for each letter in the word trieNode *newNode = malloc(sizeof(trieNode)); // malloc a new trieNode for (int i = 0; i < N; i++) // put in 27 pointers and s { // all set to NULL newNode->children[i] = NULL; } // set all 27 pointers to null // iterate through the letters in the word for (letterPosition = 0; letterPosition < wordLength; letterPosition++) { ////////// // set the ascii value of the letters to index at 0 alphaPointer = (word[letterPosition] - 'a'); printf("alphaPointer %d\n", alphaPointer); printf("the letter is %c\n", word[letterPosition]); printf("the ascii value is %d\n", (word[letterPosition] - 'a')); printf("letterPosition index is %d\n", (letterPosition)); // at the end of a word we need to go to the next word in the dictionary // if no node exists at this location if (newNode->children[alphaPointer] == NULL) { // struct trieNode* currentNode; // struct trieNode currentNode; // trieNode *currentNode = malloc(sizeof(trieNode)); // malloc a new trieNode for (int i = 0; i < N; i++) // put in 27 pointers and s { // all set to NULL currentNode->children[i] = NULL; // currentNode->children[i]->value = alphaPointer; printf("the value of alphapointer is %d\n", alphaPointer); } // set all 27 pointers to null // // put the value of the letter position into the node printf("!!! new trie node made her !!!\n"); // tell the node to load at the pointerIndex location trav = newNode->children[alphaPointer]; // print statement shows that the loop iterates through the different letters of the dictionary printf("alphaPointer value is %i\n\n", alphaPointer); // printf("trav is %c", trav->children[alphaPointer]); // NEED TO PUT THE CHARACTER INTO THE NEWNODE OF THE TRIE // THEN CYCLE BACK UP TO ROOT TO START FOLLOWING THE TRIE AGAIN recursively continue; // while (newNode->children[alphaPointer] != NULL) { printf("moving to next letter"); continue; // newNode = trav->children[letterPosition]; // trav->children[pointerIndex] = newNode; // trav = trav->children[index]; } trav->is_word = true; printf("is_word is true"); // mark word as true // newNode->is_word = true; // trav = trav->children[pointerIndex]; // Have children[i] point to it } // } } // printf("\nContents of a structure %s are:\trieNode: %d\nis_word: %d\n", trieNode->name, trieNode->, trieNode->is_word); // for every word in the dictionary // for each letter in the word // if (the node alpha pointer points to NULL) // malloc a new trieNode // Have children[i] point to it // // // Inserting a key into Trie is a simple approach. // Every character of the input key is inserted as an individual Trie node. // Note that the children is an array of pointers (or references) to next level trie nodes. // The key character acts as an index into the array children. // If the input key is new or an extension of the existing key, we need to construct non-existing nodes of the key, and mark end of the word for the last node. // If the input key is a prefix of the existing key in Trie, we simply mark the last node of the key as the end of a word. // The key length determines Trie depth. // } // Close dictionary fclose(file); // Indicate success return true; } // Returns number of words in dictionary if loaded else 0 if not yet loaded unsigned int size(void) { // TODO return 0; } // Returns true if word is in dictionary else false bool check(const char *word) { // check should return true for words in the dictionary // TODO // Searching for a key is similar to insert operation, // we only compare the characters and move down. // search can terminate due to the end of a string if the isEndofWord field of the last node is true, then the key exists in the trie. // // search can terminate due to lack of key in the trie, the search terminates without examining all the characters of the key, since the key is not present in the trie. return false; } // Unloads dictionary from memory, returning true if successful else false bool unload(void) { // TODO return false; }
C
/* getfloat.c - parse float array */ #include <ctype.h> #include <stdio.h> int getch(void); void ungetch(int c); int getfloat(double *pn) { int c, sign; int power; while (isspace(c = getch())) /* skip white space */ ; if (!isdigit(c) && c != EOF && c != '+' && c != '-') { ungetch(c); return 0; } sign = (c == '-') ? -1 : 1; if (c == '-' || c == '+') c = getch(); if (!isdigit(c)) { ungetch(c); return 0; } for (*pn = 0; isdigit(c); c = getch()) *pn = 10 * *pn + (c - '0'); if (c != '.') { goto getfloat_ret; } c = getch(); for (power = 1.0; isdigit(c); c = getch()) { *pn = 10 * *pn + (c - '0'); power *= 10.0; } *pn /= power; getfloat_ret: *pn *= sign; if (c != EOF) ungetch(c); return c; } main() { int r; double n; while ((r = getfloat(&n)) != EOF && r > 0) printf("%f\t", n); }
C
/* * This program explores and discusses arrays and strings :) * written by Helena Kertesz * 06/04/2016 * compile with gcc-o arrays arrays.c (it's bad but it means it should complile on both you home computer and on cse) * There are questions for you to answer next to some lines in the code to test your knowledge (some are quite tricky). Answers are down the bottom. * Don't worry about the BLUE, RED and RESET - I'm just doing it to make the printout pretty, it's not from this course. * * Try and answer all the questions before looking at the answers (compile and run the program for help). * Bonus challenge: try and answer all/most of the questions without compiling and running the program. */ #include<stdio.h> #include<string.h> //you don't need to worry about these #define or when I have BLUE, RED and RESET in printf's //(unless you want to learn how to colour your outputs - in which case feel free to send me an email / look it up online) #define BLUE "\x1b[34m" #define RED "\x1b[31m" #define RESET "\x1b[0m" void printIntArray(int array[], int size); void catsCatsCats (int array[]); void printString(char * string); void badPrint(char * string); int main(){ int a[10] = {0}; //initialise an array "a" containing 10 integers and set everything to 0. printf(BLUE "\nint a[10] = {0};\n" RESET); printf("a[0] is %d\n", a[0]); //Q1: what value will this be and why? printf("a[10] is %d\n", a[10]); //Q2: what value will this be and why? (try running the program a few times and see if it's the same each time) int b[10]; //create array "b" containing 10 integers. Values are uninitialised. printf(BLUE "\nint b[10] (note: values uninitialied)\n" RESET); printf("b[0] is %d\n", b[0]); // Q3: what value will this be and why? printf("b = %p, &b[0] %p\n", b, &b[0]); // Q4: a) what is being printed, b) will the two values be the same? printf("sizeof(b[0]) = %lu\n", sizeof(b[0])); // Q5: What will this print? (ie. what is the size of each element in the array?) printf("&b[1] = %p, &b[2 = %p, &b[3] = %p\n", &b[1], &b[2], &b[3]); //Q6: a) what will the spacing between these pointers be? (clue: this carries on from the previous question). // b) What does this tell you about how an array is stored in memory? int c[5] = {4 ,8 ,2 ,6 ,0 }; //initialise an array with 5 integers. printf(BLUE "\nint c[5] = {4 ,8 ,2 ,6 ,0 }\n" RESET); int size = sizeof(c)/sizeof(c[0]); // Q7: What is being calculated here? Why am I dividing by sizeof(c[0])? printf("size = %d\n", size); printf("printing the array using printIntArray\n"); printIntArray( c , size ); // Q8: What am I passing to this function? catsCatsCats( c ); // Q9: What am I passing to this function? Why is this a bad idea? (Q10 is next to the function) printf( BLUE "\nLETS PLAY WITH STRINGS!!\n" RESET ); // a string is simply an array of characters, but there are a few equivalent ways of playing with them. printf("\n\\0 = %d and EOF = %d\n\n", '\0', EOF); // Q11: What values will these print? What are these used for? char foo[] = {'c', 'a', 't', 's', '\0'}; //Initialise an array of characters "foo" and set the first five elements. Note I set no size of the array. printf(BLUE "char foo[] = {'c', 'a', 't', 's', '\\0'};\n" RESET ); printf("foo[3] = %c\n", foo[3]); // Q12: What will this print? (remembering that the first element is foo[0] not foo[1])? printf("foo[4] = char '%c' = int '%d'\n", foo[4], foo[4]); // Q13: What will this print? What are the purposes of these characters? printf("printing out foo as a string gives: %s\n", foo); // Q14: What will this print? (note the %s format specifier) Think about how the printout knows when to stop. printString(foo); // Have a look at this function. It shows how printing a string works. // Think about why I can get away with not giving it the size of the array (as I had to do with the int arrays). char * bar = "cats"; printf( BLUE "\nchar * bar = \"cats\"\n" RESET ); // FUN FACT: to print out the " you must put a \ before it (the same thing goes for printing out \ on line 57) printf("printing bar as a string gives: %s\n", bar); printString(bar); printf("bar[4] = %d\n", bar[4]); //Q15: What will this print? Why? printf("strcmp(foo, bar) returns %d\n", strcmp(foo, bar)); //Q16: What will this return and why (use "man strcmp" if unsure)? // I've made all the print out from badPrint red to help you see it. // Q17: What one mistake in this function makes the printout so funky? // hint: compare it with printString. // Q18: EXTENSION (which means I'll only give you the answer if you email me - try and figure it out on your own). // Why does badPrint behave differently for foo and bar? // hint: google where strings are stored when they are given something in quotation marks (ie "cats") which can't be changed. Try to change some character bar[n] and foo[n]. printf("\nprinting bar using badPrint\n"); badPrint(bar); printf("\n"); // Only uncomment the next three lines if you want to do Q18 EXTENTION or just try it out. Run it serval times to see if it changes. This may cause a seg fault (or may not). // printf("\nprinting foo using badPrint (must uncomment)\n"); // badPrint(foo); // printf("\n"); return 0; } //this function prints out an array given a pointer to it and the size of the array. Make sure it makes sense to you. void printIntArray( int array[], int size){ int i = 0; while(i <= size - 1){ printf("array[%d] is %d\n", i, array[i]); i++; } } //This function takes an array and changes the 3rd element to 3, the 5th element to 5 and the 7th element to 7. void catsCatsCats(int array[]){ array[2] = 3; array[4] = 5; array[6] = 7; // Q10: Why is this potentialy REALLY bad? How would you change this function to fix this? } //This function prints an array of characters. void printString(char * string){ int n = 0; while(string[n] != '\0'){ printf("'%c' ", string[n]); n++; } printf("\n"); } void badPrint(char * string){ int n = 0; while(string[n] != EOF){ printf( RED "%c" RESET, string[n]); //ignore RED and RESET (I'm just making the printout red for you to see) n++; } } /*ANSWERS * 1. will be zero because each value in the array is initialied to zero. * * 2. Will be junk (whatever was at the memory address set aside for this array). This is because a[10] is NOT an element of the initialied array. * The 10 elements are a[0], a[1], a[2], a[3]... a[9]. Thus, the last element of an array delcared as a[n] (n elements) will be a[n-1], because we start from a[0]. * * 3. This depends on your version of gcc. Newer versions (such as on the cse machines) will automatically set all elements to zero, so this will print out zero. * However, older version will print junk, since the values in the array were not initialised. * The junk will be whatever was already in the section of memory that was set aside for this array. * * 4. a) a pointer the the first element in the array b) yes. b is a pointer the the first element (the name of an array on its own always is) and &b[0] finds the integer * (since this is an integer array) stored at the first element in the array and then uses & to find out where this int is stored * - again giving the memory adress of the first element of the array * * 5. Each element of this particular array is an integer. Therefore sizeof( b[n] ) = sizeof( int ) = 4 or 8 depending on your system. * * 6. a) Each pointer is 4 bytes after the one before. This is becaus the size of an int is 4 bytes and this is an array of integers. * b) elements of an array are stored sequentially in memory (this means you can traverse arrays using pointer arithmatic - NOT something you need in * this course but fun to know) * * 7. This calculates the number of items in the array. (take the amount of memory set aside for the array (size of array) and divide it by the size of each element). * * 8. Passing a pointer to an array and the number of elements in the array. * * 9. By only passing the pointer to the array the function could try and use elements that don't exist. This is called overflow, and can be used to overwrite different * points in memory - which is a security risk!!! Never write a function that gets passed an array without specifying its size. * * 10. This is an example of overflow. The array passed to this function only has five elements but the function doesn't know this, and calls array[6] * , overwriting a point in memory somewhere after the array. In this case it shouldn't do anything horrible, but this can be exploited. To fix this, always pass the * size of an array along with the pointer to an array, such as for the printIntArray function. * * 11. EOF will print -1. This character is used to declare the end of a file (hence EOF). \0 will return 0. It is used to declar the end of a string. * * 12. This will print 's' - the 4th element in the array. * * 13. This will print char '' and int '0'. This is because foo[4] is '\0'. * * 14. This will print "cats". when you use %s it will stop when it gets to '\0' * * 15. This will print 0. When you initialise a string using a word in quotation maarks (ie "cats") it automatically adds a '\0' to the end. * Thus bar[4] (one past the last element in the string) is '\0', which prints to integer 0. * * 16. This will return 0, telling you that foo and bar are the same. * Thus the delcalarations char foo[] = {'c','a','t','s','\0'} and char * bar = "cats" are equivalent and produce identical strings. * (although those who have a look at Q18 will see that there are some differences) * * 17. The function runs while string[n] != EOF -> if should be while string[n] != '\0' because '\0' is what marks the end of a string. * Thus it will overflow and print whatever is the memory after where te string is stored until it comes across an EOF. * In this case it prints the text in the printf's from this program (which is pretty cool). */
C
#include <stdio.h> #include <stdlib.h> #include<string.h> #include<math.h> int main() { int cont,temp; double vetor[100]; for(cont=0;cont<100;cont++) scanf("%lf",&vetor[cont]); for (cont=0;cont<100;cont++) if (vetor[cont]<=10.0){ temp = vetor[cont]; if ((vetor[cont]-temp)!=0) printf("A[%d] = %.1lf\n",cont,vetor[cont]); else printf("A[%d] = %.0lf\n",cont,vetor[cont]); } return 0; }
C
#include <stdio.h> int main() { char s1[100],s2[100]; int i,c1=0,c2=0; printf("Enter the string1 \n"); scanf("%[^\n]s",s1); printf("Enter string 2 \n"); scanf("%[^\n]s",s2); for(i=0;s1[i]!='\0';i++) { c1=c1+1; } for(i=0;s2[i]!='\0';i++) { c2=c2+1; } if(c1>c2) { printf("%s",s1); } else if(c1==c2) { printf("%s",s2); } else { printf("%s",s2); } return 0; }
C
/* 网新恒天2014校园招聘 * Sep 06, 2013 * * Problem Description: * 已知memcpy的函数为: void* memcpy(void *dst , const void* src , size_t n) * 其中dst是目的指针,src是源指针。不调用c++/c的memcpy库函数,请编写memcpy。 * */ #include <assert.h> void *memcpy(void *dst, const void *src, size_t n) { /* special cases */ if(n == 0 || dst == src) return dst; unsigned char * pdst = (unsigned char *)dst; const unsigned char * psrc = (const unsigned char *)src; /* sanity check */ assert(pdst != NULL && psrc != NULL); /* to avoid memory overlap */ assert(!(psrc <= pdst && pdst < psrc + n)); assert(!(pdst <= psrc && psrc < pdst + n)); while(n--) *pdst++ = *psrc++; return dst; }
C
#include "HC_SR.h" #include "sys.h" #include "includes.h" uint32_t US_Count = 0; //ÿһζʱжUS_Countһ void US_AddCount() { US_Count++; } uint32_t US_GetCount() { return US_Count; } void US_ClearCount() { US_Count=0; } void HC_SR_Configuration(void) { GPIO_InitTypeDef GPIO; NVIC_InitTypeDef MyNVIC; EXTI_InitTypeDef MyEXTI; //Enable APB2 Bus RCC_APB2PeriphClockCmd(Trig_CLKLine | Echo_CLKLine, ENABLE); //Register IO GPIO.GPIO_Pin = Trig_Pin; GPIO.GPIO_Speed = GPIO_Speed_50MHz; GPIO.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(Trig_Port, &GPIO); Trig = 0; //Register IO GPIO.GPIO_Pin = Echo_Pin; GPIO.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(Echo_Port, &GPIO); NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); MyNVIC.NVIC_IRQChannel = EXTI3_IRQn; MyNVIC.NVIC_IRQChannelPreemptionPriority = 0; MyNVIC.NVIC_IRQChannelSubPriority = 1; MyNVIC.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&MyNVIC); GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource3); MyEXTI.EXTI_Line = EXTI_Line3; MyEXTI.EXTI_Trigger = EXTI_Trigger_Rising; MyEXTI.EXTI_Mode = EXTI_Mode_Interrupt; MyEXTI.EXTI_LineCmd = ENABLE; EXTI_Init(&MyEXTI); } void US_SendStartSignal(void) { Trig = 1; delay_us(20); Trig = 0; } float US_DataConversion(uint32_t count) { float result = 0; result = (float)((float)(count * 340) / 2000.0); return result; } void EXTI3_IRQHandler(void) { float Distance; if (EXTI_GetITStatus(EXTI_Line3) != RESET) { // OS_CPU_SR cpu_sr=0; // OS_ENTER_CRITICAL(); // TIM_SetCounter(TIM4,0); // while(Echo==1); // Distance=(float)((float)TIM_GetCounter(TIM4)*340)/200.0; // OS_EXIT_CRITICAL(); // if(Distance>0) // { // printf("Distance:%d %f cm\r\n",TIM_GetCounter(TIM4),Distance); // } EXTI_ClearITPendingBit(EXTI_Line3); } }
C
#ifndef STACK_LIST_H #define STACK_LIST_H struct Node; typedef struct Node *PtrNode;//声明了一个名为PtrNode的类型,该类型是指向结构体Node的指针 typedef PtrNode Stack; int IsEmpty(Stack S); Stack CreateStack(void); void MakeEmpty(Stack S); void Push(int x, Stack S); void pop(Stack S); int Top(Stack S); #endif
C
#include "libprintf.h" int ft_printf(char *format, ...) { va_list arg; unsigned int i; i = 0; va_start(arg, format); while(*format) { if(*format == '%') i += ft_lookup(arg, *++format); else i += ft_putchar(*format); format++; } va_end(arg); return(i); } int ft_lookup(va_list arg, char c) { int i; int n; i = 0; switch (c) { case 's': return (ft_puts(va_arg(arg, char *))); case 'c': return (ft_putchar(va_arg(arg, int))); case 'i': case 'd': n = va_arg(arg, int); i = n > 0 ? 0 : ft_putchar('-'); return (ft_printitoa((t_ul)(n > 0 ? n : -n), 10) + i); case 'p': return (ft_putptr((t_ul)va_arg(arg, void *))); case 'o': return (ft_printitoa((t_ul)va_arg(arg, unsigned int), 8)); case 'u': return (ft_printitoa((t_ul)va_arg(arg, unsigned int), 10)); case 'x': return (ft_printitoa((t_ul)va_arg(arg, unsigned int), 16)); case '%': return (ft_putchar('%')); } return 0; }
C
/* -- PCF Operating System -- * See [docs\COPYRIGHT.txt] for more info */ /** @file include\system\kernel\x86\paging.h @brief PCF paging */ #ifndef INCLUDE_SYSTEM_KERNEL_X86_PAGING_H #define INCLUDE_SYSTEM_KERNEL_X86_PAGING_H #include <kernel\x86\irq.h> /** @brief Bit position. Used in the bitset algorithms */ #define INDEX_FROM_BIT(a) (a/(8*4)) /** @brief Bit offset. Used in the bitset algorithms */ #define OFFSET_FROM_BIT(a) (a%(8*4)) /** @brief 4 KB Page struct. Contains Page info */ typedef struct _x86PageStruct { /** @brief Page present in memory. If this is not set writing or reading to this page will cause a Page Fault */ unsigned int present:1; /** @brief Read-only if clear, readwrite if set */ unsigned int rw:1; /** @brief Supervisor level only if clear */ unsigned int user:1; /** @brief Has the page been accessed since last refresh ? */ unsigned int accessed:1; /** @brief Has the page been written since last refresh ? */ unsigned int dirty:1; /** @brief Amalgamation of unused and reserved bits */ unsigned int unused:7; /** @brief Frame address (shifted right 12 bits) */ unsigned int frame:20; } x86PageStruct; /** @brief Page Table struct. Each page table contains 1024 pages (4 MB)*/ typedef struct x86PageTableStruct { /** @brief 1024 page, 4KB each = 4MB */ x86PageStruct pages[1024]; } x86PageTableStruct; /** @brief Page Directory struct. Each PD contains 1024 Page Tables (4 GB) */ typedef struct x86PageDirectoryStruct { /** @brief Pointer to page tables */ x86PageTableStruct *PageTables[1024]; /** @brief Physical address to page tables */ unsigned int PageTablesPhysical[1024]; /** @brief Physical address of PageTablesPhysical */ unsigned int PhysicalAddr; } x86PageDirectoryStruct; /** @fn void x86PagingAllocFrame(x86PageStruct *Page, int Kernel, int WriteAble) @brief Sets the Page as used @ingroup sys_kernel_arch_x86 @param Page Page @param Kernel Is this a kernel page ? ( ReadAble from user if = 0 ) @param WriteAble Is this write able from user ? */ void x86PagingAllocFrame(x86PageStruct *Page, int Kernel, int WriteAble); /** @fn void x86PagingFreeFrame(x86PageStruct *Page) @brief Sets the Page free @ingroup sys_kernel_arch_x86 @param Page Page */ void x86PagingFreeFrame(x86PageStruct *Page); /** @fn void x86PagingInit(unsigned int MemoryToMap) @brief Init paging. Map MemoryToMap bytes @ingroup sys_kernel_arch_x86 @param MemoryToMap Bytes to map */ void x86PagingInit(unsigned int MemoryToMap); /** @fn void x86SwitchPageDirectory(x86PageDirectoryStruct *new) @brief Switch to Page Directory new @ingroup sys_kernel_arch_x86 @param new PD to switch */ void x86SwitchPageDirectory(x86PageDirectoryStruct *new); /** @fn x86PageStruct *x86PagingGetPage(unsigned int Address, int Make, x86PageDirectoryStruct *Dir) @brief Return page in which addreess Adress is. @ingroup sys_kernel_arch_x86 @param Address This address is inside the page returned @param Make Make this page if it is not present @param Dir Page Directory to search in @return Page */ x86PageStruct *x86PagingGetPage(unsigned int Address, int Make, x86PageDirectoryStruct *Dir); /** @fn x86PageDirectoryStruct *x86ClonePageDirectory(x86PageDirectoryStruct *src) @brief Clones a page directory @ingroup sys_kernel_arch_x86 @param src Original PD @return New PD (clone) */ x86PageDirectoryStruct *x86ClonePageDirectory(x86PageDirectoryStruct *src); /** @fn void x86PageFaultHandler(x86RegistersStruct *regs) @brief Page fault handler. Clears faulting address and calls debug shell @ingroup sys_kernel_arch_x86 @param regs CPU registers */ void x86PageFaultHandler(x86RegistersStruct *regs); #endif
C
/* * libgit2 "checkout" example - shows how to perform checkouts * * Written by the libgit2 contributors * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along * with this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "common.h" #include <assert.h> /* Define the printf format specifer to use for size_t output */ #if defined(_MSC_VER) || defined(__MINGW32__) # define PRIuZ "Iu" # define PRIxZ "Ix" # define PRIdZ "Id" #else # define PRIuZ "zu" # define PRIxZ "zx" # define PRIdZ "zd" #endif /** * The following example demonstrates how to do checkouts with libgit2. * * Recognized options are : * --force: force the checkout to happen. * --[no-]progress: show checkout progress, on by default. * --perf: show performance data. */ typedef struct { int force : 1; int progress : 1; int perf : 1; } checkout_options; static void print_usage(void) { fprintf(stderr, "usage: checkout [options] <branch>\n" "Options are :\n" " --git-dir: use the following git repository.\n" " --force: force the checkout.\n" " --[no-]progress: show checkout progress.\n" " --perf: show performance data.\n"); exit(1); } static void parse_options(const char **repo_path, checkout_options *opts, struct args_info *args) { if (args->argc <= 1) print_usage(); memset(opts, 0, sizeof(*opts)); /* Default values */ opts->progress = 1; for (args->pos = 1; args->pos < args->argc; ++args->pos) { const char *curr = args->argv[args->pos]; int bool_arg; if (strcmp(curr, "--") == 0) { break; } else if (!strcmp(curr, "--force")) { opts->force = 1; } else if (match_bool_arg(&bool_arg, args, "--progress")) { opts->progress = bool_arg; } else if (match_bool_arg(&bool_arg, args, "--perf")) { opts->perf = bool_arg; } else if (match_str_arg(repo_path, args, "--git-dir")) { continue; } else { break; } } } /** * This function is called to report progression, ie. it's called once with * a NULL path and the number of total steps, then for each subsequent path, * the current completed_step value. */ static void print_checkout_progress(const char *path, size_t completed_steps, size_t total_steps, void *payload) { (void)payload; if (path == NULL) { printf("checkout started: %" PRIuZ " steps\n", total_steps); } else { printf("checkout: %s %" PRIuZ "/%" PRIuZ "\n", path, completed_steps, total_steps); } } /** * This function is called when the checkout completes, and is used to report the * number of syscalls performed. */ static void print_perf_data(const git_checkout_perfdata *perfdata, void *payload) { (void)payload; printf("perf: stat: %" PRIuZ " mkdir: %" PRIuZ " chmod: %" PRIuZ "\n", perfdata->stat_calls, perfdata->mkdir_calls, perfdata->chmod_calls); } /** * This is the main "checkout <branch>" function, responsible for performing * a branch-based checkout. */ static int perform_checkout_ref(git_repository *repo, git_annotated_commit *target, checkout_options *opts) { git_checkout_options checkout_opts = GIT_CHECKOUT_OPTIONS_INIT; git_commit *target_commit = NULL; int err; /** Setup our checkout options from the parsed options */ checkout_opts.checkout_strategy = GIT_CHECKOUT_SAFE; if (opts->force) checkout_opts.checkout_strategy = GIT_CHECKOUT_FORCE; if (opts->progress) checkout_opts.progress_cb = print_checkout_progress; if (opts->perf) checkout_opts.perfdata_cb = print_perf_data; /** Grab the commit we're interested to move to */ err = git_commit_lookup(&target_commit, repo, git_annotated_commit_id(target)); if (err != 0) { fprintf(stderr, "failed to lookup commit: %s\n", git_error_last()->message); goto cleanup; } /** * Perform the checkout so the workdir corresponds to what target_commit * contains. * * Note that it's okay to pass a git_commit here, because it will be * peeled to a tree. */ err = git_checkout_tree(repo, (const git_object *)target_commit, &checkout_opts); if (err != 0) { fprintf(stderr, "failed to checkout tree: %s\n", git_error_last()->message); goto cleanup; } /** * Now that the checkout has completed, we have to update HEAD. * * Depending on the "origin" of target (ie. it's an OID or a branch name), * we might need to detach HEAD. */ if (git_annotated_commit_ref(target)) { err = git_repository_set_head(repo, git_annotated_commit_ref(target)); } else { err = git_repository_set_head_detached_from_annotated(repo, target); } if (err != 0) { fprintf(stderr, "failed to update HEAD reference: %s\n", git_error_last()->message); goto cleanup; } cleanup: git_commit_free(target_commit); return err; } /** That example's entry point */ int main(int argc, char **argv) { git_repository *repo = NULL; struct args_info args = ARGS_INFO_INIT; checkout_options opts; git_repository_state_t state; git_annotated_commit *checkout_target = NULL; int err = 0; const char *path = "."; /** Parse our command line options */ parse_options(&path, &opts, &args); /** Initialize the library */ err = git_libgit2_init(); if (!err) check_lg2(err, "Failed to initialize libgit2", NULL); /** Open the repository corresponding to the options */ check_lg2(git_repository_open_ext(&repo, path, 0, NULL), "Could not open repository", NULL); /** Make sure we're not about to checkout while something else is going on */ state = git_repository_state(repo); if (state != GIT_REPOSITORY_STATE_NONE) { fprintf(stderr, "repository is in unexpected state %d\n", state); goto cleanup; } if (args.pos >= args.argc) { fprintf(stderr, "unhandled\n"); err = -1; goto cleanup; } else if (strcmp("--", args.argv[args.pos])) { /** * Try to checkout the given path */ fprintf(stderr, "unhandled path-based checkout\n"); err = 1; goto cleanup; } else { /** * Try to resolve a "refish" argument to a target libgit2 can use */ err = resolve_refish(&checkout_target, repo, args.argv[args.pos]); if (err != 0) { fprintf(stderr, "failed to resolve %s: %s\n", args.argv[args.pos], git_error_last()->message); goto cleanup; } err = perform_checkout_ref(repo, checkout_target, &opts); } cleanup: git_annotated_commit_free(checkout_target); git_repository_free(repo); git_libgit2_shutdown(); return err; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <stdbool.h> #include <string.h> #ifndef FUNCTIONS_H_INCLUDED #define FUNCTIONS_H_INCLUDED enum blocks { Energy = 1, Mitosis, Forbidden, Normal }; typedef struct cell{ char name[11]; char owner; int x; int y; int cell_energy; bool cell_moved; int num; struct cell*next; }cell; typedef struct block{ int x,y; int type; int block_energy; cell* mycell; }block; typedef struct game_data{ bool single_player; bool load; char last_team; }game_data; char *rand_string(size_t size) { char *str = (char*)malloc((size + 1) * sizeof(char)); const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; for (size_t i = 0; i < size; i++) { int key = rand() % (sizeof(charset) / sizeof(char) - 1); str[i] = charset[key]; } str[size] = '\0'; return str; } int show_menu(void){ int q; printf("[1]Load\n[2]New single player game\n[3]New Multiplayer game\n[4]Exit\n"); scanf("%d",&q); return q; } int show_menu2(void){ printf("[1] Move\n[2] Split cell\n[3] Boost energy\n[4] Save\n[5] Exit\n"); int q; scanf("%d",&q); return q; } int show_menu_moves(void){ printf("[1]North\n[2]South\n[3]NorthEast\n[4]NorthWest\n[5]SouthEast\n[6]SouthWest\n"); int q; scanf("%d" , &q); return q; } void print_cell(cell*head , int n,bool mp){ cell* current=head; int i = 1; while(current!=NULL){ if(mp && current->cell_moved == true) { current->num = 0; current=current->next; continue; } printf("%d: %s (%d,%d) with %d energy. \n",i,current->name,current->y, n-1-current->x,current->cell_energy); current->num = i; current=current->next; i++; } } char check_turn(char team,cell*head){ cell*current=head; for(current;current!=NULL;current=current->next) if(current->cell_moved==false)return team; current=head; for(current;current!=NULL;current=current->next){ current->cell_moved = current->owner == team?true:false; } if(team == 'X')return 'Y'; else return 'X'; } #endif
C
/** * recover.c * * Computer Science 50 * Problem Set 4 * * Recovers JPEGs from a forensic image. */ #include <stdint.h> #include <stdio.h> // prototype void safe_close(FILE* file); int main(int argc, char* argv[]) { // forensic image filename static const char * filename = "card.raw"; // open forensic image FILE* file = fopen(filename, "r"); if (file == NULL) { printf("Could not open %s.\n", filename); return 1; } // block size static const int blockSize = 512; uint8_t block[blockSize]; FILE* outfile = NULL; int curFile = 0; // read the file block by block for (size_t bytesRead = 0; (bytesRead = fread(block, sizeof(*block), blockSize, file)) == blockSize; ) { // check for JPEG signature if (((block[0] == 0xff) && (block[1] == 0xd8) && (block[2] == 0xff)) && ((block[3] == 0xe0) || (block[3] == 0xe1))) { // close current outfile, if open safe_close(outfile); // start writing new file char filename[4]; sprintf(filename, "%03i.jpg", curFile++); outfile = fopen(filename, "wb"); } // write block to outfile, if open if (outfile != NULL) { fwrite(block, sizeof(*block), blockSize, outfile); } } // close outfile, if open safe_close(outfile); // close forensic image fclose(file); } // closes file pointer if not null void safe_close(FILE* file) { if (file != NULL) { fclose(file); } }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct _S_ITEM{ char m_szName[32]; int m_nType; int m_nValue; }_S_ITEM; _S_ITEM item_list[]={ {"short sword",0,10}, {"wood shield",0,5}, {"dagger",0,6}, {"sling",0,3}, {"staff",0,7} }; unsigned long getHashCode(const char *szStr) { int nLength=strlen(szStr); int nHash=5381; for(int i=0;i<nLength;i++){ //printf("%d\r\n",szStr[i]); //nHash+=szStr[i]; int c=szStr[i]; nHash=((nHash<<5)+nHash)+c; } return nHash; } _S_ITEM *finditem(const char *szName) { int item_list_lenght=sizeof(item_list)/sizeof(_S_ITEM); for(int i=0;i<item_list_lenght;i++){ _S_ITEM *pitem=&(item_list[i]); if(strcmp(szName,pitem->m_szName)==0){ return pitem; } } } int main() { printf("%d\r\n",getHashCode("staff")); printf("%d\r\n",getHashCode("stafp")); //_S_ITEM *pItem=finditem("staff"); //printf("%s %d\r\n",pItem->m_szName,pItem->m_nValue); /*printf("%d %d\r\n",getHashCode("staff"),getHashCode("step")); if(getHashCode("staff")==getHashCode("step")){ puts("같은문장입니다.\r\n"); } else{ puts("다른문장입니다.\r\n"); }*/ return 0; }
C
/*Program 4 :- WAP to print a given Number but without last digit.*/ #include<stdio.h> int main() { int a,x; printf("Enter Value of A:\n"); scanf("%d",&a); x=a/10; printf("Given Number is without last Digit:-\n"); printf("%d\n",x); }
C
// // Created by student on 11.02.2020. // #include <fcntl.h> #include "log_maker.h" int _log_maker_desc=-1; int create_log(char* name) { char path[256]; sprintf(path,"logs/name.%i",getpid()); _log_maker_desc = open(path,O_CREAT|O_TRUNC|O_WRONLY,0666); return _log_maker_desc; } int print_time(char end) { if(_log_maker_desc==-1) return -1; struct timespec time; clock_gettime(CLOCK_REALTIME,&time); int minutes = (int)time.tv_sec/60; char temp = (char)(minutes % 100 /10+48); (void)write(_log_maker_desc,&temp,sizeof(char)); temp = (char)(minutes % 10 + 48); (void) write(_log_maker_desc,&temp,sizeof(char)); temp = ':'; (void) write(_log_maker_desc,&temp,sizeof(char)); int seconds = (int)time.tv_sec % 60; temp = (char)(seconds /10 +48); (void) write(_log_maker_desc,&temp,sizeof(char)); temp = (char)(seconds %10 +48); (void) write(_log_maker_desc,&temp,sizeof(char)); temp = ','; (void) write(_log_maker_desc,&temp,sizeof(char)); int nanoseconds = time.tv_nsec; int j =0; int n = 6; for (int i=1000000000;i>1 ;i/=10) { temp = (char)(nanoseconds%i/(i/10)+48); n++; (void) write(_log_maker_desc,&temp,sizeof(char)); if (j == 1 && n<16) { n++; temp = '.'; (void) write(_log_maker_desc,&temp,sizeof(char)); j=0; } else j=1; } (void) write(_log_maker_desc,&end,sizeof(char)); return 0; } int print_message(char* message) { if(_log_maker_desc==-1) return -1; int len = (int)strlen(message); print_time(' '); (void)write(_log_maker_desc,message,len); char temp = '\n'; write(_log_maker_desc,&temp, sizeof(char)); return 0; }
C
/* ============================================================================ Name : Worksheet4.c Author : Christine Pace Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #define BOOL int #define TRUE 1 #define FALSE 0 BOOL check_if_number(char* string){ for(int i = 0; i < strlen(string); i++){ if(!isdigit(string[i]) && string[i] != '-'){ return FALSE; } } return TRUE; } int main(int argc, char *argv[]) { int valid = 0; int num1; int num2; if(argc > 1){ // Check first argument if(argc == 2){ if(!check_if_number(argv[1])){ printf("\nError: missing number\n"); }else if(strcmp(argv[1], "-") != 0){ printf("\nError: missing operator \n"); } } //Check second argument if(argc == 3){ if(!check_if_number(argv[2])){ printf("\nError: missing number\n"); }else if(strcmp(argv[2], "-") != 0){ printf("\nError: missing operator \n"); } } if(argc == 4){ if(valid == 0){ if(!check_if_number(argv[1])){ printf("\nError: invalid number\n"); } else if(!check_if_number(argv[3])){ printf("\nError: invalid number\n"); }else{ valid = 1; } } if(valid == 1){ num1 = atoi(argv[1]); num2 = atoi(argv[3]); if(strcmp(argv[2], "-") == 0){ printf("\n%d - %d = %d \n", num1, num2, (num1-num2)); } else if(strcmp(argv[2], "+") == 0){ printf("\n%d + %d = %d \n", num1, num2, (num1+num2)); } else if(strcmp(argv[2], "x") == 0){ printf("\n%d x %d = %d \n", num1, num2, (num1*num2)); } else if(strcmp(argv[2], "/") == 0){ printf("\n%d / %d = %f \n", num1, num2, ((float)num1/num2)); }else{ printf("\nError: invalid operator\n"); } } } } else{ printf("\nError: No Arguments\n"); } return EXIT_SUCCESS; }
C
#include <math.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdbool.h> #include <stdlib.h> #include "bibliotecaStruct.h" #include "bibliotecaFreq.h" // Main para execução ! // Alunos : Laerte Souza e Gustavo de Oliveira. // Professor Dr: Alexander Robert Kutzke. int main(int argc, char *argv[]) { switch (verificaArgumento(argv[1])) { case 1: freq(argv); break; case 2: freq_word(argv); break; case 3: search(argv); default: printf("Verificar o parametro passado !\n"); break; } return 0; }
C
#include <stdio.h> #include <string.h> #include <signal.h> #include <pthread.h> #include <math.h> pthread_mutex_t mx1=PTHREAD_MUTEX_INITIALIZER; int st; int vec; int vec2[10000]; void *f1(void *arg) { int i,j; while(st) { pthread_mutex_lock(&mx1); // Monitor j=0; for(i=0;i<10000;i++) if (vec2[i]==1)j++; //printf("Vec %d \n",vec); printf("Vec %d \n",j); //sleep(1); pthread_mutex_unlock(&mx1); sleep(1); } pthread_exit(arg); } void *fr(void *arg) { int i; while(st) { pthread_mutex_lock(&mx1); //read //printf("rd \n"); //sleep(2); vec--; for(i=0;i<10000;i++) if (vec2[i]==1){vec2[i]=0;break;} pthread_mutex_unlock(&mx1); } pthread_exit(arg); } void *fw(void *arg) { int i; while(st) { pthread_mutex_lock(&mx1); //write //printf("wr \n"); //sleep(3); vec++; for(i=0;i<10000;i++) if (vec2[i]==0){vec2[i]=1;break;} pthread_mutex_unlock(&mx1); } pthread_exit(arg); } void ha(int i) { st=0; signal(SIGINT,ha); } int main(int args, char **argv, char **argc) { int nM,nN,i; pthread_t t; pthread_t tr[100]; pthread_t tw[100]; // printf(" %0.2f \n",a); if(args==1) { printf("prg3 N n \n"); } vec=0; if(args==3) { signal(SIGINT,ha); //nN=atof(&argv[1][0]); //N - interval nN=atoi(&argv[1][0]); //N - Rd nM=atoi(&argv[2][0]); //m - Wr if(nN>100)exit(1); if(nM>100)exit(1); st=1; for(i=0;i<nN;i++) pthread_create(&tr[i],NULL,fr,NULL); for(i=0;i<nM;i++) pthread_create(&tw[i],NULL,fw,NULL); pthread_create(&t,NULL,f1,NULL); //---------- for(i=0;i<nM;i++) pthread_join(tw[i],NULL); for(i=0;i<nN;i++) pthread_join(tr[i],NULL); pthread_join(t,NULL); printf("Ok \n"); // pthread_create // getpid // pthread_cond_wait - ??? // pthread_exit // pthread_join return 0; } }
C
struct Node{ int value; struct Node* left; struct Node* right; }; struct Node* newNode(int value){ struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->value = value; node->left = NULL; node->right = NULL; return (node); } int maxSum(struct Node* temp){ if (temp == NULL) return 0; int left1 = maxSum(temp->left); int right1 = maxSum(temp->right); if(left1 < right1) return right1 + temp->value; else return left1 + temp->value; } int main(){ struct Node* root = newNode(1); root->left = newNode(5); root->right = newNode(10); root->left->left = newNode(20); root->left->left->left = newNode(999); root->left->right = newNode(4); root->right->right = newNode(20); root->right->right->right = newNode(15); root->right->left = newNode(21); root->right->left->left = newNode(13); printf("maximum sum of tree nodes: %d\n", maxSum(root)); return 0; }
C
/*----------------------------------------------- ƣ99ʱ ˾ϺӿƼ޹˾ վwww.doflye.cn дʦ ڣ2009.5 ޸ģ ݣͨʱʱ ------------------------------------------------*/ #include<reg52.h> //ͷļһҪĶͷļ⹦ܼĴĶ code unsigned char tab[]= {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f}; // 0-9 unsigned char Dis_Shiwei;//ʮλ unsigned char Dis_Gewei; //λ /******************************************************************/ /* ʱ */ /******************************************************************/ void delay(unsigned int cnt) { while(--cnt); } /******************************************************************/ /* */ /******************************************************************/ main() { TMOD |=0x01;//ʱ 10ms in 12M crystalģʽ116λʱ TH0=0xd8; TL0=0xf0; IE= 0x82; //ж TR0=1; //򿪶ʱ while(1) { P0=Dis_Shiwei;//ʾʮλ P2=0; delay(300); //ʱ P0=Dis_Gewei; //ʾλ P2=1; delay(300); } } /******************************************************************/ /* ʱжϺ */ /******************************************************************/ void tim(void) interrupt 1 using 1 { static unsigned char second,count; TH0=0xd8; //¸ֵ TL0=0xf0; count++; if (count==100) //100x10ms=1Sʱʱ { count=0; second++; //1 if(second==100) second=0; Dis_Shiwei=tab[second/10];//ʮλʾֵ Dis_Gewei=tab[second%10]; //λʾ } }
C
#include<stdio.h> int main(void) { printf("a 빮ڷ ǥϸ %c Դϴ. \n", 'A'); printf("%s %c Դϴ. \n", "a 빮ڷ ǥϸ", 'A'); printf("%s %d %s \n", "2 ϱ 3", 2*3, "Դϴ."); system("pause"); return 0; }
C
#include <sys/types.h> #include <unistd.h> #include <stdio.h> int main() { uid_t uid = getuid(); uid_t euid = geteuid(); printf("UID real -> %d\nUID efectivo -> %d\n", uid, euid); if (uid == euid) { printf("El bit setuid está activado, porque uid y euid coinciden\n"); } else { printf("El bit setuid está NO activado, porque uid y euid NO coinciden\n"); } return 1; }
C
/* * @lc app=leetcode.cn id=142 lang=c * * [142] 环形链表 II */ // @lc code=start /** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode *detectCycle(struct ListNode *head) { struct ListNode* fast = head; struct ListNode* slow = head; //判断是否有环 while(fast != NULL && fast->next != NULL){ fast = fast->next->next; slow = slow->next; if(slow == fast) break; } if(fast == NULL || fast->next == NULL) return 0; //找到环的起点 fast = head; while(slow != fast){ slow = slow->next; fast = fast->next; } return fast; } // @lc code=end
C
#include<stdio.h> #include<string.h> int main() { char str[50]; printf("enter the string:"); scanf("%s",str); if(strrev(str[50])=str) printf("isomorphism"); else printf("not isomorphism"); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main(){ int x,ano,mes,mes2,dia; scanf("%d", &x); ano=x/365; mes=x-(ano*365); mes2=mes/30; dia=mes-(mes2*30); printf("%d ano(s)\n",ano); printf("%d mes(es)\n",mes2 ); printf("%d dia(s)\n", dia); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <Largeint.h> int main(void) { largeInt l1, l2,sum,diff,product; div_result divi; int x; printf("Enter 1st number:"); readint(&l1); printf("Enter 2nd number:"); readint(&l2); printf("\nThe 1st number is :\n"); showI(l1); printf("\n"); printf("\nThe 2nd number is :\n"); showI(l2); printf("\n"); sum=addl(l1,l2); // Addition.. printf("\n\nSum="); showI(sum); diff=subl(l1,l2);//SUBSTRACTION printf("\n\nDifference="); showI(diff); product=multl(l1,l2);//MULTIPLICATION printf("\n\nproduct="); showI(product); printf("\n\n"); divi=divl(l1,l2);//DIVISION showDiv(divi); printf("\nmodulus of 1st and 2nd number:"); showI(modl(l1,l2)); x=Isprime(l1);// CHECKING PRIME OR NOT !! if(x==1) printf("\nPRIME"); else printf("\nNOT PRIME\n"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: oshudria <oshudria@student.unit.ua> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/05/20 13:14:13 by oshudria #+# #+# */ /* Updated: 2017/05/21 15:22:31 by oshudria ### ########.fr */ /* */ /* ************************************************************************** */ #include "alum.h" static int get_file_descriptor(int argc, char **argv) { int fd; fd = 0; if (argc == 1) { ft_putstr(BLUE_PRINT_ON); ft_putendl("Please, enter the map from keyboard"); ft_putstr(COLOR_PRINT_OFF); return (fd); } else { fd = open(argv[1], O_RDONLY); if (fd > 2) return (fd); return (-1); } } int main(int argc, char **argv) { t_data *data; int fd; data = NULL; if (argc > 2) write(2, "ERROR\n", 6); else { if ((fd = get_file_descriptor(argc, argv)) == -1) write(2, "ERROR\n", 6); else if ((data = parse_input_board(fd)) == NULL) write(2, "ERROR\n", 6); else { play(data); clean_data(&data); } close(fd); } return (0); }
C
/* Program to extract a last digit from a given number */ /* Author:Sravanthi_Yachareni */ #include<stdio.h> #include<conio.h> void main() { int number,digit; printf("Enter a number"); scanf("%d",&number); digit=number%10; printf("Last digit is:%d",digit); }
C
#ifndef _Move #define _Move #include <avr/io.h> #include <avr/interrupt.h> void MotorsInit() { sei(); DDRD = 0xFF; DDRB = 0xFF; TCCR0A = 0xA3; TCCR0B = 0x04; TCNT0 = 0x00; } void Forward(int duty) { OCR0B = duty; OCR0A = duty; PORTD = 0b11100000; PORTB = 0b00001000; } void Backward(int duty) { OCR0B = duty; OCR0A = duty; PORTD = 0b01100000; PORTB = 0b00000011; } void Stop() { PORTD = 0b00000000; PORTB = 0b00000000; } void Left(int duty) { OCR0B = duty; OCR0A = duty; PORTD = 0b01100000; PORTB = 0b00001001; } void Right(int duty) { OCR0B = duty; OCR0A = duty; PORTD = 0b11100000; PORTB = 0b00000010; } void square_move() { Forward(150); _delay_ms(1500); Stop(); _delay_ms(500); Right(150); _delay_ms(650); Stop(); _delay_ms(500); Forward(150); _delay_ms(1500); Stop(); _delay_ms(500); Right(150); _delay_ms(650); Stop(); _delay_ms(500); Forward(150); _delay_ms(1500); Stop(); _delay_ms(500); Right(150); _delay_ms(650); Stop(); _delay_ms(500); Forward(150); _delay_ms(1500); Stop(); _delay_ms(500); Right(150); _delay_ms(650); Stop(); _delay_ms(500); } void Circle_move(int i, int j) { OCR0B = i; OCR0A = j; PORTD = 0b11100000; PORTB = 0b00001000; } void Lab_Demo() { Forward(225); _delay_ms(2000); Stop(); _delay_ms(500); Backward(127); _delay_ms(4000); Stop(); _delay_ms(500); Left(225); _delay_ms(2000); Stop(); _delay_ms(500); Right(127); _delay_ms(3000); Stop(); _delay_ms(500); } #endif
C
/* colorConv - Color conversion program. */ #include "common.h" #include "linefile.h" #include "hash.h" #include "options.h" #include "memgfx.h" #include "portable.h" static char const rcsid[] = "$Id: colorConv.c,v 1.1 2009/06/19 19:14:42 mikep Exp $"; void usage() /* Explain usage and exit. */ { errAbort( "colorConv - Color conversion program\n" "usage:\n" " colorConv (rgb|hsv|hsl) x,y,x\n" " colorConv (rgb|hsv|hsl) x y x\n" "\n" " colorConv rgbTransformHsl|rgbTransformHsv|rgbMatrixTransformHsv r,g,b h s [v|l]\n" " colorConv rgbTransformHsl|rgbTransformHsv|rgbMatrixTransformHsv r g b h s [v|l]\n" " rgbTransformHsl = transformation of r,g,b value conversion to hsl and scaling by h,s,l factors\n" " rgbTransformHsv = transformation of r,g,b value conversion to hsv and scaling by h,s,v factors\n" " h = hue shift in degrees (0-360, 0.0=none)\n" " s = saturation scaling factor (1.0=none)\n" " l/v = lightness/value scaling factor (1.0=none)\n" "\n" " colorConv test\n" // "options:\n" ); } int eps, maxErrs; char *factors[3]; // identity static struct optionSpec options[] = { {"eps", OPTION_INT}, {"maxErrs", OPTION_INT}, {NULL, 0}, }; boolean eq(int a, int b, int eps) { return abs(a-b) <= eps; } struct hsvColor parseHsv(char *vals[]) { struct hsvColor hsv; hsv.h = atoi(vals[0]); hsv.s = atoi(vals[1]); hsv.v = atoi(vals[2]); return hsv; } struct hslColor parseHsl(char *vals[]) { struct hslColor hsl; hsl.h = atoi(vals[0]); hsl.s = atoi(vals[1]); hsl.l = atoi(vals[2]); return hsl; } struct rgbColor parseRgb(char *vals[]) { struct rgbColor rgb; rgb.r = atoi(vals[0]); rgb.g = atoi(vals[1]); rgb.b = atoi(vals[2]); return rgb; } void rgbConv(char *vals[3]) /* Convert rgb to hsv and hsl */ { struct rgbColor rgb = parseRgb(vals); struct hsvColor hsv = mgRgbToHsv(rgb); struct hslColor hsl = mgRgbToHsl(rgb); printf("hsv %d,%d,%d\nhsl %d,%d,%d\n", (int)hsv.h, hsv.s, hsv.v, (int)hsl.h, hsl.s, hsl.l); } void hslConv(char *vals[3]) /* Convert hsl to rgb and hsv */ { struct hslColor hsl = parseHsl(vals); struct rgbColor rgb = mgHslToRgb(hsl); struct hsvColor hsv = mgRgbToHsv(rgb); printf("rgb %d,%d,%d\nhsv %d,%d,%d\n", rgb.r, rgb.g, rgb.b, (int)hsv.h, hsv.s, hsv.v); } void hsvConv(char *vals[3]) /* Convert hsv to rgb and hsl */ { struct hsvColor hsv = parseHsv(vals); struct rgbColor rgb = mgHsvToRgb(hsv); struct hslColor hsl = mgRgbToHsl(rgb); printf("rgb %d,%d,%d\nhsl %d,%d,%d\n", rgb.r, rgb.g, rgb.b, (int)hsl.h, hsl.s, hsl.l); } void rgbTransformHsl(char *vals[3]) /* transform rgb to hsl, then scale by hsl factors, and transform back to rgb */ { struct rgbColor rgb = parseRgb(vals); struct rgbColor rgb2 = mgRgbTransformHsl(rgb, atof(factors[0]), atof(factors[1]), atof(factors[2])); printf("rgb %d,%d,%d hsv %f,%f,%f\nrgbTransformHsl %d,%d,%d\n", rgb.r, rgb.g, rgb.b, atof(factors[0]), atof(factors[1]), atof(factors[2]), rgb2.r, rgb2.g, rgb2.b); } void rgbTransformHsv(char *vals[3]) /* transform rgb to hsv, then scale by hsv factors, and transform back to rgb */ { struct rgbColor rgb = parseRgb(vals); struct rgbColor rgb2 = mgRgbTransformHsv(rgb, atof(factors[0]), atof(factors[1]), atof(factors[2])); printf("rgb %d,%d,%d hsv %f,%f,%f\nrgbTransformHsv %d,%d,%d\n", rgb.r, rgb.g, rgb.b, atof(factors[0]), atof(factors[1]), atof(factors[2]), rgb2.r, rgb2.g, rgb2.b); } void testTransform(char *label, struct rgbColor (*transformRgb)(struct rgbColor in, double h, double s, double x), double h, double s, double x, int rStart, int gStart, int bStart, int eps, int maxErrs) { long start, end, success = 0, failed = 0; int r, g, b; struct rgbColor rgbIn, rgbOut; start = clock1000(); for (r = rStart ; r<256 ; ++r) for (g = gStart ; g<256 ; ++g) for (b = bStart ; b<256 ; ++b) { rgbIn = (struct rgbColor){r, g, b}; rgbOut = (*transformRgb)(rgbIn, h, s, x); if (eq(rgbIn.r,rgbOut.r, eps) && eq(rgbIn.g, rgbOut.g, eps) && eq(rgbIn.b, rgbOut.b, eps)) { ++success; } else { ++failed; if (failed <= maxErrs) warn("%s conversion failed: {%d,%d,%d} != {%d,%d,%d}", label, rgbIn.r, rgbIn.g, rgbIn.b, rgbOut.r, rgbOut.g, rgbOut.b); } } end = clock1000(); warn("%s: %ld / %ld OK (%.5f%%) (%ld failed) %ld per second.", label, success, success+failed, 100.0*success/(success+failed), failed, 1000L*((256-rStart)*(256-gStart)*(256-bStart)/(end-start))); } struct rgbColor convRgbHslRgb(struct rgbColor in) { return mgHslToRgb(mgRgbToHsl(in)); } struct rgbColor convRgbHsvRgb(struct rgbColor in) { return mgHsvToRgb(mgRgbToHsv(in)); } void testConversion(char *label, struct rgbColor (*convRgb)(struct rgbColor), int rStart, int gStart, int bStart, int eps, int maxErrs) { long start, end, success = 0, failed = 0; int r, g, b; struct rgbColor rgbIn, rgbOut; start = clock1000(); for (r = rStart ; r<256 ; ++r) for (g = gStart ; g<256 ; ++g) for (b = bStart ; b<256 ; ++b) { rgbIn = (struct rgbColor){r, g, b}; rgbOut = (*convRgb)(rgbIn); if (eq(rgbIn.r,rgbOut.r, eps) && eq(rgbIn.g, rgbOut.g, eps) && eq(rgbIn.b, rgbOut.b, eps)) { ++success; } else { ++failed; if (failed <= maxErrs) warn("%s conversion failed: {%d,%d,%d} != {%d,%d,%d}", label, rgbIn.r, rgbIn.g, rgbIn.b, rgbOut.r, rgbOut.g, rgbOut.b); } } end = clock1000(); warn("%s: %ld / %ld OK (%.5f%%) (%ld failed) %ld per second.", label, success, success+failed, 100.0*success/(success+failed), failed, 1000L*((256-rStart)*(256-gStart)*(256-bStart)/(end-start))); } void test(char *vals[3]) { int r0 = atoi(vals[0]), g0 = atoi(vals[1]), b0 = atoi(vals[2]); testConversion("rgb->hsl->rgb", &convRgbHslRgb, r0, g0, b0, eps, maxErrs); testConversion("rgb->hsv->rgb", &convRgbHsvRgb, r0, g0, b0, eps, maxErrs); testTransform("rgbTransformHsl", &mgRgbTransformHsl, 0.0, 1.0, 1.0, r0, g0, b0, eps, maxErrs); testTransform("rgbTransformHsv", &mgRgbTransformHsv, 0.0, 1.0, 1.0, r0, g0, b0, eps, maxErrs); } int main(int argc, char *argv[]) /* Process command line. */ { struct hash *handler = newHash(0); void (*convert)(char *words[3]); char *words[3] = {"0", "0", "0"}; optionInit(&argc, argv, options); --argc; ++argv; hashAdd(handler, "rgb", &rgbConv); hashAdd(handler, "hsv", &hsvConv); hashAdd(handler, "hsl", &hslConv); hashAdd(handler, "rgbTransformHsl", &rgbTransformHsl); hashAdd(handler, "rgbTransformHsv", &rgbTransformHsv); hashAdd(handler, "test", &test); eps = optionInt("eps",0); maxErrs = optionInt("maxErrs",10); if (argc == 1) ; // use default 0,0,0 else if (argc == 2) chopByChar(argv[1], ',', words, 3); else if (argc == 4) { words[0] = argv[1]; words[1] = argv[2]; words[2] = argv[3]; } else if (argc == 5) { chopByChar(argv[1], ',', words, 3); factors[0] = argv[2]; factors[1] = argv[3]; factors[2] = argv[4]; } else if (argc == 7) { words[0] = argv[1]; words[1] = argv[2]; words[2] = argv[3]; factors[0] = argv[4]; factors[1] = argv[5]; factors[2] = argv[6]; } else usage(); if (!(convert = hashFindVal(handler, argv[0]))) errAbort("Cannot convert %s types\n", argv[0]); convert(words); return 0; }
C
#include <stdlib.h> #include <stdio.h> int **matrix_create(int n) { int i, j; int **m; m = (int **)calloc(n, sizeof(int *)); for(i=0; i<n; i++) { m[i] = (int *)calloc(n, sizeof(int)); for(j=0; j<n; j++) scanf("%d", &m[i][j]); } return m; } int check_rows(int **m, int n, int *row_sum) { int i, j; int *sum; sum = (int *)calloc(n, sizeof(int)); for(j=0;j<n;j++) { for(i=0;i<n;i++) sum[j] += m[j][i]; } for(i=0;i<n-1;i++) { if(sum[i] != sum[i+1]) { free(sum); return 0; } } *row_sum = sum[0]; free(sum); return 1; } int diag_sum1(int **m, int n) { int i, diag; diag = 0; for(i=0; i<n; i++) diag += m[i][i]; return diag; } int diag_sum2(int **m, int n) { int i, diag; diag = 0; for(i=0; i<n; i++) diag += m[i][n-i-1]; return diag; } int check_all(int **m, int n) { int i, diag1, diag2; int row_sum; if(!check_rows(m, n, &row_sum)) { printf("NAO\n"); return -1; } diag1 = diag_sum1(m, n); diag2 = diag_sum2(m, n); if(diag1 == diag2 && diag2 == row_sum) printf("SIM\n"); else printf("NAO\n"); return 0; } int main(int argc, char *argv[]) { int n, i; int **matrix; scanf("%d", &n); matrix = matrix_create(n); check_all(matrix, n); for(i=0; i< n; i++) free(matrix[i]); free(matrix); return 0; }
C
//this is a program designed for project 0 part B //by Yanfei Li //last edited at 9/7/2021 #include <stdio.h> #include <string.h> #include <stdlib.h>//gcc -o wzip wzip.c -Wall -Werror FILE* fp=NULL; char str[100],ch,in; int Counter=1; size_t size; int main(int argc, char* argv[]){ switch (argc) { case 1: //if user only type in wzip without file names printf("wzip:[file1] [file2...]\n"); //error pops up break; default: while(--argc > 0) { //while there is argument(s) if ((fp=fopen(*++argv, "r")) == NULL) //if filepointer has nothing { printf("wzip: cannot open file\n"); //print error message. return 1; } else { while(fgets(str,100,fp) != NULL) //or while there is something in the filepointer { // c = str[0]; for(int i=0;i<sizeof(str);i++)//in the for loop of whole file { if(str[i]==str[i+1])// if first char is the same as the second char { Counter++;//increase the counter in=Counter+'0'; fwrite(&in,sizeof(char),1,stdout); return(0); } else//else write the char to the compressed file. { //what do i need? all the arguments in fwrite() //what is it? 1.char array 2.size of ele 3.# of ele 4.fp //what stop me? //passing the value of int(checked) and value of a element of a char array to char array // in=Counter+'0'; // strncpy(temp,str[i]); // printf("%c\n",str[i]); fwrite(&str[i],sizeof(char),1,stdout); printf("\n"); return(0); // fwrite(&in,sizeof(char),1,stdout); } // printf("%c",str[i]); } } } fclose(fp); //close the file } break; } return(0); }
C
// **** Include libraries here **** // Standard libraries //CMPE13 Support Library #include "BOARD.h" // Microchip libraries #include <xc.h> #include <plib.h> // User libraries #include "Stack.h" // **** Set macros and preprocessor directives **** // **** Define global, module-level, or external variables here **** // **** Declare function prototypes **** /* * Function prototype for ProcessBackspaces() - This function should be defined * below main after the related comment. */ int ProcessBackspaces(char *rpn_sentence); // If this code is used for testing, rename main to something we can call from our testing code. We // also skip all processor configuration and initialization code. #ifndef LAB4_TESTING int main() { BOARD_Init(); #else int their_main(void) { #endif // LAB4_TESTING /******************************** Your custom code goes below here *******************************/ printf("Welcome to Lab 4 RPN Calculator \n"); struct Stack myStack; myStack.initialized = TRUE; //True is from GenericTypeDefs.h struck Stack *stackPointer = &myStack; stackPointer->initialized = TRUE; myStack.stackItems = 60; //String should handle up to 60 chars /*************************************************************************************************/ // You can never return from main() in an embedded system (one that lacks an operating system). // This will result in the processor restarting, which is almost certainly not what you want! while (1); } /** * Extra Credit: Define ProcessBackspaces() here - This function should read through an array of * characters and when a backspace character is read it should replace the preceding character with * the following character. It should be able to handle multiple repeated backspaces and also * strings with more backspaces than characters. It should be able to handle strings that are at * least 256 characters in length. * @param rpn_sentence The string that will be processed for backspaces. This string is modified in * place. * @return Returns the size of the resultant string in `rpn_sentence`. */ int ProcessBackspaces(char *rpn_sentence) { return 0; }
C
/* 문제3. for 반복문을 사용하여 1부터 입력한 숫자까지의 합계를 구하는 C프로그램을 작성하여 보시오. - 출력예 - 정수를 입력하세요 : 50 1부터 50까지의 합계는 1275입니다. */ #include <stdio.h> void main() { int sum = 0; int n; printf("1에서 n까지 더할 값을 입력하세요 n: "); scanf("%d", &n); for (size_t i = 1; i <= n; i++) { sum += i; } printf("1 ~ %d까지의 합계는 %d입니다.\n", n, sum); }
C
// motors.h // Contains all code required to initialize and update PWM signals used to // control twelve motors. // This file is part of Dreamer Head v0.1. // Travis Llado, travis@travisllado.com // Last modified 2016.06.18 //////////////////////////////////////////////////////////////////////////////// // motorInit() // Initializes all PWM control signals for 12 motors on pins // PA6, PA7, PB4, PB5, PB6, PB7, PD0, PD1, PE4, PE5, PF2, PF3. // Sets PWM frequency to user specified value. void motorInit(void); //////////////////////////////////////////////////////////////////////////////// // motorUpdate() // Updates PWM duty cycles corresponding to desired motor speeds for all twelve // motors. void motorUpdate(int32_t *speed);
C
/* * setZero.h * * Created on: 2014-04-30 * Author: frye */ #ifndef SETZERO_H_ #define SETZERO_H_ void setZeroes(vector<vector<int> > &matrix) { int height = matrix.size(); int width = matrix[0].size(); bool firstRowZero = false, firstColZero = false; for(int i=0;i<height;i++){ if (matrix[i][0]==0){ firstColZero = true; break; } } for(int i=0;i<width;i++){ if (matrix[0][i]==0){ firstRowZero = true; break; } } for(int i=1;i<height;i++){ for(int j=0;j<width;j++) if (matrix[i][j]==0){ matrix[i][0] = 0; } } for(int i=1;i<width;i++){ for(int j=0;j<height;j++) if (matrix[j][i]==0){ matrix[0][i] = 0; } } for(int i=1;i<height;i++){ if (matrix[i][0]==0) for(int j=1;j<width;j++) matrix[i][j] = 0; } for(int i=1;i<width;i++){ if (matrix[0][i]==0) for(int j=1;j<height;j++) matrix[j][i] = 0; } if (firstRowZero) for(int i=0;i<width;i++) matrix[0][i] = 0; if (firstColZero) for(int i=0;i<height;i++) matrix[i][0] = 0; } #endif /* SETZERO_H_ */
C
#include <stdio.h> #include <string.h> char *rtrim(char *str){ int n = 0; n = strlen(str); for( ;n>=0; n--){ if(str[n] == ' ' || str[n] == 0 || str[n] == -1 || str[n] == '\t' || str[n] == '\r' || str[n] == '\n') { str[n] = '\0'; }else{ break; } } return str; } char *ltrim(char *str){ int n, i; n = strlen(str); for( i=0; i < n; i++){ if(str[i] == ' ' || str[i] == 0 || str[i] == -1 || str[i] == '\t' || str[i] == '\r' || str[i] == '\n') { }else{ break; } } if(i > 0) strcpy(str, str+i); return str; } char *Trim(char *ptr) { int l, i; l = strlen(ptr); while(ptr[l-1] == ' ' && l > 0) l--; ptr[l] = 0; i = 0; while(ptr[i] == ' ' && i < l) i++; strcpy(ptr, ptr + i); return ptr; } void sreplace(char *src, char *dest, const char *s1, const char *s2){ int l1, l2; char *tmp, *sptr; l1 = strlen(s1); l2 = strlen(s2); if(l1 == 0){ strcpy(dest, src); return; } sptr = src; dest[0] = 0; while( (tmp = strstr(sptr, s1) ) > 0){ strncat(dest, sptr, tmp-sptr); strcat(dest, s2); sptr = tmp + l1; } strcat(dest, sptr); } /*ֶַȡ chip Ϊָ src еĵ fld η dst */ int substring(char *dst, char *src, char chip, int fld){ char *ptr, *ptr1; int index; ptr1 = ptr = src; while(fld > 1 && (ptr1 = strchr(ptr, chip)) > 0){ ptr = ptr1 + 1; fld --; } if(fld > 1) return 0; ptr1 = strchr(ptr, chip); if(ptr1 <= 0){ strcpy(dst, ptr); }else{ strncpy(dst, ptr, ptr1-ptr); dst[ptr1-ptr] = '\0'; } return 1; } /* - split - divide a string into fields, like awk split() = int split(char *string, char *fields[], int nfields, char *sep); */ int /* number of fields, including overflow */ split( char *string, char *fields[], /* list is not NULL-terminated */ int nfields, /* number of entries available in fields[] */ char *sep /* "" white, "c" single char, "ab" [ab]+ */ ) { register char *p = string; register char c; /* latest character */ register char sepc = sep[0]; register char sepc2; register int fn; register char **fp = fields; register char *sepp; register int trimtrail; /* white space */ if (sepc == '\0') { while ((c = *p++) == ' ' || c == '\t') continue; p--; trimtrail = 1; sep = " \t"; /* note, code below knows this is 2 long */ sepc = ' '; } else trimtrail = 0; sepc2 = sep[1]; /* now we can safely pick this up */ /* catch empties */ if (*p == '\0') return(0); /* single separator */ if (sepc2 == '\0') { fn = nfields; for (;;) { *fp++ = p; fn--; if (fn == 0) break; while ((c = *p++) != sepc) if (c == '\0') return(nfields - fn); *(p-1) = '\0'; } /* we have overflowed the fields vector -- just count them */ fn = nfields; for (;;) { while ((c = *p++) != sepc) if (c == '\0') return(fn); fn++; } /* not reached */ } /* two separators */ if (sep[2] == '\0') { fn = nfields; for (;;) { *fp++ = p; fn--; while ((c = *p++) != sepc && c != sepc2) if (c == '\0') { if (trimtrail && **(fp-1) == '\0') fn++; return(nfields - fn); } if (fn == 0) break; *(p-1) = '\0'; while ((c = *p++) == sepc || c == sepc2) continue; p--; } /* we have overflowed the fields vector -- just count them */ fn = nfields; while (c != '\0') { while ((c = *p++) == sepc || c == sepc2) continue; p--; fn++; while ((c = *p++) != '\0' && c != sepc && c != sepc2) continue; } /* might have to trim trailing white space */ if (trimtrail) { p--; while ((c = *--p) == sepc || c == sepc2) continue; p++; if (*p != '\0') { if (fn == nfields+1) *p = '\0'; fn--; } } return(fn); } /* n separators */ fn = 0; for (;;) { if (fn < nfields) *fp++ = p; fn++; for (;;) { c = *p++; if (c == '\0') return(fn); sepp = sep; while ((sepc = *sepp++) != '\0' && sepc != c) continue; if (sepc != '\0') /* it was a separator */ break; } if (fn < nfields) *(p-1) = '\0'; for (;;) { c = *p++; sepp = sep; while ((sepc = *sepp++) != '\0' && sepc != c) continue; if (sepc == '\0') /* it wasn't a separator */ break; } p--; } /* not reached */ } /*case-insensitive version of strstr*/ char *strcasestr(const char *str, const char *sub) { int l1, l2, i, j; l1 = strlen(str); l2 = strlen(sub); for(i=0, j=0; i<l1; i++){ if(toupper(str[i]) == toupper(sub[j])) j++; else j = 0; if(j == l2) return (char *)(str + i - j + 1); } return (char *)NULL; }
C
#include <stdio.h> #include <stdlib.h> #include "queue.h" int Que_create(QueHndl *hndl, uint32_t maxLen) { pthread_mutexattr_t mutex_attr; pthread_condattr_t cond_attr; int status=QUE_OK; hndl->curRd = hndl->curWr = 0; hndl->count = 0; hndl->len = maxLen; hndl->queue = malloc(sizeof(int32_t)*hndl->len); if(hndl->queue==NULL) { printf("Que_Create() = %d \r\n", status); return -1; } status |= pthread_mutexattr_init(&mutex_attr); status |= pthread_condattr_init(&cond_attr); status |= pthread_mutex_init(&hndl->lock, &mutex_attr); status |= pthread_cond_init(&hndl->condRd, &cond_attr); status |= pthread_cond_init(&hndl->condWr, &cond_attr); if(status!=QUE_OK) printf("Que_Create() = %d \r\n", status); pthread_condattr_destroy(&cond_attr); pthread_mutexattr_destroy(&mutex_attr); return status; } int Que_delete(QueHndl *hndl) { if(hndl->queue!=NULL) free(hndl->queue); pthread_cond_destroy(&hndl->condRd); pthread_cond_destroy(&hndl->condWr); pthread_mutex_destroy(&hndl->lock); return 0; } int Que_put(QueHndl *hndl, int32_t value, uint32_t timeout) { int status = QUE_ERR; pthread_mutex_lock(&hndl->lock); while(1) { if( hndl->count < hndl->len ) { hndl->queue[hndl->curWr] = value; hndl->curWr = (hndl->curWr+1)%hndl->len; hndl->count++; status = QUE_OK; pthread_cond_signal(&hndl->condRd); break; } else { if(timeout == QUE_NO_WAIT) break; status = pthread_cond_wait(&hndl->condWr, &hndl->lock); } } pthread_mutex_unlock(&hndl->lock); return status; } int Que_get(QueHndl *hndl, int32_t *value, uint32_t timeout) { int status = QUE_ERR; pthread_mutex_lock(&hndl->lock); while(1) { if(hndl->count > 0 ) { if(value!=NULL) { *value = hndl->queue[hndl->curRd]; } hndl->curRd = (hndl->curRd+1)%hndl->len; hndl->count--; status = QUE_OK; pthread_cond_signal(&hndl->condWr); break; } else { if(timeout == QUE_NO_WAIT) break; status = pthread_cond_wait(&hndl->condRd, &hndl->lock); } } pthread_mutex_unlock(&hndl->lock); return status; } uint32_t Que_getQueuedCount(QueHndl *hndl) { uint32_t queuedCount = 0; pthread_mutex_lock(&hndl->lock); queuedCount = hndl->count; pthread_mutex_unlock(&hndl->lock); return queuedCount; } int Que_peek(QueHndl *hndl, int32_t *value) { int status = QUE_ERR; pthread_mutex_lock(&hndl->lock); if(hndl->count > 0 ) { if(value!=NULL) { *value = hndl->queue[hndl->curRd]; status = QUE_OK; } } pthread_mutex_unlock(&hndl->lock); return status; } bool Que_isEmpty(QueHndl *hndl) { bool isEmpty; pthread_mutex_lock(&hndl->lock); if (hndl->count == 0) { isEmpty = true; } else { isEmpty = false; } pthread_mutex_unlock(&hndl->lock); return isEmpty; }
C
/* * Exercise 18: http://c.learncodethehardway.org/ * * Use pointers to functions to implement Bubble sort with custom comparison * callbacks. */ #include <stdio.h> #include <stdlib.h> #include <string.h> void print_array(int *arr, int count, const char *caption) { printf("%s:\n", caption); int j = 0; for (j = 0; j < count; j++) printf("%d ", arr[j]); printf("\n"); } typedef int (*compare_cb)(int a, int b); int *bubble_sort(int *numbers, int count, compare_cb compare) { int tmp = 0; int i = 0; int j = 0; int *result = malloc(count * sizeof(int)); if (!result) { printf("Memory error"); exit(1); } memcpy(result, numbers, count * sizeof(int)); for (i = 0; i < count - 1; i++) { for (j = 0; j < count - i - 1; j++) { if (compare(result[j], result[j+1]) > 0) { tmp = result[j+1]; result[j+1] = result[j]; result[j] = tmp; } } } return result; } int compare_asc(int a, int b) { return a > b; } int compare_desc(int a, int b) { return a < b; } int main(int argc, char *argv[]) { printf("We are a bubble sort. We sort.\n"); int array_size = 7; int test[] = { 5, 1, 4, 7, 6, 2, 3 }; int *arr = malloc(array_size * sizeof(int)); memcpy(arr, test, array_size * sizeof(int)); print_array(arr, array_size, "\nOriginal array"); int *asc = bubble_sort(arr, array_size, compare_asc); int *desc = bubble_sort(arr, array_size, compare_desc); print_array(asc, array_size, "\nAscending"); print_array(desc, array_size, "\nDescending"); free(arr); free(asc); free(desc); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include "btree.h" int maxHeight; int nNodesIns; int nNodesDel; int nKeysIns; int nKeysDel; int nDiskReads; int nDiskWrites; int bErrLineNo; static hNode hList; static hNode *h; #define error(rc) lineError(__LINE__, rc) static bErrType lineError(int lineno, bErrType rc) { if (rc == bErrIO || rc == bErrMemory) if (!bErrLineNo) bErrLineNo = lineno; return rc; } static bAdrType allocAdr(void) { bAdrType adr; adr = h->nextFreeAdr; h->nextFreeAdr += h->sectorSize; return adr; } static bErrType flush(bufType *buf) { int len; len = h->sectorSize; if (buf->adr == 0) len *= 3; if (fseek(h->fp, buf->adr, SEEK_SET)) return error(bErrIO); if (fwrite(buf->p, len, 1, h->fp) != 1) return error(bErrIO); buf->modified = false; nDiskWrites++; return bErrOk; } static bErrType flushAll(void) { bErrType rc; bufType *buf; if (h->root.modified) if ((rc = flush(&h->root)) != 0) return rc; buf = h->bufList.next; while (buf != &h->bufList) { if (buf->modified) if ((rc = flush(buf)) != 0) return rc; buf = buf->next; } return bErrOk; } static bErrType assignBuf(bAdrType adr, bufType **b) { bufType *buf; bErrType rc; if (adr == 0) { *b = &h->root; return bErrOk; } buf = h->bufList.next; while (buf->next != &h->bufList) { if (buf->valid && buf->adr == adr) break; buf = buf->next; } if (buf->valid) { if (buf->adr != adr) { if (buf->modified) { if ((rc = flush(buf)) != 0) return rc; } buf->adr = adr; buf->valid = false; } } else { buf->adr = adr; } buf->next->prev = buf->prev; buf->prev->next = buf->next; buf->next = h->bufList.next; buf->prev = &h->bufList; buf->next->prev = buf; buf->prev->next = buf; *b = buf; return bErrOk; } static bErrType writeDisk(bufType *buf) { buf->valid = true; buf->modified = true; return bErrOk; } static bErrType readDisk(bAdrType adr, bufType **b) { int len; bufType *buf; bErrType rc; if ((rc = assignBuf(adr, &buf)) != 0) return rc; if (!buf->valid) { len = h->sectorSize; if (adr == 0) len *= 3; if (fseek(h->fp, adr, SEEK_SET)) return error(bErrIO); if (fread(buf->p, len, 1, h->fp) != 1) return error(bErrIO); buf->modified = false; buf->valid = true; nDiskReads++; } *b = buf; return bErrOk; } typedef enum { MODE_FIRST, MODE_MATCH } modeEnum; static int search(bufType *buf, void *key, keyType **mkey, modeEnum mode) { int cc; int m; int lb; int ub; bool foundDup; foundDup = false; lb = 0; ub = ct(buf) - 1; while (lb <= ub) { m = (lb + ub) / 2; *mkey = fkey(buf) + ks(m); cc = h->comp(key, key(*mkey)); if (cc < 0) ub = m - 1; else if (cc > 0) lb = m + 1; else { return cc; } } if (ct(buf) == 0) { *mkey = fkey(buf); return CC_LT; } return cc; } static bErrType scatterRoot(void) { bufType *gbuf; bufType *root; root = &h->root; gbuf = &h->gbuf; memcpy(fkey(root), fkey(gbuf), ks(ct(gbuf))); childLT(fkey(root)) = childLT(fkey(gbuf)); ct(root) = ct(gbuf); leaf(root) = leaf(gbuf); return bErrOk; } static bErrType scatter(bufType *pbuf, keyType *pkey, int is, bufType **tmp) { bufType *gbuf; keyType *gkey; bErrType rc; int iu; int k0Min; int knMin; int k0Max; int knMax; int sw; int len; int base; int extra; int ct; int i; gbuf = &h->gbuf; gkey = fkey(gbuf); ct = ct(gbuf); iu = is; if (leaf(gbuf)) { k0Max= h->maxCt - 1; knMax= h->maxCt - 1; k0Min= (h->maxCt / 2) + 1; knMin= (h->maxCt / 2) + 1; } else { k0Max = h->maxCt - 1; knMax = h->maxCt; k0Min = (h->maxCt / 2) + 1; knMin = ((h->maxCt+1) / 2) + 1; } while(1) { if (iu == 0 || ct > (k0Max + (iu-1)*knMax)) { if ((rc = assignBuf(allocAdr(), &tmp[iu])) != 0) return rc; if (leaf(gbuf)) { if (iu == 0) { prev(tmp[0]) = 0; next(tmp[0]) = 0; } else { prev(tmp[iu]) = tmp[iu-1]->adr; next(tmp[iu]) = next(tmp[iu-1]); next(tmp[iu-1]) = tmp[iu]->adr; } } iu++; nNodesIns++; } else if (iu > 1 && ct < (k0Min + (iu-1)*knMin)) { iu--; if (leaf(gbuf) && tmp[iu-1]->adr) { next(tmp[iu-1]) = next(tmp[iu]); } next(tmp[iu-1]) = next(tmp[iu]); nNodesDel++; } else { break; } } base = ct / iu; extra = ct % iu; for (i = 0; i < iu; i++) { int n; n = base; if (i && extra) { n++; extra--; } ct(tmp[i]) = n; } if (iu != is) { if (leaf(gbuf) && next(tmp[iu-1])) { bufType *buf; if ((rc = readDisk(next(tmp[iu-1]), &buf)) != 0) return rc; prev(buf) = tmp[iu-1]->adr; if ((rc = writeDisk(buf)) != 0) return rc; } sw = ks(iu - is); if (sw < 0) { len = ks(ct(pbuf)) - (pkey - fkey(pbuf)) + sw; memmove(pkey, pkey - sw, len); } else { len = ks(ct(pbuf)) - (pkey - fkey(pbuf)); memmove(pkey + sw, pkey, len); } if (ct(pbuf)) ct(pbuf) += iu - is; else ct(pbuf) += iu - is - 1; } for (i = 0; i < iu; i++) { if (leaf(gbuf)) { childLT(fkey(tmp[i])) = 0; if (i == 0) { childLT(pkey) = tmp[i]->adr; } else { memcpy(pkey, gkey, ks(1)); childGE(pkey) = tmp[i]->adr; pkey += ks(1); } } else { if (i == 0) { childLT(fkey(tmp[i])) = childLT(gkey); childLT(pkey) = tmp[i]->adr; } else { childLT(fkey(tmp[i])) = childGE(gkey); memcpy(pkey, gkey, ks(1)); childGE(pkey) = tmp[i]->adr; gkey += ks(1); pkey += ks(1); ct(tmp[i])--; } } memcpy(fkey(tmp[i]), gkey, ks(ct(tmp[i]))); leaf(tmp[i]) = leaf(gbuf); gkey += ks(ct(tmp[i])); } leaf(pbuf) = false; if ((rc = writeDisk(pbuf)) != 0) return rc; for (i = 0; i < iu; i++) if ((rc = writeDisk(tmp[i])) != 0) return rc; return bErrOk; } static bErrType gatherRoot(void) { bufType *gbuf; bufType *root; root = &h->root; gbuf = &h->gbuf; memcpy(p(gbuf), root->p, 3 * h->sectorSize); leaf(gbuf) = leaf(root); ct(root) = 0; return bErrOk; } static bErrType gather(bufType *pbuf, keyType **pkey, bufType **tmp) { bErrType rc; bufType *gbuf; keyType *gkey; if (*pkey == lkey(pbuf)) *pkey -= ks(1); if ((rc = readDisk(childLT(*pkey), &tmp[0])) != 0) return rc; if ((rc = readDisk(childGE(*pkey), &tmp[1])) != 0) return rc; if ((rc = readDisk(childGE(*pkey + ks(1)), &tmp[2])) != 0) return rc; gbuf = &h->gbuf; gkey = fkey(gbuf); childLT(gkey) = childLT(fkey(tmp[0])); memcpy(gkey, fkey(tmp[0]), ks(ct(tmp[0]))); gkey += ks(ct(tmp[0])); ct(gbuf) = ct(tmp[0]); if (!leaf(tmp[1])) { memcpy(gkey, *pkey, ks(1)); childGE(gkey) = childLT(fkey(tmp[1])); ct(gbuf)++; gkey += ks(1); } memcpy(gkey, fkey(tmp[1]), ks(ct(tmp[1]))); gkey += ks(ct(tmp[1])); ct(gbuf) += ct(tmp[1]); if (!leaf(tmp[2])) { memcpy(gkey, *pkey+ks(1), ks(1)); childGE(gkey) = childLT(fkey(tmp[2])); ct(gbuf)++; gkey += ks(1); } memcpy(gkey, fkey(tmp[2]), ks(ct(tmp[2]))); ct(gbuf) += ct(tmp[2]); leaf(gbuf) = leaf(tmp[0]); return bErrOk; } bErrType bOpen(bOpenType info, bHandleType *handle) { bErrType rc; int bufCt; bufType *buf; int maxCt; bufType *root; int i; nodeType *p; if ((info.sectorSize < sizeof(hNode)) || (info.sectorSize % 4)) return bErrSectorSize; maxCt = info.sectorSize - (sizeof(nodeType) - sizeof(keyType)); maxCt /= sizeof(bAdrType) + info.keySize + sizeof(eAdrType); if (maxCt < 6) return bErrSectorSize; if ((h = malloc(sizeof(hNode))) == NULL) return error(bErrMemory); memset(h, 0, sizeof(hNode)); h->keySize = info.keySize; h->sectorSize = info.sectorSize; h->comp = info.comp; h->ks = sizeof(bAdrType) + h->keySize + sizeof(eAdrType); h->maxCt = maxCt; bufCt = 7; if ((h->malloc1 = malloc(bufCt * sizeof(bufType))) == NULL) return error(bErrMemory); buf = h->malloc1; if ((h->malloc2 = malloc((bufCt+6) * h->sectorSize + 2 * h->ks)) == NULL) return error(bErrMemory); p = h->malloc2; h->bufList.next = buf; h->bufList.prev = buf + (bufCt - 1); for (i = 0; i < bufCt; i++) { buf->next = buf + 1; buf->prev = buf - 1; buf->modified = false; buf->valid = false; buf->p = p; p = (nodeType *)((char *)p + h->sectorSize); buf++; } h->bufList.next->prev = &h->bufList; h->bufList.prev->next = &h->bufList; root = &h->root; root->p = p; p = (nodeType *)((char *)p + 3*h->sectorSize); h->gbuf.p = p; h->curBuf = NULL; h->curKey = NULL; if ((h->fp = fopen(info.iName, "r+b")) != NULL) { if ((rc = readDisk(0, &root)) != 0) return rc; if (fseek(h->fp, 0, SEEK_END)) return error(bErrIO); if ((h->nextFreeAdr = ftell(h->fp)) == -1) return error(bErrIO); } else if ((h->fp = fopen(info.iName, "w+b")) != NULL) { memset(root->p, 0, 3*h->sectorSize); leaf(root) = 1; h->nextFreeAdr = 3 * h->sectorSize; } else { free(h); return bErrFileNotOpen; } if (hList.next) { h->prev = hList.next; h->next = &hList; h->prev->next = h; h->next->prev = h; } else { h->prev = h->next = &hList; hList.next = hList.prev = h; } *handle = h; return bErrOk; } bErrType bClose(bHandleType handle) { h = handle; if (h == NULL) return bErrOk; if (h->next) { h->next->prev = h->prev; h->prev->next = h->next; } if (h->fp) { flushAll(); fclose(h->fp); } if (h->malloc2) free(h->malloc2); if (h->malloc1) free(h->malloc1); free(h); return bErrOk; } bErrType bFindKey(bHandleType handle, void *key, eAdrType *rec) { keyType *mkey; bufType *buf; bErrType rc; h = handle; buf = &h->root; while (1) { if (leaf(buf)) { if (search(buf, key, &mkey, MODE_FIRST) == 0) { *rec = rec(mkey); h->curBuf = buf; h->curKey = mkey; return bErrOk; } else { return bErrKeyNotFound; } } else { if (search(buf, key, &mkey, MODE_FIRST) < 0) { if ((rc = readDisk(childLT(mkey), &buf)) != 0) return rc; } else { if ((rc = readDisk(childGE(mkey), &buf)) != 0) return rc; } } } } bErrType bInsertKey(bHandleType handle, void *key, eAdrType rec) { int rc; keyType *mkey; int len; int cc; bufType *buf, *root; bufType *tmp[4]; unsigned int keyOff; bool lastGEvalid; bool lastLTvalid; bAdrType lastGE; unsigned int lastGEkey; int height; h = handle; root = &h->root; lastGEvalid = false; lastLTvalid = false; if (ct(root) == 3 * h->maxCt) { if ((rc = gatherRoot()) != 0) return rc; if ((rc = scatter(root, fkey(root), 0, tmp)) != 0) return rc; } buf = root; height = 0; while(1) { if (leaf(buf)) { if (height > maxHeight) maxHeight = height; switch(search(buf, key, &mkey, MODE_MATCH)) { case CC_LT: if (h->comp(key, mkey) == CC_EQ) return bErrDupKeys; break; case CC_EQ: return bErrDupKeys; break; case CC_GT: if (h->comp(key, mkey) == CC_EQ) return bErrDupKeys; mkey += ks(1); break; } keyOff = mkey - fkey(buf); len = ks(ct(buf)) - keyOff; if (len) memmove(mkey + ks(1), mkey, len); memcpy(key(mkey), key, h->keySize); rec(mkey) = rec; childGE(mkey) = 0; ct(buf)++; if ((rc = writeDisk(buf)) != 0) return rc; if (!keyOff && lastLTvalid) { bufType *tbuf; keyType *tkey; if ((rc = readDisk(lastGE, &tbuf)) != 0) return rc; tkey = fkey(tbuf) + lastGEkey; memcpy(key(tkey), key, h->keySize); rec(tkey) = rec; if ((rc = writeDisk(tbuf)) != 0) return rc; } nKeysIns++; break; } else { bufType *cbuf; height++; if ((cc = search(buf, key, &mkey, MODE_MATCH)) < 0) { if ((rc = readDisk(childLT(mkey), &cbuf)) != 0) return rc; } else { if ((rc = readDisk(childGE(mkey), &cbuf)) != 0) return rc; } if (ct(cbuf) == h->maxCt) { if ((rc = gather(buf, &mkey, tmp)) != 0) return rc; if ((rc = scatter(buf, mkey, 3, tmp)) != 0) return rc; if ((cc = search(buf, key, &mkey, MODE_MATCH)) < 0) { if ((rc = readDisk(childLT(mkey), &cbuf)) != 0) return rc; } else { if ((rc = readDisk(childGE(mkey), &cbuf)) != 0) return rc; } } if (cc >= 0 || mkey != fkey(buf)) { lastGEvalid = true; lastLTvalid = false; lastGE = buf->adr; lastGEkey = mkey - fkey(buf); if (cc < 0) lastGEkey -= ks(1); } else { if (lastGEvalid) lastLTvalid = true; } buf = cbuf; } } return bErrOk; } bErrType bDeleteKey(bHandleType handle, void *key) { int rc; keyType *mkey; int len; int cc; bufType *buf; bufType *tmp[4]; unsigned int keyOff; bool lastGEvalid; bool lastLTvalid; bAdrType lastGE; unsigned int lastGEkey; bufType *root; bufType *gbuf; h = handle; root = &h->root; gbuf = &h->gbuf; lastGEvalid = false; lastLTvalid = false; buf = root; while(1) { if (leaf(buf)) { if (search(buf, key, &mkey, MODE_MATCH) != 0) return bErrKeyNotFound; keyOff = mkey - fkey(buf); len = ks(ct(buf)-1) - keyOff; if (len) memmove(mkey, mkey + ks(1), len); ct(buf)--; if ((rc = writeDisk(buf)) != 0) return rc; if (!keyOff && lastLTvalid) { bufType *tbuf; keyType *tkey; if ((rc = readDisk(lastGE, &tbuf)) != 0) return rc; tkey = fkey(tbuf) + lastGEkey; memcpy(key(tkey), mkey, h->keySize); rec(tkey) = rec(mkey); if ((rc = writeDisk(tbuf)) != 0) return rc; } nKeysDel++; break; } else { bufType *cbuf; if ((cc = search(buf, key, &mkey, MODE_MATCH)) < 0) { if ((rc = readDisk(childLT(mkey), &cbuf)) != 0) return rc; } else { if ((rc = readDisk(childGE(mkey), &cbuf)) != 0) return rc; } if (ct(cbuf) == h->maxCt/2) { if ((rc = gather(buf, &mkey, tmp)) != 0) return rc; if (buf == root && ct(root) == 2 && ct(gbuf) < (3*(3*h->maxCt))/4) { scatterRoot(); nNodesDel += 3; continue; } if ((rc = scatter(buf, mkey, 3, tmp)) != 0) return rc; if ((cc = search(buf, key, &mkey, MODE_MATCH)) < 0) { if ((rc = readDisk(childLT(mkey), &cbuf)) != 0) return rc; } else { if ((rc = readDisk(childGE(mkey), &cbuf)) != 0) return rc; } } if (cc >= 0 || mkey != fkey(buf)) { lastGEvalid = true; lastLTvalid = false; lastGE = buf->adr; lastGEkey = mkey - fkey(buf); if (cc < 0) lastGEkey -= ks(1); } else { if (lastGEvalid) lastLTvalid = true; } buf = cbuf; } } return bErrOk; } bErrType bFindFirstKey(bHandleType handle, void *key, eAdrType *rec) { bErrType rc; bufType *buf; h = handle; buf = &h->root; while (!leaf(buf)) { if ((rc = readDisk(childLT(fkey(buf)), &buf)) != 0) return rc; } if (ct(buf) == 0) return bErrKeyNotFound; memcpy(key, key(fkey(buf)), h->keySize); *rec = rec(fkey(buf)); h->curBuf = buf; h->curKey = fkey(buf); return bErrOk; } bErrType bFindLastKey(bHandleType handle, void *key, eAdrType *rec) { bErrType rc; bufType *buf; h = handle; buf = &h->root; while (!leaf(buf)) { if ((rc = readDisk(childGE(lkey(buf)), &buf)) != 0) return rc; } if (ct(buf) == 0) return bErrKeyNotFound; memcpy(key, key(lkey(buf)), h->keySize); *rec = rec(lkey(buf)); h->curBuf = buf; h->curKey = lkey(buf); return bErrOk; } bErrType bFindNextKey(bHandleType handle, void *key, eAdrType *rec) { bErrType rc; keyType *nkey; bufType *buf; h = handle; if ((buf = h->curBuf) == NULL) return bErrKeyNotFound; if (h->curKey == lkey(buf)) { if (next(buf)) { if ((rc = readDisk(next(buf), &buf)) != 0) return rc; nkey = fkey(buf); } else { return bErrKeyNotFound; } } else { nkey = h->curKey + ks(1); } memcpy(key, key(nkey), h->keySize); *rec = rec(nkey); h->curBuf = buf; h->curKey = nkey; return bErrOk; } bErrType bFindPrevKey(bHandleType handle, void *key, eAdrType *rec) { bErrType rc; keyType *pkey; keyType *fkey; bufType *buf; h = handle; if ((buf = h->curBuf) == NULL) return bErrKeyNotFound; fkey = fkey(buf); if (h->curKey == fkey) { if (prev(buf)) { if ((rc = readDisk(prev(buf), &buf)) != 0) return rc; pkey = fkey(buf) + ks((ct(buf) - 1)); } else { return bErrKeyNotFound; } } else { pkey = h->curKey - ks(1); } memcpy(key, key(pkey), h->keySize); *rec = rec(pkey); h->curBuf = buf; h->curKey = pkey; return bErrOk; }
C
/* * File: parallel_quicksort_module.h * * Purpose: Implement parallel quicksort. * */ #include <omp.h> void quicksort(int arr[], int first, int last); void parallel_quicksort(int arr[], int n, int thread_count); int partition(int arr[], int first, int last); void swap(int* i, int* j); /*------------------------------------------------------------------- * Function: parallel_quicksort * Purpose: initiate parallel sort on an array * In args: arr: the array to be sorted * n: the size of the array * thread_count: number of threads */ void parallel_quicksort( int arr[], int n, int thread_count) { # pragma omp parallel num_threads(thread_count) \ default(none) shared(arr, n) { // start parallel block # pragma omp single nowait { quicksort(arr, 0, n - 1); } } // end of parallel block } /*------------------------------------------------------------------- * Function: quicksort * Purpose: Sort the array in parallel * In args: arr: the array to be sorted * first: index of the first element * last: index of the last element */ void quicksort( int arr[], int first, int last) { int partition_index; if (first < last) { partition_index = partition(arr, first, last); # pragma omp task default(none) firstprivate(arr, first, partition_index) { quicksort(arr, first, partition_index - 1); } # pragma omp task default(none) firstprivate(arr, partition_index, last) { quicksort(arr, partition_index + 1, last); } //# pragma omp taskwait } } /*------------------------------------------------------------------- * Function: partition * Purpose: Partition the array/subarray into two subarrays/subproblems * In args: arr: the array to be sorted * first: index to the first element in the partition * last: index to the last element in the partition */ int partition ( int arr[], int first, int last) { int pivot = arr[last]; // last element is the pivot int store_index = first - 1; for (int i = first; i < last; i++) { if (arr[i] <= pivot) { store_index += 1; swap(&arr[store_index], &arr[i]); } } swap(&arr[store_index + 1], &arr[last]); return store_index + 1; } /*------------------------------------------------------------------- * Function: swap * Purpose: Swaps two elements in an array (Auxiliary function) * In args: i: The pointer of an element in the array * j: The pointer of another element in the array */ void swap ( int* i /* in */, int* j /* in */) { int temp = *i; *i = *j; *j = temp; }
C
// #include <codecvt> // #include <string> // #include <iostream> // #include <string> // #include <locale> // #include <iomanip> // #include <stdexcept> // #include <bitset> // using namespace std; #include <stdio.h> #include <stdlib.h> #include <wchar.h> #include <uchar.h> #include <locale.h> #include <wchar.h> /* * The standard library has removed support for printing char32 characters. However, you can create a * null terminated wchar_t string using from the char32_t character and convert it to a multi-byte string * for printing. * * This works because a char32_t character is the same size as a wchar_t character on Unix systems (but * not on Windows). So we create a wchar_t array of size 2 and fill it with nulls. Then we overwrite * element zero with our char32_t before converting to multi-byte with wcstombs. */ void printChar32_t(const char32_t c32) { wchar_t wstr[2] = {}; // fill with nulls wstr[0] = (wchar_t)c32; // overwrite first element // now convert to wide string to multi-byte char mbstr[8] = {}; int bytesConverted = wcstombs(mbstr, wstr, 8); if(bytesConverted != -1) printf("char32_t: %s\n", mbstr); else printf("wcstoms failed to convert char32_t\n"); } int main() { setlocale(LC_ALL, ""); char32_t dollar = 0x0024; char32_t cent = 0x00A2; char32_t euro = 0x20AC; char32_t pài = 0x200A2; printChar32_t(dollar); printChar32_t(cent); printChar32_t(euro); printChar32_t(pài); }
C
/* * Interval abstract domain * - we represent intervals as pairs of 64bit signed numbers, * which should be safe for our NTT */ #ifndef INTERVALS_H #define INTERVALS_H #include <stdint.h> typedef struct interval_s { int64_t min; int64_t max; } interval_t; /* * Constructors: all allocate and return a pointer to an interval * structure. */ extern interval_t *point(int64_t x); extern interval_t *interval(int64_t min, int64_t max); /* * Destructor: just calls free */ extern void delete_interval(interval_t *a); /* * Basic operations */ extern interval_t *add(const interval_t *a, const interval_t *b); extern interval_t *sub(const interval_t *a, const interval_t *b); extern interval_t *neg(const interval_t *a); /* * Reductions * - red(a) = [l, h] such that l <= red(x) <= h for any x in a * - red_mul(a, b) = [l, h] such that l <= red(x * y) <= h for any x in a and y in b. * - red_scale(k, a) = [l, h] such that l <= red(x * k) <= h for any x in a * - red_twice(a) = [l, h] such that l <= red(red(x)) <= h for x in a. */ extern interval_t *red(const interval_t *a); extern interval_t *red_mul(const interval_t *a, const interval_t *b); extern interval_t *red_scale(int64_t k, const interval_t *a); extern interval_t *red_twice(const interval_t *a); /* * Reduction modulo q: [l, h] such that l <= x % q <= h whenever x is in a. * The modulo operation returns an integer between 0 and q-1 here. * - q is 12289. */ extern interval_t *normal(const interval_t *a); /* * Multiply by inverse(3) then reduce modulo q */ extern interval_t *normal_inv3(const interval_t *a); /* * Shift representation: a must be a sub-interval of [0 .. q-1] * - returns [l, h] such that l <= shift(x) <= h where * shift(x) = x if 0 <= x <= (q-1)/2 * shift(x) = x - q if (q-1/2) < x <= q-1 */ extern interval_t *shift(const interval_t *a); /* * Correct: assume x is in the interval [-q, 2*q-1] then * correct(x) is if (x<0) then x+q elsif (x >= q) then x-q else x. * So correct(x) is in thee interval [0 .. q-1] * * Interval a must be a subinterval of [-q, 2q-1] * Correct(a) returns [l, h] such that l <= correct(x) <= h for x in a. */ extern interval_t *correct(const interval_t *a); #endif /* INTERVALS_H */
C
#include <stdio.h> #include <stdlib.h> typedef struct chunkdata { char c; int offset; }chunkdata; int main(int argc, const char * argv[]) { chunkdata data1; FILE *file1; char c; file1 = fopen("crypt.bin","rb"); if (file1 == NULL) { printf("File not found!\n"); return 0; } while(1) { fread(&data1.c,1,sizeof(char),file1); fread(&data1.offset,1,sizeof(int),file1); if (data1.c == 0 && data1.offset == 0) break; c = (char)(data1.c - data1.offset); printf("%c",c); } }
C
/* -------------------------------------------------------------------- Project: PAL: Palmtop Application Library Module: <The name of the module - usually the filename> Author: <The name(s) of the autor(s)> Started: <Date when started> Subject: <What does it do, what is it there for ?> -------------------------------------------------------------------- */ [This is a template for a PAL .C or .H module. Delete the comments in angular brackets when creating a module, and also remember to fill out the header fields. If you modified an existing module, add your name and comments on your modification/extension below the 'Subject:' field, in a 'Modified:' field. Remove empty sections unless you feel that they won't be empty RSN.] /* -------------------------------------------------------------------- standard includes -------------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> [Add more of the standard ANSI C include headers here as needed. Please do add only those #include files that are needed, but do add those. If this module is a .H file, please try to avoid (nested) includes if at all possible. Remove these sections entirely in this case.] /* -------------------------------------------------------------------- msdos includes -------------------------------------------------------------------- */ [MSDOS-specific includes go here if needed, like <bios.h> or <conio.h>] /* -------------------------------------------------------------------- local includes -------------------------------------------------------------------- */ #include "pal.h" #include "palpriv.h" [If your module has an include file in its subdirectory, add it here.] /* -------------------------------------------------------------------- constant definitions -------------------------------------------------------------------- */ [#define FOO 42 stuff] /* -------------------------------------------------------------------- macro definitions -------------------------------------------------------------------- */ [Any #define FOO(bar) foobar(bar) sort of thing] /* -------------------------------------------------------------------- type definitions -------------------------------------------------------------------- */ [for typedefs. Always create a typedef for structures.] /* -------------------------------------------------------------------- global variables -------------------------------------------------------------------- */ [If you _really_ need them, put them here.] /* -------------------------------------------------------------------- prototypes -------------------------------------------------------------------- */ [Add ANSI prototypes here. Prototypes should rarely be needed in .C files - use bottom-up ordering instead.] /* -------------------------------------------------------------------- functions -------------------------------------------------------------------- */ [Here's where your function or functions come in. Please ease full ANSI style headers, i.e. void MyFunction(int x) instead of my_function(x) int x; If you have several functions in a .C file, please order them callee first, then caller, i.e. bottom-up style. This requires less prototypes. Please include a header before each function describing what it does. Avoid 'boxy' comments - they look nice, but are less likely to get updated. No functions should ever appear in .H files of course.]
C
#include <stdio.h> #include <sys/socket.h> #include <stdlib.h> #include <netinet/in.h> #include <unistd.h> pthread_t tid[20]; void *counting(void *faktorial) { pthread_t id=pthread_self(); int i,j,k=1; int a=(int)faktorial; if (a<0) { printf ("Error\n"); } else { for (i=a;i>=1;i--) { k = k*i; } printf ("hasil %d!= %d",a,k); } } int main() { int angka[20],err,faktorial=0,i; char space; while(1) { scanf ("%d%c",&angka[faktorial],&space); faktorial++; if (space == ' ') { break; } } for (i=0;i<faktorial;i++) { err=pthread_create(&(tid[i]),NULL,&counting,NULL);//membuat thread if(err!=0)//cek error { printf("\n can't create thread : [%s]",strerror(err)); exit(EXIT_FAILURE); } } for (i=0;i<faktorial;i++) { pthread_join(tid[i],NULL); } exit(EXIT_SUCCESS); }
C
// // main.c // LRU // // Created by Liam van Leynseele on 11/4/18. // Copyright © 2018 Liam van Leynseele. All rights reserved. // #include <stdio.h> #include <stdlib.h> int main(int argc, const char * argv[]) { int available=atoi(argv[1]); //takles in the number available frames from command line int frames[available]; int faults=0; //counts number of faults int read=0; //counts number of inputs char * input= NULL; size_t allocated=0; ssize_t readin; //var for getline function while (readin=getline(&input, &allocated, stdin)!=-1) { int current_page, j; current_page=atoi(input); int found=available; read++; //increments the number of page request read in from input file for (j=0; j<available; j++) { if (current_page==frames[j]) { found=j; break; } } if (found==available){ faults++; fprintf(stderr,"%d\n",current_page); found--;//set to last index of array, available-1 } for (j=found; j>0; j--) { //move every value up to found one spot forward frames[j]=frames[j-1]; } frames[0]=current_page; } fprintf(stderr,"Number of faults %d\n",faults); fprintf(stderr,"Hit rate = %f\n",(read-faults)/(double)read); return 0; } //3727
C
#include <stdio.h> int main(void) { int a, b, c; printf("Input 3 numbers: "); scanf("%d %d %d", &a, &b, &c); int mx; if (a > b) { if (a > c) { mx = a; } else { mx = c; } } else { if (b > c) { mx = b; } else { mx = c; } } printf("\n%d\n", mx); return 0; }
C
#include<stdio.h> int main(){ int a, b, count; count = 0; scanf("%d%d", &a, &b); while (a<=b){ a*=3; b*=2; count++; } printf("%d", count); return 0; }
C
#include "shell.h" /** * add_history - adds a node to the hist_t list * @count: pointer to hist_count * @head: pointer to first node in hist_t list * @cmd: command line added to history * Return: the added history node */ hist_t *add_history(int *count, hist_t **head, char *cmd) { hist_t *new_node; hist_t *temp_node; if (!cmd || cmd[0] == ' ') return (NULL); new_node = malloc(sizeof(hist_t)); if (!new_node) return (NULL); new_node->cmd = _strdup(cmd); if (!*head) { new_node->index = 0; new_node->next = *head; *head = new_node; } else { *count = *count + 1; new_node->next = NULL; temp_node = *head; while (temp_node->next) temp_node = temp_node->next; new_node->index = *count; temp_node->next = new_node; } return (new_node); }
C
#include <unistd.h> #include <signal.h> #include <pthread.h> #include <stdbool.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #if 0 int pthread_mutex_lock(pthread_mutex_t *mutex); int pthread_mutex_trylock(pthread_mutex_t *mutex); int pthread_mutex_unlock(pthread_mutex_t *mutex); #endif // 0 static pthread_mutex_t power; static long count = 0; void poweron() { int ret = pthread_mutex_trylock(&power); //fprintf(stdout, "poweron: ret = %d\n", ret); if(!ret) { fprintf(stdout, "printer power on...\n"); pthread_mutex_unlock(&power); } } void printer(const char *content) { poweron(); pthread_mutex_lock(&power); while(*content) { fputc(*content, stdout); fflush(stdout); content++; count++; usleep(100 * 1000); } pthread_mutex_unlock(&power); } void *thread01(void *args) { printer("ABCDEFGHIJKLMNOPQRSTUVWXYZ\n"); pthread_exit(NULL); } void *thread02(void *args) { printer("abcdefghijklmnopqrstuvwxyz\n"); pthread_exit(NULL); } int main(int argc, char *argv[]) { pthread_mutex_init(&power, NULL); pthread_t tid1; pthread_t tid2; pthread_create(&tid1, NULL, thread01, NULL); pthread_create(&tid2, NULL, thread02, NULL); pthread_join(tid1, NULL); pthread_join(tid2, NULL); printf("count = %ld\n", count); pthread_mutex_destroy(&power); return 0; }
C
#include <stdio.h> #include <fcntl.h> #include "get_next_line.h" int main(void) { int fd; int return_num; char **output; char *files[10] = {"empty.txt", "1char.txt", "single_line.txt", "60_lines.txt", "3000chars_1line.txt", "3000x300lines.txt", "long.txt", "long_line.txt", "magna_carta.txt"}; for (int i = 0; i < 9; i++) { fd = open(files[i], O_RDONLY); printf("\n\n======fd = %d======\nfilename = %s\n\n", fd, files[i]); int j = 1; output = malloc(sizeof(char **)); while (1) { return_num = get_next_line(fd, output); printf("line%d return = %d\nline = \"%s\"\n", j++, return_num, *output); free(*output); if (return_num != 1) { return_num = get_next_line(fd, output); printf("line%d return = %d\nline = \"%s\"\n", j++, return_num, *output); free(*output); break; } } free(output); } }
C
#include<stdio.h> int main() { int a=20; int b=40; printf("Enter the values of swaping a,b"); a=a^b; b=a^b; printf("values of swaping a,b"); return 0; }
C
main() { int input; syscall_print_string("Please enter a non-negative integer: "); input = syscall_read_int(); if (input < 0){ printf("The integer you entered is negative.\n"); exit(1); } int result = 0; for (int i = 1; i * i < input || i * i == input; i++){ result = i; } printf("%i\n", result); }
C
#pragma once /* * Dependencies : must be included right at the top */ //Dimension of health bar #define LENGTH_OF_BAR 5 #define WIDTH_OF_BAR 0.5 //Dimension of inventory bar #define HEIGHT_OF_INV 1 #define HEIGHT_OF_INFO 1.5 #define LENGTH_OF_INFO 5 //Initializer for UI int screen_width, screen_height; float healthBar_x = 5, healthBar_y = 4; float inventoryBar_x = 5, inventoryBar_y = -4; float selectedItemInfo_x = -5.6, selectedItemInfo_y = 4.2; int number_of_items; static GLuint Infotexture; //Struct for items in inventory struct item { int itemCode; char itemName[25]; int instances; struct item* prev, * next; }; //Doubly Linked List for inventory typedef struct item item; item* inventory, * selectedItem, * temp; //Sets up the DLL for Inventory Management void inventorySetup() { item* p, * q; int i; fscanf(inventoryData, "%d\n", &(number_of_items)); if (number_of_items < 1) { number_of_items = 0; printf("WARNING: Inventory disabled | n<1 in inventorySettings file\n"); } else { inventory = (item*)malloc(sizeof(item)); fscanf(inventoryData, "%d\n", &(inventory->itemCode)); fscanf(inventoryData, "%[^\n]s\n", (inventory->itemName)); fscanf(inventoryData, "%d\n", &(inventory->instances)); inventory->next = NULL; inventory->prev = NULL; q = inventory; for (i = 0; i < number_of_items - 1; i++) { p = (item*)malloc(sizeof(item)); fscanf(inventoryData, "%d\n", &(p->itemCode)); fscanf(inventoryData, "%[^\n]s\n", (p->itemName)); fscanf(inventoryData, "%d\n", &(p->instances)); p->prev = q; q->next = p; p->next = NULL; q = p; } selectedItem = inventory; temp = inventory; printf("Inventory loaded successfully...\n"); /*p = inventory; for (i = 0; i < number_of_items; i++) { printf("%d, %s\n", p->itemCode, p->itemName); p = p->next; }*/ } } //UI Renderer void showUI() { int i = 0, offset = 1, len; char instances[25]; //printf("Screen : %d, %d\n", screen_width, screen_width); //Health Bar Background glColor3f(1, 0, 0); glBegin(GL_QUADS); glVertex3f(healthBar_x, healthBar_y, 0); glVertex3f(healthBar_x - LENGTH_OF_BAR, healthBar_y, 0); glVertex3f(healthBar_x - LENGTH_OF_BAR, healthBar_y - WIDTH_OF_BAR, 0); glVertex3f(healthBar_x, healthBar_y - WIDTH_OF_BAR, 0); //Health Bar Foreground glColor3f(0, 1, 0); glVertex3f(healthBar_x, healthBar_y, 0); glVertex3f(healthBar_x, healthBar_y - WIDTH_OF_BAR, 0); glVertex3f(-LENGTH_OF_BAR * (health / 100)+ healthBar_x, healthBar_y - WIDTH_OF_BAR, 0); glVertex3f(-LENGTH_OF_BAR * (health / 100) + healthBar_x, healthBar_y, 0); glEnd(); glFlush(); //Inventory bar temp = inventory; for (i = 0; i < (number_of_items * offset); i += offset) { if (selectedItem->itemCode == temp->itemCode) { glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBegin(GL_QUADS); glTexCoord2d(0.62, 1); glVertex3f(inventoryBar_x - i, inventoryBar_y, 0); glTexCoord2d(0.88, 1); glVertex3f(inventoryBar_x - i - offset + 0.05, inventoryBar_y, 0); glTexCoord2d(0.88, 0.75); glVertex3f(inventoryBar_x - i - offset + 0.05, inventoryBar_y + HEIGHT_OF_INV, 0); glTexCoord2d(0.62, 0.75); glVertex3f(inventoryBar_x - i, inventoryBar_y + HEIGHT_OF_INV, 0); glEnd(); glDisable(GL_BLEND); glDisable(GL_TEXTURE_2D); } else { glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBegin(GL_QUADS); glTexCoord2d(0, 1); glTexCoord2d(0.4, 1); glVertex3f(inventoryBar_x - i, inventoryBar_y, 0); glTexCoord2d(0.55, 1); glVertex3f(inventoryBar_x - i - offset + 0.05, inventoryBar_y, 0); glTexCoord2d(0.55, 0.8); glVertex3f(inventoryBar_x - i - offset + 0.05, inventoryBar_y + HEIGHT_OF_INV, 0); glTexCoord2d(0.4, 0.8); glVertex3f(inventoryBar_x - i, inventoryBar_y + HEIGHT_OF_INV, 0); glEnd(); glDisable(GL_BLEND); glDisable(GL_TEXTURE_2D); } temp = temp->next; //glVertex3f(/*-(screen_width / 1000) + */inventoryBar_x - i - 0.05, inventoryBar_y + 0.05, 0); //glVertex3f(/*-(screen_width / 1000) + */inventoryBar_x - i - offset + 0.05 + 0.05, inventoryBar_y + 0.05, 0); //glVertex3f(/*-(screen_width / 1000) + */inventoryBar_x - i - offset + 0.05 + 0.05, inventoryBar_y + HEIGHT_OF_INV - 0.05, 0); //glVertex3f(/*-(screen_width / 1000) + */inventoryBar_x - i - 0.05, inventoryBar_y + HEIGHT_OF_INV - 0.05, 0); } glFlush(); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //Equipped Item info glBegin(GL_QUADS); glTexCoord2d(1, 0.4); glVertex3f(selectedItemInfo_x, selectedItemInfo_y, 0); glTexCoord2d(0, 0.4); glVertex3f(selectedItemInfo_x + LENGTH_OF_INFO, selectedItemInfo_y, 0); glTexCoord2d(0, 0.6); glVertex3f(selectedItemInfo_x + LENGTH_OF_INFO, selectedItemInfo_y - HEIGHT_OF_INFO, 0); glTexCoord2d(1, 0.6); glVertex3f(selectedItemInfo_x, selectedItemInfo_y - HEIGHT_OF_INFO, 0); glEnd(); glDisable(GL_BLEND); glDisable(GL_TEXTURE_2D); glColor3f(0, 0, 0); glRasterPos3f(selectedItemInfo_x + LENGTH_OF_INFO - 1.5, selectedItemInfo_y - 0.7, 0); len = strlen(selectedItem->itemName); for (i = 0; i < len; i++) { glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, (selectedItem->itemName)[i]); } glRasterPos3f(selectedItemInfo_x + LENGTH_OF_INFO - 1.5, selectedItemInfo_y - 0.9, 0); sprintf(instances, "Ammo: %d", selectedItem->instances); len = strlen(instances); for (i = 0; i < len; i++) { glutBitmapCharacter(GLUT_BITMAP_9_BY_15, instances[i]); } glColor3f(1, 1, 1); }
C
// ¥ D-Day ϰ D-Day Ҵ ϴ α׷ ۼϼ. #include <stdio.h> #include <time.h> #pragma warning(disable:4996) #define DAYSEC 86400L void main(void) { time_t now; struct tm t, dday = { 0,0,0,8,8,2020 }; //2005 8 8 int n1, n2, nDday; now = time(NULL); localtime_s(&t, &now); dday.tm_year -= 1900; dday.tm_mon -= 1; t.tm_hour = 0; t.tm_min = 0; t.tm_sec = 0; n1 = mktime(&t); //ð ʷιٲ n2 = mktime(&dday); //DDAY ʷ ٲ. nDday = (n2 - n1) / DAYSEC; printf(" ¥ %s", ctime(&now)); printf("ּ : %d ҽϴ. (%d/%d/%d)\n", nDday, dday.tm_year + 1900, dday.tm_mon + 1, dday.tm_mday); } //α׷ ̽ļ̶ α׷ ҽ ڵ带  ȯ濡 ٸ ȯ 󸶳 ̵ų ִ ϴ Դϴ. //C ̽ļ α׷ ϳ.
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> void printArray(int arr[], int n) { printf("Orignal array:-\n"); for (int i = 0; i < n; i++) { printf("%d\t", arr[i]); } printf("\n"); } //Question 1 int count_sort_MP(int arr[], int n) { int max = arr[0]; int arr2[n]; for (int i = 0; i < n; i++) { if (arr[i] > max) { max = arr[i]; } } int freq[max + 1]; memset(freq, 0, sizeof(freq)); for (int i = 0; i < n; i++) { freq[arr[i]] += 1; } int max2 = 0, t = 0; for (int i = 0; i < max + 1; i++) { if (freq[i] >= max2) { max2 = freq[i]; t = i; } } //Sorting the array for (int i = 1; i < max + 1; i++) { freq[i] += freq[i - 1]; } for (int i = 0; i < n; i++) { arr2[--freq[arr[i]]] = arr[i]; } for (int i = 0; i < n; i++) { arr[i] = arr2[i]; } return t; } //Question 2 int partition(int arr[], int low, int high) { int pivot = arr[high]; int i = (low - 1); for (int j = low; j <= high - 1; j++) { if (arr[j] < pivot) { i++; int r = arr[i]; arr[i] = arr[j]; arr[j] = r; } } int r = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = r; return (i + 1); } void quick_sort(int arr[], int low, int high) { int index; if (low < high) { index = partition(arr, low, high); quick_sort(arr, low, index - 1); quick_sort(arr, index + 1, high); } } void Pair_of_sum(int arr[], int n) { int k = rand() % 99 + 1; printf("The sum to be searched: %d", k); int maximum = arr[0]; for (int i = 1; i < n; i++) { if (maximum < arr[i]) maximum = arr[i]; } int digits = 0; while (maximum > 0) { digits++; maximum /= 10; } int power = 1; for (int i = 0; i < digits; i++) { int new_array[n]; int count[10]; for (int j = 0; j < 10; j++) count[j] = 0; for (int j = 0; j < n; j++) { int num = (arr[j] / power) % 10; count[num]++; } for (int j = 1; j < 10; j++) { count[j] += count[j - 1]; } for (int j = n - 1; j >= 0; j--) { int num = (arr[j] / power) % 10; new_array[count[num] - 1] = arr[j]; count[num]--; } for (int j = 0; j < n; j++) arr[j] = new_array[j]; power *= 10; } int l = -1, h = -1, cnt = 0; printf("\nPairs generating the sum:"); for (int i = 0; i < n && arr[i] <= k; i++) { l = i; for (int j = l; j < n; j++) { if (arr[l] + arr[j] == k) { h = j; } if (l != -1 && h != -1) { printf("%d %d\n", arr[l], arr[h]); cnt++; } h = -1; } } if (cnt == 0) { printf(" No such Pair found\n"); } } int main() { //Question 1 printf("\nQuestion1:-\n"); printf("\n"); srand((unsigned int)time(NULL)); int n = 10; int arr1[n], arr2[n], arr3[n]; for (int i = 0; i < n; i++) { arr1[i] = rand() % 99 + 1; arr2[i] = rand() % 99 + 1; arr3[i] = rand() % 99 + 1; } printArray(arr1, n); printf("Value with max frequency = %d\n", count_sort_MP(arr1, n)); printf("\n"); printf("The time complexity of quick sort is O(n+k)\nThe space complexity of quick sort is O(n+k)/n\n"); printf("---------------------------------------------------------------------------\n"); //Question 2 printf("\nQuestion2:-\n"); printf("\n"); printArray(arr2, n); quick_sort(arr2, 0, n - 1); printf("\nMaximum product of two integers(%d , %d) in array = %d\n", arr2[n - 1], arr2[n - 2], arr2[n - 1] * arr2[n - 2]); printf("\n"); printf("The time complexity of quick sort is O(n^2)\nThe space complexity of quick sort is O(logn)\n"); printf("---------------------------------------------------------------------------\n"); //Question 3 printf("\nQuestion3:-\n"); printf("\n"); printArray(arr3, n); printf("\n"); Pair_of_sum(arr3, n); printf("\nThe time complexity of sorting array using Radix sort is O(d(n+k))\nThe space complexity of radix sort is O(n+k)\n"); printf("---------------------------------------------------------------------------\n"); return 0; }
C
#include "printflib.h" #include <stdio.h> void clean_printing_format(printing_format *formated_str) { formated_str->flag = '\0'; formated_str->width = '\0'; formated_str->id = '\0'; formated_str->precision = 0; formated_str->zero_fill = false; formated_str->validity = false; } void print_printing_format(printing_format *formated_str) { printf("flag=>%c\n", formated_str->flag); printf("width=>%i\n", formated_str->width); printf("mod=>%s\n", formated_str->mod); printf("id=>%c\n", formated_str->id); printf("precision=>%i\n", formated_str->precision); printf("zero_fill=>%u\n", formated_str->zero_fill); printf("validity=>%u\n", formated_str->validity); printf("word.tok=>%s\n", formated_str->word.tok); printf("word.type =>%s\n", formated_str->word.type); printf("=>-------------------------------------------\n\n\n"); } /** * _printf - a function that prints anything using * posix callex via the write function * @format: formated string to be printed * Return: the number of things printed */ int _printf(const char *format, ...) { va_list items; char *t_str = NULL, *str = NULL, *str_mod = smalloc(20), *replaced = NULL; edge **grammer_list = prepare_lexer(); /*make it null here and creat it in the function*/ printing_format *formated_str = smalloc(sizeof(printing_format)); printing_format *returned = NULL; /*accepting state of the different lexer grammers at index*/ /*abstract this away in some function call*/ int accepting[] = {7, 6, 5, 4, 6, 5, 4, 3, 6, 5, 4, 4, 5, 4, 3, 2, 1}; int i = 0; /*open printer*/ printer(NULL, 0); if (!format || (*format == '%' && _strlen((char *)format) == 1)) return (-1); str = _strdup((char *)format); t_str = str; formated_str->word.tok = smalloc(100); va_start(items, format); while (true) { returned = NULL; /*clean up the format holder*/ clean_printing_format(formated_str); i = 0; while (!returned && i < 17) formated_str->replaced = 0, returned = fsm_sim(0, str, grammer_list[i], accepting[i], 0, formated_str, str_mod), i += 1; print_printing_format(formated_str); str += formated_str->replaced; if (is_valid(formated_str)) { formated_str->formater = get_formater(formated_str->id); if (!(formated_str->formater)) return (0); replaced = (formated_str->formater)(items, formated_str); printer(replaced, 1); } else printer(formated_str->word.tok, 1); if (!str) break; if (!_strlen(str)) break; _strcpy(formated_str->word.tok, ""); _strcpy(str_mod, ""); } /*Print everything in the que*/ printer(NULL, 2); free(t_str); va_end(items); return (10); } /*parser()*/ /*{*/ /*}*/
C
#include <stdio.h> union U { struct s { char c; int p; } s; struct t { char c; double p; } t; struct v { char c; char* p; } v; }; int main() { union U u; char c = 'c'; u.v.c = '*'; u.v.p = &c; printf("%u\n", u.s.p); printf("%lf\n", u.t.p); printf("%u\n", *(u.v.p)); printf("%c\n", u.s.c); printf("%c\n", u.t.c); printf("%c\n", u.v.c); printf("%p\n", &u.v.c); printf("%p\n", &u.s.p); printf("%p\n", &u.t.p); printf("%p\n", &u.v.p); printf("%lu\n", sizeof(u)); return 0; }
C
/* criterion(1) * criterion(1) is a tools that can be used by manager of the organization * to made a decision under uncertainty environment. * * Please see README.md for the details. * * Copyright 2015 Bayu Aldi Yansyah <bayualdiyansyah@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <stdlib.h> int main(void) { printf("============================================================\n"); printf("== Keputusan Dalam Ketidakpastian ==\n"); printf("============================================================\n"); printf("Masukkan jumlah tindakan (T) : "); int ntindakan = 0; if(scanf("%d", &ntindakan) != 1 || ntindakan == 0 || ntindakan > 99) { printf("Jumlah tindakan maksimal adalah 99.\n"); exit(EXIT_FAILURE); } printf("Masukkan jumlah keadaan/kejadian (K) : "); int nkejadian = 0; if(scanf("%d", &nkejadian) != 1 || nkejadian == 0 || nkejadian > 99) { printf("Jumlah keadaan/kejadian maksimal adalah 99.\n"); exit(EXIT_FAILURE); } /* Allocate memory for payoff matrix; * PAYOFF_M is an array of array of float. We allocate contiguous * NTINDAKAN block of memory with size SIZEOF *PAYOFF_M for each * block.*/ float **payoff_m = calloc(ntindakan, sizeof *payoff_m); int i = 0, j = 0; for(i = 0; i < ntindakan; i++) { payoff_m[i] = calloc(nkejadian, sizeof *payoff_m[i]); for(j = 0; j < nkejadian; j++) { printf("Masukkan nilai untuk V(T%d, K%d) : ", i + 1, j + 1); if(scanf("%f", &payoff_m[i][j]) != 1) { printf("Exit, Pastikan input anda benar.\n"); exit(EXIT_FAILURE); } } } printf("\n"); /* Print the matrix payoff to the STDOUT */ printf("============================================================\n"); printf("== Matriks Payoff ==\n"); printf("============================================================\n"); /* Table header */ for(j = 0; j < nkejadian; j++) { if(j == 0) { printf(" K(%d)", j + 1); } else { printf(" K(%d)", j + 1); } } printf("\n"); for(i = 0; i < ntindakan; i++) { printf("T(%d) ", i + 1); for(j = 0; j < nkejadian; j++) { printf("%8.4f ", payoff_m[i][j]); } printf("\n"); } printf("\n"); printf("============================================================\n"); printf("== Analisa 4 Kriteria ==\n"); printf("============================================================\n"); printf("1. Kriteria Laplace\n"); printf(" Ketik 1 untuk Maximum 2 untuk Minimum : "); int lp_n = 0; if(scanf("%d", &lp_n) != 1 || lp_n < 0 || lp_n > 2) { printf("\nInput anda tidak valid.\n"); exit(EXIT_FAILURE); } printf("%d\n", lp_n); /* Maximum */ if(lp_n == 1) { printf(" Maximum terpilih\n"); } /* Minimum */ if(lp_n == 2) { printf(" Minimum terpilih\n"); } /* for maximum */ float lp_t_max = 0.0; int lp_t_max_i = 0; /* for minimum */ float lp_t_min = 0.0; int lp_t_min_i = 0; for(i = 0; i < ntindakan; i++) { float tindakan_sum = 0.0; for(j = 0; j < nkejadian; j++) { tindakan_sum += payoff_m[i][j]; } /* set as the first row value; this * will handle negative values */ if(i == 0) { lp_t_max = tindakan_sum; lp_t_min = tindakan_sum; } tindakan_sum = (1 / (float)nkejadian) * tindakan_sum; printf(" * T%d: %f\n", i + 1, tindakan_sum); if(tindakan_sum > lp_t_max) { lp_t_max = tindakan_sum; lp_t_max_i = i + 1; } if(tindakan_sum < lp_t_min) { lp_t_min = tindakan_sum; lp_t_min_i = i + 1; } } if(lp_n == 1) { printf(" Tindakan yang dipilih = T%d\n", lp_t_max_i); } if(lp_n == 2) { printf(" Tindakan yang dipilih = T%d\n", lp_t_min_i); } printf("\n"); printf("2. Kriteria Wald\n"); printf(" Ketik 1 untuk Maximin 2 untuk Minimax : "); int wald_n = 0; int wald_t_i = 0; /* Ti choosed */ if(scanf("%d", &wald_n) != 1 || wald_n < 0 || wald_n > 2) { printf("\nInput anda tidak valid.\n"); exit(EXIT_FAILURE); } /* Minimax * We choose the maximum of Kj and the minimum of Ti */ float minimax_t_min = 0.0; /* Maximin * We choose the minimum of Kj and the maximum of Ti */ float maximin_t_max = 0.0; /* Maximin */ if(wald_n == 1) { printf(" Maximin terpilih\n"); } /* Minimax */ if(wald_n == 2) { printf(" Minimax terpilih\n"); } for(i = 0; i < ntindakan; i++) { /* Kmax & Kmin should reset for each row */ float minimax_k_max = 0.0; float maximin_k_min = 0.0; for(j = 0; j < nkejadian; j++) { float kj = payoff_m[i][j]; /* set the first Kj in a row as default value */ if(j == 0) { maximin_k_min = kj; minimax_k_max = kj; } if(kj < maximin_k_min) { maximin_k_min = kj; } if(kj > minimax_k_max) { minimax_k_max = kj; } } /* set the first value */ if(i == 0) { maximin_t_max = maximin_k_min; minimax_t_min = minimax_k_max; } /* Maximin */ if(wald_n == 1) { printf(" * T%d: %f\n", i + 1, maximin_k_min); if(maximin_k_min > maximin_t_max) { maximin_t_max = maximin_k_min; wald_t_i = i + 1; } } /* Minimax */ if(wald_n == 2) { printf(" * T%d: %f\n", i + 1, minimax_k_max); if(minimax_k_max < minimax_t_min) { minimax_t_min = minimax_k_max; wald_t_i = i + 1; } } } printf(" Tindakan yang dipilih = T%d\n", wald_t_i); printf("\n"); printf("3. Kriteria Savage Minimax Regret\n"); printf(" Ketik 1 jika V(Ti,Kj) laba; 2 jika V(Ti, Kj) kerugian : "); int savage_n = 0; if(scanf("%d", &savage_n) != 1 || savage_n < 0 || savage_n > 2) { printf("\nInput anda tidak valid.\n"); exit(EXIT_FAILURE); } /* create new table; copy payoff matrix */ float **savage_payoff = calloc(ntindakan, sizeof *savage_payoff); for(i = 0; i < ntindakan; i++) { savage_payoff[i] = calloc(nkejadian, sizeof *savage_payoff[i]); for(j = 0; j < nkejadian; j++) { savage_payoff[i][j] = payoff_m[i][j]; } } for(j = 0; j < nkejadian; j++) { /* savage_v_max & savage_v_min should reset for each column */ float savage_v_max = 0.0; float savage_v_min = 0.0; for(i = 0; i < ntindakan; i++) { /* set the first V(Tk, Kj) as default value */ if(i == 0) { savage_v_max = savage_payoff[i][j]; savage_v_min = savage_payoff[i][j]; } if(savage_payoff[i][j] > savage_v_max) { savage_v_max = savage_payoff[i][j]; } if(savage_payoff[i][j] < savage_v_min) { savage_v_min = savage_payoff[i][j]; } } for(i = 0; i < ntindakan; i++) { if(savage_n == 1) { savage_payoff[i][j] = savage_v_max - savage_payoff[i][j]; } if(savage_n == 2) { savage_payoff[i][j] -= savage_v_min; } } } printf(" =========================================================\n"); printf(" == Tabel Kerugian Baru ==\n"); printf(" =========================================================\n"); /* Table header */ for(j = 0; j < nkejadian; j++) { if(j == 0) { printf(" K(%d)", j + 1); } else { printf(" K(%d)", j + 1); } } printf("\n"); for(i = 0; i < ntindakan; i++) { printf(" T(%d) ", i + 1); for(j = 0; j < nkejadian; j++) { printf("%8.4f ", savage_payoff[i][j]); } printf("\n"); } printf("\n"); /* Minimax for a new payoff matrix */ int savage_t_i = 0; float s_minimax_t_min = 0.0; printf(" Hasil Kriteria Minimax: \n"); for(i = 0; i < ntindakan; i++) { float s_minimax_k_max = 0.0; for(j = 0; j < nkejadian; j++) { float kj = savage_payoff[i][j]; if(kj > s_minimax_k_max) { s_minimax_k_max = kj; } } printf(" * T%d: %f\n", i + 1, s_minimax_k_max); /* set the first maximum Kj as minimum Ti */ if(i == 0) { s_minimax_t_min = s_minimax_k_max; } if(s_minimax_k_max < s_minimax_t_min) { s_minimax_t_min = s_minimax_k_max; savage_t_i = i + 1; } } printf(" Tindakan yang dipilih = T%d\n", savage_t_i); printf("\n"); printf("4. Kriteria Hurwics\n"); printf(" Ketik 1 jika V(Ti,Kj) laba; 2 jika V(Ti, Kj) biaya : "); int hrw_n = 0; int hrw_t_i = 0; if(scanf("%d", &hrw_n) != 1 || hrw_n <= 0 || hrw_n > 2) { printf("\nInput anda tidak valid.\n"); exit(EXIT_FAILURE); } printf("%d\n", hrw_n); printf(" Masukkan nilai indeks optimisme : "); float hrw_io = 0; if(scanf("%f", &hrw_io) != 1 || hrw_io < 0.0 || hrw_io > 1.0) { printf("\nInput anda tidak valid.\n"); exit(EXIT_FAILURE); } printf("%8.4f\n", hrw_io); printf(" Max Min Expected Value\n"); float hrw_v_max = 0.0; float hrw_v_min = 0.0; for(i = 0; i < ntindakan; i++) { float hrw_max = 0.0; float hrw_min = 0.0; float hrw_v = 0.0; for(j = 0; j < nkejadian; j++) { float kj = payoff_m[i][j]; /* Reset value for each row */ if(j == 0) { hrw_min = kj; hrw_max = kj; } if(kj > hrw_max) { hrw_max = kj; } if(kj < hrw_min) { hrw_min = kj; } } /* profit */ if(hrw_n == 1) { hrw_v = (hrw_io * hrw_max) + (1.0 - hrw_io) * hrw_min; if(i == 0) { hrw_v_max = hrw_v; } if(hrw_v > hrw_v_max) { hrw_v_max = hrw_v; hrw_t_i = i + 1; } } /* loss */ if(hrw_n == 2) { hrw_v = (hrw_io * hrw_min) + (1.0 - hrw_io) * hrw_max; if(i == 0) { hrw_v_min = hrw_v; } if(hrw_v < hrw_v_min) { hrw_v_min = hrw_v; hrw_t_i = i + 1; } } printf(" T(%d) %8.4f %8.4f %8.4f\n", i+1, hrw_max, hrw_min, hrw_v); } printf(" Tindakan yang dipilih = T%d\n", hrw_t_i); printf("\n"); /* deallocate the memory */ for(i = 0; i < ntindakan; i++) { free(payoff_m[i]); free(savage_payoff[i]); payoff_m[i] = NULL; savage_payoff[i] = NULL; } free(payoff_m); free(savage_payoff); payoff_m = NULL; savage_payoff = NULL; return EXIT_SUCCESS; }
C
#include "gds.h" void register_mod_fileds(struct module *mod, char *opt, char *usage, struct mod_table *table, struct mod_info *info, int n_item, int n_col, void *data_collect) { sprintf(mod->opt_line, "%s", opt); sprintf(mod->usage, "%s", usage); mod->table = table; mod->info = info; mod->n_item = n_item; mod->n_col = n_col; mod->data_collect = data_collect; } void set_mod_record(struct module *mod, char *record) { } /* * load module from dir */ void load_modules() { char buf[LEN_128] = {0}; char mod_path[LEN_128] = {0}; struct module *mod = NULL; int (*mod_register)(struct module *); int i; /* get the full path of modules */ sprintf(buf, "/usr/local/gds/modules"); for (i = 0; i < statis.total_mod_num; i++) { mod = &mods[i]; if (!mod->lib) { memset(mod_path, '\0', LEN_128); snprintf(mod_path, LEN_128, "%s/%s.so", buf, mod->name); logRecord(LOG_INFO, "%s(%d): load_modules: %s\n", __FUNCTION__, __LINE__, mod_path); if (!(mod->lib = dlopen(mod_path, RTLD_NOW|RTLD_GLOBAL))) { logRecord(LOG_ERR, "%s(%d): dlopen module %s err %s\n", __FUNCTION__, __LINE__, mod->name, dlerror()); } else { mod_register = dlsym(mod->lib, "mod_register"); if (dlerror()) { logRecord(LOG_ERR, "%s(%d): dlsym module %s err %s\n", __FUNCTION__, __LINE__, mod->name, dlerror()); } else { mod_register(mod); mod->enable = 1; logRecord(LOG_INFO, "%s(%d): load new module '%s' to mods\n", __FUNCTION__, __LINE__, mod_path); } } } } } /* * match return 1 */ int is_include_string(char *mods, char *mod) { char *token, n_str[LEN_512] = {0}; memcpy(n_str, mods, strlen(mods)); token = strtok(n_str, DATA_SPLIT); while (token) { if (!strcmp(token, mod)) { return 1; } token = strtok(NULL, DATA_SPLIT); } return 0; } /* * reload modules by mods, if not find in mods, then set module disable */ void reload_modules(char *s_mod) { int i; struct module *mod; if (!s_mod || !strlen(s_mod)) return; for (i = 0; i < statis.total_mod_num; i++) { mod = &mods[i]; if (is_include_string(s_mod, mod->name) || is_include_string (s_mod, mod->opt_line)) mod->enable = 1; else mod->enable = 0; } } /* * 1.alloc or realloc store array * 2.set mod->n_item */ void init_module_fields() { struct module *mod = NULL; int i; for (i = 0; i < statis.total_mod_num; i++) { mod = &mods[i]; if (!mod->enable) continue; /* get mod->n_item first, and mod->n_item will be reseted in reading next line */ if (mod->n_item) { mod->emp_array = (double *)calloc(mod->emp_record * mod->n_col, sizeof(U_64)); mod->amp_array = (double *)calloc(mod->amp_record * mod->n_col, sizeof(U_64)); mod->ser_array = (double *)calloc(mod->ser_record * mod->n_col, sizeof(double)); } } } /* * 1.realloc store array when mod->n_item is modify */ void realloc_module_array(struct module *mod, int n_n_item) { if (n_n_item > mod->n_item) { if (mod->emp_array) { mod->emp_array = (double *)realloc(mod->emp_array, n_n_item * mod->n_col * sizeof (U_64)); mod->amp_array = (double *)realloc(mod->amp_array, n_n_item * mod->n_col * sizeof (U_64)); mod->ser_array = (double *)realloc(mod->ser_array, n_n_item * mod->n_col * sizeof (double)); } else { mod->emp_array = (double *)calloc(mod->emp_record * mod->n_col, sizeof(U_64)); mod->amp_array = (double *)calloc(mod->amp_record * mod->n_col, sizeof(U_64)); mod->ser_array = (double *)calloc(mod->ser_record * mod->n_col, sizeof(double)); } } } /* * set st result in ser_array */ void set_st_record(struct module *mod) { } /* * computer mod->ser_array and swap cur_info to pre_info * return: 1 -> ok * 0 -> some mod->n_item have modify will reprint header */ int collect_record_stat() { return 0; } /* * free module info */ void free_modules() { int i; struct module *mod; for (i = 0; i < statis.total_mod_num; i++) { mod = &mods[i]; if (mod->lib) dlclose(mod->lib); if (mod->emp_array) { free(mod->emp_array); mod->emp_array = NULL; } if (mod->amp_array) { free(mod->amp_array); mod->amp_array = NULL; } if (mod->ser_array) { free(mod->ser_array); mod->ser_array = NULL; } } } /* * read line from file to mod->record */ void read_line_to_module_record(char *line) { } /* * if col num is zero then disable module */ void disable_col_zero() { struct module *mod = NULL; int i; for (i = 0; i < statis.total_mod_num; i++) { mod = &mods[i]; if (!mod->enable) continue; if (!mod->n_col) mod->enable = 0; } }
C
#include <stdio.h> #include <stdbool.h> int main() { int n, m; scanf("%d %d", &n, &m); int clock = 0; // last clock int current_clock; // clock of the current reference int page_id; // id of referenced page int hits = 0; // count of hits happened int misses = 0; // count of misses happened int virtual_memory[n][2]; // table of n rows with id of each page and its counter of references for(int i = 0; i < n; i++){ // initially all ids are -1 and counters are 0 virtual_memory[i][0] = -1; virtual_memory[i][1] = 0; } int r_bits[n]; for(int i = 0; i < n; i++){ r_bits[i] = 0; } for(int i = 0; i < m; i++){ scanf("%d %d", &current_clock, &page_id); if(current_clock > clock){ // if clock has been changed, then we should update counters in virtual memory using R bits clock = current_clock; for(int j = 0; j < n; j++){ virtual_memory[j][1] = (virtual_memory[j][1] >> 1) | (r_bits[j] << 7); r_bits[j] = 0; } } bool hit = 0; for(int j = 0; j < n; j++){ // trying to find id in virtual memory if(virtual_memory[j][0] == page_id){ r_bits[j] = 1; hit = 1; // if found, then hit happened break; } } if(hit){ hits++; printf("1\n"); }else{ // if hit didn't happen, the it's miss misses++; printf("0\n"); int min_counter = 256; int id_of_min; int index_of_min; for(int j = 0; j < n; j++){ // finding the page with the oldest reference or the empty row if(virtual_memory[j][1] < min_counter){ min_counter = virtual_memory[j][1]; id_of_min = virtual_memory[j][0]; index_of_min = j; }else if(virtual_memory[j][1] == min_counter && virtual_memory[j][0] < id_of_min){ id_of_min = virtual_memory[j][0]; index_of_min = j; } } virtual_memory[index_of_min][0] = page_id; virtual_memory[index_of_min][1] = 0; r_bits[index_of_min] = 1; } } double ratio = (double) hits / (double) misses; printf("%f", ratio); return 0; }
C
#include <include.h> #include BINARY_SEARCH_TREE_H void Execute_Tree(void) { int Option; MyBTree* Bin_Tree = GetMyBTree(); while (1) { printf_s("1. Insert Element\n2. In Order Traversal\n3. Pre Order Traversal\n"); printf_s("4. Post Order Traversal\n5. Find Element\n6. Delete Element\n"); switch (Option) { case 1: { printf_s("Enter the Element : \n"); scanf_s("%d", &Option); if (MyBTree_InsertElement(Bin_Tree, Option)) { printf_s("Element inserted successfully\n"); } else { printf_s("Failed at inserting element\n"); } break; } case 5: { printf_s("Enter the Element : \n"); scanf_s("%d", &Option); if (MyBTree_FindElement(Bin_Tree, Option)) { printf_s("Element found!\n"); } else { printf_s("Element not found!\n"); } break; } } } }
C
#include<stdio.h> int main() { int i,j,a=1; //~ scanf("%d",&n); for(i=1;i<=5;i++) { for(j=1;j<=7;j++) { if(a>31) { break; } else if(a%2==0) { printf("** "); } else if(a==17||a==31) { printf("$$ "); } else { printf("%02d ",a); } a++; } printf("\n"); } return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_5__ TYPE_2__ ; typedef struct TYPE_4__ TYPE_1__ ; /* Type definitions */ typedef int mode_t ; struct TYPE_4__ {int st_mode; int /*<<< orphan*/ st_gid; int /*<<< orphan*/ st_uid; } ; struct TYPE_5__ {int /*<<< orphan*/ name; TYPE_1__ sb; int /*<<< orphan*/ type; } ; typedef TYPE_2__ ARCHD ; /* Variables and functions */ int FILEBITS ; int O_CREAT ; int O_EXCL ; int O_TRUNC ; int O_WRONLY ; scalar_t__ chk_path (int /*<<< orphan*/ ,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ; int errno ; scalar_t__ nodirs ; int open (int /*<<< orphan*/ ,int,int) ; int /*<<< orphan*/ syswarn (int,int,char*,int /*<<< orphan*/ ) ; scalar_t__ unlnk_exist (int /*<<< orphan*/ ,int /*<<< orphan*/ ) ; int file_creat(ARCHD *arcn) { int fd = -1; mode_t file_mode; int oerrno; /* * assume file doesn't exist, so just try to create it, most times this * works. We have to take special handling when the file does exist. To * detect this, we use O_EXCL. For example when trying to create a * file and a character device or fifo exists with the same name, we * can accidentally open the device by mistake (or block waiting to * open). If we find that the open has failed, then spend the effort * to figure out why. This strategy was found to have better average * performance in common use than checking the file (and the path) * first with lstat. */ file_mode = arcn->sb.st_mode & FILEBITS; if ((fd = open(arcn->name, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, file_mode)) >= 0) return(fd); /* * the file seems to exist. First we try to get rid of it (found to be * the second most common failure when traced). If this fails, only * then we go to the expense to check and create the path to the file */ if (unlnk_exist(arcn->name, arcn->type) != 0) return(-1); for (;;) { /* * try to open it again, if this fails, check all the nodes in * the path and give it a final try. if chk_path() finds that * it cannot fix anything, we will skip the last attempt */ if ((fd = open(arcn->name, O_WRONLY | O_CREAT | O_TRUNC, file_mode)) >= 0) break; oerrno = errno; if (nodirs || chk_path(arcn->name,arcn->sb.st_uid,arcn->sb.st_gid) < 0) { syswarn(1, oerrno, "Unable to create %s", arcn->name); return(-1); } } return(fd); }
C
// // Created by bear on 2021-03-30. // #ifndef ECS_BITWISE_H #define ECS_BITWISE_H #include <stdio.h> #include <stdint.h> #include <stdbool.h> typedef uint64_t bits64; #define BITWISE_IS_COVER(bits,b) ((bits | b) == bits) #define BITWISE_SET_TRUE_AT(bits,index) (bits | (((bits64)1) << index)) #define BITWISE_SET_FALSE_AT(bits,index) (bits & (~(((bits64)1) << index))) #define BITWISE_IS_TRUE_AT(bits,index) (bitwise_set_true_at(bits, index) == bits) #define BITWISE_IS_FALSE_AT(bits,index) (!bitwise_is_true_at(bits,index)) #define BITWISE_VALUE_AT(bits,index) (bitwise_is_true_at(bits,index)) static inline bits64 char_to_bits(const char *s) { bits64 i = 0; while (*s) { i <<= 1; i += *s++ - '0'; } return i; } static inline bits64 bits_to_char(bits64 bits) { for (int bit_index = sizeof(bits)-1; bit_index >= 0; --bit_index) { bool bit = bits >> bit_index & true; printf("%d", bit); } } bits64 bitwise_contain(bits64 bits, bits64 b){ return (bits | b) == bits; } bits64 bitwise_set_true_at(bits64 bits, int index){ return bits | (((bits64)1) << index); } bits64 bitwise_set_false_at(bits64 bits, int index){ return bits & (~(((bits64)1) << index)); } bool bitwise_is_true_at(bits64 bits, int index){ return bitwise_set_true_at(bits, index) == bits; } bool bitwise_is_false_at(bits64 bits, int index){ return !bitwise_is_true_at(bits,index); } bool bitwise_value_at(bits64 bits, int index){ return bitwise_is_true_at(bits,index); } #endif //ECS_BITWISE_H
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* realloc.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sle-guil <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/02/17 17:44:49 by sle-guil #+# #+# */ /* Updated: 2017/02/17 17:45:08 by sle-guil ### ########.fr */ /* */ /* ************************************************************************** */ #include "malloc.h" static void *st_norme(void *ptr, t_alloc *alloc, size_t size) { void *ret; ret = ptr; pthread_mutex_lock(&(g_saved.lock)); if (alloc->size < M && size < M && alloc->next && alloc->size < size \ && alloc->size + alloc->next->size > size && alloc->next->is_free) { alloc->size += alloc->next->size + sizeof(t_alloc); alloc->next = alloc->next->next; pthread_mutex_unlock(&(g_saved.lock)); } else if (alloc->size < size) { pthread_mutex_unlock(&(g_saved.lock)); ret = malloc(size); } else pthread_mutex_unlock(&(g_saved.lock)); return (ret); } void *realloc(void *ptr, size_t size) { void *ret; t_alloc *alloc; if (!ptr) return (malloc(size)); alloc = (t_alloc*)ptr; alloc--; pthread_mutex_lock(&(g_saved.lock)); if (!is_alloc(ptr)) { pthread_mutex_unlock(&(g_saved.lock)); return (NULL); } pthread_mutex_unlock(&(g_saved.lock)); ret = st_norme(ptr, alloc, size); if (!ret) return (NULL); if (ret != ptr) { ft_memcpy(ret, ptr, (alloc->size < size) ? alloc->size : size); free(ptr); } return (ret); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_t_string_concat.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sclolus <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/03/28 01:19:16 by sclolus #+# #+# */ /* Updated: 2017/09/18 18:40:58 by sclolus ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" t_string *ft_t_string_concat(t_string *string, char *str) { uint64_t total_len; uint64_t str_len; if (!str || !string) return (NULL); str_len = ft_strlen(str); total_len = string->len + str_len; if (total_len >= string->capacity) { ft_t_string_expand(string); return (ft_t_string_concat(string, str)); } else { ft_memcpy(string->string + string->len, str, str_len); string->len = total_len; string->string[string->len] = '\0'; } return (string); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> //input shouldn't be longer than 1024 characters #define MAX 1024 int main(){ //Open file with strings FILE * letter; letter = fopen("letter.txt", "r"); //declare and initialize n int n = 0; //prompts user for input printf("Enter a number for n: "); //read what the user types in: %i is an integer variable from an console //also it reads it into a variable &n scanf("%i", &n); //declare a dynamically allocated array using malloc which //allocates the specific number of bytes //to store the strings //Allocate a memory of n bytes on the heap char * array = (char*)malloc(sizeof(char)); //array = (char*)malloc(n*sizeof(char)); //reading in the file with fgets() //char *fgets(char *str, int n, FILE *stream) //safe because it checks array bounds int i; fgets(array, n, letter); //gets rid of the \n fgets produces //size_t is an unsigned int type //find the last value and replaces it size_t len = strlen(array)-1; if(array[len] == '\n') array[len] = '\0'; //print the array for(i = 0; i < n; i++){ printf("%s", &array[i]); } return 0; }
C
#include <stdio.h> int main() { printf("Hello World\n"); printf("This is change\n"); printf("This is second change\n"); return 0; }
C
/******************** * CPE 101 Section 9 * * Dr. Campbell * * Shiva Empranthiri * * Quad Tests * * 1/13/2014 * ********************/ #include <stdio.h> #include <math.h> #include "checkit.h" #include "functions.h" int main() { checkit_double(quad(10.0), 3024); checkit_double(quad(9.0), 1680); checkit_double(quad(25.3), 268934.5881); checkit_double(quad(-41.2), 3642142.233600); checkit_double(quad(100.0), 90345024); checkit_double(quad(54.32), 7204189.967094); checkit_double(quad(4.36), 3.882334); checkit_double(quad(6.7), 267.63205); checkit_double(quad(9.9), 2862.320100); checkit_double(quad( -5.1), 3192.380100); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* flags_ast.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: curquiza <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/05/29 17:46:28 by curquiza #+# #+# */ /* Updated: 2017/10/18 14:06:16 by sfranc ### ########.fr */ /* */ /* ************************************************************************** */ #include "shell.h" void ft_padding(int padd) { int i; i = 0; while (++i < padd) write(1, "\t", 1); } void ft_print_node(t_ast *ast, char *side, int lvl) { t_lexeme *tmp; ft_padding(lvl); ft_putstr("** "); ft_putstr(side); ft_putnbr(lvl); ft_putendl(" **"); ft_padding(lvl); tmp = ast->lex; ft_putstr(B_PINK); while (tmp) { ft_putstr(tmp->s); ft_putstr(" "); tmp = tmp->next; } ft_putendl(DEF); ft_padding(lvl); ft_putendl("************"); } void ft_print_ast(t_ast *ast, char *side, int lvl) { if (!ast) return ; if (ast->left) ft_print_ast(ast->left, "left", ++lvl); else ++lvl; ft_print_node(ast, side, lvl); if (ast->right) ft_print_ast(ast->right, "right", lvl--); else --lvl; } void ft_putast(t_ast *ast) { if (ast) { ft_putendl_col("\n---- AST -----\n", B_YELLOW, DEF); ft_print_ast(ast, "root", 0); ft_putendl_col("--------------", B_YELLOW, DEF); } }
C
//programm for structure performance #include<stdio.h> #include<string.h> typedef struct employee { int emp_id; char emp_name[100]; char dept_name[10]; float b_sal; }emp; void sort1(emp *m,int num) { int i,j,temp; emp s; printf("\n\tTo sort the records according to the emp-ID:\n"); for(i=0;i<num-1;i++) for(j=0;j<num-1;j++) { if((m+j)->emp_id > (m+j+1)->emp_id) { s=*(m+j); *(m+j)=*(m+j+1); *(m+j+1)=s; } } printf("\nAfter sorting:\n"); for(i=0;i<num;i++) { printf("\nThe emp_id %d:",i+1); printf("%d",(m+i)->emp_id); printf("\nThe emp_name %d:",i+1); puts((m+i)->emp_name); printf("The dept_name %d:",i+1); puts((m+i)->dept_name); printf("The bsal ofemp %d:",i+1); printf("%.2f",(m+i)->b_sal); printf("\n"); } } void sort2(emp *m,int num) { int i,j,temp; emp s; printf("\n\tTo sort the records according to the emp-Name:\n"); for(i=0;i<num-1;i++) for(j=0;j<num-1;j++) { if((m+j)->emp_name[0] > (m+j+1)->emp_name[0]) { s=*(m+j); *(m+j)=*(m+j+1); *(m+j+1)=s; } } printf("\nAfter sorting:\n"); for(i=0;i<num;i++) { printf("\nThe emp_id %d:",i+1); printf("%d",(m+i)->emp_id); printf("\nThe emp_name %d:",i+1); puts((m+i)->emp_name); printf("The dept_name %d:",i+1); puts((m+i)->dept_name); printf("The bsal ofemp %d:",i+1); printf("%.2f",(m+i)->b_sal); printf("\n"); } } void edit(emp *m,int num) { printf("\n\tTo Edit basic salary of employees in finance department:\n"); int i; emp ar[100]; for(i=0;i<num;i++) { //(ar+i)->b_sal=(m+i)->b_sal*0.15+(m+i)->b_sal; (ar+i)->emp_id=(m+i)->emp_id; strcpy((ar+i)->emp_name,(m+i)->emp_name); strcpy((ar+i)->dept_name,(m+i)->dept_name); if(strcmp((m+i)->dept_name,"finance")==0) (ar+i)->b_sal=(m+i)->b_sal*0.15+(m+i)->b_sal; else (ar+i)->b_sal=(m+i)->b_sal; } printf("\nAfter deletion of the record:\n"); for(i=0;i<num;i++) { printf("\nThe emp_id %d:",i+1); printf("%d",(ar+i)->emp_id); printf("\nThe emp_name %d:",i+1); puts((ar+i)->emp_name); printf("The dept_name %d:",i+1); puts((ar+i)->dept_name); printf("The bsal ofemp %d:",i+1); printf("%.2f",(ar+i)->b_sal); printf("\n"); } } void delete1(emp *m,int num) { int i,n,count=0; emp ar[100]; printf("\n\tTo search and delete the record having emp id:\n"); printf("\nEntre the emp id to delete:\n"); scanf("%d",&n); for(i=0;i<num;i++) { if((m+i)->emp_id!=n) { count++; (ar+i)->emp_id=(m+i)->emp_id; strcpy((ar+i)->emp_name,(m+i)->emp_name); strcpy((ar+i)->dept_name,(m+i)->dept_name); (ar+i)->b_sal=(m+i)->b_sal; } } printf("\nAfter deletion of the record:\n"); for(i=0;i<count;i++) { printf("\nThe emp_id %d:",i+1); printf("%d",(ar+i)->emp_id); printf("\nThe emp_name %d:",i+1); puts((ar+i)->emp_name); printf("The dept_name %d:",i+1); puts((ar+i)->dept_name); printf("The bsal ofemp %d:",i+1); printf("%.2f",(ar+i)->b_sal); printf("\n"); } } void delete2(emp *m,int num) { int i,count=0; emp ar[100]; printf("\n\tTo search and delete the record having dep_name=sales:\n"); for(i=0;i<num;i++) { if(strcmp((m+i)->dept_name,"sales")) { count++; (ar+i)->emp_id=(m+i)->emp_id; strcpy((ar+i)->emp_name,(m+i)->emp_name); strcpy((ar+i)->dept_name,(m+i)->dept_name); (ar+i)->b_sal=(m+i)->b_sal; } } printf("\nAfter deletion of the record:\n"); for(i=0;i<count;i++) { printf("\nThe emp_id %d:",i+1); printf("%d",(ar+i)->emp_id); printf("\nThe emp_name %d:",i+1); puts((ar+i)->emp_name); printf("The dept_name %d:",i+1); puts((ar+i)->dept_name); printf("The bsal ofemp %d:",i+1); printf("%.2f",(ar+i)->b_sal); printf("\n"); } } void display(emp *m,int num) { int i; printf("\n\tDisplaying all the input records:\n"); for(i=0;i<num;i++) { printf("\nThe emp_id %d:",i+1); printf("%d",(m+i)->emp_id); printf("The emp_name %d:",i+1); puts((m+i)->emp_name); printf("The dept_name %d:",i+1); puts((m+i)->dept_name); printf("The bsal ofemp %d:",i+1); printf("%.2f",(m+i)->b_sal); printf("\n"); } } int main() { int num,i; emp s[100]; printf("Enter number of employes:\n"); scanf("%d",&num); for(i=0;i<num;i++) { printf("\nEnter emp_id %d:",i+1); scanf("%d",&(s+i)->emp_id); fgetc(stdin); printf("Enter the emp_name %d:",i+1); scanf("%[^\n]",(s+i)->emp_name); fgetc(stdin); printf("Enter the dept_name %d:",i+1); scanf("%[^\n]",(s+i)->dept_name); printf("Enter the bsal ofemp %d:",i+1); scanf("%f",&(s+i)->b_sal); printf("\n"); } display(s,num); delete1(s,num); delete2(s,num); edit(s,num); sort1(s,num); sort2(s,num); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<string.h> #include<fcntl.h> #define MAX_INDEX 16 struct _chunk { long pointer; long length; } chunk[MAX_INDEX]; int chunk_idx = 0; int std_read(unsigned char *buf, unsigned int count) { int idx = 0, i = 0; unsigned char c_in; for (i = 0; i <= count; i++){ if ( read(STDIN_FILENO, (void *)&c_in, 1) < 0 ) { return -1; } if( c_in == '\n' ) { *(buf + i) = 0; return i; } *(buf + i) = c_in; } buf[i-1] = 0; return i-1; } int std_atoi() { char s_idx[8] = {0}; std_read(s_idx, 8); return atoi(s_idx); } int output_banner() { puts("Welcome to Alibaba Living Area, here you can"); return 0; } int output_choice() { puts("1. Init the message"); puts("2. Set the message"); puts("3. Delete the message"); puts("4. Show the message"); puts("5. Exit"); printf("Choice:"); return std_atoi(); } int Init_message() { int idx = 0; int len = 0; if ((chunk_idx<0) || (chunk_idx>=16)) { puts("Not allow~!"); return 1; } printf("Input the message length:"); len = std_atoi(); if ((len<0) || (len>256)) { puts("Not allow~!"); return 1; } char *A = malloc(len); while (chunk[idx].length>0) { idx++; } chunk[idx].pointer = A; chunk[idx].length = len; chunk_idx++; puts("Done~!"); return 0; } int Set_message() { int idx; printf("Input the message index:"); idx = std_atoi(); if ((idx<0) || (idx>MAX_INDEX)) { puts("Not allow~!"); return 1; } if (chunk[idx].length > 0) { printf("Input the message content:"); std_read(chunk[idx].pointer, chunk[idx].length); } else { puts("Not allow~!"); return 1; } puts("Done~!"); return 0; } int Delete_message() { int idx; printf("Input the message index:"); idx = std_atoi(); if ((idx<0) || (idx>MAX_INDEX)) { puts("Not allow~!"); return 1; } if (chunk[idx].length > 0) { chunk[idx].length = 0; free(chunk[idx].pointer); chunk_idx--; } else { puts("Not allow~!"); return 1; } puts("Done~!"); return 0; } void Show_message() { puts("Not allow~!"); } void Exit() { puts("Bye~!"); exit(0); } int main(int argc, char** argv, char** envp) { int idx; setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stdin, NULL, _IONBF, 0 ); alarm(30); output_banner(); while(1) { idx = output_choice(); switch (idx) { case 1: Init_message(); break; case 2: Set_message(); break; case 3: Delete_message(); break; case 4: Show_message(); break; case 5: Exit(); default: puts("Invalid input\n"); } } return 0; }
C
/*Program 4.1 : Program to display array elements with their addresses.*/ #include<stdio.h> #include<conio.h> void main() { int a[3]={5,4,3}; printf("\n a[0] ,value=%d : address=%u",a[0],&a[0]); printf("\n a[1] ,value=%d : address=%u",a[1],&a[1]); printf("\n a[2] ,value=%d : address=%u",a[2],&a[2]); getch(); } /* *** OUTPUT *** a[0] ,value=5 : address=65520 a[1] ,value=4 : address=65522 a[2] ,value=3 : address=65524 */
C
#include <stdio.h> int main(void) { char a[100],i,b=0; scanf("%s",a); for(i=0;a[i]!='\0';i++) b++; a[b/2]='*'; for(i=0;a[i]!='\0';i++) printf("%c",a[i]); return 0; }
C
#include "cpu.h" void enable_irq (int irq) { /* Make sure that the IRQ is an allowable number. Up to 32 is * used. * * NOTE: If you are using the interrupt definitions from the header * file, you MUST SUBTRACT 16!!! */ if (irq > 32) { //printf("\nERR! Invalid IRQ value passed to enable irq function!\n"); } else { /* Set the ICPR and ISER registers accordingly */ NVIC_ICPR |= 1 << (irq%32); NVIC_ISER |= 1 << (irq%32); } }
C
int compare(const void *a, const void *b){ return strcmp((char*)a, (char*)b); } bool isAnagram(char * s, char * t){ qsort(s, strlen(s), sizeof(char), compare); qsort(t, strlen(t), sizeof(char), compare); if (strcmp(s, t)) return false; return true; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: salmeta <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/08/17 14:53:09 by salmeta #+# #+# */ /* Updated: 2019/08/17 14:53:15 by salmeta ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" int line_verif(char **line, char **tmp, int res, char **str) { *str = NULL; if (res == 0 && ft_strlen(*tmp) > 0) { *line = *tmp; *tmp = NULL; return (1); } return (res); } char *read_line(char *tmp) { int t; char *line; t = 0; while (tmp[t] != '\n') t++; line = (char *)malloc((t + 1) * sizeof(char)); line = ft_strncpy(line, tmp, t); line[t] = '\0'; return (line); } char *cpycat(char *s1, char *s2) { char *tmp; tmp = NULL; tmp = ft_memalloc(ft_strlen(s1) + ft_strlen(s2)); s1 ? tmp = ft_strcpy(tmp, s1) : NULL; s1 ? tmp = ft_strncat(tmp, s2, ft_strlen(s2)) : NULL; //printf("%s\n", tmp); return (tmp); } int get_next_line(int const fd, char **line) { static char *str = NULL; int res; char *buf; char *tmp; if (fd < 0 || !line || BUFF_SIZE < 1 || BUFF_SIZE > 10000000) return (-1); buf = ft_strnew(BUFF_SIZE + 1); if (str == NULL) str = ft_memalloc(BUFF_SIZE); tmp = ft_strncpy(ft_memalloc(BUFF_SIZE), str, BUFF_SIZE); while (!(ft_strchr(tmp, '\n'))) { if ((res = read(fd, buf, BUFF_SIZE)) < 1) return (line_verif(line, &tmp, res, &str)); buf[res] = '\0'; tmp = cpycat(tmp, buf); } *line = read_line(tmp); if (ft_strchr(tmp, '\n')) str = ft_strncpy(str, ft_strchr(tmp, '\n') + 1, BUFF_SIZE); free(tmp); free(buf); return (1); } /* void get_line(char *str) { int i; char *new_s; i = 0; new_s = ft_memalloc(ft_strlen(str)); while (str[i] != '\n') { new_s[i] = str[i]; i++; } } int get_next_line(int fd, char **line) { int res; char *buf; static char *str = NULL; if (fd < 0 || (res = read(fd, buf, BUFF_SIZE)) == -1) return (-1); buf = ft_strnew(BUFF_SIZE + 1); if (str = NULL) str = ft_memalloc(BUFF_SIZE); get_line(buf); }*/
C
#include<stdio.h> // ANSI-Cores #define F_VERMELHO "\033[41m\033[37m" #define F_VERDE "\033[42m\033[30m" #define F_LARANJA "\033[43m\033[30m" #define F_AZUL "\033[44m\033[37m" #define F_ROSA "\033[45m\033[37m" #define F_CIANO "\033[46m\033[30m" #define F_BRANCO "\033[47m\033[30m" #define F_PRETO "\033[40m\033[37m" #define L_VERMELHO "\033[31m\033[47m" #define L_VERDE "\033[32m\033[40m" #define L_LARANJA "\033[33m\033[40m" #define L_AZUL "\033[34m\033[47m" #define L_ROSA "\033[35m\033[47m" #define L_CIANO "\033[36m\033[40m" #define L_BRANCO "\033[37m\033[40m" #define L_PRETO "\033[30m\033[47m" #define S_VERMELHO "\033[31m" #define S_VERDE "\033[32m" #define S_LARANJA "\033[33m" #define S_AZUL "\033[34m" #define S_ROSA "\033[35m" #define S_CIANO "\033[36m" #define S_BRANCO "\033[37m" #define S_PRETO "\033[30m" #define RESTAURA "\033[00m" // Funcoes de cores void f_vermelho (char string[]) {printf("%s%s%s\n",F_VERMELHO,string,RESTAURA);} void f_verde (char string[]) {printf("%s%s%s\n",F_VERDE ,string,RESTAURA);} void f_laranja (char string[]) {printf("%s%s%s\n",F_LARANJA ,string,RESTAURA);} void f_azul(char string[]) {printf("%s%s%s\n",F_AZUL ,string,RESTAURA);} void f_rosa(char string[]) { printf("%s%s%s\n",F_ROSA ,string,RESTAURA);} void f_ciano (char string[]) {printf("%s%s%s\n",F_CIANO ,string,RESTAURA);} void f_branco (char string[]) { printf("%s%s%s\n",F_BRANCO ,string,RESTAURA);} void f_preto (char string[]) {printf("%s%s%s\n",F_PRETO ,string,RESTAURA);} void l_vermelho (char string[]) {printf("%s%s%s\n",L_VERMELHO,string,RESTAURA);} void l_verde (char string[]) {printf("%s%s%s\n",L_VERDE ,string,RESTAURA);} void l_laranja (char string[]) {printf("%s%s%s\n",L_LARANJA ,string,RESTAURA);} void l_azul(char string[]) {printf("%s%s%s\n",L_AZUL ,string,RESTAURA);} void l_rosa(char string[]) { printf("%s%s%s\n",L_ROSA ,string,RESTAURA);} void l_ciano (char string[]) {printf("%s%s%s\n",L_CIANO ,string,RESTAURA);} void l_branco (char string[]) { printf("%s%s%s\n",L_BRANCO ,string,RESTAURA);} void l_preto (char string[]) {printf("%s%s%s\n",L_PRETO ,string,RESTAURA);} void s_vermelho (char string[]) {printf("%s%s%s\n",S_VERMELHO,string,RESTAURA);} void s_verde (char string[]) {printf("%s%s%s\n",S_VERDE ,string,RESTAURA);} void s_laranja (char string[]) {printf("%s%s%s\n",S_LARANJA ,string,RESTAURA);} void s_azul(char string[]) {printf("%s%s%s\n",S_AZUL ,string,RESTAURA);} void s_rosa(char string[]) { printf("%s%s%s\n",S_ROSA ,string,RESTAURA);} void s_ciano (char string[]) {printf("%s%s%s\n",S_CIANO ,string,RESTAURA);} void s_branco (char string[]) { printf("%s%s%s\n",S_BRANCO ,string,RESTAURA);} void s_preto (char string[]) {printf("%s%s%s\n",S_PRETO ,string,RESTAURA);} // Principal int main() { f_vermelho("Vermelho"); f_verde ("Verde"); f_laranja ("Laranja"); f_azul ("Azul"); f_rosa ("ROSA"); f_ciano ("Ciano"); f_branco ("Branco"); f_preto ("Preto"); printf("\n"); l_vermelho("Vermelho"); l_verde ("Verde"); l_laranja ("Laranja"); l_azul ("Azul"); l_rosa ("ROSA"); l_ciano ("Ciano"); l_branco ("Branco"); l_preto ("Preto"); printf("\n"); s_vermelho("Vermelho"); s_verde ("Verde"); s_laranja ("Laranja"); s_azul ("Azul"); s_rosa ("ROSA"); s_ciano ("Ciano"); s_branco ("Branco"); s_preto ("Preto"); }
C
#include <assert.h> #include <stdbool.h> #include <ctype.h> #include <stdio.h> // pomocna funkce // obecny prevod znaku na hodnotu cislice (az do zakladu 36) int char2digit(int c) { c = toupper(c); if (isdigit(c)) return c - '0'; if (isalpha(c)) return c - 'A' + 10; else return 99; // neni cislice v zadne soustave } unsigned long str2ul(const char *s, const char **p, int radix) { unsigned long result = 0; int digit; assert(radix >= 2 && radix <= 36); // preskocime pripadne bile znaky while (isspace(*s)) s++; // vlastni prevod retezec->cislo while ((digit = char2digit(*s)) < radix) { // je dalsi platna cislice //// zde by byla pripadna kontrola preteceni result = result * radix + digit; s++; } // konec prevodu - neni dalsi cislice if (p) *p = s; // vratime pozici, pokud je pozadovano (!=NULL) // vraceni vysledku return result; } bool ul2str(unsigned long x, int radix, char *s, int n) { char *p = s; assert(radix >= 2 && radix <= 36); // vlastni prevod cislo->retezec do { int digit = x % radix; // koncova cislice x /= radix; // odstraneni koncove cislice if (--n <= 0) // kontrola limitu return false; // prevod cislice na znak v retezci *s++ = (digit < 10) ? '0' + digit : 'A' + digit - 10; } while (x != 0); // do-while zvladne dobre x==0 // ukoncit C-string *s-- = '\0'; // otocit poradi -- prevod ukladal obracene while (p < s) { int tmp = *p; *p = *s; *s = tmp; p++; s--; } return true; // hotovo } #define TEST(p) do{ printf("%s\n",#p); p; }while(0) #define N 80 #define RADIX 2 int main(void) { unsigned long x = 12345; char s[N] = ""; bool b; printf("\n"); printf("RADIX = %d\n", RADIX); printf("sizeof(s) = %d\n", sizeof(s)); printf("\n"); #if 1 TEST(b = ul2str(x, RADIX, s, sizeof(s))); if (b) printf("uspesny prevod: %lu -> \"%s\"\n", x, s); else printf("NEuspesny prevod: %lu -> \"%s\"\n", x, s); printf("\n"); #endif const char *p; TEST(x = str2ul(s, &p, RADIX)); printf("prevod: \"%s\" -> %lu\n", s, x); printf("prevod skoncil na pozici: %d v \"%s\"\n", p - s, s); printf("\n"); return 0; }
C
/** ****************************************************************************** * @file pack_deal.c * @author qsunj * @date 21-5-26 * @brief ****************************************************************************** */ #include "pack_deal.h" /******************ݸʽ****************** ֡ͷ мݣ ֵK1-K10K21-K22K11-K14 λƣADC1-ADC8K21K22K23-K26 ֡β ********************************************/ const uint8_t FRAMEHEAD = '\"'; const uint8_t FRAMETAIL = 0xee; uint8_t tramsmitdata_buffer_key[ FRAMELENGTH_KEY ] = {0};//ֵݴ uint16_t transmitData_buffer_float[ FRAMELENGTH_FLOAT ] = {0};//ֵ uint8_t TransmitData_SendFrame[FRAMELENGTH] = {0};//ڴ uint8_t TransmitData_ReceiveFrame[FRAMELENGTH] = {0};//ڴ /** * @brief :ý * @param :ѡK1-K14;K23-K26;R_X,R_Y,L_X,L_Y * @note : * @retval: */ uint16_t Get_NRF_Deal_ReceiveData(TransmitDataLocateNum num) { uint16_t returndata=0; if ( num < R_X ) { Serial_Send(Serial1, "The param of Get_ReceiveData is error!\r\n"); return 0; } else if ( num < K1 ) { returndata = TransmitData_ReceiveFrame[num+1]; returndata |= TransmitData_ReceiveFrame[num+2]<<8; } else if ( num < K9 ) { returndata += TransmitData_ReceiveFrame[K_PECK1+1] & (1 << (7-(num-K1)) ); } else if ( num < K16 ){ returndata += TransmitData_ReceiveFrame[K_PECK2+1] & (1 << (7-(num-K9)) ); } return returndata; } /** * @brief :ݽ * @param : * @note : * @retval: */ void ReceiveData_Task() { uint8_t i=0; for (i=0; i<FRAMELENGTH; i++) { Serial_SendByte(Serial1, TransmitData_ReceiveFrame[i]); } } void TransmitData_UnPack_CheckTask(uint8_t* buf, uint8_t len) { uint8_t i=0; for (i=0; i<len; i++) { TransmitData_UnPack( *(buf+i) ); } } /** * @brief :ݴ * @param : * @note :ݴ TransmitData_SendFrame() * @retval:ɰ-- */ void TransmitData_Pack(void) { uint8_t i=0; uint8_t *TransmitData_SendFrame_temppoint = &TransmitData_SendFrame[2-1]; for (i=0; i<FRAMELENGTH_KEY; i++) { TransmitData_SendFrame_temppoint[i] = tramsmitdata_buffer_key[i]; } for (i=0; i<FRAMELENGTH_FLOAT; i++) { //Ͱλǰ TransmitData_SendFrame_temppoint[FRAMELENGTH_KEY+2*i] = transmitData_buffer_float[i] & 0xff; TransmitData_SendFrame_temppoint[FRAMELENGTH_KEY+2*i+1] = transmitData_buffer_float[i] >> 8; } TransmitData_SendFrame[0] = FRAMEHEAD; TransmitData_SendFrame[FRAMELENGTH-1] = FRAMETAIL; } /** * @brief :ݽ * @param : * @note :ݴ TransmitData_RecevieFrame() * @retval: */ void TransmitData_UnPack(uint8_t receive_data) { static uint8_t transmit_processbit=0;//̱־λ:ڿʼݽպͿƽݵλ // if (receive_data==FRAMEHEAD && !transmit_processbit) { TransmitData_ReceiveFrame[transmit_processbit] = receive_data; transmit_processbit = 1; } else if (transmit_processbit>0) { TransmitData_ReceiveFrame[transmit_processbit] = receive_data; transmit_processbit++; if (transmit_processbit==FRAMELENGTH) { transmit_processbit = 0; } } else { transmit_processbit = 0; } //֡ if (TransmitData_ReceiveFrame[FRAMELENGTH-1]==FRAMETAIL) { //ReceiveData_Task(); TransmitData_ReceiveFrame[FRAMELENGTH-1] = 0x00; } } /** * @brief :ֵ * @param : * data:Ҫ * locate:ݵIJַ * @note : * @retval: */ void Insert_transmitdata_buffer_key(uint8_t data, uint8_t locate) { tramsmitdata_buffer_key[locate] = data; } /** * @brief :ADCֵ * @param : * data:Ҫ * locate:ݵIJַ * @note : * @retval: */ void Insert_transmitdata_buffer_float(uint16_t data, uint8_t locate) { transmitData_buffer_float[locate] = data; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* filo_one.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cjani <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/05 15:47:05 by cjani #+# #+# */ /* Updated: 2021/04/05 15:47:10 by cjani ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/philo_one.h" int ft_init_philos(t_tab *tab) { t_philo *philo; int i; i = -1; philo = (t_philo *)malloc(tab->philos * sizeof(t_philo)); tab->bigb = ft_get_time(); while (++i < tab->philos) { ft_make_school(&philo[i], tab, i); pthread_create(&philo[i].philo, NULL, &ft_acient_greece, &philo[i]); } i = -1; while (++i < tab->philos) pthread_join(philo[i].philo, NULL); free(philo); return (1); } int main(int argc, char **argv) { t_tab tab; if (argc < 5 || argc > 6) { printf("Wrong arguments' amount"); return (1); } if (ft_init_table(argv, &tab, argc)) return (1); ft_init_philos(&tab); pthread_mutex_destroy(&tab.mutx_print); pthread_mutex_destroy(&tab.mutx_patrol); pthread_mutex_destroy(&tab.mutx_polite); while (--tab.philos >= 0) pthread_mutex_destroy(&tab.m_fork[tab.philos]); free(tab.m_fork); return (0); }
C
#include<stdio.h> void swap(int *,int *); int main() { int a,b; printf("enter the number"); scanf("%d%d",&a,&b); printf("number is before swapping %d%d",a,b); swap(&a,&b); printf("number after swapping %d%d",a,b); } void swap(int *a,int *b) { *a=*a+*b; *b=*a-*b; *a=*a-*b; printf("swap function a&b values are %d%d",*a,*b); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "./headers/interpretador.h" #include "./headers/auxiliares.h" #include "./headers/comandos.h" void erro_sintaxe(int tipo) { switch (tipo) { case 1: printf("Erro no comando\n"); break; case 2: printf("Erro nos argumentos\n"); break; case 3: printf("Erro nos tipos\n"); break; case 4: printf("Espao em local no permitido\n"); break; } printf("Encerrando execuo\n"); exit(1); } void interpreta(char *comando) { // Separando o OPCODE char *opcode = strtok(comando, " \n"); if (opcode == NULL) return; toupper_string(&opcode); // Comando que no recebem argumentos if (strcmp(opcode, "EB") == 0) { EB(); return; } if (strcmp(opcode, "LT") == 0) { LT(); return; } // Comandos que recebem um argumento // Separando o primeiro argumento char *arg1 = strtok(NULL, " "); if (arg1 == NULL) erro_sintaxe(2); if (strcmp(opcode, "RT") == 0) { char *tabela = arg1; RT(tabela); return; } if (strcmp(opcode, "AT") == 0) { char *tabela = arg1; AT(tabela); return; } if (strcmp(opcode, "AR") == 0) { char *tabela = arg1; AR(tabela); return; } if (strcmp(opcode, "RR") == 0) { char *tabela = arg1; RR(tabela); return; } // Comandos que recebem dois argumentos char *arg2 = strtok(NULL, "\0"); if (arg2 == NULL) erro_sintaxe(2); if (strcmp(opcode, "CT") == 0) { char *tabela = arg1; char *campos = arg2; CT(tabela, campos); return; } if (strcmp(opcode, "IR") == 0) { char *tabela = arg1; char *registro = arg2; IR(tabela, registro); return; } if (strcmp(opcode, "RI") == 0) { char *tabela = arg1; char *chave = arg2; RI(tabela, chave); return; } if (strcmp(opcode, "GI") == 0) { char *tabela = arg1; char *chave = arg2; GI(tabela, chave); return; } // Comandos que recebem trs argumentos // ARG2 utilizado para separar a prxima parte do cdigo char *temp = strtok(arg2, " "); if (temp == NULL) erro_sintaxe(2); // Separando o terceiro argumento char *arg3 = strtok(NULL, "\0"); if (arg3 == NULL) erro_sintaxe(2); if (strcmp(opcode, "BR") == 0) { char modo = toupper(arg1[0]); if (modo != 'N' && modo != 'U') erro_sintaxe(3); char *tabela = temp; char *busca = arg3; BR(modo, tabela, busca); return; } if (strcmp(opcode, "CI") == 0) { char modo = toupper(arg1[0]); if (modo != 'A' && modo != 'H') erro_sintaxe(3); char *tabela = temp; char *chave = arg3; CI(modo, tabela, chave); return; } erro_sintaxe(1); }
C
//--------------------------------------------------------------------------- #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <regex.h> #include "WMMHeader.h" //--------------------------------------------------------------------------- /* WMM sublibrary is used to make a command prompt program. The program reads location data from command line, performs computations and returns. The program expects the files libwmm.c, WMMHEADER.H, WMM.COF and EGM9615.BIN to be in the same directory. Manoj.C.Nair Nov 23, 2009 (Modified by Matthew Wampler-Doty March 23, 2011) * * MODIFICATIONS * * Date Version * ---- ----------- * Nov 15, 2009 0.1 Jan 28, 2010 1.0 March 23, 2011 1.1 */ // Checks if a file exists int file_exists (char *filename) { struct stat buf; return !stat (filename, &buf); } // Reads in position data in the form of latitude, longitude, and altitude int read_pos (char *latb, char *lonb, char *altb, WMMtype_CoordGeodetic * CoordGeodetic, WMMtype_Geoid * Geoid) { sscanf (latb, "%lf", &CoordGeodetic->phi); // latitude sscanf (lonb, "%lf", &CoordGeodetic->lambda); // longitude Geoid->UseGeoid = 1; sscanf (altb, "%lf", &CoordGeodetic->HeightAboveGeoid); WMM_ConvertGeoidToEllipsoidHeight (CoordGeodetic, Geoid); return 1; } /***** Date reading routines *****/ // Checks if a regular expression matches int match (char *str, char *pat) { int status; regex_t re; if (regcomp (&re, pat, REG_EXTENDED | REG_NOSUB)) return 0; status = regexec (&re, str, (size_t) 0, NULL, 0); regfree (&re); return !status; } // Checks if a string is a Gregorian decimal year (ie, a floating point number) int is_gdy (char *dateb) { return match (dateb, "[-+]?[0-9]*\\.?[0-9]*"); } // Checks if a string is of the form "YYYY/MM/DD" int is_ymd (char *dateb) { return match (dateb, "[0-9][0-9][0-9][0-9]/[0-9]?[0-9]/[0-9]?[0-9]"); } // The epoch - read from COF file. We are lazy and make it a global. int epoch = 0; // Prints an error message about the form of the date void print_date_error () { fprintf (stderr, "Date must be entered in as YYYY/MM/DD or Gregorian decimal year, and only times after %d/01/01 and before %d/01/01 are supported\n", (int) epoch, (int) epoch + 5); } // Reads date from Gregorian decimal year int read_gdy (char *dateb, WMMtype_Date * MagneticDate) { sscanf (dateb, "%lf", &MagneticDate->DecimalYear); return (epoch <= MagneticDate->DecimalYear && MagneticDate->DecimalYear <= epoch + 5); } // Reads date from YYYY/MM/DD int read_ymd (char *dateb, WMMtype_Date * MagneticDate) { char Error_Message[255]; sscanf (dateb, "%d/%d/%d", &MagneticDate->Year, &MagneticDate->Month, &MagneticDate->Day); if (!(epoch <= MagneticDate->Year && MagneticDate->Year <= epoch + 5)) return 0; else if (!(WMM_DateToYear (MagneticDate, Error_Message))) { fprintf (stderr, "%s\n", Error_Message); return 0; } else return 1; } // Reads in date data int read_date (char *dateb, WMMtype_Date * MagneticDate) { int status = 0; if (is_ymd (dateb)) status = read_ymd (dateb, MagneticDate); else if (is_gdy (dateb)) status = read_gdy (dateb, MagneticDate); if (status == 0) { print_date_error (); return 0; } else return 1; } /***** Usage Warning *****/ void print_usage (char *progname) { fprintf (stderr, "\nUsage:\n" "%s <latitude> <longitude> <altitude> YYYY/MM/DD\n" // "- WMM.COF is a file containing world magnetic model spherical harmonic coefficients\n" "- latitude and longitude are given in (signed) degrees\n" "- altitude is given in kilometers\n" "\n" "OUTPUTS: X, Y, and Z components of geomagnetic field vector, seperated by spaces\n" "- X is the northerly intensity in nanoteslas\n" "- Y is the easterly intensity in nanoteslas\n" "- Z is the verticle intensity, positive downwards in nanoteslas\n", progname); } int main (int argc, char *argv[]) { WMMtype_MagneticModel *MagneticModel, *TimedMagneticModel; WMMtype_Ellipsoid Ellip; WMMtype_CoordSpherical CoordSpherical; WMMtype_CoordGeodetic CoordGeodetic; WMMtype_Date UserDate; WMMtype_GeoMagneticElements GeoMagneticElements; WMMtype_Geoid Geoid; int NumTerms; char filename[] = "WMM.COF"; /*** Memory allocation ***/ NumTerms = ((WMM_MAX_MODEL_DEGREES + 1) * (WMM_MAX_MODEL_DEGREES + 2) / 2); /* WMM_MAX_MODEL_DEGREES is defined in WMM_Header.h */ MagneticModel = WMM_AllocateModelMemory (NumTerms); /* For storing the WMM Model parameters */ TimedMagneticModel = WMM_AllocateModelMemory (NumTerms); /* For storing the time modified WMM Model parameters */ if (MagneticModel == NULL || TimedMagneticModel == NULL) WMM_Error (2); WMM_SetDefaults (&Ellip, MagneticModel, &Geoid); /* Set default values and constants */ /* Check for Geographic Poles */ if (!file_exists (filename)) { fprintf (stderr, "File %s does not exist\n", argv[1]); print_usage (argv[0]); exit (EXIT_FAILURE); } //WMM_readMagneticModel_Large(filename, MagneticModel); //Uncomment this line when using the 740 model, and comment out the WMM_readMagneticModel line. WMM_readMagneticModel (filename, MagneticModel); WMM_InitializeGeoid (&Geoid); /* Read the Geoid file */ epoch = (int) MagneticModel->epoch; // Set the epoch //WMM_GeomagIntroduction (MagneticModel); /* Print out the WMM introduction */ /*** Get parameters from command line ***/ if (!(argc == 5 && read_pos (argv[1], argv[2], argv[3], &CoordGeodetic, &Geoid) && read_date (argv[4], &UserDate))) { print_usage (argv[0]); exit (EXIT_FAILURE); } /*** Perform Calculations ***/ WMM_GeodeticToSpherical (Ellip, CoordGeodetic, &CoordSpherical); /*Convert from geodeitic to Spherical Equations: 17-18, WMM Technical report */ WMM_TimelyModifyMagneticModel (UserDate, MagneticModel, TimedMagneticModel); /* Time adjust the coefficients, Equation 19, WMM Technical report */ WMM_Geomag (Ellip, CoordSpherical, CoordGeodetic, TimedMagneticModel, &GeoMagneticElements); /* Computes the geoMagnetic field elements and their time change */ WMM_CalculateGridVariation (CoordGeodetic, &GeoMagneticElements); /*** Output ***/ //WMM_PrintUserData (GeoMagneticElements, CoordGeodetic, UserDate, TimedMagneticModel, &Geoid); /* Print the results */ // Print the three Geogmagnetic elements printf ("%lf %lf %lf\n", GeoMagneticElements.X, GeoMagneticElements.Y, GeoMagneticElements.Z); /*** Memory Cleanup ***/ WMM_FreeMagneticModelMemory (MagneticModel); WMM_FreeMagneticModelMemory (TimedMagneticModel); if (Geoid.GeoidHeightBuffer) { free (Geoid.GeoidHeightBuffer); Geoid.GeoidHeightBuffer = NULL; } exit (EXIT_SUCCESS); }
C
/* mem.c */ /* These functions manage the standard C library functions malloc(), realloc() and free() to automatically reclaim unused memory. They do not impose an "all your pointers are belong to us" regime. If you bypass them at your own risk, use tools such as valgrind to check for leaks. The algorithms are distinct from reference counting and tracing (mark and sweep) whilst incorporating aspects of both. The data structures and code aim for most of the benefits of those techniques without the drawbacks. In particular, this design tries to maximize processor cache performance, keeping the working set small by freeing unused memory early. There is more documentation at the end of this file. The code is being written in stages using two techniques: 1. Using simple reference counting to get something usable asap. 2. Using reference tracking with more metadata about references so as to detect cycles and free them when they are no longer used. */ #include <assert.h> /* assert */ #include <string.h> /* memset */ #include <stdlib.h> /* malloc realloc free */ #include "mem.h" /* this file's API */ /* mem_init */ void * mem_init() { struct mem_block * rootblock; struct mem_rootdata * rootdata; rootblock = (struct mem_block *) malloc( sizeof(struct mem_block) + sizeof(struct mem_rootdata) ); #if defined(REFCOUNT_ONLY) rootdata = (struct mem_rootdata *)(rootblock + 1); rootblock->rootdata = rootdata; /* only the root is loopy */ #else struct mem_node * node; node = (struct mem_node *) malloc(sizeof(struct mem_node)); node->rootnode = node; /* only the root is loopy */ rootdata = ((void *) node) + sizeof(struct mem_node); #endif rootdata->totalobjects = 0; rootdata->totalbytes = 0L; /* TODO: start a collector thread */ return (void *) rootdata; } /* mem_final */ void mem_final(void * rootdata, int freeflag) { struct mem_block * rootblock; /* TODO: stop the collector thread */ if (freeflag) { #if defined(REFCOUNT_ONLY) rootblock = (struct mem_block *)rootdata - 1; free(rootblock); #endif } } /* mem_scalar_new */ void * mem_scalar_new(void * parent, int size) { struct mem_block * block; struct mem_node * node; assert( size > 0 ); block = (struct mem_block *) malloc(sizeof(struct mem_block) + size); node = (struct mem_node *) malloc(sizeof(struct mem_node)); block->node = node; node->block = block; block->size = size; block->rootdata = (struct mem_rootdata *) parent; block->rootdata->totalobjects++; block->rootdata->totalbytes += size; #if defined(REFCOUNT_ONLY) block->refcount = 1; #endif return (void *)(block + 1); } /* mem_scalar_resize */ void * mem_scalar_resize(void * object, int newsize) { int sizedifference; struct mem_block * block; assert( newsize >= 0); block = (struct mem_block *)object - 1; sizedifference = newsize - block->size; block = realloc(block, sizeof(struct mem_block) + newsize); assert( block != NULL ); block->node->block = block; block->size = newsize; #if defined(REFCOUNT_ONLY) block->rootdata->totalbytes += sizedifference; #endif return (void *)(block + 1); } /* mem_scalar_set_ref */ void mem_scalar_set_ref(void * object, void * target) { struct mem_block * block; struct mem_node * node; void ** objectp; /* Receive parameters and check them for sanity */ objectp = object; block = (struct mem_block *)object - 1; assert( block->size >= -1 ); node = block->node; if (block->size >= 0 ) { /* If a scalar currently contains a value, replace that with a pointer */ if (block->size != sizeof(void *)) { /* Currently a different number of bytes is allocated */ node->block = realloc(node->block, sizeof(struct mem_block) + sizeof(void *)); assert( node->block != NULL ); block->node = node; object = objectp = (void *)(block + 1); } block->size = -1; * objectp = NULL; } if (target != * objectp) { /* update only if something changes */ if (* objectp) { /* unreference the previously referenced object (this may recurse) */ ; } /* assign the pointer */ * objectp = target; if (target) { /* reference the new target */ ; } } } /* mem_scalar_get_ref */ void * mem_scalar_get_ref(void * object) { void ** objectp; /* Receive parameters and check them for sanity */ objectp = object; return * objectp; } /* mem_list_new */ void * mem_list_new(void * parent) { struct mem_node * node; struct mem_block * block; struct mem_listblock * listblock; void ** list; /* Allocate three structs on the heap */ node = (struct mem_node *) malloc(sizeof(struct mem_node)); block = (struct mem_block *) malloc(sizeof(struct mem_block) + sizeof(struct mem_listblock)); list = calloc(1,sizeof(void *)); /* Link these structs to each other */ listblock = (struct mem_listblock *)(block + 1); listblock->list = list; listblock->listsize = 1; /* because calloc made one NULL pointer */ block->node = node; node->block = block; block->size = -2; /* "magic" value indicating list */ block->rootdata = (struct mem_rootdata *) parent; block->rootdata->totalobjects++; #if defined(REFCOUNT_ONLY) block->refcount = 1; #endif return (void *) listblock; } /* mem_list_put */ void mem_list_put(void * object, int offset, void * target) { struct mem_block * block; struct mem_listblock * listblock; assert( object != NULL ); block = (struct mem_block *)object - 1; assert( block->size == -2 ); listblock = (struct mem_listblock *) object; if (offset >= listblock->listsize) { listblock->list = realloc(listblock->list, (offset+1) * sizeof(void *)); memset(listblock->list+listblock->listsize,0,(offset+1-listblock->listsize)*sizeof(void *)); /* set all the new pointers to NULL */ listblock->listsize = offset + 1; } assert( offset*sizeof(void *) < block->size ); listblock->list[offset] = target; } /* mem_list_get */ void * mem_list_get(void * object, int offset) { struct mem_block * block; struct mem_listblock * listblock; /* Convert and sanity check the parameters */ assert( object != NULL ); assert( (block=(struct mem_block *)object-1, block->size == -2) ); assert( offset >= 0 ); listblock = (struct mem_listblock *) object; assert( offset < listblock->listsize ); /* The actual work is so simple, it could be inlined. */ return listblock->list[offset]; } /* mem_refdel */ void mem_refdel(void * referrer, void * object) { /* TODO: Add this node to a queue for a background thread to process */ int i; struct mem_block * block; struct mem_listblock * listblock; void * child; block = (struct mem_block *)object - 1; if (block->size >= -1) { /* scalar value or scalar reference */ #if defined(REFCOUNT_ONLY) block->refcount--; if (block->refcount == 0) { if (block->size == -1) { child = (void *) * (void **)object; if (child != NULL) { mem_refdel(referrer, child); /* recurse */ } } block->rootdata->totalbytes -= block->size; block->rootdata->totalobjects--; free(block->node); free(block); } #endif } else { /* list */ assert( block->size == -2 ); /* "magic" number for a list */ #if defined(REFCOUNT_ONLY) block->refcount--; if (block->refcount == 0) { /* Un-reference the list's children */ listblock = (struct mem_listblock *) object; for (i=0; i<listblock->listsize; ++i) { child = listblock->list[i]; if (child != NULL) { mem_refdel(referrer, child); /* recurse */ } } /* Free the list's own memory */ free(listblock->list); free(block->node); free(block); } #endif } } /* mem_objects */ int mem_objects(void * allocation) { struct mem_block * block; struct mem_rootdata * rootdata; block = (struct mem_block *)allocation - 1; #if defined(REFCOUNT_ONLY) rootdata = block->rootdata; #else struct mem_node * rootnode; rootnode = block->rootnode; #endif return rootdata->totalobjects; } /* mem_bytes */ long mem_bytes(void * allocation) { struct mem_block * block; struct mem_rootdata * rootdata; block = (struct mem_block *)allocation - 1; #if defined(REFCOUNT_ONLY) rootdata = block->rootdata; #else struct mem_node * rootnode; rootnode = block->rootnode; #endif return rootdata->totalbytes; } /* The system manages two kinds of application objects in memory: scalars and lists. They are more primitive than Perl scalars and lists, but are the foundation upon which those, and hashes, will be built. A scalar may contain from 0 to MAXINT bytes of opaque data, or a single reference to one other memory object. A list contains from 0 to MAXINT references to other memory objects. The maxima are actually a tad short of MAXINT, but let's not spoil a good story with hard facts. A reference is just a (void *) pointer but there is a fixed size memory management struct at a fixed offset before the pointed to address. It is called mem_block but application code should not access it. Memory objects may move if resized (they use realloc()), but tracking via pointers is easier with stationary data, so each memory object also has a stationary mem_node struct. A possible future optimization would be for the case of fixed size memory objects, to concatenate these structs in a single stationary memory allocation, but this is a low priority. Reference counting structures, for example three scalars: +----------------+ +-------------+ +-------------+ | rootdata | | node 1 | | block 1 | | totalobjects |<--------------rootdata |<--------------node | | totalbytes | | block---------------->| size | | node next--------------->| refcount | +-------------+ | node prev | NULL<------node prev |<-----+ | object 1 | +----------------+ | node next-----+ | | (user data) | ^ ^ +-------------+ | | +-------------+ | | | | | | +-------------+ | | +-------------+ | | | node 2 etc |<--+ | | block 2 | | +----------------------rootdata |<--------------node | | | block---------------->| size | | | refcount | | +-------------+ | | node prev--------+ | object 2 | | | node next-----+<-+ | (user data) | | +-------------+ | | +-------------+ | | | | +-------------+ | | +-------------+ | | node 3 etc |<--+ | | block 3 | +------------------------rootdata |<--------------node | | block---------------->| size | | refcount | | +-------------+ | node prev--------+ | object 3 | | node next---->NULL | (user data) | +-------------+ +-------------+ An array containing a scalar and an array (prev and next links omitted): +----------------+ +-------------+ +-------------+ | rootdata | +-->| node 2 | | block 2 | | totalobjects | | | rootdata |<--------------node | | totalbytes | | | block---------------->| size | | node prev | | | refcount | +-------------+ | node next--------+ | | node prev | | object 2 | +----------------+ | | | node next | | (user data) | | | +-------------+ +-------------+ | | | +---------------------------------------------+ | | +-------------+ | +-------------+ +-----------+ | | node 1 |<---=-+ | block 1 | +--->| element 0-----+ | rootdata |<-----------------node | | +-----------+ | block------------------->| size | | | element 1-----+ | refcount | +-------------+ | +-----------+ | | node prev | | listblock 1 | | | element 2 | | | node next | | listsize | | +-----------+ | +-------------+ | list-------------+ | etc | | +-------------+ +-----------+ | | +-------------------------------------------------+ | +-------------+ | +-------------+ +-----------+ | node 3 |<-----+ | block 3 | +--->| element 0 | | rootdata |<-----------------node | | +-----------+ | block------------------->| size | | | element 1 | | refcount | +-------------+ | +-----------+ | node prev | | listblock 3 | | | etc | | node next | | listsize | | +-----------+ +-------------+ | list-------------+ +-------------+ If an object contains a reference, the user data is a pointer to the node struct of (usually another) object, although the user code would have requested it by passing a pointer to the user data object. The automatic memory management works by tracking references, each from a parent node to a child node. A parent can have any number of children and a child has one or more parents. A recycler frees orphaned children and orphaned cycles of children. Background threads collect garbage incrementally. The API has function names like mem_malloc() with referrer and referent arguments where needed. Like other heap managers, the API has no mem_free(). The mem_refdel() function deletes a reference and leaves the reachability checking to a background thread. References to nodes are tracked in ordered single linked lists, not counted. The order is by minimum hop count from a root node, to detect and correctly handle reference cycles. Every node except the root must have at least one reference from another node. Application code can create or delete a reference between any pair of referrer and referent nodes. A node contains either opaque scalar data (eg numeric, string, function pointer) or a list, which is a resizeable array of references to other nodes. More complex structures such as objects with named members will have to be built on top of these. The linked lists live in a node header structure, so the space overhead is only in node size, costing no extra items on the heap. References connect nodes in a hierarchy from a root, a bit like inodes in a Unix file system. Each node is referenced by one or more other nodes and contains typed data and a variable size list of references to other nodes. This is the node header layout: Name Type Description ---- ---- ----------- referrers pointer start of a linked list of other nodes that point to to node this one. Only the root node has a null here. ref_next pointer next referrer node that points to the same referent to node (node being pointed to). destructor pointer function to free memory related to this node. to function level int number of links in shortest path from root to here. datatype int application defined data description (enum) datasize int number of bytes excluding this header [data] void not a struct member, just the opaque contents In addition to being a general purpose heap manager, this code also aims to support 6model/c, an experimental C version of 6model, a platform for dynamic languages such as Perl 6. To do so requires hashes as well as the already provided scalars and lists. By combining with a hashtable library, a 6model/c hash is a list with the data in entry 0 pointing to a hashtable whose keys are any sequences of bytes and whose values are list subscripts greater than 0. This design keeps the mem code isolated from the hashtable code, but requires hash nodes to point to a hashtable destructor function. See also: Connectivity based garbage collection (simulation, Java) http://www-plan.cs.colorado.edu/diwan/cbgc.pdf Ulterior Reference Counting: Fast Garbage Collection without a Long Wait http://cs.anu.edu.au/~Steve.Blackburn/pubs/papers/urc-oopsla-2003.pdf Beltway: Getting Around Garbage Collection Gridlock ftp://ftp.cs.umass.edu/pub/osl/papers/pldi2002.ps.gz The Treadmill: Real-Time Garbage Collection Without Motion Sickness http://home.pipeline.com/~hbaker1/NoMotionGC.html The Garbage Collection Handbook The art of automatic memory management by Richard Jones, Antony Hosking, Eliot Moss 1420082795 978-1420082791 http://www.gchandbook.org/contents.html Garbage Collection Page (by Richard Jones) - excellent resources http://www.cs.kent.ac.uk/people/staff/rej/gc.html Concurrent Cycle Collection in Reference Counted Systems (by David F. Bacon and V.T. Rajan) - promising but hard to implement. http://www.research.ibm.com/people/d/dfb/papers/Bacon01Concurrent.pdf */ /* end of mem.c */