language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include "kamus.h" int main() { // Membuka driver framebuffer fb_driver = open("/dev/fb0", O_RDWR); if (fb_driver == -1) { perror("Error: driver framebuffer tidak dapat dibuka"); exit(1); } // Get fixed screen information if (ioctl(fb_driver, FBIOGET_FSCREENINFO, &fix_info) == -1) { perror("Error reading fixed information"); exit(2); } // Get variable screen information if (ioctl(fb_driver, FBIOGET_VSCREENINFO, &var_info) == -1) { perror("Error reading variable information"); exit(3); } // Mapping framebuffer ke memori int screensize = var_info.xres * var_info.yres * var_info.bits_per_pixel / 8; fb = (char *)mmap(0, screensize, PROT_READ | PROT_WRITE, MAP_SHARED, fb_driver, 0); if((int)fb == -1){ perror("Error: failed to map framebuffer device to memory"); exit(4); } clear_screen(800, 600); color bg = {0,0,0,0}; // Author int x = 25; int xjudul = 300; for (int y0=600; y0>=-600; y0--) { int y = y0; refresh(0, 800, y, 600); draw_kata(&xjudul, &y,"Manly"); int p, q; for(p = 0; p < layarx; p++) for(q= 0; q < y; q++){ color c = {200,0,0,255}; if(buffer_r[p][q] == 0) c = bg; if (q < layary) { draw_dot(p, q, &c); } } y += 32; int ytemp = y; draw_kata(&x, &y,"Yoga SMAN 1 Pemali"); for(p = 0; p < layarx; p++) for(q= ytemp; q < y; q++){ color c = {130,100,233,100}; if (q<0) q=0; if(buffer_r[p][q] == 0) c = bg; if (q < layary) { draw_dot(p, q, &c); } } ytemp = y; draw_kata(&x, &y,"Hafis SMAN 1 Padang"); for(p = 0; p < layarx; p++) for(q= ytemp; q < y; q++){ color c = {200,200,200,255}; if (q<0) q=0; if(buffer_r[p][q] == 0) c = bg; if (q < layary) { draw_dot(p, q, &c); } } ytemp = y; draw_kata(&x, &y,"Husein SMAN 1 Klaten"); for(p = 0; p < layarx; p++) for(q= ytemp; q < y; q++){ color c = {200,200,0,255}; if (q<0) q=0; if(buffer_r[p][q] == 0) c = bg; if (q < layary) { draw_dot(p, q, &c); } } ytemp = y; draw_kata(&x, &y,"Irfan SMAN 1 Bogor"); for(p = 0; p < layarx; p++) for(q= ytemp; q < y; q++){ color c = {200,0,200,255}; if (q<0) q=0; if(buffer_r[p][q] == 0) c = bg; if (q < layary) { draw_dot(p, q, &c); } } ytemp = y; draw_kata(&x, &y,"Nandha SMAN 2 Kediri"); for(p = 0; p < layarx; p++) for(q= ytemp; q < y; q++){ color c = {0,200,200,255}; if (q<0) q=0; if(buffer_r[p][q] == 0) c = bg; if (q < layary) { draw_dot(p, q, &c); } } ytemp = y; draw_kata(&x, &y,"Azka MAN Insan Cndekia"); for(p = 0; p < layarx; p++) for(q= ytemp; q < y; q++){ color c = {0,0,200,255}; if (q<0) q=0; if(buffer_r[p][q] == 0) c = bg; if (q < layary) { draw_dot(p, q, &c); } } ytemp = y; draw_kata(&x, &y,"Trian SMAN 2 Cimahi"); for(p = 0; p < layarx; p++) for(q= ytemp; q < y; q++){ color c = {0,200,0,255}; if (q<0) q=0; if(buffer_r[p][q] == 0) c = bg; if (q < layary) { draw_dot(p, q, &c); } } usleep(1000); } // Turret & Plane int y1 = 500; int x2 = 475; int y2 = 535; int x3 = 325; int y3 = 535; for (int x=700; x>=-24; x--) { // START REFRESH int p, q; for(p=0; p < layarx; p++) for(q=0; q < layary; q++){ if(buffer_r[p][q] == 0) { color c = bg; draw_dot(p, q, &c); } else if (buffer_r[p][q] == 15){ color c = {0,200,0,255}; draw_dot(p, q, &c); buffer_r[p][q] == 0; //printf("masuk\n"); } } refresh(0, 800, 0, 600); // END REFRESH color warna = {0,200,0,255}; draw_turret(&warna); color warnap = {0,200,0,255}; draw_pesawat(x, 100, &warnap); color warnat1 = {200,0,0,255}; color warnat2 = {0,0,200,255}; color warnat3 = {200,200,200,255}; //tembak1 draw_garis(399,401,y1-60,y1-60,&warnat3); draw_garis(398,402,y1,y1,&warnat3); draw_garis(399,399,y1,y1-60,&warnat3); draw_garis(401,401,y1,y1-60,&warnat3); // tembak2 //draw_garis(x2,x2+10,y2,y2-60,&warnat3); // tembak3 //draw_garis(x3,x3-10,y3,y3-60,&warnat3); jedug(1,1,799,599); for(p=0; p < layarx; p++) for(q=0; q < layary; q++){ if (buffer_r[p][q] == 15){ color c = {0,200,0,255}; draw_dot(p, q, &c); } } x3--; y3--; x2++; y2--; y1--; if (y1 == 179) { color warnae = {200,0,0,255}; for (int wait=0; wait < 1000; wait++) { draw_garis(340,400,120,60,&warnae); draw_garis(400,460,60,120,&warnae); draw_garis(460,400,120,180,&warnae); draw_garis(400,340,180,120,&warnae); } usleep(999999); for(int p = 340; p < 700; p++) for(int q= 60; q < 200; q++){ draw_dot(p, q, &bg); buffer_r[p][q] = 0; } int aaa = 340; int bbb = 100; draw_kata(&aaa,&bbb,"BOOM"); for(int p = 340; p < 700; p++) for(int q= 60; q < 200; q++){ if(buffer_r[p][q] == 0) { draw_dot(p, q, &bg); } else { draw_dot(p, q, &warnae); } } aaa += 50; bbb -= 50; usleep(999999); for(int p = 340; p < 700; p++) for(int q= 60; q < 200; q++){ draw_dot(p, q, &bg); buffer_r[p][q] = 0; } for (int y0=bbb; y0<580; y0++) { int y = y0; refresh(0, 800, y, 600); int ytemp = y; draw_kata(&aaa, &y,"O"); int p, q; for(p=0; p < layarx; p++) for(q=0; q < y; q++){ color c = {200,0,0,255}; if(buffer_r[p][q] == 0) c = bg; if (q < layary) { draw_dot(p, q, &c); buffer_r[p][q] = 0; } } } for (int y0=580; y0>500; y0--) { int y = y0; refresh(0, 800, y, 600); int ytemp = y; draw_kata(&aaa, &y,"O"); int p, q; for(p=0; p < layarx; p++) for(q=0; q < y; q++){ color c = {200,0,0,255}; if(buffer_r[p][q] == 0) c = bg; if (q < layary) { draw_dot(p, q, &c); buffer_r[p][q] = 0; } } } for (int y0=500; y0<580; y0++) { int y = y0; refresh(0, 800, y, 600); int ytemp = y; draw_kata(&aaa, &y,"O"); int p, q; for(p=0; p < layarx; p++) for(q=0; q < y; q++){ color c = {200,0,0,255}; if(buffer_r[p][q] == 0) c = bg; if (q < layary) { draw_dot(p, q, &c); buffer_r[p][q] = 0; } } } for (int y0=580; y0>560; y0--) { int y = y0; refresh(0, 800, y, 600); int ytemp = y; draw_kata(&aaa, &y,"O"); int p, q; for(p=0; p < layarx; p++) for(q=0; q < y; q++){ color c = {200,0,0,255}; if(buffer_r[p][q] == 0) c = bg; if (q < layary) { draw_dot(p, q, &c); buffer_r[p][q] = 0; } } } for (int y0=560; y0<580; y0++) { int y = y0; refresh(0, 800, y, 600); int ytemp = y; draw_kata(&aaa, &y,"O"); int p, q; for(p=0; p < layarx; p++) for(q=0; q < y; q++){ color c = {200,0,0,255}; if(buffer_r[p][q] == 0) c = bg; if (q < layary) { draw_dot(p, q, &c); buffer_r[p][q] = 0; } } } usleep(9999999); break; } usleep(10000); } munmap(fb, screensize); close(fb_driver); return 0; }
C
#include<stdio.h> #include<stdlib.h> int cmpfunc(const void* a, const void* b) { return *(int*)a - *(int*)b; } int main() { int n,m; scanf("%d %d",&n,&m); int a[n+1]; a[0] = 0; int sum = 0; for(int i=1;i<=n;++i) { scanf("%d", &a[i]); sum+=a[i]; } qsort(a,n+1,sizeof(int),cmpfunc); int mr =0; int prev = 0; for(int i=1;i<=n;++i) { mr++; if(a[i]>prev) prev++; } mr += a[n]-prev; printf("%d",sum-mr); }
C
#include<stdio.h> #include<conio.h> int main() { int sqr,cube,number; char a; printf("Enter '1'to sqr or'2 to take cube'"); scanf("%c",&a); switch(a) {case '1': printf("Enter the number you want to take square"); scanf("%d",&number); number=number*number; printf("sqr of no is%d",number); break; case'2': printf("Enter the number you want to take cube"); scanf("%d",&number); number=number*number*number; printf("cube of no is%d",number); break; default: printf("soory"); return 0; } }
C
/* * error.c: Error handling * * Written by: Stefan Frank * Ullrich Hafner * * Credits: Modelled after variable argument routines from Jef * Poskanzer's pbmplus package. * * This file is part of FIASCO (Fractal Image And Sequence COdec) * Copyright (C) 1994-2000 Ullrich Hafner <hafner@bigfoot.de> "int dummy = " change to int dummy; dummy =" for Netpbm to avoid unused variable warning. */ /* * $Date: 2000/06/14 20:49:37 $ * $Author: hafner $ * $Revision: 5.1 $ * $State: Exp $ */ #define _ERROR_C #include "config.h" #include <stdio.h> #include <errno.h> #include <stdarg.h> #define VA_START(args, lastarg) va_start(args, lastarg) #include <string.h> #if HAVE_SETJMP_H # include <setjmp.h> #endif /* HAVE_SETJMP_H */ #include "types.h" #include "macros.h" #include "error.h" #include "misc.h" #include "fiasco.h" /***************************************************************************** local variables *****************************************************************************/ static fiasco_verbosity_e verboselevel = FIASCO_SOME_VERBOSITY; static char *error_message = NULL; #if HAVE_SETJMP_H jmp_buf env; #endif /* HAVE_SETJMP_H */ /***************************************************************************** public code *****************************************************************************/ void set_error (const char *format, ...) /* * Set error text to given string. */ { va_list args; unsigned len = 0; const char *str = format; VA_START (args, format); len = strlen (format); while ((str = strchr (str, '%'))) { str++; if (*str == 's') { char *vstring = va_arg (args, char *); len += strlen (vstring); } else if (*str == 'd') { int dummy; dummy = va_arg (args, int); len += 10; } else if (*str == 'c') { int dummy; dummy = va_arg (args, int); len += 1; } else return; str++; } va_end(args); VA_START (args, format); if (error_message) Free (error_message); error_message = Calloc (len, sizeof (char)); vsprintf (error_message, format, args); va_end (args); } void error (const char *format, ...) /* * Set error text to given string. */ { va_list args; unsigned len = 0; const char *str = format; VA_START (args, format); len = strlen (format); while ((str = strchr (str, '%'))) { str++; if (*str == 's') { char *vstring = va_arg (args, char *); len += strlen (vstring); } else if (*str == 'd') { int dummy; dummy = va_arg (args, int); len += 10; } else if (*str == 'c') { int dummy; dummy = va_arg (args, int); len += 1; } else { #if HAVE_SETJMP_H longjmp (env, 1); #else /* not HAVE_SETJMP_H */ exit (1); #endif /* HAVE_SETJMP_H */ }; str++; } va_end(args); VA_START (args, format); if (error_message) Free (error_message); error_message = Calloc (len, sizeof (char)); vsprintf (error_message, format, args); va_end (args); #if HAVE_SETJMP_H longjmp (env, 1); #else /* not HAVE_SETJMP_H */ exit (1); #endif /* HAVE_SETJMP_H */ } const char * fiasco_get_error_message (void) /* * Return value: * Last error message of FIASCO library. */ { return error_message ? error_message : ""; } const char * get_system_error (void) { return strerror (errno); } void file_error (const char *filename) /* * Print file error message and exit. * * No return value. */ { error ("File `%s': I/O Error - %s.", filename, get_system_error ()); } void warning (const char *format, ...) /* * Issue a warning and continue execution. * * No return value. */ { va_list args; VA_START (args, format); if (verboselevel == FIASCO_NO_VERBOSITY) return; fprintf (stderr, "Warning: "); vfprintf (stderr, format, args); fputc ('\n', stderr); va_end (args); } void message (const char *format, ...) /* * Print a message to stderr. */ { va_list args; VA_START (args, format); if (verboselevel == FIASCO_NO_VERBOSITY) return; vfprintf (stderr, format, args); fputc ('\n', stderr); va_end (args); } void debug_message (const char *format, ...) /* * Print a message to stderr. */ { va_list args; VA_START (args, format); if (verboselevel < FIASCO_ULTIMATE_VERBOSITY) return; fprintf (stderr, "*** "); vfprintf (stderr, format, args); fputc ('\n', stderr); va_end (args); } void info (const char *format, ...) /* * Print a message to stderr. Do not append a newline. */ { va_list args; VA_START (args, format); if (verboselevel == FIASCO_NO_VERBOSITY) return; vfprintf (stderr, format, args); fflush (stderr); va_end (args); } void fiasco_set_verbosity (fiasco_verbosity_e level) { verboselevel = level; } fiasco_verbosity_e fiasco_get_verbosity (void) { return verboselevel; }
C
#include<stdio.h> // Max size for cache memory. #define MAX_SIZE 100 // Fibbinacci Number using memoisation to optimise the time complexity. static long int cache[MAX_SIZE]; long int fibbonacci(int n){ if (cache[n] != 0){ return cache[n]; } if (n == 0 || n ==1 ){ cache[n] = 1; } else { cache[n] = fibbonacci(n-1) + fibbonacci(n-2); } return cache[n]; } // Fibbonacci Number using reccursive function int fibbo(int n){ if (n == 0 || n == 1){ return 1; } else{ return fibbo(n-1) + fibbo(n-2); } } // Fibonacci number using simple iterative function int fib(int n){ int a=1,b=1,result; if(n == 1 ){ return 1;} if(n == 2){ return 2; } for (int i = 2; i <= n; i++) { result = a + b; a = b; b = result; } return result; } int main(void){ printf("%ld",fibbonacci(45)); }
C
/*==================================================== * Copyright (C) 2017 All rights reserved. * * 文件名称:execl.c * 创 建 者:cqb 2848319176@qq.com * 创建日期:2017年12月27日 * 描 述: ================================================================*/ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> int main(int argc, char *argv[]) { pid_t pid = fork(); if(pid == 0) { //int ret = execl("/bin/lsx","lsx","-l","-a","./",NULL); int ret = execl("./c.out","c.out",NULL); if(ret != 0 ) exit(ret); else exit(0); } int sta =0; wait(&sta); printf("execl ret = %u \n",WEXITSTATUS(sta)); return 0; }
C
#ifndef DEBUG_IS_DEF #define DEBUG_IS_DEF // La fonction PRINT_DEBUG permet d'afficher selectivement certains messages // de debug. Le choix du type des messages s'effectue au moyen d'une // chaine contenant des filtres. Ces filtres sont : // // '+' -- active tous les messages de debug // 'g' -- graphics // 'c' -- computations // 's' -- scheduler // 't' -- threads // 'o' -- OpenCL // 'm' -- monitoring #include <stdlib.h> #include <stdio.h> #include <stdarg.h> void debug_init (char *flags); int debug_enabled (char flag); extern char *debug_flags; static inline void PRINT_DEBUG (char flag, char *format, ...) { if (debug_flags != NULL && debug_enabled (flag)) { va_list ap; va_start (ap, format); vfprintf (stderr, format, ap); va_end (ap); } } #endif
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef scalar_t__ pid_t ; /* Variables and functions */ int /*<<< orphan*/ WEXITED ; int /*<<< orphan*/ WEXITSTATUS (int) ; scalar_t__ WIFEXITED (int) ; int WTERMSIG (int) ; int /*<<< orphan*/ badioctl (scalar_t__) ; int /*<<< orphan*/ exit (int /*<<< orphan*/ ) ; int /*<<< orphan*/ fflush (int /*<<< orphan*/ ) ; scalar_t__ fork () ; scalar_t__ getpid () ; int /*<<< orphan*/ printf (char*,int) ; int /*<<< orphan*/ stdout ; scalar_t__ waitpid (scalar_t__,int*,int /*<<< orphan*/ ) ; int main() { pid_t child, parent = getpid(); int status; for (;;) { if ((child = fork()) == 0) badioctl(parent); while (waitpid(child, &status, WEXITED) != child) continue; if (WIFEXITED(status)) { /* * Our child exited by design -- we'll exit with * the same status code. */ exit(WEXITSTATUS(status)); } /* * Our child died on a signal. Respawn it. */ printf("badioctl: child died on signal %d; respawning.\n", WTERMSIG(status)); fflush(stdout); } /* NOTREACHED */ return (0); }
C
// generic target-agnostic assembly parser // // “but... isn't that impossible...?” // // Well strictly yes, in the sense that different platforms do not have a common // assembly format. Even different assemblers do not have a common format. // Instead of trying to cope directly with this variation, this parser works on // the fuzzy notion that each line of an assembly file consists of one of the // following forms: // // 1. #define FOO... // 2. #include <...> or #include "..." // 3. function_name: // 4. branch_instruction target // 5. something else irrelevant // // (1) and (2) give us enough pre-processor functionality for Clink’s needs. For // (3), the rules for what can be a function name are essentially // “[a-zA-Z_.][\w_.$@]*”. This isn't accurate, but matches most symbols humans // come up with. For (4), the parser has a loose understanding of what branch // instructions look like on several relevant platforms. Anything else that // falls under (5) just gets ignored. // // The above sounds like quite a dumb approach, but you would be surprised how // well it works. #pragma once #include <clink/db.h> #ifdef __cplusplus extern "C" { #endif #ifndef CLINK_API #define CLINK_API __attribute__((visibility("default"))) #endif /** parse the given assembly file into the given database * * The \p filename parameter must be an absolute path. * * \param db Database to insert into * \param filename Path to source file to parse * \return 0 on success or an errno on failure */ CLINK_API int clink_parse_asm(clink_db_t *db, const char *filename); #ifdef __cplusplus } #endif
C
//i2c.c // NOTE: /* Currently, using the following methods to implement i2c have a problem: when used to transmit multiple characters to a LCD screen in one function call, some character will ended up missing. There's no telling what caused this, but it could be caused by the transmittion speed difference between Atmega328p and LCD screen. Current solution is to instead decrease i2c speed to half (50 kHz), and only send one character at a time. (Or just a few?) */ /* ----------------------------------------------------------------------- */ /* i2c_io - write and read bytes to a slave I2C device This funtions write "an" bytes from array "ap" and then "wn" bytes from array "wp" to I2C device at address "device_addr". It then reads "rn" bytes from the same device to array "rp". Return values (might not be a complete list): 0 - Success 0x20 - NAK received after sending device address for writing 0x30 - NAK received after sending data 0x38 - Arbitration lost with address or data 0x48 - NAK received after sending device address for reading - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This "i2c_io" I2C routine is an attempt to provide an I/O function for both reading and writing, rather than have separate functions. I2C writes consist of sending a stream of bytes to the slave device. In some cases the first few bytes may be the internal address in the device, and then the data to be stored follows. For example, EEPROMs like the 24LC256 require a two-byte address to precede the data. The DS1307 RTC requires a one-byte address. I2C reads often consist of first writing one or two bytes of internal address data to the device and then reading back a stream of bytes starting from that address. Some devices appear to claim that that reads can be done without first doing the address writes, but so far I haven't been able to get any to work that way. This function does writing and reading by using pointers to three arrays "ap", "wp", and "rp". The function performs the following actions in this order: If "an" is greater than zero, then "an" bytes are written from array "ap" If "wn" is greater then zero, then "wn" bytes are written from array "wp" If "rn" is greater then zero, then "rn" byte are read into array "rp" Any of the "an", "wn", or "rn" can be zero. The reason for separate "ap" and "wp" arrays is that the address data can be taken from one array (ap), and then the write data from another (wp) without requiring that the contents be merged into one array before calling the function. This means the following three calls all do exactly the same thing. i2c_io(0xA0, buf, 100, NULL, 0, NULL, 0); i2c_io(0xA0, NULL, 0, buf, 100, NULL, 0); 12c_io(0xA0, buf, 2, buf+2, 98, NULL, 0); In all cases 100 bytes from array "buf" will be written to the I2C device at bus address 0xA0. A typical write with a 2-byte address is done with i2c_io(0xA0, abuf, 2, wbuf, 50, NULL, 0); A typical read with a 1-byte address is done with i2c_io(0xD0, abuf, 1, NULL, 0, rbuf, 20); */ #include "i2c.h" uint8_t i2c_io(uint8_t device_addr, uint8_t *ap, uint16_t an, uint8_t *wp, uint16_t wn, uint8_t *rp, uint16_t rn) { uint8_t status, send_stop, wrote, start_stat; status = 0; wrote = 0; send_stop = 0; if (an > 0 || wn > 0) { wrote = 1; send_stop = 1; TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTA); // Send start condition while (!(TWCR & (1 << TWINT))); // Wait for TWINT to be set status = TWSR & 0xf8; if (status != 0x08) // Check that START was sent OK return(status); TWDR = device_addr & 0xfe; // Load device address and R/W = 0; TWCR = (1 << TWINT) | (1 << TWEN); // Start transmission while (!(TWCR & (1 << TWINT))); // Wait for TWINT to be set status = TWSR & 0xf8; if (status != 0x18) { // Check that SLA+W was sent OK if (status == 0x20) // Check for NAK goto nakstop; // Send STOP condition return(status); // Otherwise just return the status } // Write "an" data bytes to the slave device while (an-- > 0) { TWDR = *ap++; // Put next data byte in TWDR TWCR = (1 << TWINT) | (1 << TWEN); // Start transmission while (!(TWCR & (1 << TWINT))); // Wait for TWINT to be set status = TWSR & 0xf8; if (status != 0x28) { // Check that data was sent OK if (status == 0x30) // Check for NAK goto nakstop; // Send STOP condition return(status); // Otherwise just return the status } } // Write "wn" data bytes to the slave device while (wn-- > 0) { TWDR = *wp++; // Put next data byte in TWDR TWCR = (1 << TWINT) | (1 << TWEN); // Start transmission while (!(TWCR & (1 << TWINT))); // Wait for TWINT to be set status = TWSR & 0xf8; if (status != 0x28) { // Check that data was sent OK if (status == 0x30) // Check for NAK goto nakstop; // Send STOP condition return(status); // Otherwise just return the status } } status = 0; // Set status value to successful } if (rn > 0) { send_stop = 1; // Set the status value to check for depending on whether this is a // START or repeated START start_stat = (wrote) ? 0x10 : 0x08; // Put TWI into Master Receive mode by sending a START, which could // be a repeated START condition if we just finished writing. TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTA); // Send start (or repeated start) condition while (!(TWCR & (1 << TWINT))); // Wait for TWINT to be set status = TWSR & 0xf8; if (status != start_stat) // Check that START or repeated START sent OK return(status); TWDR = device_addr | 0x01; // Load device address and R/W = 1; TWCR = (1 << TWINT) | (1 << TWEN); // Send address+r while (!(TWCR & (1 << TWINT))); // Wait for TWINT to be set status = TWSR & 0xf8; if (status != 0x40) { // Check that SLA+R was sent OK if (status == 0x48) // Check for NAK goto nakstop; return(status); } // Read all but the last of n bytes from the slave device in this loop rn--; while (rn-- > 0) { TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA); // Read byte and send ACK while (!(TWCR & (1 << TWINT))); // Wait for TWINT to be set status = TWSR & 0xf8; if (status != 0x50) // Check that data received OK return(status); *rp++ = TWDR; // Read the data } // Read the last byte TWCR = (1 << TWINT) | (1 << TWEN); // Read last byte with NOT ACK sent while (!(TWCR & (1 << TWINT))); // Wait for TWINT to be set status = TWSR & 0xf8; if (status != 0x58) // Check that data received OK return(status); *rp++ = TWDR; // Read the data status = 0; // Set status value to successful } nakstop: // Come here to send STOP after a NAK if (send_stop) TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO); // Send STOP condition return(status); } /* i2c_init - Initialize the I2C port */ void i2c_init(uint8_t bdiv) { TWSR = 0; // Set prescalar for 1 TWBR = bdiv; // Set bit rate register }
C
int howtoplay(){ int i,point=0; system("cls"); printf("\n\n\n\t"); for(i=0;i<57;i++){printf("#"); } printf("\n\t#"); for(i=0;i<55;i++){ printf(" "); } printf("#\n"); printf("\t#"); textcolor(COLOR_CYAN,COLOR_BLACK);printf(" ||||| || || ||||| |||||| || || || || ");resetcolor();printf("#\n"); printf("\t#"); textcolor(COLOR_CYAN,COLOR_BLACK);printf(" || || || || || || || || || || || ");resetcolor();printf("#\n"); printf("\t#"); textcolor(COLOR_CYAN,COLOR_BLACK);printf(" || || || || || || || ||| || || ");resetcolor();printf("#\n"); printf("\t#"); textcolor(COLOR_CYAN,COLOR_BLACK);printf(" || || || || || || || || || || || ");resetcolor();printf("#\n"); printf("\t#"); textcolor(COLOR_CYAN,COLOR_BLACK);printf(" ||||| ||||| ||||| |||||| || || ||||| ");resetcolor();printf("#\n"); printf("\t# #\n"); printf("\t#"); textcolor(COLOR_VIOLET,COLOR_BLACK);printf(" How to play ");resetcolor();printf("#\n"); printf("\t# #\n\t"); for(i=0;i<57;i++){ printf("#");} textcolor(COLOR_AQUA,COLOR_BLACK);printf("\n\n\n\t The aim of the puzzle is to fill each cell of the grid "); printf("\n\twith digits from1 to 9. Each row,column,and subgrid must "); printf("\n\tcontain only one instance of each digit. Finish each puzzle"); printf("\n\t as fast as possible to reach a high score. "); printf("\n\n\t The player must enter the number of rows and number of digits. "); printf("\n\tThe accuracy of the space before. It will be seen from the red channel. "); printf("\n\tThen on the right. It is the answer to the puzzle. If you want to leave"); printf("\n\tthe game.Player just try to wear the number 0 to return to the menu."); resetcolor(); printf(" \n\n"); textcolor(COLOR_YELLOW,COLOR_BLACK);printf("\t Press to back menu..");resetcolor(); getch(); system("cls"); return 0;; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { // give me an expression -maybe later char word[] = "abbabba"; int length = strlen(word); // for (int i = 0; i < length/2; i++) { if ( word[i] != word[length-1-i]) { printf("This is not palindrome\n"); break; } } printf("\n"); return 0; }
C
//gesto de funes relativas aos alunos #include <stdio.h> #include <stdlib.h> #include <string.h> #include "gestao_Alunos.h" #include "funcoes_auxiliares.h" void mostrarDadosAlunos(tipoAluno vetorAluno[], int quantAlunos) { int i; if (quantAlunos == 0) { printf("\n\nERRO: Nao existem alunos inscritos!!\n\n"); } else { printf("\n\n**************** /* DADOS DOS ALUNOS */ ****************\n"); for (i=0; i < quantAlunos; i++) { escreverDadosAluno(vetorAluno[i]); } } } void escreverDadosAluno(tipoAluno aluno) { printf("\n\n**************** /* ALUNO %d */ ****************", aluno.numero); printf("\nNome: %s", aluno.nome); } void acrescentarAluno(tipoAluno vetorAluno[], int *quantAlunos) { int posicao; if(*quantAlunos==MAX_ALUNOS) { printf("\n\nERRO: Impossivel inscrever o aluno!!"); printf("\n O limite dos alunos foi atingido!!\n\n"); } else { vetorAluno[*quantAlunos]=lerDadosAluno(); posicao=procuraAlunoNumero(vetorAluno, *quantAlunos, vetorAluno[*quantAlunos].numero); if(posicao!=-1) { printf("\n\nERRO: Ja existe um aluno com o numero indicado!!"); } else { (*quantAlunos)++; } } } int procuraAlunoNumero(tipoAluno vetorAluno[], int quantAlunos, int numero) { int i, posicao; posicao = -1; for(i=0; i<quantAlunos; i++) { if(vetorAluno[i].numero==numero) { posicao=i; i=quantAlunos; } } return posicao; } tipoAluno lerDadosAluno() { tipoAluno aluno; printf("\n**************** /* NOVO ALUNO */ ****************\n"); aluno.numero=lerInteiro("\nNumero de Estudante: ", MIN_NUMALUNO, MAX_NUMALUNO); lerString("\nNome do Aluno: ",aluno.nome, MAX_STRING); return aluno; }
C
/** * @file: types.h * Definition of simple types used in implementation */ /* * Utils library * Copyright (C) 2012 Boris Shurygin */ #pragma once #ifndef TYPES_H #define TYPES_H /* Size-dependent types (architechture-dependent byte order) */ typedef signed char Int8; /* 8 bit signed */ typedef unsigned char UInt8; /* 8 bit unsigned */ typedef short Int16; /* 16 bit signed */ typedef unsigned short UInt16; /* 16 bit unsigned */ typedef int Int32; /* 32 bit signed */ typedef unsigned int UInt32; /* 32 bit unsigned */ typedef float Float; /* Single-precision floating point value */ typedef double Double; /* Double-precision floating point value */ #if defined(OS_WIN32) && !defined(CC_GNU) typedef __int64 Int64; /* 64 bit signed */ typedef unsigned __int64 UInt64; /* 64 bit unsigned */ #else typedef long long Int64; /* 64 bit signed */ typedef unsigned long long UInt64; /* 64 bit unsigned */ #endif #endif /* TYPES_H */
C
// Copyright 2018 Schibsted #include <stdbool.h> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <stdlib.h> #include <arpa/inet.h> #include <string.h> #include <err.h> #include <fcntl.h> #include <unistd.h> #include <signal.h> #include <netdb.h> #include "sbp/macros.h" #include "sbp/popt.h" bool ipv4, ipv6, flood; POPT_USAGE("[options] addr port [ack_fifo]"); POPT_ARGUMENT("addr", "Address to send to."); POPT_ARGUMENT("port", "Port to send to."); POPT_ARGUMENT("ack_fifo", "Optionally read acks from this path."); POPT_BOOL("4", false, &ipv4, "Use only IPv4."); POPT_BOOL("6", false, &ipv6, "Use only IPv6."); POPT_BOOL("flood", false, &flood, "Read only one input and send it as fast as possible continuously."); static void transmit(int s, char *buf, struct addrinfo *res, int ack_sock) { if (sendto(s, buf, strlen(buf), 0, res->ai_addr, res->ai_addrlen) < 0) warn("sendto"); if (ack_sock != -1) { char ackbuf[4]; alarm(4); /* signal(SIGALRM, sig_alarm); */ if (read(ack_sock, ackbuf, 4) == -1) { err(1, "reading ACK failed"); } alarm(0); } } int main(int argc, char *argv[]) { int s; char buf[1024]; int ack_sock = -1; struct addrinfo hints = { .ai_socktype = SOCK_DGRAM, .ai_flags = AI_ADDRCONFIG }; struct addrinfo *res = NULL; int r; popt_parse_ptrs(&argc, &argv); if (argc < 2) popt_usage(NULL, false); if (ipv4) hints.ai_family = AF_INET; if (ipv6) hints.ai_family = AF_INET6; if ((r = getaddrinfo(argv[0], argv[1], &hints, &res))) errx(1, "getaddrinfo(%s, %s): %s", argv[0], argv[1], gai_strerror(r)); s = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (s < 0) err(1, "socket"); /* Wait for an ack */ if (argc == 3) { ack_sock = open(argv[2], O_RDONLY); if (ack_sock == -1) err(1, "open"); } if (!flood) { while (fgets(buf, sizeof(buf), stdin)) { transmit(s, buf, res, ack_sock); } } else { UNUSED_RESULT(fgets(buf, sizeof(buf), stdin)); while (1) { transmit(s, buf, res, ack_sock); } } if (ack_sock != -1) close(ack_sock); freeaddrinfo(res); return 0; }
C
#include "../buildins/minishell.h" char *get_value_by_key(t_data *data, char *key) { int key_d_len; int key_s_len; t_list *tmp; tmp = data->env_lst; key_s_len = ft_strlen(key); while (tmp) { key_d_len = ft_strlen(((t_env *)tmp->content)->key); if (!ft_strncmp(((t_env *)tmp->content)->key, key, \ key_d_len) && (key_s_len == key_d_len)) { if (((t_env *)tmp->content)->value) return (ft_strdup(((t_env *)tmp->content)->value)); else return (NULL); } tmp = tmp->next; } return (NULL); } int perr(char *cmd, char *arg, char *err, int code) { ft_putstr_fd("minishell", STDERR_FILENO); ft_putstr_fd(": ", STDERR_FILENO); if (cmd) { ft_putstr_fd(cmd, STDERR_FILENO); ft_putstr_fd(": ", STDERR_FILENO); } if (arg) { ft_putstr_fd(arg, STDERR_FILENO); ft_putstr_fd(": ", STDERR_FILENO); } if (err) ft_putstr_fd(err, STDERR_FILENO); ft_putstr_fd("\n", STDERR_FILENO); return (code); } int is_dir(char *path) { struct stat sb; if (stat(path, &sb) == -1) return (0); if ((sb.st_mode & S_IFMT) == S_IFDIR) return (1); return (0); } int check_cmd(char *arg) { if (ft_strrchr(arg, '/')) { return (1); } return (0); } void check_fd(t_command *tmp_cmd, char **args) { if ((tmp_cmd->fd_out == -1 || tmp_cmd->fd_in == -1 || tmp_cmd->fd_hr_doc == -1)) exit(perr(args[0], 0, strerror(errno), 1)); }
C
#include <stdio.h> #include <stdlib.h> #include <SDL.h> #include <SDL2/SDL_image.h> #include <time.h> #include "Briques.h" #define SCREEN_WIDTH 1024 #define SCREEN_HEIGHT 780 void initbriques(SDL_Rect2 briques[32]){ //BUT: Remplir un tableau avec les coordonnes des briques //ENTREE: Tableau de briques vide //SORTIE: Tableau de briques rempli avec les bonnes coordonnes int i,x,y; x=0; y=24; for(i=0;i<32;i++){ briques[i].brique.x=x; briques[i].brique.y=y; briques[i].brique.w=64; briques[i].brique.h=24; briques[i].destroyed=False; x=x+64; if(i==15){ y=y+24; x=0; } } }
C
// SeqList.h #ifndef _SEQLIST_H_ #define _SEQLIST_H_ #include"Common.h" #define SEQLIST_DEFAULT_SIZE 8 //˳Ľṹ typedef struct SeqList { ElemType *base; size_t capacity; size_t size; }SeqList; void SeqListInit(SeqList *plist); void SeqListDestroy(SeqList *plist);// void SeqListPushBack(SeqList *plist, ElemType x); void SeqListPushFront(SeqList *plist, ElemType x); void SeqListShow(SeqList *plist); void SeqListPopBack(SeqList *plist); void SeqListPopFront(SeqList *plist); void SeqListClear(SeqList *plist); bool SeqListInsertByPos(SeqList *plist, int pos, ElemType x); void SeqListInsertByVal(SeqList *plist, ElemType x); void SeqListEraseByPos(SeqList *plist, int pos); void SeqListEraseByVal(SeqList *plist, ElemType key); void SeqListSort(SeqList *plist); size_t SeqListLength(SeqList *plist); size_t SeqListCapacity(SeqList *plist); int SeqListFind(SeqList *plist, ElemType key); void SeqListReverse(SeqList *plist); ///////////////////////////////////////////////////////////////////////////////// void SeqListPopFront(SeqList *plist); ////////////////////////////////////////////////////////////////////////////////// bool IsFull(SeqList *plist) { assert(plist != NULL); return plist->size >= plist->capacity; } bool IsEmpty(SeqList *plist) { assert(plist != NULL); return plist->size == 0; } void SeqListInit(SeqList *plist) { assert(plist != NULL); plist->capacity = SEQLIST_DEFAULT_SIZE; plist->base = (ElemType*)malloc(sizeof(ElemType)*plist->capacity); plist->size = 0; } void SeqListDestroy(SeqList *plist) { assert(plist != NULL); free(plist->base); plist->base = NULL; plist->capacity = plist->size = 0; } size_t SeqListLength(SeqList *plist) { assert(plist != NULL); return plist->size; } size_t SeqListCapacity(SeqList *plist) { assert(plist != NULL); return plist->capacity; } void SeqListPushBack(SeqList *plist, ElemType x) { assert(plist != NULL); if (IsFull(plist)) { printf("˳%d β.\n", x); return; } plist->base[plist->size] = x; plist->size++; } void SeqListPushFront(SeqList *plist, ElemType x) { assert(plist != NULL); if (IsFull(plist)) { printf("˳%d ͷ.\n", x); return; } for (size_t i = plist->size; i > 0; --i) { plist->base[i] = plist->base[i - 1]; } plist->base[0] = x; plist->size++; } void SeqListShow(SeqList *plist) { assert(plist != NULL); for (size_t i = 0; i < plist->size; ++i) { printf("%d ", plist->base[i]); } printf("\n"); } void SeqListPopBack(SeqList *plist) { assert(plist != NULL); if (IsEmpty(plist)) { printf("˳ѿգܽβɾ.\n"); return; } plist->size--; } void SeqListPopFront(SeqList *plist) { assert(plist != NULL); if (IsEmpty(plist)) { printf("˳ѿգܽͷɾ.\n"); return; } for (size_t i = 0; i < plist->size; ++i) { plist->base[i] = plist->base[i + 1]; } plist->size--; } bool SeqListInsertByPos(SeqList *plist, int pos, ElemType x) { assert(plist != NULL); if (IsFull(plist)) { printf("˳%d ܲ.\n", x); return false; } if (pos<0 || pos>plist->size) { printf("Ҫλ[%d]ǷǷλ, %d ܲ.\n", pos, x); return false; } for (size_t i = pos ; i < plist->size; ++i) { plist->base[pos + 1] = plist->base[pos]; } plist->base[pos] = x; plist->size++; return true; } void SeqListInsertByVal(SeqList *plist, ElemType x) { assert(plist != NULL); if (IsFull(plist)) { printf("˳,%d ܲ.\n", x); return false; } size_t i = 0; while (x>plist->base[i]){ ++i; } size_t pos = i; for (i = plist->size; i >pos; --i){ plist->base[i] = plist->base[i - 1]; } plist->base[pos] = x; plist->size++; } void SeqListEraseByPos(SeqList *plist, int pos) { assert(plist != NULL); if (IsEmpty(plist)) { printf("˳ѿգܽɾ.\n"); return; } if (pos < 0 || pos >= plist->size){ printf("λòϷλ.\n"); return; } for (size_t i = pos; i < plist->size; ++i){ plist->base[i] = plist->base[i + 1]; } plist->size--; } void SeqListEraseByVal(SeqList *plist, ElemType key) { assert(plist != NULL); int pos = SeqListFind(plist, key); if (pos == -1) return; SeqListEraseByPos(plist, pos); } int SeqListFind(SeqList *plist, ElemType key) { assert(plist != NULL); int pos = 0; while (pos < plist->size&&key != plist->base[pos]){ pos++; } if (plist->size == pos ){ pos = -1; } return pos; } void SeqListSort(SeqList *plist) { assert(plist != NULL); for (size_t i = 0; i < plist->size - 1; i++) { for (size_t j = 0; j < plist->size - 1 - i; j++) { if (plist->base[j]>plist->base[j - +1]) { Swap(&plist->base[j], &plist->base[j + 1]); } } } } void SeqListReverse(SeqList *plist) { assert(plist != NULL); if (plist->size == 1) return; int start = 0; int end = plist->size - 1; while (start < end){ Swap(&plist->base[start], &plist->base[end]); start++; end--; } } void SeqListClear(SeqList *plist) { assert(plist != NULL); plist->size = 0; } #endif
C
/**\ * Copyright (c) 2021 Bosch Sensortec GmbH. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause **/ /******************************************************************************/ /*! Header Files */ #include <stdio.h> #include "bmi270_legacy.h" #include "common.h" /******************************************************************************/ /*! Macro definition */ /*! Earth's gravity in m/s^2 */ #define GRAVITY_EARTH (9.80665f) /******************************************************************************/ /*! Static Function Declaration */ /*! * @brief This internal API is used to set configurations for accel. * * @param[in] dev : Structure instance of bmi2_dev. * * @return Status of execution. */ static int8_t set_accel_config(struct bmi2_dev *dev); /*! * @brief This function converts lsb to meter per second squared for 16 bit accelerometer at * range 2G, 4G, 8G or 16G. * * @param[in] val : LSB from each axis. * @param[in] g_range : Gravity range. * @param[in] bit_width : Resolution for accel. * * @return Gravity. */ static float lsb_to_mps2(int16_t val, float g_range, uint8_t bit_width); /******************************************************************************/ /*! Functions */ /* This function starts the execution of program. */ int main(void) { /* Sensor initialization configuration. */ struct bmi2_dev dev; /* Status of api are returned to this variable. */ int8_t rslt; /* Variable to define limit to print accel data. */ uint8_t limit = 20; /* Assign accel sensor to variable. */ uint8_t sensor_list = BMI2_ACCEL; /* Create an instance of sensor data structure. */ struct bmi2_sens_data sensor_data = { { 0 } }; /* Initialize the interrupt status of accel. */ uint16_t int_status = 0; uint8_t indx = 0; float x = 0, y = 0, z = 0; /* Interface reference is given as a parameter * For I2C : BMI2_I2C_INTF * For SPI : BMI2_SPI_INTF */ rslt = bmi2_interface_init(&dev, BMI2_SPI_INTF); bmi2_error_codes_print_result(rslt); /* Initialize bmi270_legacy. */ rslt = bmi270_legacy_init(&dev); bmi2_error_codes_print_result(rslt); if (rslt == BMI2_OK) { /* Accel configuration settings. */ rslt = set_accel_config(&dev); bmi2_error_codes_print_result(rslt); if (rslt == BMI2_OK) { /* NOTE: * Accel enable must be done after setting configurations */ rslt = bmi270_legacy_sensor_enable(&sensor_list, 1, &dev); bmi2_error_codes_print_result(rslt); printf("Accel raw data and gravity data in m/s^2 \n"); /* Loop to print the accel data when interrupt occurs. */ while (indx <= limit) { /* To get the status of accel data ready interrupt. */ rslt = bmi2_get_int_status(&int_status, &dev); bmi2_error_codes_print_result(rslt); /* To check the accel data ready interrupt status and print the status for 10 samples. */ if (int_status & BMI2_ACC_DRDY_INT_MASK) { /* Get accelerometer data for x, y and z axis. */ rslt = bmi2_get_sensor_data(&sensor_data, &dev); bmi2_error_codes_print_result(rslt); printf("\nAcc_X = %d\t", sensor_data.acc.x); printf("Acc_Y = %d\t", sensor_data.acc.y); printf("Acc_Z = %d\t", sensor_data.acc.z); /* Converting lsb to meter per second squared for 16 bit accelerometer at 2G range. */ x = lsb_to_mps2(sensor_data.acc.x, 2, dev.resolution); y = lsb_to_mps2(sensor_data.acc.y, 2, dev.resolution); z = lsb_to_mps2(sensor_data.acc.z, 2, dev.resolution); /* Print the data in m/s2. */ printf("Acc_ms2_X = %4.2f, Acc_ms2_Y = %4.2f, Acc_ms2_Z = %4.2f\n", x, y, z); indx++; } } } } bmi2_coines_deinit(); return rslt; } /*! * @brief This internal API is used to set configurations for accel. */ static int8_t set_accel_config(struct bmi2_dev *dev) { /* Status of api are returned to this variable. */ int8_t rslt; /* Structure to define accelerometer configuration. */ struct bmi2_sens_config config; /* Configure the type of feature. */ config.type = BMI2_ACCEL; /* Get default configurations for the type of feature selected. */ rslt = bmi270_legacy_get_sensor_config(&config, 1, dev); bmi2_error_codes_print_result(rslt); if (rslt == BMI2_OK) { /* NOTE: The user can change the following configuration parameters according to their requirement. */ /* Output Data Rate */ config.cfg.acc.odr = BMI2_ACC_ODR_100HZ; /* Gravity range of the sensor (+/- 2G, 4G, 8G, 16G). */ config.cfg.acc.range = BMI2_ACC_RANGE_2G; /* The bandwidth parameter is used to configure the number of sensor samples that are averaged * if it is set to 2, then 2^(bandwidth parameter) samples * are averaged, resulting in 4 averaged samples. * Note1 : For more information, refer the datasheet. * Note2 : A higher number of averaged samples will result in a lower noise level of the signal, but * this has an adverse effect on the power consumed. */ config.cfg.acc.bwp = BMI2_ACC_NORMAL_AVG4; /* Enable the filter performance mode where averaging of samples * will be done based on above set bandwidth and ODR. * There are two modes * 0 -> Ultra low power mode * 1 -> High performance mode(Default) * For more info refer datasheet. */ config.cfg.acc.filter_perf = BMI2_PERF_OPT_MODE; /* Set the accel configurations. */ rslt = bmi270_legacy_set_sensor_config(&config, 1, dev); bmi2_error_codes_print_result(rslt); /* Map data ready interrupt to interrupt pin. */ rslt = bmi2_map_data_int(BMI2_DRDY_INT, BMI2_INT1, dev); bmi2_error_codes_print_result(rslt); } return rslt; } /*! * @brief This function converts lsb to meter per second squared for 16 bit accelerometer at * range 2G, 4G, 8G or 16G. */ static float lsb_to_mps2(int16_t val, float g_range, uint8_t bit_width) { float half_scale = ((float)(1 << bit_width) / 2.0f); return (GRAVITY_EARTH * val * g_range) / half_scale; }
C
#define _XOPEN_SOURCE 700 #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/times.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> void childParentProcessing(int processStatus, pid_t pId); int main(int argv,char * args[]){ time_t start, stop; int status =0; //struct tms buf, data typr: struct tms. // this has the following functions: // tms_utime //tms_stime //tms_cutime // tms_cstime struct tms buf; clock_t sinceStart; start = time(NULL); //start the clock printf("START: %ld\n",start); //if the child id remains awith value of -1 after code line 19 // then there is a problem statrting the child process... terminate the program. pid_t currentProcessID = fork(); if(currentProcessID == -1){ printf("Error: child process did not initiate!\n"); exit(1); } // getppid() returns parent PID, // getpid() retrurns child PID //if child pid == 0 then exe code for child // else child pid will be positice and exe code for parent. if(currentProcessID == 0){ childParentProcessing(status,currentProcessID); // instead of zeros }else{ waitpid(currentProcessID,&status, 0); childParentProcessing(status,currentProcessID); sleep(2);// to delay the time difference 2 seconds // popilating the struct. sinceStart = times(&buf); printf("USER: %ld, SYS: %ld\nCUSER: %ld, CSYS: %ld\n",buf.tms_utime,buf.tms_stime,buf.tms_cutime, buf.tms_cstime); //the times needs to be delayed because this sould be the last program to run. printf("STOP: %ld\n",time(NULL)); } return 0; }//main // Function manages the different process and displays their results. void childParentProcessing(int processStatus, pid_t currentProcessid) { pid_t pid = getpid(); pid_t ppid = getppid(); if(processStatus == 0 && currentProcessid == 0) { printf("PPID: %d, PID: %d\n",ppid, pid); }else { printf("PPID: %u, PID: %u, CPID: %d, RETVAL: %d\n",ppid, pid, currentProcessid,processStatus); } }//childParentProcessing
C
#ifndef LIST_H #define LIST_H #define SUCCESS 0 #define FAILURE 1 typedef struct node{ int value; struct node *next; }node_t; node_t * newNode(int); node_t * push(node_t *, node_t *); node_t * pop(node_t *); void checkValue(node_t *, int); node_t * deleteNode(node_t *, int); node_t * reverseList(node_t *); void printList(node_t *); void freeList(node_t *); #endif // LIST_H
C
#include <iostream> #include <unistd.h> #include <pthread.h> #include <pruio.h> #define NOTE1_GPIO 60 #define NOTE2_GPIO 50 #define NOTE3_GPIO 51 #define NOTE4_GPIO 30 #define NOTE5_GPIO 31 #define NOTE6_GPIO 48 #define NOTE7_GPIO 49 #define NOTE1_ANGLE 90 #define OTHER_NOTE_ANGLE0 0 #define OTHER_NOTE_ANGLE45 45 #define OTHER_NOTE_ANGLE60 60 #define STRUM_TIME 1000000 // 1 second #define NOTE_COUNT 7 #define CHORD_COUNT 2 struct note_gpio_mapping { uint8_t gpio_pin; uint32_t servo_angle; }; note_gpio_mapping chord_mappings[CHORD_COUNT][NOTE_COUNT - 1] = { // Chord 1 { {NOTE2_GPIO, OTHER_NOTE_ANGLE0}, {NOTE3_GPIO, OTHER_NOTE_ANGLE0}, {NOTE4_GPIO, OTHER_NOTE_ANGLE45}, {NOTE5_GPIO, OTHER_NOTE_ANGLE60}, {NOTE6_GPIO, OTHER_NOTE_ANGLE60}, {NOTE7_GPIO, OTHER_NOTE_ANGLE0}, }, // Chord 2 { {NOTE3_GPIO, OTHER_NOTE_ANGLE0}, {NOTE4_GPIO, OTHER_NOTE_ANGLE0}, {NOTE5_GPIO, OTHER_NOTE_ANGLE45}, {NOTE6_GPIO, OTHER_NOTE_ANGLE60}, {NOTE2_GPIO, OTHER_NOTE_ANGLE60}, {NOTE7_GPIO, OTHER_NOTE_ANGLE0}, } }; pthread_mutex_t pru_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t strum_done_cond = PTHREAD_COND_INITIALIZER; void* playChord(void *vargp) { for (int c = 0; c < CHORD_COUNT; c++) { pthread_mutex_lock(&pru_mutex); pruIo *io = pruio_new(PRUIO_DEF_ACTIVE, 0x98, 0, 1); if (io->Err) { printf("pruio_new failed (%s)\n", io->Err); pruio_destroy(io); pthread_mutex_unlock(&pru_mutex); return NULL; } for (int i = 0; i < NOTE_COUNT - 1; i++) { pruio_pwm_setangle(io, chord_mappings[c][i].gpio_pin, chord_mappings[c][i].servo_angle); if (io->Err) { printf("failed setting servo angle (%s)\n", io->Err); pruio_destroy(io); pthread_mutex_unlock(&pru_mutex); return NULL; } } pthread_cond_signal(&strum_done_cond); pthread_mutex_unlock(&pru_mutex); usleep(STRUM_TIME); pruio_destroy(io); } return NULL; } void* playNote1(void *vargp) { for (int c = 0; c < CHORD_COUNT; c++) { pthread_mutex_lock(&pru_mutex); pthread_cond_wait(&strum_done_cond, &pru_mutex); pruIo *io = pruio_new(PRUIO_DEF_ACTIVE, 0x98, 0, 1); if (io->Err) { printf("pruio_new failed (%s)\n", io->Err); pruio_destroy(io); pthread_mutex_unlock(&pru_mutex); return NULL; } pruio_pwm_setangle(io, NOTE1_GPIO, NOTE1_ANGLE); if (io->Err) { printf("failed setting servo angle (%s)\n", io->Err); pruio_destroy(io); pthread_mutex_unlock(&pru_mutex); return NULL; } pthread_mutex_unlock(&pru_mutex); usleep(STRUM_TIME); pruio_destroy(io); } return NULL; } int main() { pthread_t thread_id1, thread_id2; pthread_create(&thread_id1, NULL, playChord, NULL); pthread_create(&thread_id2, NULL, playNote1, NULL); pthread_join(thread_id1, NULL); pthread_join(thread_id2, NULL); return 0; }
C
#include<stdio.h> int main() { char name[10]; char fname[10]; printf("Please enter your name and firstname:\n"); scanf("%s%s",&name,&fname); printf("%s,%s",name,fname); return 0; }
C
/*! @file * * @brief RTC module: Routines for controlling the Real Time Clock (RTC) on the TWR-K70F120M. * * This module contains the functions for operating the real time clock (RTC). * * @author Liang Wang * @date 2016-06-28 */ /*! ** @addtogroup RTC_module RTC module documentation ** @{ */ /* MODULE RTC */ // new types #include "types.h" #include "MK70F12.h" #include "PE_Types.h" #include "LEDs.h" #include "RTC.h" void (*userFunctionB)(void *); /*!< Callback function. */ void *userArgumentsB; /*!< Callback function. */ BOOL RTC_Init(void (*userFunction)(void *), void *userArguments) { /*!save status register and disable interrupt*/ EnterCritical(); userFunctionB = userFunction; /*!assign user callback function to local userFunction.*/ userArgumentsB = userArguments; /*!assign user arguments to local user argument.*/ SIM_SCGC6 |= SIM_SCGC6_RTC_MASK; /*!enable the clock gate*/ RTC_CR |= RTC_CR_OSCE_MASK; /*!enable 32.768kHz oscillator*/ RTC_CR |= RTC_CR_SC2P_MASK; /*!enable the additional load*/ RTC_CR |= RTC_CR_SC16P_MASK; RTC_LR &= ~RTC_LR_CRL_MASK; /*!lock the control register.*/ RTC_SR |= RTC_SR_TCE_MASK; /*!enable the counter.*/ RTC_IER |= RTC_IER_TSIE_MASK; /*!Seconds interrupt enable.*/ RTC_SR &= ~RTC_SR_TCE_MASK; /*!disable counter to make sure that the RTC_TSR and PRC_TPR can be read and written.*/ RTC_TPR = 0; /*!initial the time*/ RTC_TSR = 0; RTC_SR |= RTC_SR_TCE_MASK; /*!enable the counter*/ NVICICPR2 = (1<<3); /*! clear any pending interrupts on : by using table 3-5 the Seconds interrupt's IRQ is 67 NCIC number is 2, using function 67 mode 32*/ NVICISER2 = (1<<3); /*!enable interrupts from RTC module*/ /*!restore status register*/ ExitCritical(); return bTRUE; } /*! @brief Sets the value of the real time clock. * * @param hours The desired value of the real time clock hours (0-23). * @param minutes The desired value of the real time clock minutes (0-59). * @param seconds The desired value of the real time clock seconds (0-59). * @note Assumes that the RTC module has been initialized and all input parameters are in range. */ void RTC_Set(const uint8_t hours, const uint8_t minutes, const uint8_t seconds) { uint32_t setSecond; /*!< a 32 bit time in second*/ setSecond = 3600*hours +60*minutes+ seconds; /*!Separate set hours, minutes and seconds*/ RTC_SR &= ~RTC_SR_TCE_MASK; /*!disable counter to make sure that the RTC_TSR and PRC_TPR can be read and written*/ RTC_TPR = 0; /*!set TPR 0 to set TSR*/ RTC_TSR = setSecond; /*!write time into TSR*/ RTC_SR &= ~RTC_SR_TOF_MASK; /*!time overflow has not occurred*/ RTC_SR &= ~RTC_SR_TIF_MASK; /*!time is valid*/ RTC_SR |= RTC_SR_TCE_MASK; /*!enable the counter*/ } void RTC_Get(uint8_t* const hours, uint8_t* const minutes, uint8_t* const seconds) { uint32_t getSecond; /*!< a 32 bit time in second*/ RTC_SR &= ~RTC_SR_TCE_MASK; /*!disable the counter*/ getSecond = RTC_TSR; /*!read from TSR*/ *hours = (getSecond/3600); /*!calculate the hour*/ if(*hours >=24) /*!if hour >= 24, make hour 0*/ *hours=0; *minutes = (getSecond%3600)/60; /*!calculate the minute*/ *seconds = getSecond%60; /*!calculate the seconds*/ RTC_SR |= RTC_SR_TCE_MASK; /*!enable the counter*/ } void __attribute__ ((interrupt)) RTC_ISR(void) { (*userFunctionB) (userArgumentsB); /*!call the user callback function*/ } /* END RTC */ /*! ** @} */
C
/* Programme to print n numbers using switch case */ #include<stdio.h> #include<conio.h> void main() { int a=1,n; clrscr(); printf("\nHow many numbers do you want to print:"); scanf("%d",&n); num: if(a<=n) { printf("\n%d",a); a=a+1; goto num; } getch(); }
C
# include <stdio.h> # include <string.h> # include <stdlib.h> int main(void) { char *str = strdup("salut ca va"); // length = 11 + 1 char *str2 = strdup("ouai nickel"); printf("addresses str: [%p]\n" " str2: [%p]\n", str, str2); printf("before overflow -> str: [%s]\n" " str2: [%s]\n", str, str2); //overflow memset(str, 'C', 18); printf("after overflow -> str: [%s]\n" " str2: [%s]\n", str, str2); return (0); }
C
#if defined(__APPLE__) static inline int16_t bswap16(int16_t n) { return (n << 8) | (n >> 8); } static inline int32_t bswap32(int32_t n) { return ((n & 0xff000000) >> 24) | \ ((n & 0x00ff0000) >> 8) | \ ((n & 0x0000ff00) << 8) | \ ((n & 0x000000ff) << 24); } static inline int64_t bswap64(int64_t n) { return ((n & 0xff00000000000000ull) >> 56) | \ ((n & 0x00ff000000000000ull) >> 40) | \ ((n & 0x0000ff0000000000ull) >> 24) | \ ((n & 0x000000ff00000000ull) >> 8) | \ ((n & 0x00000000ff000000ull) << 8) | \ ((n & 0x0000000000ff0000ull) << 24) | \ ((n & 0x000000000000ff00ull) << 40) | \ ((n & 0x00000000000000ffull) << 56); } #define htobe16(n) bswap16(n) #define htobe32(n) bswap32(n) #define htobe64(n) bswap64(n) #define be16toh(n) bswap16(n) #define be32toh(n) bswap32(n) #define be64toh(n) bswap64(n) #else #include <endian.h> #endif
C
#include "../Includes/plaspaint.h" /** * Processus principale (initialisation + loop ) */ int mouse[6] = {0, 0, 0, 0, 0, 0}; int keyb[6] = {0, 0, 0, 0, 0, 0}; int displayMode = 0; void getMouse(); void getKeyb(); int main(int argc, char **argv) { // Initialisation du programme initOledBitmap(); initSketch(); clearSketch(WHITE); updateCursorMatrix(SQUARE); // Une première fois pour initialiser la matrix. int size_pencil = 1; int size_eraser = 1; int pressed = 0; int size = 1; //Boucle infinie do { // Mis à jour des valeurs de la souris et du clavier getMouse(); getKeyb(); /** * MODE HOME SCREEN */ if (displayMode == MODE_HOMESCREEN) { homeScreen(); if (mouse[L_CLICK] == 1) { setCurrentTool(PENCIL); setShape(SQUARE); displayMode = MODE_NORMAL; } } /** * MODE DESSIN DE BASE */ if (displayMode == MODE_NORMAL) { // Mis à jour du curseur, obligatoire avant toutes les fonctions de dessins !!! updateCursor(mouse[X_POS], mouse[Y_POS]); // Pinceau : Outil de base if (mouse[L_CLICK]) { if (getCurrentTool() == PENCIL) pencil(size_pencil, getShape()); if(getCurrentTool() == ERASER) eraser(size_eraser); if (getCurrentTool() == EYEDROPPER) getColor(); } // DEBUG : Test du clavier if (keyb[TOUCHE] == D) { if (keyb[APPUI] == 0) { paintAllBackground(BLACK); } } // Sélection outil if ((keyb[TOUCHE] == 1) && (!keyb[APPUI])) { setCurrentTool(PENCIL); size = size_pencil; } if ((keyb[TOUCHE] == 2) && (!keyb[APPUI])) { setCurrentTool(ERASER); size = size_eraser; } if ((keyb[TOUCHE] == 3) && (!keyb[APPUI])) { setCurrentTool(EYEDROPPER); } // Change la forme if ((getCurrentTool() == PENCIL) && (keyb[TOUCHE] == C)) { if (!keyb[APPUI] && (pressed == 0)) { pressed = 1; } if (keyb[APPUI]) { pressed = 0; } if (pressed == 1) { if ((getShape() != 23)) setShape(getShape() + 1); else setShape(20); pressed = 2; } } // Taille curseur + if (keyb[TOUCHE] == A) { if (!keyb[APPUI] && (pressed == 0)) { pressed = 1; } if (keyb[APPUI]) { pressed = 0; } if (pressed == 1) { (size > 15) ? (size = 1) : size++; pressed = 2; } } // Taille curseur - if (keyb[TOUCHE] == B) { // Appui du bouton if (!keyb[APPUI] && (pressed == 0)) { pressed = 1; } // Bouton relaché if (keyb[APPUI]) { pressed = 0; } // Change la taille if (pressed == 1) { (size == 1) ? (size = 1) : size--; pressed = 2; } } if (getCurrentTool() == PENCIL) size_pencil = size; if (getCurrentTool() == ERASER) size_eraser = size; // Si appuie sur E, on efface le tableau de travail (sketch) if (keyb[TOUCHE] == E) { clearSketch(WHITE); } // Affichage du skecth sur lequel on travail displaySketch(); if (mouse[MID_CLICK] == 1) { displayMode = MODE_CHROMATIC; updateCursorMatrix(COLOR_SELECTOR); setCurrentColor(WHITE); } } /** * Mode chromatic, choix de la couleur */ if (displayMode == MODE_CHROMATIC) { // Mis à jour du curseur updateCursor(mouse[X_POS], mouse[Y_POS]); // Affichage de la palette de couleurs displayChromaticScaleColors(); // Si l'utilisateur relache le bouton du milieu, on valide la sélection de la couleur if (mouse[MID_CLICK] == 0) { updateColor(); setCurrentTool(getCurrentTool()); displayMode = MODE_NORMAL; } } } while (1); } void getMouse() { mouse[X_POS] = MemoryRead(MOUSE_X); mouse[Y_POS] = MemoryRead(MOUSE_Y); mouse[Z_POS] = MemoryRead(MOUSE_Z); mouse[L_CLICK] = MemoryRead(MOUSE_BUTTONS) & 0x00000001; mouse[MID_CLICK] = (MemoryRead(MOUSE_BUTTONS) >> 1) & 0x00000001; mouse[R_CLICK] = (MemoryRead(MOUSE_BUTTONS) >> 2) & 0x00000001; } void getKeyb() { keyb[APPUI] = (MemoryRead(KEYS_DECODE) >> 8) & 0x00000001; keyb[TOUCHE] = MemoryRead(KEYS_DECODE) & 0x0000000F; }
C
/** * @file example.c */ #include "gaba.h" /* just include gaba.h */ #include <stdint.h> #include <stdio.h> #include <string.h> #include <inttypes.h> int printer(void *fp, uint64_t len, char c) { return(fprintf((FILE *)fp, "%" PRIu64 "%c", len, c)); } int main(int argc, char *argv[]) { /* create config */ gaba_t *ctx = gaba_init(GABA_PARAMS( .xdrop = 100, GABA_SCORE_SIMPLE(2, 3, 5, 1) /* match award, mismatch penalty, gap open penalty (G_i), and gap extension penalty (G_e) */ )); char const *a = "\x01\x08\x01\x08\x01\x08"; /* 4-bit encoded "ATATAT" */ char const *b = "\x01\x08\x01\x02\x01\x08"; /* 4-bit encoded "ATACAT" */ char const t[64] = { 0 }; /* tail array */ struct gaba_section_s asec = gaba_build_section(0, a, strlen(a)); struct gaba_section_s bsec = gaba_build_section(2, b, strlen(b)); struct gaba_section_s tail = gaba_build_section(4, t, 64); /* create thread-local object */ gaba_dp_t *dp = gaba_dp_init(ctx); /* dp[0] holds a 64-cell-wide context */ // gaba_dp_t *dp_32 = &dp[_dp_ctx_index(32)]; /* dp[1] and dp[2] are narrower ones */ // gaba_dp_t *dp_16 = &dp[_dp_ctx_index(16)]; /* init section pointers */ struct gaba_section_s const *ap = &asec, *bp = &bsec; struct gaba_fill_s const *f = gaba_dp_fill_root(dp, /* dp -> &dp[_dp_ctx_index(band_width)] makes the band width selectable */ ap, 0, /* a-side (reference side) sequence and start position */ bp, 0, /* b-side (query) */ UINT32_MAX /* max extension length */ ); /* until X-drop condition is detected */ struct gaba_fill_s const *m = f; /* track max */ while((f->status & GABA_TERM) == 0) { if(f->status & GABA_UPDATE_A) { ap = &tail; } /* substitute the pointer by the tail section's if it reached the end */ if(f->status & GABA_UPDATE_B) { bp = &tail; } f = gaba_dp_fill(dp, f, ap, bp, UINT32_MAX); /* extend the banded matrix */ m = f->max > m->max ? f : m; /* swap if maximum score was updated */ } struct gaba_alignment_s *r = gaba_dp_trace(dp, m, /* section with the max */ NULL /* custom allocator: see struct gaba_alloc_s in gaba.h */ ); printf("score(%" PRId64 "), path length(%" PRIu64 ")\n", r->score, r->plen); gaba_print_cigar_forward( printer, (void *)stdout, /* printer */ r->path, /* bit-encoded path array */ 0, /* offset is always zero */ r->plen /* path length */ ); printf("\n"); /* clean up */ gaba_dp_res_free(dp, r); gaba_dp_clean(dp); gaba_clean(ctx); return 0; } /** * end of example.c */
C
/*++ Copyright (c) 1993 Microsoft Corporation Module Name: party.c Abstract: IP Multicast party line to demo the usage of IP Multicast on Microsoft TCP/IP. Compile this as a QuickWin application using Large memory model. Author: Azfar Moazzam (AzfarM) 22-May-1994 Environment: User Revision History: dd-mmm-yyy <email> --*/ #include <windows.h> #include <stdio.h> #include <winsock.h> #include <stdlib.h> #include <string.h> #define PARTY_PORT 9999 #define PARTY_LINE "233.1.1.1" VOID usage(); main(int argc, char *argv[]) { long RetCode = 0; WSADATA wsaData; SOCKET sock; struct sockaddr_in sock_addr, dst_sock_addr, new_sock_addr; int new_sock_addr_len; long bytes; char *buf; char *Text; struct ip_mreq mreq; struct in_addr MCastAddr; char MCastAddress[16]; char LocalAddress[16]; int Port; char *UserName; char *MachineName; buf = (char *) malloc (300*sizeof(char)); Text = (char *) malloc (255*sizeof(char)); UserName = (char *) malloc (255*sizeof(char)); MachineName = (char *) malloc (16*sizeof(char)); if (argc<2) { usage(); exit(1); } RetCode = WSAStartup(0x0101, &wsaData); if (RetCode != 0) { printf ("\nError in DLL initialization %d", RetCode); return (1); } // Creating Udp Socket if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) { printf ("\nError creating socket - %d", WSAGetLastError()); return (1); } printf ("\nIP Multicast Address [Enter 0 for default]: "); scanf ("%s",MCastAddress); if (*MCastAddress == '0') strcpy (MCastAddress, PARTY_LINE); printf ("IP Multicast Address: %s", MCastAddress); printf ("\nPort [Enter 0 for default]: "); scanf("%d", &Port); if (!Port) Port = PARTY_PORT; printf ("Port: %d", Port); printf("\nLocal IP interface: "); scanf ("%s",LocalAddress); printf ("Local IP Interface: %s", LocalAddress); switch (argv[1][1]) { case ('C'): case ('c'): printf("\nEnter User Name: "); scanf ("%s", UserName); printf("\nEnter your message (no longer than 255 characters)"); printf("\nType !EXIT to quit client and !KILL to quit server\n"); sock_addr.sin_family = AF_INET; sock_addr.sin_addr.s_addr = inet_addr (LocalAddress); sock_addr.sin_port = 0; // Binding the socket to the address if (bind(sock, (LPSOCKADDR) &sock_addr, sizeof(sock_addr))==SOCKET_ERROR) { printf ("\nError in binding the socket - %d", WSAGetLastError()); WSACleanup(); return(1); } // Setting default IP interface for multicast MCastAddr.s_addr = inet_addr(LocalAddress); if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, (char *) &MCastAddr, sizeof(struct in_addr))==-1) printf("\nWarning: Could not set Default MCast Interface - %d", WSAGetLastError()); dst_sock_addr.sin_family = AF_INET; dst_sock_addr.sin_addr.s_addr = inet_addr(MCastAddress); dst_sock_addr.sin_port = htons(Port); while (TRUE) { printf("\nText: "); gets(Text); if (!strcmp(Text, "!EXIT")) break; if (strlen(Text)+strlen(UserName)>300) { printf("\nPlease enter a smaller message"); continue; } if (!strcmp(Text, "!KILL")) strcpy(buf, Text); else sprintf(buf,"%s: %s", UserName, Text); if (sendto(sock, buf, strlen(buf), MSG_DONTROUTE, (LPSOCKADDR) &dst_sock_addr, sizeof(dst_sock_addr))==INVALID_SOCKET) { printf ("\nError in Sending data on the socket - %d", WSAGetLastError()); WSACleanup(); return(1); } } printf("\nExiting..."); break; case ('S'): case ('s'): sock_addr.sin_family = AF_INET; sock_addr.sin_addr.s_addr = inet_addr(LocalAddress); sock_addr.sin_port = htons(Port); // Binding the socket to the address if (bind(sock, (LPSOCKADDR) &sock_addr, sizeof(sock_addr))==SOCKET_ERROR) { printf ("\nError in binding the socket - %d", WSAGetLastError()); return(1); } printf("\nWelcome to the IP Multicast Party Line"); printf("\nParty On... \n\n"); // Joining a multicast group mreq.imr_multiaddr.s_addr = inet_addr(MCastAddress); mreq.imr_interface.s_addr = inet_addr (LocalAddress); if (setsockopt(sock, IPPROTO_IP, 5, (char *) &mreq, sizeof(struct ip_mreq)) == -1) { printf("\nError %d in joining Multicast Group", WSAGetLastError()); exit(1); } while(1) { buf = (char *) calloc (300,sizeof (char)); buf[0]='\0'; new_sock_addr_len = sizeof(new_sock_addr); if (((bytes=recvfrom(sock, buf, 300, 0, (LPSOCKADDR) &new_sock_addr, (int *) &new_sock_addr_len)) == INVALID_SOCKET)) { printf ("\nError in receiving data - %d", WSAGetLastError()); return(1); } if (!strcmp(buf, "!KILL")) { printf ("\nSignal received from client. Exiting.."); // Dropping membership from the Mcast group setsockopt(sock, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char *) &mreq, sizeof(mreq)); break; } printf ("%s\n", buf); free(buf); } break; default: usage(); WSACleanup(); exit(1); } closesocket(sock); free (buf); free (Text); free (MachineName); free (UserName); WSACleanup(); } VOID usage() { printf("\nUsage: PARTY -s | -c "); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "avl.c" #include "tabdispersao.c" #include "lista.c" void avlImprimeCrescente(no_avl *no) { if(!no) { return; } avlImprimeCrescente(no->esquerda); printf("%s ", no->str); avlImprimeCrescente(no->direita); } void avlImprimeDecrescente(no_avl *no) { if(!no) { return; } avlImprimeDecrescente(no->direita); printf("%s ", no->str); avlImprimeDecrescente(no->esquerda); } void avl_imprime_ord(arvore_avl *avl, int ordem) { if(!avl) { return; } if(ordem >= 0) { avlImprimeCrescente(avl->raiz); } else { avlImprimeDecrescente(avl->raiz); } puts(""); } void valida_passwds(FILE *f, lista *login, lista *passwd) { if(!f || !login || !passwd || login->tamanho != passwd->tamanho) { return; } tabela_dispersao *td = tabela_nova(10, hash_djbm); if(!td) { return; } for(;;) { char username[30], password[30]; if(fscanf(f, "%s %s", username, password) < 2) { break; } if(tabela_adiciona(td, username, password) != TABDISPERSAO_OK) { tabela_apaga(td); return; } } for(elemento *username = login->inicio, *password = passwd->inicio; username && password; username = username->proximo, password = password->proximo) { printf("Login: %s\nPassword: %s\n", username->str, password->str); char *teste = (char*)tabela_valor(td, username->str); if(!teste) { break; } if(strcmp(teste, password->str) == 0) { puts("Authentication succeeded"); } else { puts("Authentication failed"); } } tabela_apaga(td); } /* Aqui começa o código de teste. Não modificar! */ int main() { /* teste problema 1.1 */ { arvore_avl *res; int i; char data[][4] = {"ENG", "BEL", "NED", "GER", "FRA", "RUS", "SUI", "CRO", "BIH", "ITA", "ESP", "POR", "GRE"}; printf("* Problema 1.1 *\n"); res = avl_nova(); for (i = 0; i < 13; i++) avl_insere(res, data[i]); printf("Arvore original: "); avl_imprime(res->raiz); printf("Ordem alfabetica crescente: "); avl_imprime_ord(res, 1); printf("\n\n"); avl_apaga(res); } /* teste problema 1.2 */ { FILE *f; lista *lg, *psswd; int i; char login[][TAMANHO_VALOR] = {"maria", "tiago", "ricardo"}; char password[][TAMANHO_CHAVE] = {"contrary", "contrary", "sheeplost"}; printf("* Problema 1.2 *\n"); f = fopen("passwords.txt", "r"); if (!f) { printf("Nao foi possivel abrir ficheiro!\n"); return -1; } lg = lista_nova(); for (i = 0; i < 3; i++) lista_insere(lg, login[i], NULL); psswd = lista_nova(); for (i = 0; i < 3; i++) lista_insere(psswd, password[i], NULL); valida_passwds(f, lg, psswd); lista_apaga(lg); lista_apaga(psswd); fclose(f); } return 0; }
C
#ifndef _MERGE_H #define _MERGE_H void merge(void *a, int size, int p, int q, int r, int(*comp)(void *,void *)){ int i,j,k,n1=q-p+1,n2=r-q; void *L = (void *)malloc(n1*size); void *R = (void *)malloc(n2*size); memcpy(L,a+p*size,n1*size); memcpy(R,a+(q+1)*size,n2*size); i=j=0; k=p; while(i<n1&&j<n2) if(comp(L+i*size,R+j*size)<0) //L[i]<R[j] memcpy(a+(k++)*size,L+(i++)*size,size); //a[k]<-L[i] else memcpy(a+(k++)*size,R+(j++)*size,size); //a[k]<-R[i] if(i<n1) memcpy(a+k*size,L+i*size,(n1-i)*size); //将L[i...n1]复制到a[k...r] if(j<n2) memcpy(a+k*size,R+j*size,(n2-j)*size); //将R[j...n2]复制到a[k...r] free(L);L=NULL; free(R);R=NULL; } #endif /* _MERGE_H */
C
/* * Sanjana Goli, April 2019 * Lab 5 (Tiny Search Engine) - index.h * * index.h contains a library of function that are called in indexer.c and indextest.c */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <ctype.h> #include "webpage.h" #include <string.h> #include "hashtable.h" #include "pagedir.h" #include "counters.h" #include "file.h" typedef struct index index_t; // opaque to users of the module /* index_new: takes in number of slots to initailize the hashtable num_slots depends on whether the caller knows how many words/keys are going to be inputted hashtable contains several sets with keys that are words and values that are counters counters correspond to pageId and wordcount values */ index_t * index_new(int num_slots); /* index_insert_word: takes in word and pageId to confirm whether they are valid inputs (pageId > 0) if the word does not exist, create a counter for the word and insert into hashtable if the word already exists, updated counter to be called in index_build */ void index_insert_word(index_t *index, const char *word, int pageId); /* index_set_wordcount: takes in word and pageId to confirm whether they are valid inputs (pageId > 0) if the word does not exist, create a counter for the word and insert into hashtable with key and value combination to be called in index_load */ void index_set_wordcount(index_t *index, const char *word, int pageId, int countVal); /* index_save: create new writable file and print word, pageId, and count in format specfied below */ void index_save(char *filename, index_t *index); /* get_num_lines: call lines_in_file from file.c in order to determine the size of the hashtable in index data structure */ int get_num_lines(char *filename); /* print_word_counter iterates through the counter to print id and count in the format specified below */ void print_word_counter(void *arg, const char *key, void *item); /* print_count_helper is a method passed into counter_iterate to print id and count in this format: word id count id count */ void print_count_helper(void *arg, const int key, const int count); /* index_load: loads in words from input file to index data structure, calls index_set_wordcount */ void index_load(char *filename, index_t *index); /* index_delete: frees memory allocated to the data structure --> frees index itself and hashtable of data structure */ void index_delete(index_t *index); /* delete_helper: helper method is necessary for hashtable_delete --> frees each of the counters in hashtable with counters_delete */ void delete_helper(void *item); /* index_build: scans file that is inputted, creates a webpage from url and html given, parses html to find words, inserts words into index using index_insert_word */ void index_build(char *directory, index_t *index); /* index_find: uses hashtable_find in order to find a key within the hashtable of the given index */ void * index_find(index_t *index, const char key[]); /* createFilename: creates filename of format dirname/id free(filename) needs to be called after method is invoked */ char * createFilename(int id, char *dirname);
C
#include <stdio.h> int main(void) { //Variable Declarations int iArray_nrl[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }; //Integer Array int* ptr_iArray_nrl = NULL; //Integr Pointer //code //#### Using Array Name As A pointer i.e. : Value Of xth Element Of iArray : *(iArray + x) and Address Of xth Element Of iArray : (iArray + x) #### printf("\n\n *** Using Array Name As A Pointer i.e. Value Of xth Element Of iArray : *(iArray + x) AND Address Of xth Element Of iArray : (iArray_nrl + x) ***\n\n"); printf("Integer Array Element And Address : \n\n"); printf("*(iArray + 0) =%d\t At Address (iArray + 0) :%p\n", *(iArray_nrl + 0), (iArray_nrl + 0)); printf("*(iArray + 1) =%d\t At Address (iArray + 1) :%p\n", *(iArray_nrl + 1), (iArray_nrl + 1)); printf("*(iArray + 2) =%d\t At Address (iArray + 2) :%p\n", *(iArray_nrl + 2), (iArray_nrl + 2)); printf("*(iArray + 3) =%d\t At Address (iArray + 3) :%p\n", *(iArray_nrl + 3), (iArray_nrl + 3)); printf("*(iArray + 4) =%d\t At Adreess (iArray + 4) :%p\n", *(iArray_nrl + 4), (iArray_nrl + 4)); printf("*(iArray + 5) =%d\t At Address (iArray + 5) :%p\n", *(iArray_nrl + 5), (iArray_nrl + 5)); printf("*(iArray + 6) =%d\t At Address (iArray + 6) :%p\n", *(iArray_nrl + 6), (iArray_nrl + 6)); printf("*(iArray + 7) =%d\t At Address (iArray + 7) :%p\n", *(iArray_nrl + 7), (iArray_nrl + 7)); printf("*(iArray + 8) =%d\t At Address (iArray + 8) :%p\n", *(iArray_nrl + 8), (iArray_nrl + 8)); printf("*(iArray + 9) =%d\t At Address (iArray + 9) :%p\n", *(iArray_nrl + 9), (iArray_nrl + 9)); // Assigning Base Address Of integer Array 'iArray' To Integer Pointer 'ptr_iArray' // Name Of Any Array Is Its Own Address ptr_iArray_nrl = iArray_nrl; // Same As ... ptr_iArray = &iArray[0] // #### Using Pointer As Array Name i.e. : Value Of xth Element Of iArray : ptr_iArray[x] AND Address Of xth Element Of iArray : &ptr_iArray[x] #### printf("\n\n **** Using Pointer As Array Name i.e. : Value Of xth Element Of iArray : ptr_iArray[x] And Address Of xth Element Of iArray : &ptr_iArray[x] ****\n\n"); printf("Integer Array Elements And Their Addresses : \n\n"); printf("ptr_iArray[0] =%d\t At Address &ptr_iArray[0] : %p\n", ptr_iArray_nrl[0], &ptr_iArray_nrl[0]); printf("ptr_iArray[1] =%d\t At Address &ptr_iArray[1] : %p\n", ptr_iArray_nrl[1], &ptr_iArray_nrl[1]); printf("ptr_iArray[2] =%d\t At Address &ptr_iArray[2] : %p\n", ptr_iArray_nrl[2], &ptr_iArray_nrl[2]); printf("ptr_iArray[3] =%d\t At Address &ptr_iArray[3] : %p\n", ptr_iArray_nrl[3], &ptr_iArray_nrl[3]); printf("ptr_iArray[4] =%d\t At Address &ptr_iArray[4] : %p\n", ptr_iArray_nrl[4], &ptr_iArray_nrl[4]); printf("ptr_iArray[5] =%d\t At Address &ptr_iArray[5] : %p\n", ptr_iArray_nrl[5], &ptr_iArray_nrl[5]); printf("ptr_iArray[6] =%d\t At Address &ptr_iArray[6] : %p\n", ptr_iArray_nrl[6], &ptr_iArray_nrl[6]); printf("ptr_iArray[7] =%d\t At address &ptr_iArray[7] : %p\n", ptr_iArray_nrl[7], &ptr_iArray_nrl[7]); printf("ptr_iArray[8] =%d\t At Address &ptr_iArray[8] : %p\n", ptr_iArray_nrl[8], &ptr_iArray_nrl[8]); printf("ptr_iArray[9] =%d\t At Address &ptr_iArray[9] : %p\n", ptr_iArray_nrl[9], &ptr_iArray_nrl[9]); return(0); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "trees.h" static TNode *newNode(char *word, MP3Tag_t *tag) { TNode *node = malloc(sizeof(TNode)); if(node == NULL) { fprintf(stderr, "Error allocating new TNode @ newNode\n"); return NULL; } node->data = listCreate(); if(node->data == NULL) { fprintf(stderr, "Error allocating TNode->data @ newNode\n"); free(node); return NULL; } listAdd(node->data, tag); int len = strlen(word); node->word = malloc(len + 1); if(node->word == NULL) { fprintf(stderr, "Error allocating TNode->word @ newNode\n"); free(node); return NULL; } strcpy(node->word, word); node->word[len] = 0; node->left = node->right = NULL; return node; } static void insertNode(TNode *root, TNode *node) { if(root->word == NULL) { root->word = node->word; root->data = node->data; free(node); return; } int cmp = strcmp(root->word, node->word); if(cmp < 0) { if(root->right == NULL) root->right = node; else insertNode(root->right, node); } else { if(root->left == NULL) root->left = node; else insertNode(root->left, node); } } TNode *treeCreate(void) { TNode *tree = malloc(sizeof(TNode)); if(tree == NULL) { fprintf(stderr, "Error allocating new TNode @ treeCreate\n"); return NULL; } tree->data = NULL; tree->word = NULL; tree->left = tree->right = NULL; return tree; } void treeAdd(TNode *root, MP3Tag_t *tag, char *word) { LNode *list = treeGet(root, word); if(list != NULL) { listAdd(list, tag); return; } TNode *node = newNode(word, tag); if(node == NULL) { fprintf(stderr, "Error allocating node @ treeAdd\n"); return; } insertNode(root, node); } LNode *treeGet(TNode *root, char *word) { if(root == NULL || root->word == NULL) return NULL; int cmp = strcmp(root->word, word); if(cmp == 0) return root->data; if(cmp < 0) return treeGet(root->right, word); return treeGet(root->left, word); } void treeDelete(TNode *root) { if(root == NULL) return; if(root->word != NULL) { listDelete(root->data); free(root->word); treeDelete(root->left); treeDelete(root->right); } free(root); } static TNode *treeToSortedList(TNode *r, TNode *link) { TNode *p; if(r == NULL) return link; p = treeToSortedList(r->left, r); r->left = NULL; r->right = treeToSortedList(r->right, link); return p; } static TNode* sortedListToBalancedTree(TNode **listRoot, int n) { if(n == 0) return NULL; TNode *leftChild = sortedListToBalancedTree(listRoot, n/2); TNode *parent = *listRoot; parent->left = leftChild; *listRoot = (*listRoot)->right; parent->right = sortedListToBalancedTree(listRoot, n-(n/2 + 1)); return parent; } void treeBalance(TNode *root) { }
C
#include "dx/dx.h" #include <stdio.h> #include <unistd.h> #define MAX_PARAMS 21 exit_handler(int fd, Pointer arg) { getchar(); exit(0); } main() { int rcode; ModuleInput minput[MAX_PARAMS]; ModuleOutput moutput[MAX_PARAMS]; float iso_value = 0.1; Object isosurface_out, autocamera_out, import_cloud_out; DXInitModules(); /* This program will exit when the enter key is hit */ DXRegisterInputHandler(exit_handler, STDIN_FILENO, 0) ; /* Import - setup in/outputs and call module */ DXModSetStringInput(&minput[0], "name", "cloudwater"); DXModSetObjectOutput(&moutput[0], "data", &import_cloud_out); rcode = DXCallModule("Import", 1, minput, 1, moutput); if (rcode == ERROR) goto error; /* Isosurface - setup in/outputs and call module */ /* no need to reference import_cloud_out before using it here */ /* because we will not use it again. After this module is */ /* called import_cloud_out will be deleted. */ DXModSetObjectInput(&minput[0], "data", import_cloud_out); DXModSetFloatInput(&minput[1], "value", iso_value); DXModSetObjectOutput(&moutput[0], "surface", &isosurface_out); rcode = DXCallModule("Isosurface", 2, minput, 1, moutput); if (rcode == ERROR) goto error; /* AutoCamera - setup in/outputs and call module */ /* We need to reference isosurface_out, because we will need */ /* it again as an input to Display */ /* If it were not referenced here, it would be deleted after the */ /* call to DXCallModule */ DXReference(isosurface_out); DXModSetObjectInput(&minput[0], "object", isosurface_out); DXModSetObjectOutput(&moutput[0], "camera", &autocamera_out); rcode = DXCallModule("AutoCamera", 1, minput, 1, moutput); if (rcode == ERROR) goto error; /* Display - setup in/outputs and call module */ DXModSetObjectInput(&minput[0], "object", isosurface_out); DXModSetObjectInput(&minput[1], "camera", autocamera_out); rcode = DXCallModule("Display", 2, minput, 0, moutput); if (rcode == ERROR) goto error; /* Delete the extra reference we put on isosurface_out that kept */ /* it from being deleted. */ DXDelete(isosurface_out); fprintf(stderr, "Hit the enter key to exit: "); /* enables the refresh of the display window, and the */ /* handling of the exit on carriage return */ while(1) { DXCheckRIH(1); } error: exit (-1); }
C
/* * do_while.c * * Created on: 1 de abr de 2021 * Author: igor */ #include<stdio.h> #include<stdint.h> int main(void){ do { printf("Hello\n"); // Será executado pelo menos uma vez mesmo que a condição seja falsa. } while (0); return 0; }
C
#include <jni.h> #include <sys/types.h> #include <unistd.h> #include "posix_Process.h" /*double quotes tells it to search current directory*/ JNIEXPORT jint JNICALL Java_posix_Process_setuid (JNIEnv * jnienv, jclass j, jint uid){ return((jint)setuid((uid_t)uid)); } JNIEXPORT jint JNICALL Java_posix_Process_seteuid (JNIEnv * jnienv, jclass j, jint uid){ return((jint)seteuid((uid_t)uid)); } JNIEXPORT jint JNICALL Java_posix_Process_setgid (JNIEnv * jnienv, jclass j, jint gid){ return((jint)setgid((uid_t)gid)); } JNIEXPORT jint JNICALL Java_posix_Process_setegid (JNIEnv * jnienv, jclass j, jint gid){ return((jint)setegid((uid_t)gid)); }
C
#include <stdlib.h> //for random function #include <stdio.h> #include "parameter.h" #include <time.h> int AverageStudyCredits(STUDENT* students, int len) { int totalCredits = 0; int i = 0; for (; i < len; i++) { totalCredits += students[i].StudyCredits; } int average = totalCredits/len; return average; } void AddStudents(STUDENT* students, int len) { srand(time(NULL)); int i = 0; int random_number; for (; i < len; i++) { students[i].StudentNumber = i; random_number = rand() % 10 + 1; students[i].StudyCredits = random_number; } }
C
// // Created by jor-dro on 1/29/20. // #include <string.h> #include <stdlib.h> #include <stdio.h> #include "graph.h" #include "ops.h" #include "hashmap.h" void user() { int input; char *name_db, path_db[MAX_STRING]; ERROR_CODE error = NO_ERROR; printf("1. Create DB \n2. Read DB \n3. Exit \n"); scanf("%d", &input); switch(input) { case 1: { printf("\nPlease enter name of DB: "); scanf("%s", name_db); printf("\nInteraction with graph %s \n", name_db); printf("1. Vertex \n2. Edge \n3. Set graph property \n4. Exit \n"); int input = 0; scanf("%d", &input); char *path = (char*) malloc(MAX_STRING*sizeof(char)); sprintf(path, "%s.graphml", name_db); graph *g = create_graph(name_db, path, error); switch(input) { case 1: printf("\n1. Create Vertex \n2. Update Vertex \n3. Delete Vertex\n4. Find Vertex \n5. Exit \n"); int input = 0; scanf("%d", &input); switch(input) { case 1: printf("No action here yet!\n"); break; case 2: printf("No action here yet!\n"); break; case 3: printf("No action here yet!\n"); break; case 4: printf("\n1. Per path \n2. Per ID \n3. Per property \n4. Exit \n"); break; int input = 0; scanf("%d", &input); switch(input) { case 1: printf("\nStart ID \n"); break; uint64_t id; scanf("%lld", &id); printf("\nInput: %lld", id); int input = 0; scanf("%d", &input); printf("\nFind destination \n1. per ID \n2. per property \n3. per label \n4. Exit \n"); switch(input) { case 1: printf("1. Depth Search \n2. Breadth Search \n"); //add scanf and switch case here case 2: printf("1. Depth Search \n2. Breadth Search \n"); //add scanf and switch case here case 3: printf("1. Depth Search \n2. Breadth Search \n"); //add scanf and switch case here case 4: break; default: printf("Please choose the menu by entering the number! \n"); break; } case 2: printf("Please enter ID: "); //uint64_t id; //scanf("%d", &id); //printf("Input: %d", &id); case 3: printf("Please enter name of property: "); //add scanf for property here. printf("Please enter type of property: "); //add scanf for property_t here printf("Please enter value of property: "); //add scanf for value here case 4: break; default: printf("Please choose the menu by entering the number! \n"); break; } case 5: break; default: printf("Please choose the menu by entering the number! \n"); break; } break; case 2: printf("1. Create Edge \n2. Update Edge \n3. Delete Edge \n4. Find Edge \n5. Exit \n"); break; case 3: printf("No action here yet!"); break; case 4: break; default: printf("Please choose the menu by entering the number! \n"); break; } } break; case 2: printf("Please enter path of DB: "); scanf("%s", path_db); printf("\nPlease enter name of DB: "); scanf("%s", name_db); //printf("Ihre Eingabe: %s und %s ", path_db, name_db); break; case 3: break; default: printf("\nPlease choose the menu by entering the number! \n"); } }
C
#include <REG517A.H> #define INTERVAL 10000 #define _BV(x) (1 << x) #define NELEMS(x) (sizeof(x) / sizeof((x)[0])) /* ## 8-bit resolution This means that only eight bits of the 16-bit wide timer and compare circuitry are used to generate the PWM signal. Thus the duty cycle of the signal is programmable in 256 steps. Input clock is set to fOSC/2, the timer is incremented every machine cycle (166.6 ns at 12 MHz) We want a period cycle of at least, 100 Hz (1/(256 * 128 * 166.6) = 183,2 Hz) ## Input clock The input clock is set to fOSC/2/128. This can be done in special function register CTCON. Prescaler value is set by SFR bits CLK2(1) CLK1(1) CLK0(0) in register CTCON Compare timer overflow flag is set by SFR bit CTF in register CTCON ## Reload register The reload register CTRELH (high byte) is set to 0xFF, CTRELL (low byte) must contain 0x00. Thus the timer counts from 0xFF00 to 0xFFFF (= 8-bit reload ? 256 steps). Restriction of module range = (1/2n) * 100% = 0.195% This leads to a variation of the duty cycle from 0.195% to 99.805% when 8 of 16 bits are used. ## Compare mode Compare register CM0 (consisting of CMH0 and CML0) is used in compare mode 0. This means bit CMSEL.0 must be set (in register CMSEL) to assign CM0 to the compare timer and switch on compare mode 0. ## Enable port output For P4.0, the compare is enabled with SFR bit CMEN.0 in register CMEN. ## Enable Interrupt The compare timer overflow interrupt is enabled by SFR bit ECT in register IEN2. The general enable flag EAL in register IEN0 must be set, too. ## References * http://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM * https://electrosome.com/pwm-pic-microcontroller-hi-tech-c/ * SAB 80C517A/83C517A-5 Manual */ unsigned char duty[] = {0x40, 0x80, 0xC0}; // {25%, 50%, 75%} volatile unsigned long count = 0; /* Initialize Compare Timer & Interrupts */ void init() { EAL = 0; IEN2 &= ~(_BV(3)); CMSEL |= _BV(0); CMEN |= _BV(0); CTCON |= (_BV(2) | _BV(1)); IEN2 |= _BV(3); EAL = 1; } /* Start Compare Timer by writing into it */ void start() { CTRELH = 0xFF; CTRELL = 0x00; } /* Set duty cycle in Reload Register */ void set_duty() { CMH0 = 0xFF; CML0 = duty[count/INTERVAL]; } /* Compare Timer Interrupt service routine */ void compare_timer() interrupt 19 using 2 { if (++count >= NELEMS(duty) * INTERVAL) { count = 0; } if (count % INTERVAL == 0) { set_duty(); } // Clear CTF bit in CTCON rregister CTCON &= ~(_BV(3)); } void main() { init(); set_duty(); start(); while(1); }
C
#include "pilhaA.h" #include <stdio.h> #include <stdlib.h> #include <stdbool.h> No* empilhar(No *pilha, char valor){ No *novo = malloc(sizeof(No)); if(novo){ novo->caracter = valor; novo->proximo = pilha; return novo; } else printf("\tErro ao alocar memoria!\n"); return NULL; } No* desempilhar(No **pilha){ No *remover = NULL; if(*pilha){ remover = *pilha; *pilha = remover->proximo; } else printf("\tPilha vazia\n"); return remover; } void imprimir(No *pilha){ printf("\n\tPILHA\n"); while(pilha){ printf("\t%c\n", pilha->caracter); pilha = pilha->proximo; } printf("\tFIM PILHA\n\n"); } //2.A int forma_par(char f, char d){ switch(f){ case ')': if(d == '(') return 1; // bem formada else return 0; // mal formada break; case ']': if(d == '[') return 1; // bem formada else return 0; // mal formada break; case '}': if(d == '{') return 1; // bem formada else return 0; // mal formada break; } } int identifica_formacao(char x[]){ int i = 0; No *remover, *pilha = NULL; while(x[i] != '\0'){ if(x[i] == '[' || x[i] == '(' || x[i] == '{'){ pilha = empilhar(pilha, x[i]); imprimir(pilha); } else if(x[i] == ']' || x[i] == ')' || x[i] == '}'){ remover = desempilhar(&pilha); if(remover){ if(forma_par(x[i], remover->caracter) == 0){ printf("\tEXPRESSAO MAL FORMADA!\n"); return 1; // expressao está mal formada } free(remover); } else{ printf("\tEXPRESSAO MAL FORMADA!\n"); return 1; // expressao está mal formada } } i++; } imprimir(pilha); if(pilha){ printf("\tExpressao mal formada!\n"); return 1; } else{ printf("\tEXPRESSAO BEM FORMADA!\n"); return 0; } } void Resposta2A(){ char exp[50]; printf("\t______________________________\n"); printf("\tDigite um expressao: "); scanf("%49[^\n]", exp); printf("\nExpressao: %s\nRetorno: %d\n", exp, identifica_formacao(exp)); printf("\t______________________________\n"); }
C
#include<stdio.h> struct node { int info; struct node *prev; struct node *next; }; struct node *addtoempty2(struct node *start,int data); struct node *addatbeg2(struct node *start,int data); struct node *reverse2(struct node *start); void fun2() { struct node *start=NULL; int ch,data,item,pos; while(1) { printf("1.Create List\n"); printf("2.Display\n"); printf("3.Search\n"); printf("4. Add at beginning\n"); printf("5.Add at end\n"); printf("6.Add after node\n"); printf("7.Add before node\n"); printf("8.Add at position\n"); printf("9.Delete\n"); printf("10.Reverse\n"); printf("Enter your choice : "); scanf("%d",&ch); switch(ch) { case 1: start=create_list2(start); break; case 2: display2(start); break; case 3: printf("Enter the element to be searched : "); scanf("%d",&data); search2(start,data); break; case 4: printf("Enter the element to be inserted : "); scanf("%d",&data); start=addatbeg2(start,data); break; case 5: printf("Enter the element to be inserted : "); scanf("%d",&data); start=addatend2(start,data); break; case 6: printf("Enter the element to be inserted : "); scanf("%d",&data); printf("Enter the element after which to insert : "); scanf("%d",&item); start=addafter2(start,data,item); break; struct node *create_list2(struct node *start) { int i,n,data; printf("Enter the number of nodes : "); scanf("%d",&n); start=NULL; if(n==0) return start; printf("Enter the element to be inserted : "); scanf("%d",&data); start=addtoempty2(start,data); for(i=2;i<=n;i++) { printf("Enter the element to be inserted : "); scanf("%d",&data); start=addatend2(start,data); } return start;} void display2(struct node *start) { struct node *p; if(start==NULL) { printf("List is empty\n"); return; } p=start; printf("List is :\n"); while(p!=NULL) { printf("%d ",p->info); p=p->next; } printf("\n"); struct node *addtoempty2(struct node *start,int data) { struct node *tmp; tmp=(struct node *)malloc(sizeof(struct node)); tmp->info=data; tmp->prev=NULL; tmp->next=NULL; start=tmp; return start; struct node *addatbeg2(struct node *start,int data) { struct node *tmp; tmp = (struct node *)malloc(sizeof(struct node)); tmp->info=data; tmp->prev=NULL; tmp->next=start; start->prev=tmp; start=tmp; return start; struct node *addatend2(struct node *start,int data) { struct node *tmp,*p; tmp=(struct node *)malloc(sizeof(struct node)); tmp->info=data; p=start; while(p->next!=NULL) p=p->next; p->next=tmp; tmp->next=NULL; tmp->prev=p; return start; struct node *addafter2(struct node *start,int data,int item) { struct node *tmp,*p; tmp=(struct node *)malloc(sizeof(struct node)); tmp->info=data; p=start; while(p!=NULL) { if(p->info==item) { tmp->prev=p; tmp->next=p->next; if(p->next!=NULL) p->next->prev=tmp; p->next=tmp; return start; } p=p->next; } printf("%d not present in the list\n\n",item); return start; struct node *addbefore2(struct node *start,int data,int item) { struct node *tmp,*q; if(start==NULL ) { printf("List is empty\n"); return start; } if(start->info==item) { tmp = (struct node *)malloc(sizeof(struct node)); tmp->info=data; tmp->prev=NULL; tmp->next=start; start->prev=tmp; start=tmp; return start; } q=start; while(q!=NULL) { if(q->info==item) { tmp=(struct node *)malloc(sizeof(struct node)); tmp->info=data; tmp->prev=q->prev; tmp->next = q; q->prev->next=tmp; q->prev=tmp; return start; } q=q->next; } printf("%d not present in the list\n",item); return start; struct node *del2(struct node *start,int data) { struct node *tmp; if(start==NULL) { printf("List is empty\n"); return start; } if(start->next==NULL) /*only one node in the list*/ if(start->info==data) { tmp=start; start=NULL; free(tmp); return start; } else { printf("Element %d not found\n",data); return start; } if(start->info==data) { tmp=start; start=start->next; start->prev=NULL; free(tmp); return start; } tmp=start->next; while(tmp->next!=NULL ) { if(tmp->info==data) { tmp->prev->next=tmp->next; tmp->next->prev=tmp->prev; free(tmp); return start; } tmp=tmp->next; } if(tmp->info==data) { tmp->prev->next=NULL; free(tmp); return start; } printf("Element %d not found\n",data); return start; } struct node *reverse2(struct node *start) { struct node *p1,*p2; p1=start; p2=p1->next; p1->next=NULL; p1->prev=p2; while(p2!=NULL) { p2->prev=p2->next; p2->next=p1; p1=p2; p2=p2->prev; } start=p1; printf("List reversed\n"); return start; }
C
/*! * @file utility/compare.c * @brief Comparison functions * @author Sam Thomas <s@ghost.sh> * * @section LICENSE * Copyright (c) 2011 Sam Thomas <s@ghost.sh> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "types/types.h" #include "universal.h" #include "utility.h" #include "macro.h" /*! * @brief Compares two strings with a limit * @param str1 string to compare * @param str2 string to compare * @param limit maximum amount of characters to compare from str1 * @return The difference between either where two indexed characters from str1 * and str2 aren't equal; or where the index has reached the limit value or the * end of str1; the difference is computed as follows: str1[i] - str2[i] or 0 in * the case of no differences * @note Sets the error variable indicating success or failure */ int safe_string_compare_limit(s_string_t str1, s_string_t str2, unsigned long int limit) { if(safe_string_valid(str1) && safe_string_valid(str2)) { int diff = 0; unsigned long int i = 0; //limit = (limit > (str1->s_length > str2->s_length ? str1->s_length : str2->s_length) ? (str1->s_length > str2->s_length ? str1->s_length : str2->s_length) : limit); limit = MIN(limit, MAX(safe_string_length(str1), safe_string_length(str2))); while((i < limit) && !diff && !safe_string_error()) { diff = (safe_string_index(str1, i) - safe_string_index(str2, i)); i++; } safe_string_set_error(safe_string_error_val()); return(diff); } else { safe_string_set_error(SAFE_STRING_ERROR_NULL_POINTER); return(SAFE_STRING_EMPTY); } } /*! * @brief Compares two strings * @param str1 string to compare * @param str2 string to compare * @return The difference between either where two indexed characters from str1 * and str2 aren't equal; or where the index has reached the end of str1; the * difference is computed as follows: str1[i] - str2[i] or 0 in the case of no * differences * @note Sets the error variable indicating success or failure */ int safe_string_compare(s_string_t str1, s_string_t str2) { if(safe_string_valid(str1) && safe_string_valid(str2)) { /* check it's safe to access the structure */ return(safe_string_compare_limit(str1, str2, MIN(safe_string_length(str1), safe_string_length(str2)))); } else { safe_string_set_error(SAFE_STRING_ERROR_NULL_POINTER); return(SAFE_STRING_EMPTY); } }
C
#include<stdio.h> void binary(int list[],int x); void linear(int list[],int x); void main() { int a[30],count,i,x,y,el; printf("Enter The Number Of Elaments:"); scanf("%d",&count); printf("Enter The List Elaments\n"); for( i=0; i<=count;i++ ) { printf("Enter The %d th Elament ",i+1); scanf("%d",&el); a[i]=el; } while (1){ printf("\n1\t:\tBINARY SEARCH\n2\t:\tLINEAR SEARCH"); printf("\nEnter The Search Choice:"); scanf("%d",&x); if (x==1){ binary(a,count); } else if (x==2) linear(a,count); else printf("\nInvalid choice Tryagain"); } } void binary(int list[],int x) { int b=0,l=x-1,m,key; m=(b+l)/2; printf("\nEnter The Elament To Search:"); scanf("%d",&key); while ( (key != list[m]) && (b<=l) ) { if (key>list[m]) b=m++; else { l=m--; m=(b+l)/2; } } if ( key == list[m] ) { printf("The Elament %d is Fount At %d The Position ",key,m+1); } else printf("Elament Not fount"); } void linear(int list[],int x) { int i,key,p,flag=0; printf("Enter The Elament To Search:"); scanf("%d",&key); for (i=0 ; i<x ; i++ ) { if (list[i]==key) { p=i; flag=1; break; } } if (flag==1) printf("Elament fount in Position %d",p+1); else printf("Elament Not fount"); }
C
#include <stdio.h> void multiplication_table(int value) { int i; for(i = 1; i <= 10; i++) { printf("%d x %d = %d\n", value, i, value * i); } } int main() { int a; a = 2; printf("Multiplication table of %d:\n", a); multiplication_table(a); a = 17; printf("Multiplication table of %d:\n", a); multiplication_table(a); return 0; }
C
#define _BSD_SOURCE #include "intersect_funcs.h" #include <stdio.h> #include <stdint.h> #include <string.h> #include <math.h> #include <ctype.h> const size_t BUF_SZ = 256; int main(int argc, char *argv[]) { if(argc == 1) { fprintf(stderr, "There were no files to read\n"); return 1; } size_t file_count = 1; hash *hashy = hash_create(); char *buffer = malloc(BUF_SZ * sizeof(buffer)); while(file_count < (size_t)argc) { FILE *fp = fopen(argv[file_count], "r"); if(!fp) { perror("The file could not be opened\n"); free(buffer); return 2; } while(!feof(fp)) { if(fgets(buffer, BUF_SZ, fp) != NULL) { char *token = strtok( buffer, " \t\n\f\v\r"); //a token that stores he current place as it walks down the buffer while(token != NULL) { if(hash_fetch(hashy, token) == file_count - 1) { //if i fetch and its the same as 1 less the my files count the hash_insert(hashy, token, file_count); //then i know i need to insert otherwise it wont get changed //with insert } token = strtok(NULL, " \t\n\f\v\r"); //moves token along as the while happens } } } fclose(fp); ++file_count; } //gave in and used trees instead of a merge sort bst *new_bst = bst_create(); fill_bst(new_bst, hashy, file_count); tree_inorder(new_bst->root, print_func); free(buffer); hash_destroy(hashy); bst_destroy(new_bst); }
C
/******************************************** * Filename:"xToThePower.c" * Programer:Georgian Costea * Discription: Uses a function to calculate * the result of raising one number to the * power of another. ********************************************/ #include<stdio.h> //prototypes int headingFunction(void); int powerFunction(int oldBase,int oldExponent); int rangeCheckingFunction(int min,int max,int value); int getNum(void); int main(void) { //declaring variables int keyNumber = 0; int baseNum = 1; int exponentNum =1; int oldBase = 1; int oldExponent= 1; //infinite loop until the user press key 4 while(keyNumber !=4) { //cals the headingFunction headingFunction(); // making keynumber= getnum() keyNumber=getNum(); //if statement if the key pressed is 1 do this if( keyNumber == 1 ) { //ask for an base printf("Change Base <Between 1 and 25>\t"); //get the number baseNum=getNum(); // check if the values are in the range if(rangeCheckingFunction(1,25,baseNum)) { //if the input its out of range then the old value will take //the place of the new value oldBase = baseNum; } } //else if keynumber is 2 do this else if( keyNumber == 2 ) { //ask for an exponenet printf("Change Exponent < Between 1 and 5>\t"); exponentNum = getNum(); //check if the values are in the range if(rangeCheckingFunction(1,5,exponentNum)) { //if the input its out of range then the old value will take //the place of the new value oldExponent= exponentNum; } } //when user will press key 3 they are calling the power funtion else if( keyNumber == 3 ) { powerFunction( oldBase , oldExponent ); } } //returns 0 return 0; } int headingFunction(void) { //Headingfunction it shows the // menu bar(Power Menu) printf("\n Power Menu\n\n" "1. Change Base\n" "2. Change Exponent\n" "3. Display base raised to the exponent\n" "4. Exit program\n\n" "Option?\n\n"); return 0; } int powerFunction(int oldBase, int oldExponent) { //declaring variables int counter = 0, answer = 1; //loop for(counter = 0; counter < oldExponent; counter++) { // the answer is answer times baseNum answer *=oldBase; } //print the base raised to exponent and the answer printf("Display base raised to the exponent:%d ^ %d = %d\n\n",oldBase,oldExponent,answer); return 0; } int rangeCheckingFunction(int min ,int max,int value) { //making a statement if the value is in parameters. if((value < min) || (value > max)) { //display the error printf("Your value is not between %d and %d\n",min,max); //return 0 if its out of range return 0; } else { //return 1 if its in the range return 1; } } int getNum(void) { /* the array is 121 bytes in size; we'll see in a later lecture how we can improve this code */ char record[121] = {0}; /* record stores the string */ int number = 0; fgets(record, 121, stdin); if( sscanf_s(record, "%d", &number) != 1 ) { /* if the user did not enter a number recognizable by * the system, set number to -1 */ number = -1; } return number; }
C
/* ** game_loop.c for lemipc in /home/scutar_n/rendu/PSU/PSU_2016_lemipc/src ** ** Made by Nathan Scutari ** Login <scutar_n@epitech.net> ** ** Started on Sun Apr 2 16:00:57 2017 Nathan Scutari ** Last update Sun Apr 2 21:41:05 2017 Nathan Scutari */ #include "lemi.h" int play_game_main(t_shared *ids, t_player *list, char *map, int team) { t_player *tmp; int turn; tmp = NULL; turn = 0; while (1) { tmp = next_player(list, tmp); if (tmp->player_id != 1) player_turn(tmp->player_id, ids, list); else { if (tmp->alive) main_turn(ids, team, map); ++turn; } usleep(75000); look_for_dead(map, tmp->player_team, list, ids); print_game_state(map, turn); if (look_for_end(map, list, ids)) return (0); if (check_signal(ids)) return (1); } return (0); } int play_game(t_shared *ids, int id, int team, char *map) { int alive; t_msg msg; alive = 1; while (alive) { if (msgrcv(ids->msg_id, &msg, sizeof(msg) - sizeof(long), id, 0) == -1) exit(1); if (msg.kill) check_if_dead(team, ids, map, &alive); else if (msg.end) return (0); else { access_map(team, ids, map); msg.mtype = 1; msg.source_id = id; msg.new_player = 0; msg.team = team; msgsnd(ids->msg_id, &msg, sizeof(msg) - sizeof(long), 0); } if (check_signal(ids)) return (1); } return (0); } int player_turn(int id, t_shared *ids, t_player *list) { t_msg msg; msg.source_id = 1; msg.mtype = id; msg.kill = 0; msg.end = 0; if (msgsnd(ids->msg_id, &msg, sizeof(msg) - sizeof(long), 0) == -1) exit(1); while (get_msg(ids->msg_id, &list)); return (0); } int main_turn(t_shared *ids, int team, char *map) { struct sembuf sops; sops.sem_num = 0; sops.sem_flg = 0; sops.sem_op = -1; semop(ids->sem_id, &sops, 1); move_in_map(map, team, ids); sops.sem_op = 1; semctl(ids->sem_id, 0, SETVAL, 0); semop(ids->sem_id, &sops, 1); return (0); } t_player *next_player(t_player *list, t_player *tmp) { if (tmp == NULL || tmp->next == NULL) return (list); tmp = tmp->next; while (tmp && tmp->alive == 0) tmp = tmp->next; if (tmp == NULL) return (list); return (tmp); }
C
#include<stdio.h> #include<stdlib.h> struct Node { int data; struct Node *next; }*head = NULL; void insert_beginning(int value) { struct Node *newNode; newNode = (struct Node *)malloc(sizeof(struct Node)); newNode -> data = value; if(head == NULL) { newNode -> next = NULL; head = newNode; } else { newNode -> next = head; head = newNode; } printf("\n Node inserted successfuly"); } void insert_ending(int value) { struct Node *newNode; newNode = (struct Node *)malloc(sizeof(struct Node)); newNode -> data = value; newNode -> next = NULL; if(head == NULL) { head = newNode; } else { struct Node *temp = head; while(temp -> next != NULL) { temp = temp -> next } temp -> next = newNode; } printf("\n Node inserted successfuly"); } void insert_after(int value,int pos) { int i = 0; newNode = (struct Node *)malloc(sizeof(struct Node)); newNode -> data = value; if(head == NULL) { newNode -> next = NULL; } else { struct Node *temp = head; for(i = 0;i < pos - 1;i++) { temp = temp -> next; } newNode -> next = temp -> next; temp -> next = newNode; } printf("\n Node inserted successfuly"); } void printLL(struct Node *n) { while(n != NULL) { printf("\n Node %d:",i,n->value); n = n->next; } } void main() { int ch = -1; while(ch != 99){ printf("\n Enter your choice:"); printf("\n Insert at beginning"); printf("\n Insert at End"); printf("\n Insert at Position"); printf("\n Print Linked List"); scanf("%d",&ch); switch(ch) } }
C
// // Created by Jonathan McFadden on 8/10/18. // #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <netdb.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <time.h> //#include <pthread.h> //#include <stdint.h> //#define MAX_BUFFER_SIZE 1024 typedef struct _imu_datapoint{ char* device_id; time_t measurement_time; char* sensor_id; float gx; float gy; float gz; float ax; float ay; float az; float mx; float my; float mz; } imu_datapoint; int main(int argc, char *argv[]) { int listenfd = 0, connfd = 0, n = 0; struct sockaddr_in serv_addr; struct tm tm; int cnt = 0; char buff[1025]; // time_t ticks; imu_datapoint* theData = (imu_datapoint*) malloc(sizeof(imu_datapoint)); FILE *dataFile; char fileBuff[1025]; // // if(dataFile==NLU) // { // puts("ERROR opening file"); // return 0; // } // else // { // puts("File open successful, configuring network stuff"); listenfd = socket(AF_INET, SOCK_STREAM, 0); memset(&serv_addr, '0', sizeof(serv_addr)); memset(buff, '0', sizeof(buff)); memset(fileBuff, '0', sizeof(fileBuff)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(5000); puts("Listening on port 5000\n"); bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); listen(listenfd, 10); while(1) { connfd = accept(listenfd, (struct sockaddr*)NULL, NULL); while( (n = read(connfd, buff, sizeof(buff)-1)) > 0) { buff[n] = 0; // fputs(buff, stdout); fprintf(stdout, buff); fprintf(stdout, "\n%i\n", n); switch(cnt) { case 0: theData->device_id = buff; fprintf(stdout, "This is the buffer: \n %s", buff); // fprintf(stdout, "This is the device id: \n %s". theData->device_id); break; case 1: // const char *time_details = buff; // struct tm tm; strptime(buff, "%a %m %d %H:%M:%S %Y", &tm); theData->measurement_time = mktime(&tm); fprintf(stdout, "This is the buffer: \n %s", buff); // time_t ticks1 = theData->measurement_time; // fprintf(stdout, "This is the time: \n %.24s". ctime(&ticks1)); break; case 2: theData->sensor_id = buff; fprintf(stdout, "This is the buffer: \n %s", buff); // fprintf(stdout, "This is the sensor id: \n %s", theData->sensor_id); break; case 3: theData->gx = atof(buff); fprintf(stdout, "This is the buffer: \n %s", buff); break; case 4: theData->gy = atof(buff); fprintf(stdout, "This is the buffer: \n %s", buff); break; case 5: theData->gz = atof(buff); fprintf(stdout, "This is the buffer: \n %s", buff); break; case 6: theData->ax = atof(buff); fprintf(stdout, "This is the buffer: \n %s", buff); break; case 7: theData->ay = atof(buff); fprintf(stdout, "This is the buffer: \n %s", buff); break; case 8: theData->az = atof(buff); fprintf(stdout, "This is the buffer: \n %s", buff); break; case 9: theData->mx = atof(buff); fprintf(stdout, "This is the buffer: \n %s", buff); break; case 10: theData->my = atof(buff); fprintf(stdout, "This is the buffer: \n %s", buff); break; case 11: theData->mz = atof(buff); fprintf(stdout, "This is the buffer: \n %s", buff); break; } puts("DONE receiving measurement!\n"); fprintf(stdout, "\n%i\n", cnt); cnt++; if(cnt==12) { cnt = 0; } } dataFile = fopen("dataFile.txt", "a+"); if(dataFile==NULL) { puts("ERROR opening file"); break; } else { fseek(dataFile, 0, SEEK_END); snprintf(fileBuff, sizeof(fileBuff), "{\n"); fprintf(dataFile, fileBuff); snprintf(fileBuff, sizeof(fileBuff), "\t\"Device ID\" : \"%s\"\r\n", theData->device_id); fprintf(dataFile, fileBuff); time_t ticks2 = theData->measurement_time; snprintf(fileBuff, sizeof(fileBuff), "\t\"Time\" : \"%.24s\"\r\n", ctime(&ticks2)); fprintf(dataFile, fileBuff); snprintf(fileBuff, sizeof(fileBuff), "\t\"Sensor ID\" : \"%s\r\"\n", theData->sensor_id); fprintf(dataFile, fileBuff); snprintf(fileBuff, sizeof(fileBuff), "\t\"gx\" : %f\r\n", theData->gx); fprintf(dataFile, fileBuff); snprintf(fileBuff, sizeof(fileBuff), "\t\"gy\" : %f\r\n", theData->gy); fprintf(dataFile, fileBuff); snprintf(fileBuff, sizeof(fileBuff), "\t\"gz\" : %f\r\n", theData->gz); fprintf(dataFile, fileBuff); snprintf(fileBuff, sizeof(fileBuff), "\t\"ax\" : %f\r\n", theData->ax); fprintf(dataFile, fileBuff); snprintf(fileBuff, sizeof(fileBuff), "\t\"ay\" : %f\r\n", theData->ay); fprintf(dataFile, fileBuff); snprintf(fileBuff, sizeof(fileBuff), "\t\"az\" : %f\r\n", theData->az); fprintf(dataFile, fileBuff); snprintf(fileBuff, sizeof(fileBuff), "\t\"mx\" : %f\r\n", theData->mx); fprintf(dataFile, fileBuff); snprintf(fileBuff, sizeof(fileBuff), "\t\"my\" : %f\r\n", theData->my); fprintf(dataFile, fileBuff); snprintf(fileBuff, sizeof(fileBuff), "\t\"mz\" : %f\r\n", theData->mz); fprintf(dataFile, fileBuff); snprintf(fileBuff, sizeof(fileBuff), "}\n"); fprintf(dataFile, fileBuff); } fclose(dataFile); puts("DONE writing measurement to FILE!\n"); close(connfd); sleep(1); } }
C
#include <stdio.h> int main(){ float x,y,r; scanf("%f %f",&x,&y); r = (x + y)/2; printf("media = %.1f",r); return 0; }
C
#include<stdio.h> void main() { unsigned long int a,r; printf("enter a number:"); scanf("%lu",&a); r=a%10; a=a/1000; printf("sum of first and last digit is: %lu",r+a); }
C
/*Chapter 3 Tracing exercises problem 8. * do to hov the code is written at least one * of the values will be garbage. */ #include <stdio.h> int main() { int x = 0, y = 1, p, z; if(x < y) { p = x; } else { z = x; } printf("%d %d", p, z); }
C
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { int n,i,j,t=0,n1; scanf("%d", &n); n1=n; while(n) { i=0; if (i==0 && t>0) { printf("%d ", n1); } for (i = 1; i <=n * 2-1 ; i++) { printf("%d ", n); } if (t > 0 && i == n * 2 ) { printf("%d ", n1); } n--; t++; printf("\n"); } for (i = 0; i < n1 * 2 - 1; i++) { printf("%d ", n1); } return 0; }
C
#include<stdio.h> float week_payment(int a, float b); int main() { int horas; float valor; /*Entradas*/ printf("Digite o número de horas trabalhadas semanalmente:\n"); scanf("%d",&horas); printf("Digite o valor da hora trabalhada:\n"); scanf("%f",&valor); /*Chamada das funções*/ week_payment(horas, valor); return 0; } float week_payment(int a, float b) //Calcula o valor do salário { float payment; if (a <= 40) { payment = a * b; } else if (a > 40 && a <= 60) { payment = (a * b * 1.5); } else { payment = (a * b * 2); } printf("O seu salário semanal é de R$:%0.2f \n", payment); } /*Para caso o acréscimo seja apenas válido na diferença de horas a partir de 40h*/ /* float week_payment(int a, float b) { float payment; if (a <= 40) { payment = a * b; } else if (a > 40 && a <= 60) { payment = (40 * b) + ( (a - 40) * 1.5 ); } else { payment = (40 * b) + ( (a - 40) * 2); } printf("O seu salário semanal é de R$:%0.2f \n", payment); } */
C
/* * boot.c - a kernel template (Assignment 1, ECE 6504) * Copyright 2021 Ruslan Nikolaev <rnikola@vt.edu> */ #include <fb.h> #include <printf.h> typedef unsigned long long u64; // Write to the CR3 register with the base address of the PML4 Table void write_cr3(unsigned long long cr3_value) { asm volatile("mov %0, %%cr3" : : "r"(cr3_value) : "memory"); } void page_table(u64 *p) { u64 next_page = 0x0; //kernel for (int i = 0; i < 1048576; i++) { p[i] = (next_page + 0x3); next_page += 0x1000; } } void page_directory(u64 *pd, u64 *p) { //kernel for (int j = 0; j < 2048; j++) { u64 *start_pte = p + 512 * j; u64 page_addr = (u64)start_pte; pd[j] = page_addr + 0x3; } } void page_directory_pointer(u64 *pdp, u64 *pd) { for (int j = 0; j < 512; j++) { //first 4 entries in kernel if (j < 4) { u64 *start_pde = pd + 512 * j; u64 page_addr = (u64)start_pde; pdp[j] = page_addr + 0x3; } //other entries are null else { pdp[j] = 0x0ULL; } } } void pml4_table(u64 *pml4, u64 *pdp) { for (int j = 0; j < 512; j++) { //Level 4 containing only kernel page table //first entry for kernel if (j == 0) { pml4[j] = (u64)pdp + 0x3; } //other entries are null else { pml4[j] = 0x0ULL; } } } void setup_kernel_pagetable(void *addr) { //PTE u64 *p = (u64 *)addr; page_table(p); //PDE u64 *pd = (p + 1048576); page_directory(pd, p); //PDPE u64 *pdp = (pd + 2048); page_directory_pointer(pdp, pd); //PML4E u64 *pml4 = (pdp + 512); pml4_table(pml4, pdp); //CR3 register u64 *start_pml4e = pml4; u64 page_addr = (u64)start_pml4e; write_cr3(page_addr); } void kernel_start(void *addr, unsigned int *fb) { fb_init(fb, 800, 600); setup_kernel_pagetable(addr); printf("\nAllocated initial kernel page table.\n"); /* Never exit! */ while (1) { }; }
C
#include<stdio.h> int main() { int a,b,c,pow=1; printf("Enter the value of a: \n "); scanf("%d",&a); printf("Enter the value of b: \n "); scanf("%d",&b); c = b; while(b!=0) { pow = pow *a; b = b - 1; } printf("%d raised to power %d: %d",a,c,pow); }
C
// Copyright (C) 2009 Jesse Jones // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifdef LIBGMP #include <gmp.h> #endif #include <stdio.h> typedef struct { double startX; double startY; double dx; double dy; double bailout; int h; int v; int maxDwell; } SmallInfo; // Note that this is about 3x faster than the release C# equivalent. // [ThreadModel(ThreadModel.SingleThread)] void SmallCompute(SmallInfo info, double* outMag, unsigned short* outDwell) { double x0 = info.startX + info.h*info.dx; double y0 = info.startY - info.v*info.dy; double x = x0; double y = y0; double mag = 0.0; unsigned short dwell = 0; while (mag < info.bailout && dwell < info.maxDwell) { double temp = x*x - y*y + x0; y = 2*x*y + y0; x = temp; mag = x*x + y*y; ++dwell; } *outMag = mag; *outDwell = dwell; } #ifdef LIBGMP typedef struct { __mpf_struct startX; __mpf_struct startY; __mpf_struct dx; __mpf_struct dy; __mpf_struct bailout; int h; int v; int maxDwell; } BigInfo; // At 64 bits this is about 14x slower than SmallCompute. // [ThreadModel(ThreadModel.SingleThread)] void BigCompute(BigInfo info, double* outMag, unsigned short* outDwell) { mpf_t x0, y0, x, y, mag, temp, t1, t2; unsigned short dwell = 0; unsigned long prec = mpf_get_prec(&info.dx); mpf_init2(x0, prec); mpf_init2(y0, prec); mpf_init2(x, prec); mpf_init2(y, prec); mpf_init2(mag, prec); mpf_init2(temp, prec); mpf_init2(t1, prec); mpf_init2(t2, prec); // x0 = info.startX + info.h*info.dx mpf_mul_ui(temp, &info.dx, info.h); mpf_add(x0, &info.startX, temp); // y0 = info.startY - info.v*info.dy mpf_mul_ui(temp, &info.dy, info.v); mpf_sub(y0, &info.startY, temp); // x = x0 mpf_set(x, x0); // y = y0 mpf_set(y, y0); while (mpf_cmp(mag, &info.bailout) < 0 && dwell < info.maxDwell) { // temp = x*x - y*y + x0 mpf_mul(t1, x, x); mpf_mul(t2, y, y); mpf_sub(temp, t1, t2); mpf_add(temp, temp, x0); // y = 2*x*y + y0 mpf_mul_ui(t1, x, 2); mpf_mul(t1, t1, y); mpf_add(y, t1, y0); // x = temp mpf_set(x, temp); // mag = x*x + y*y mpf_mul(t1, x, x); mpf_mul(t2, y, y); mpf_add(mag, t1, t2); ++dwell; } *outMag = mpf_get_d(mag); *outDwell = dwell; mpf_clear(x0); mpf_clear(y0); mpf_clear(x); mpf_clear(y); mpf_clear(mag); mpf_clear(temp); mpf_clear(t1); mpf_clear(t2); } #endif #if 0 // gcc -o app.exe -m32 -lgmp *.c int main() { printf("int: %lu\n", sizeof(int)); // 4 printf("long: %lu\n", sizeof(long)); // 4 printf("size_t: %lu\n", sizeof(size_t)); // 4 #ifdef LIBGMP printf("mp_exp_t: %lu\n", sizeof(mp_exp_t)); // 4 printf("__mpf_struct: %lu\n", sizeof(__mpf_struct)); // 16 #endif return 0; } #endif
C
// C program to Check Two Matrices are Equal or Not #include<stdio.h> #include<stdlib.h> int main() { int matA[10][10]; int matB[10][10]; int i, j; int row1, row2; int column1, column2; int flag = 1; printf(" Enter the order of the matrix A \n"); scanf("%d %d", &row1, &column1); printf(" Enter the order of the matrix B \n"); scanf("%d %d", &row2, &column2); // input and store element in matrix A printf(" Enter the element of matrix A : "); for (i = 0; i < row1; i++) for (j = 0; j < column1; j++) scanf("%d", &matA[i][j]); // input and store element in matrix B printf(" Enter the element of matrix B : "); for (i = 0; i < row2; i++) for (j = 0; j < column2; j++) scanf("%d", &matB[i][j]); // Display Matrix A printf("\n Given matrix A is\n"); for (i = 0; i < row1; i++) { printf("\n"); for (j = 0; j < column1; j++) { printf("%d\t", matA[i][j]); } } // Display Matrix B printf("\n Given matrix B is \n"); for (i = 0; i < row2; i++) { printf("\n"); for (j = 0; j < column2; j++) { printf("%d\t", matB[i][j]); } } printf("\n"); // Comparing two matrix for equality if (row1 == row2 && column1 == column2) { printf(" Matrix can be compared"); for (i = 0; i < row1; i++) { for (j = 0; j < column2; j++) { if (matA[i][j] != matB[i][j]) { flag = 0; break; } } } } else { printf(" Cannot be compared\n "); exit(1); } if (flag == 1) printf("\nTwo matrices are equal \n"); else printf("\nBut, two matrices are not equal \n"); return 0; }
C
#include "ftdb.h" t_keys *init_key(int id) { t_keys *key; key = (t_keys*)malloc(sizeof(t_keys)); key->header = NULL; key->next = NULL; key->id = id; return (key); } t_header *init_node(char *information) { t_header *node; node = (t_header*)malloc(sizeof(t_header)); node->next = NULL; node->information = strdup(information); return (node); } t_header *create_headers(int argc, char **argv) { int count; t_header *head; t_header *tmp; count = 4; head = init_node(argv[3]); tmp = head; while (count < argc) { tmp->next = init_node(argv[count]); tmp = tmp->next; count++; } return (head); } void add_links_to_rows(int new_cols, t_keys **keys) { t_keys *tmp_k; t_header *tmp_h; int count; tmp_k = *keys; while (tmp_k) { count = 0; tmp_h = tmp_k->header; while (tmp_h->next) tmp_h = tmp_h->next; while (count < new_cols) { tmp_h->next = init_node("\0"); tmp_h = tmp_h->next; count++; } tmp_k = tmp_k->next; } } t_keys *add_category(int argc, char **argv, t_keys *database) { t_keys *tmp_keys; t_header *tmp_headers; int count; count = 3; if (!database || !database->header) { database = init_key(0); database->header = create_headers(argc, argv); return (database); } tmp_keys = database; tmp_headers = tmp_keys->header; while (tmp_headers->next) tmp_headers = tmp_headers->next; while (count < argc) { tmp_headers->next = init_node(argv[count]); tmp_headers = tmp_headers->next; count++; } if (tmp_keys->next && (tmp_keys = tmp_keys->next)) add_links_to_rows(argc - 2, &tmp_keys); return (database); }
C
#include<stdio.h> #include<string.h> int main() { int n,i,j; int temp=0; char s[50]; gets(s); n=strlen(s); for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(s[i]>s[j]) { temp=s[i]; s[i]=s[j]; s[j]=temp; } } } printf("%s",s); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> int power(int base, int exp){ int result = base; for(exp; exp > 1; exp--){ result = result * base; } return result; } void print_array(int *array, int N){ int i; printf("\n-----\n"); for(i = 0; i < N; i++){ printf("ARRAY[%d] = %d\n", i, array[i]); } printf("-----\n"); return; } void load_file(char *filename, int *array, int N){ char *path = "../generate_data/"; char filePath[35]; sprintf(filePath, "%s%s", path, filename); printf("\nInput file: %s\n", filePath); FILE *fp = fopen(filePath, "r"); if(!fp){ printf("\nFailed to open input file."); } int i; for(i = 0; i < N; i++){ fscanf(fp, "%d\n", &array[i]); } fclose(fp); } int verify_sorted(int *array, int N){ int i; for(i = 0; i < N-1; i++){ if(array[i] > array[i+1]){ return 0; } } return 1; } //Intercalate void intercalate(int *A, int p, int q, int r) { int p1 = p, q2 = q+1, aux = 0; int vetAux[r-p+1]; while(p1<=q && q2<=r){ if(A[p1] <= A[q2]){ vetAux[aux] = A[p1]; p1++; }else{ vetAux[aux] = A[q2]; q2++; } aux++; } while(p1<=q){ //If there are elements in the first half vetAux[aux] = A[p1]; aux++;p1++; } while(q2<=r){ //If there are still elements in the second half vetAux[aux] = A[q2]; aux++;q2++; } for(aux=p;aux<=r;aux++){ //Move the elements back to the original vector A[aux] = vetAux[aux-p]; } } //Merge void mergeSort(int *A, int p, int r){ if (p < r) { int q = (p+r)/2; mergeSort(A, p, q); mergeSort(A, q+1, r); intercalate(A, p, q, r); } } int main(int argc, char * argv[]){ // analyzing input arguments if(argc != 3){ // invalid number of arguments printf("\nUsage: sort k type\nk refers to the number of elements 2^k in the array\ntype: 1 for crescent, 2 for decrescent, 3 for 10 percent sorted, 4 for 20 percent sorted\n"); exit(0); } int k = atoi(argv[1]); if(k < 1 || k > 14){ // invalid number of elements 2^k printf("Usage: sort k type\nk refers to the number of elements 2^k in the array\ntype: 1 for crescent, 2 for decrescent, 3 for 10 percent sorted, 4 for 20 percent sorted\n"); printf("k should be between 1 and 14\n"); exit(0); } int type = atoi(argv[2]); if(type < 1 || type > 4){ // invalid type of input array printf("Usage: generator k type\nk refers to the number of elements 2^k in the array\ntype: 1 for crescent, 2 for decrescent, 3 for 10 percent sorted, 4 for 20 percent sorted\n"); printf("type must be between 1 and 4\n"); exit(0); } char *describedTypes[] = { "Ordem Crescente" , "Ordem Decrescente" , "10 porcento ordenado" , "20 porcento ordenado" }; printf("Arguments: \n --- k = %d\n --- Input array type: %s\n", k, describedTypes[type-1]); char *types[] = { "crescent" , "decrescent" , "10percent" , "20percent" }; char inputFilename[20]; sprintf(inputFilename, "k%d_%s.txt", k, types[type-1]); // counting number of elements and initializing array int N = power(2,k); int array[N]; // loading input file load_file(inputFilename, array, N); // begin time counting clock_t begin = clock(); mergeSort(array,0,N-1); // end time counting clock_t end = clock(); double time_spent = (double)(end - begin) / CLOCKS_PER_SEC; printf("\nTotal execution time: %f seconds\n", time_spent); // appending result to output file char resultFilename[35]; char *sort = argv[0]; // editing file name sprintf(sort, "%s", sort + 2); // removing "./" in the argv string sprintf(resultFilename, "%s_%s", sort, inputFilename); char resultPath[50]; sprintf(resultPath, "../results/%s", resultFilename); printf("\nOutput file: %s\n", resultPath); FILE *output = fopen(resultPath, "a"); // append result to the file if(!output){ printf("\nFailed to open output file\n"); } fprintf(output, "%f\n", time_spent); fclose(output); //print_array(array, N); int verified = verify_sorted(array, N); if(verified){ printf("\nSorted\n"); } else{ printf("\nNot sorted\n"); } return 0; }
C
/***************************************************************************** Arquivo: kalman.c Conteudo: Funções em código C relacionadas ao filtro de kalman. Autor: G. A. Borges. Atualizações: - 19/09/2008: criação por Geovany A. Borges, modulo sem init/close *****************************************************************************/ // Cabecalhos de bibliotecas C run-time #include "mex.h" // apenas quando testar impressão no matlab #include <math.h> #include <stdio.h> // Cabecalhos de modulos do projeto #include "gmatrix.h" #include "gmatrix_linalg.h" // Definicoes de uso interno // Prototipos de funcoes internas ao modulo // Variaveis globais do módulo /***************************************************************************** ****************************************************************************** ** FUNCOES COM CHAMADA EXTERNA ****************************************************************************** *****************************************************************************/ /**************************************************************************************** *** Kalman Filter ****************************************************************************************/ void kalman_KF_update_innovationform(PGMATRIX pX, PGMATRIX pXpredicted, PGMATRIX pV, PGMATRIX pP, PGMATRIX pPpredicted, PGMATRIX pR, PDUMMY_MATRICES pDummy, int FlagUpdateCovariances) { // K = Ppredicted*inv(Ppredicted+R) // X = Xpredicted + K*(v); // P = Ppredicted - K*Ppredicted; PGMATRIX_ADD_COPY(pDummy->pMat2,pPpredicted,pR); PGMATRIX_INVERSE(pDummy->pMat2); PGMATRIX_MULTIPLY_COPY(pDummy->pMat1,pPpredicted,pDummy->pMat2); // pDummy->pMat1 = Kalman Gain. PGMATRIX_MULTIPLY_COPY(pDummy->pMat2,pDummy->pMat1,pV); PGMATRIX_ADD_COPY(pX,pXpredicted,pDummy->pMat2); if (!FlagUpdateCovariances){ PGMATRIX_COPY(pP,pPpredicted); } else{ PGMATRIX_MULTIPLY_COPY(pDummy->pMat2,pDummy->pMat1,pPpredicted); PGMATRIX_SUBTRACT_COPY(pP,pPpredicted,pDummy->pMat2); } return; } void kalman_EKF_update_innovationform(PGMATRIX pX, PGMATRIX pXpredicted, PGMATRIX pV, PGMATRIX pP, PGMATRIX pPpredicted, PGMATRIX pR, PGMATRIX pH, PDUMMY_MATRICES pDummy, int FlagUpdateCovariances) { // K = Ppredicted*H'*inv(H*Ppredicted*H'+R) // X = Xpredicted + K*(V); // P = Ppredicted - K*H*Ppredicted; PGMATRIX_MULTIPLY_COPY(pDummy->pMat1,pH,pPpredicted); PGMATRIX_MULTIPLY_COPY_EXTENDED(pDummy->pMat2, pDummy->pMat1, 0, pH, 1); PGMATRIX_ADD(pDummy->pMat2,pR); PGMATRIX_INVERSE(pDummy->pMat2); PGMATRIX_MULTIPLY_COPY_EXTENDED(pDummy->pMat3,pH,1,pDummy->pMat2,0); PGMATRIX_MULTIPLY_COPY(pDummy->pMat1,pPpredicted,pDummy->pMat3); // pDummy->pMat1 = Kalman Gain. // PGMATRIX_PRINT_MATLABFORM(pDummy->pMat1); // pDummy->pMat1 = Kalman Gain. PGMATRIX_MULTIPLY_COPY(pDummy->pMat2,pDummy->pMat1,pV); PGMATRIX_ADD_COPY(pX,pXpredicted,pDummy->pMat2); if (!FlagUpdateCovariances){ PGMATRIX_COPY(pP,pPpredicted); } else{ PGMATRIX_MULTIPLY_COPY(pDummy->pMat2,pDummy->pMat1,pH); PGMATRIX_MULTIPLY_COPY(pDummy->pMat3,pDummy->pMat2,pPpredicted); PGMATRIX_SUBTRACT_COPY(pP,pPpredicted,pDummy->pMat3); } }
C
/* * @lc app=leetcode id=21 lang=c * * [21] Merge Two Sorted Lists * * https://leetcode.com/problems/merge-two-sorted-lists/description/ * * algorithms * Easy (47.36%) * Likes: 2249 * Dislikes: 317 * Total Accepted: 588.5K * Total Submissions: 1.2M * Testcase Example: '[1,2,4]\n[1,3,4]' * * Merge two sorted linked lists and return it as a new list. The new list * should be made by splicing together the nodes of the first two lists. * * Example: * * Input: 1->2->4, 1->3->4 * Output: 1->1->2->3->4->4 * * */ /** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ #include <stdlib.h> // struct ListNode // { // int val; // struct ListNode *next; // }; struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2) { if (l1 == NULL && l2 == NULL) // 都是 NULL 就返回 NULL { return NULL; } typedef struct ListNode ListNode; // 初始化新链表的头,头不记录数据 ListNode *preNode = (ListNode *)malloc(sizeof(ListNode)); preNode->next = NULL; ListNode *head = preNode; // 记录链表头用于返回 ListNode *l1CurrentNode = l1; ListNode *l2CurrentNode = l2; ListNode *newNode = NULL; while (l1CurrentNode != NULL && l2CurrentNode != NULL) { // 创建新结点,并设置好与前一个结点的链接关系 newNode = (ListNode *)malloc(sizeof(ListNode)); preNode->next = newNode; newNode->next = NULL; if (l1CurrentNode->val < l2CurrentNode->val) { newNode->val = l1CurrentNode->val; l1CurrentNode = l1CurrentNode->next; } else if (l1CurrentNode->val >= l2CurrentNode->val) { newNode->val = l2CurrentNode->val; l2CurrentNode = l2CurrentNode->next; } preNode = newNode; } // 有一条是 NULL 的话,处理另外一条 ListNode *notNullChainNode = l1CurrentNode == NULL ? l2CurrentNode : l1CurrentNode; while (notNullChainNode != NULL) { newNode = (ListNode *)malloc(sizeof(ListNode)); preNode->next = newNode; newNode->next = NULL; newNode->val = notNullChainNode->val; notNullChainNode = notNullChainNode->next; preNode = newNode; } ListNode *trueHead = head->next; free(head); return trueHead; // 头不纪录数据,因此返回下一个结点 }
C
#include <stdio.h> #include <stdlib.h> int main() { int vektor[14], i = 0, szam; vektor[i]=rand()%101; while(i<14) { szam=rand()%101; if (szam>vektor[i]) {vektor[i+1]=szam; i++; continue; } if (vektor[i]==100) {vektor[i+1]=100; i++; continue; } } for(i=0;i<14;i++) printf("%d ",vektor[i]); return 0; }
C
/* ** EPITECH PROJECT, 2017 ** pushswap ** File description: ** pushswap tests 1 */ # include <criterion/criterion.h> # include <criterion/redirect.h> # include "pushswap.h" void redirect_std_one() { cr_redirect_stdout(); cr_redirect_stderr(); } Test(pushswap, no_sorted_list, .init = redirect_std_one) { char *av[] = { "./pushswap", "2", "1", "3", "6", "5", "8" }; pushswap_main(7, av); cr_assert_stdout_eq_str("sa pb pb pb sa pa pa pa\n"); } Test(pushswap, already_sorted_list, .init = redirect_std_one) { char *av[] = { "./pushswap", "14", "50", "134", "243", "9742", "9999" }; pushswap_main(7, av); cr_assert_stdout_eq_str("\n"); } Test(pushswap, error_no_integer, .init = redirect_std_one) { char *av[] = { "./pushswap", "a", "b" }; pushswap_main(3, av); cr_assert_stderr_eq_str("Only integer authorized.\n"); } Test(pushswap, error_less_arguments, .init = redirect_std_one) { char *av[] = { "./pushswap" }; pushswap_main(1, av); cr_assert_stderr_eq_str("Usage: ./pushswap [-vT] <num1> <num2> ... <n>\n"); } Test(pushswap, no_unique_parameter, .init = redirect_std_one) { char *av[] = { "./pushswap", "3", "6", "3", "7" }; pushswap_main(5, av); cr_assert_stderr_eq_str("Arguments must be unique.\n"); }
C
#include<stdio.h> #include<math.h> int main() { float first_number, second_number, result; printf("Prvi broj\n"); scanf("%f", &first_number); printf("Drugi broj\n"); scanf("%f", &second_number); result=first_number+second_number; printf("Zbroj\n=%f", result); return 0; }
C
#include "cache.h" #define CACHE_SIZE 100 typedef struct cache { cache_unit units[CACHE_SIZE]; int fd_stock; int fd_item; }* cache; cache cache_creat (const char* stock_path, const char* item_path){ cache tmp = calloc(1, sizeof(struct cache)); tmp->fd_stock = open (stock_path, O_RDWR | O_CREAT); tmp->fd_item = open (item_path, O_RDONLY); if (tmp->fd_stock == -1 || tmp->fd_item == -1) return NULL; return tmp; } cache_unit* cache_acess (cache cach, iid_t id){ return &(cach->units[id % CACHE_SIZE]); } int cache_is_cached (cache cach, iid_t id){ return (cach->units[id%CACHE_SIZE].id == id); } void cache_save_stock (cache cach, int index){ cache_unit* cunit = cache_acess(cach, index); if (cunit->id <= 0) return; stock_wr(cunit->id, cunit->stock, cach->fd_item, cach->fd_stock); } void cache_free (cache cach){ for (int i=0; i<CACHE_SIZE; i++) cache_save_stock (cach, i); } int cache_load (cache cach, iid_t id){ if (cache_is_cached(cach, id)) return 0; if (id >= item_id_top(cach->fd_item)) return -1; cache_save_stock(cach, id); cache_unit* tmp = cache_acess(cach, id); tmp->id = id; tmp->price = item_rd_price (id, cach->fd_item); tmp->stock = stock_rd (id, cach->fd_stock); return 0; } void cache_reload_price (cache cach, iid_t id){ if (!cache_is_cached(cach, id)) return; cache_unit* tmp = cache_acess(cach, id); tmp->price = item_rd_price (id, cach->fd_item); } int cache_inc_stock (cache cach, iid_t id, stock_t amount){ if (cache_load(cach, id) == -1) return -1; cache_unit* tmp = cache_acess(cach, id); if (tmp->stock < -amount) return -1; tmp->stock += amount; return 0; } cache_unit cache_get (cache cach, iid_t id){ if (cache_load(cach, id) == -1) return (cache_unit){-1,-1,-1}; return *cache_acess(cach, id); } price_t cache_get_price (cache cach, iid_t id){ if (cache_load(cach, id) == -1) return -1; return cache_acess(cach, id)->price; }
C
#include <stdio.h> #include <stdlib.h> //#include <cs50.h> int main(int argc, char *argv[]) { //ensure proper usage if (argc != 2) { fprintf (stderr, "Usage: ./recover card.raw\n"); return 1; } //keep track of card.raw file char *rawdata = argv[1]; //open card.raw file FILE *rawinfo = fopen(rawdata, "r"); if (rawinfo == NULL) { fprintf(stderr, "Could not open file %s\n", rawdata); return 2; } //buffer to load 512bytes at a time unsigned char buffer[512]; //Flag to know if it's the first jpeg found int found = 0; //Variable to keep track of the number of jpegs found (and for the file name) int i = 1; //FILE variable to save every jpeg, one at a time FILE *img = NULL; //Bucle to fetch 512 bytes at a time, and only if it can retrive 512 bytes it will perform steps in the bucle while (fread(&buffer, sizeof(char), 512, rawinfo) == 512) { //Checks for the begining of a new jpeg if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0) { //Variable to store the name of the files char filename[3]; //Checks if this is the first jpeg found and opens a new file if it is if (found == 0) { sprintf(filename, "%03i.jpg", i++); img = fopen(filename, "w"); found = 1; } //If a jepeg has been found, the file gets closed and a new file gets open else { fclose(img); sprintf(filename, "%03i.jpg", i++); img = fopen(filename, "w"); } } //If a jpeg has been found, the below code, writes the data in the current file. if (found == 1) { fwrite(&buffer, sizeof(char), 512, img); } } fclose (img); return 0; }
C
#include <stdio.h> #include "../include/vfs_17.h" #include "../include/bst.h" #include "../include/hashtable.h" #include "../include/linkedlist.h" #include "../include/nary.h" #include "../include/vfs_errorcodes.h" #include <string.h> #include <stdlib.h> //#include <sys/statvfs.h> //global variables struct Main_Header m1; struct Block b1; struct File_Descriptor fd1; struct Free_List fl1; struct Hash_Table ht1; struct List_Node *ln1; static int MOUNTED = 0; //struct node *bstRoot = NULL; t_node *root = NULL; FILE *fptr; // pointer to the file object //special functions int textfilecheck(char *); int fileformatcheck(char*, char*); //int disccheck(long); int search_File(char*, char*); int list_File(char*, char*); /*int disccheck(long size) { struct statvfs fiData; struct statvfs *fpData; char fnPath[128]; int i; //Lets loopyloop through the argvs strcpy(fnPath,"/"); // printf("Disk %s: \n", fnPath); //printf("\tblock size: %lu\n", fiData.f_bsize); //printf("\ttotal no blocks: %d\n", fiData.f_blocks); //printf("\tfree blocks: %lu\n", fiData.f_bfree); double total = (double)fiData.f_bsize * (double)fiData.f_bfree; //printf("%lf\n",total); if(total <= (double)size) {return 0;} return 1; } */ /* function for creating the large binary file for VFS */ int create_VFS(char *vfsname, long size) { //mounted so no more vfs if(MOUNTED == 1){ return 02; } //insufficient arguments if(size == -1) { return 00; } long mysize = ((size + 5) * 1024) + sizeof(m1) + sizeof(fd1); //insufficient arguments if(strcmp(vfsname, "") == 0) { return 00; } //check for name validity if(strstr(vfsname, "/") != NULL) { return 04; } //check for vfs label too large if(strlen(vfsname) > 30) { return 07; } long reqsize = sizeof(m1)+sizeof(b1)+sizeof(fd1); /*checking for enough memory*/ //int dchk = disccheck(reqsize); //if(dchk == 0) { return 3; } /*checking for minimum size*/ if(mysize < reqsize || size < 1 || size > 1024) { return 05; } //checking for datafile already exist fptr = fopen(vfsname, "rb"); if(fptr != NULL) { fclose(fptr); return 01; } int i=1, j=1; //loop variable for creating file descritors and file blocks //printf("--------------------Creating VFS-----------------------------"); strcpy(m1.sfile_system_label, vfsname); //storing the VFS label //printf("\nvfs name : %s", m1.sfile_system_label); //printf("\nsize of meta header: %ld", sizeof(m1)); m1.lsize = mysize - sizeof(m1); // size remaining after creation of meta header //printf("\nsize left after ceation of meta header: %ld", m1.lsize); m1.ltotal_file_descriptors = (m1.lsize)/(sizeof(fd1) + sizeof(b1)); // calculating the no. of file descriptors can be used in remaining space //printf("\nsize of each file descriptor : %ld", sizeof(fd1)); //printf("\ntotal file descriptors : %ld", m1.ltotal_file_descriptors); m1.lsize = m1.lsize - (m1.ltotal_file_descriptors * sizeof(fd1)); // size remaining after creation of file descriptors //printf("\nsize left after creation of file descriptors: %ld", m1.lsize); m1.ltotal_file_blocks = (m1.lsize)/(sizeof(b1)); // calculating the no. of file blocks can be used in remaining space //printf("\nsize of each file block : %ld", sizeof(b1)); //printf("\ntotal file blocks : %ld", m1.ltotal_file_blocks); m1.lsize = m1.lsize - (m1.ltotal_file_blocks * sizeof(b1)); // calculating the space unused //printf("\nspace unsed: %ld\n", m1.lsize); /* wrting the large binary file of given size including- * 1.meta header * 2.file descriptors and * 3.file blocks */ fptr = fopen(vfsname, "wb"); // opening the file with given label in binary write mode if(fptr == NULL) { return 02; // cannot create datafile } else { //long first_loc_fblock = ftell(fptr); m1.freedescriptor = 1 + (sizeof(m1)); m1.freeblock = 1 + (m1.freedescriptor + m1.ltotal_file_descriptors*sizeof(fd1)); //printf("\n%ld", m1.freedescriptor); //printf("\n%ld", m1.freeblock); // writing meta header fwrite(&m1, sizeof(m1), 1, fptr); //printf("\nmeta header created\n"); //file descriptor default values fd1.llocation_block_no = -9999; fd1.lfile_size = 0; //strcpy(fd1.sfile_name,"bcd"); //fd1.sfile_type = 'f'; //strcpy(fd1.slocation_full_path, "\null\null"); // writing file descriptors fseek(fptr,m1.freedescriptor,SEEK_SET); for (; i<= m1.ltotal_file_descriptors; i++) { fwrite(&fd1, sizeof(fd1), 1, fptr); //printf("%ld",fd1.llocation_block_no); } //printf("file descriptor created\n"); // writing file blocks for (; j<= m1.ltotal_file_blocks; j++) { fwrite(&b1, sizeof(b1), 1, fptr); } //printf("file block created\n"); fclose(fptr); // closing the file to store it in persistent memory //printf("\n--------------------VFS Created-----------------------------\n"); } return 10; } //mounting vfs int mount_VFS(char *mname) { //vfs already mounted if(MOUNTED == 1){ return 04; } //insufficient arguments if(strcmp(mname, "") == 0) { return 00; } fptr = fopen(mname, "rb+"); // opening file for read/write if(fptr == NULL) { return 01; //datafile not found } else { //reading the meta header fseek(fptr,0,SEEK_SET); //checking for CANNOT READ FROM FILE" int checkm = fread(&m1, sizeof(m1), 1, fptr); if( checkm == 0) { return 02; } else { // //initializing bitmap bitMapInit(); //initializing hashtable initialzeHashTable(&ht1); root = nary_insert_root(); //reading file descriptors fseek(fptr,m1.freedescriptor,SEEK_SET); int k = 1; for (; k<= m1.ltotal_file_descriptors; k++) { fread(&fd1, sizeof(fd1), 1, fptr); if(fd1.llocation_block_no != -9999) { //inserting into naray insert_node(&fd1,root); //call hash table insert function //if (fd1.sfile_type == 'f') //{ //printf("%s\n", fd1.sfile_name ); insertHashTable(&ht1, &fd1); //} //call BST insert function insertBst(&fd1); } } } MOUNTED = 1; } //printf("vfs name: %s", m1.sfile_system_label); //strcpy(VFS_NAME, m1.sfile_system_label); return 10; } int make_dir(char *parent_path, char *dir_name){ //printf("******************in make dir****************"); //displayList(); //printf("%s %s", parent_path, dir_name); char parent_pathpure[512] = ""; //vfs not mounted if(MOUNTED == 0){ return 05; } if(strcmp(parent_path, "") == 0) { return 00; } if(strcmp(dir_name, "") == 0) { return 00; } int fss = freeLocation(); if (fss == -1) { return 01; } //check for name validity if(strstr(dir_name, "/") != NULL) { return 02; } if(strcmp(parent_path,"/")!=0) { if(parent_path[strlen(parent_path)- 1] == '/') { //printf("Here\n"); strncpy(parent_pathpure, parent_path, strlen(parent_path) - 1); } else{strcpy(parent_pathpure, parent_path);} } else{strcpy(parent_pathpure, parent_path);} char totalPath[512]; if(strcmp(parent_path,"/")!=0) { strcpy(totalPath,parent_pathpure); strcat(totalPath,"/"); strcat(totalPath,dir_name); } else { strcpy(totalPath,"/"); strcat(totalPath,dir_name); } //printf("dir_name : %s parent_path : %s",dir_name,parent_path); char *token[80]; int exist = searchBst(totalPath); //struct node* t = searchBstFD(parent_path); //if(t!=NULL) //printf("/n************no null**********/n" ); //else //printf("/n************null**********/n" ); if(exist!=1){ int existParentPath = searchBst(parent_pathpure); //printf("existParentPath %d",existParentPath); if(!existParentPath){ int j, i=0; char parent_path_temp[512]; strcpy(parent_path_temp,parent_pathpure); token[0] = strtok(parent_path_temp, "/"); while(token[i]!= NULL) { // printf("%s\n", token[i]); i++; token[i] = strtok(NULL, "/"); } char subPath[512]; char prevPath[512]; strcpy(subPath,"/"); for(j = 0; j <= i-1; j++) { strcpy(prevPath,subPath); if(strcmp(prevPath,"/")!=0) { strcpy(subPath,prevPath); strcat(subPath,"/"); strcat(subPath,token[j]); } else { strcpy(subPath,"/"); strcat(subPath,token[j]); } int existParent = searchBst(subPath); if(!existParent){ dirInsert(prevPath,token[j]); } } } //if(token[0]==""){ dirInsert(parent_pathpure, dir_name); //printf("BST Diplay\n \n"); //displayList(); //printf("narray Diplay\n \n"); //printtree(root); //printf("narray Diplay ends\n \n"); //} } else { return 03; } return 10; } int move_dir(char* source_path,char* destination_path){ char source_pathtmp[512] = ""; char destination_pathtmp[512] = ""; //insufficient argument //not munted if(MOUNTED == 0){ return 04; } if(strcmp(source_path, "") == 0) { return 00; } if(strcmp(destination_path, "") == 0) { return 00; } if(strcmp(source_path,"/")!=0) { if(source_path[strlen(source_path)- 1] == '/') { //printf("Here\n"); strncpy(source_pathtmp, source_path, strlen(source_path) - 1); } else{strcpy(source_pathtmp, source_path);} } else{strcpy(source_pathtmp, source_path);} if(strcmp(destination_path,"/")!=0) { if(destination_path[strlen(destination_path)- 1] == '/') { //printf("Here\n"); strncpy(destination_pathtmp, destination_path, strlen(destination_path) - 1); } else{strcpy(destination_pathtmp, destination_path);} } else{strcpy(source_pathtmp, source_path);} struct node *ndsrc4 = searchBstFD(source_pathtmp); struct node *nddest4 = searchBstFD(destination_pathtmp); //source not found if(ndsrc4 == NULL) { return 01;} //dest not found if(nddest4 == NULL) { return 02;} //source is not file if( ndsrc4->fd1->sfile_type == 'f') { return 04; } //dest is not file if( nddest4->fd1->sfile_type == 'f') { return 07; } //printf("in move dir\n"); //int errcode= move_node(root,source_pathtmp,destination_pathtmp); //if(errcode==3) //{return 05;} return 10; } int dirInsert(char *parent_path, char *dir_name){ //fseek(fptr,m1.freeblock,SEEK_SET); //printf("dir name in dir insert is %s and parent_path is %s\n", dir_name,parent_path); //getting the first free location from the Bitmap long a = freeLocation(); /*struct File_Descriptor *fd = (struct File_Descriptor*)malloc(sizeof(struct File_Descriptor)); strcpy(fd->sfile_name, dir_name); strcpy(fd->slocation_full_path, parent_path); fd->sfile_type = 'd'; fd->lfile_size = 0; fd->llocation_block_no = a;*/ //Sending pointer to write at the first location of the FDescriptor fseek(fptr,m1.freedescriptor,SEEK_SET); fseek(fptr,a*sizeof(fd1),SEEK_CUR); strcpy(fd1.sfile_name, dir_name); strcpy(fd1.slocation_full_path, parent_path); //fd1.sfile_type; fd1.lfile_size = 0; fd1.llocation_block_no = a; fd1.sfile_type = 'd'; fwrite(&fd1, sizeof(fd1), 1, fptr); //fwrite(&fd1, sizeof(fd1), 1, fptr); //Update bit map by passing block no. of occupied block bitmapUpdate(a, 1); t_node *flag = insert_node(&fd1,root); //inserting into hashtable //insertHashTable(&ht1, fd); //inserting into BST insertBst(&fd1); //inserting into hashtable insertHashTable(&ht1, &fd1); if(flag !=NULL) { //printf("SUCCESS\n"); } else { //printf("FAIL"); } return 10; } int list_dir(char* path,int flag,char *harddiskpath) { //char path[100] = ""; //printf("%s\n", harddiskpath); //not munted if(MOUNTED == 0){ return 03; } //insufficient arguments if(strcmp(path, "") == 0) { return 00; } if(flag == -1) { return 00; } if(strcmp(harddiskpath, "") == 0) { return 00; } // Invalid flag if(flag !=0 && flag !=1) {return 02;} /*if(strcmp(pathtmp,"/")!=0) { if(pathtmp[strlen(pathtmp)- 1] == '/') { //printf("Here\n"); strncpy(path, pathtmp, strlen(pathtmp) - 2); } }*/ //int errcode =10; int errcode = list_tree(&root,flag,path,harddiskpath); return errcode; } int delete_dir(char *path) { //printf("above"); //insufficient arguments char purepath[512] = ""; //not munted if(MOUNTED == 0){ return 04; } if(strcmp(path, "") == 0) { return 00; } if(strcmp(path,"/")!=0) { if(path[strlen(path)- 1] == '/') { //printf("Here\n"); strncpy(purepath, path, strlen(path) - 1); } else{ strcpy(purepath, path); } } else{strcpy(purepath, path);} struct node *nd = searchBstFD(purepath); if (nd != NULL) { //printf("in dele dir b4 dele \n"); //printtree(root); //change //int deli = delete(nd->fd1,root); //if(deli == 2) { return 02;} //printf("in dele dir after dele nary \n"); //printtree(root); //deleting from BSTl //deleteBstElm(filepath); //deleting from Hash Table //deleteHashTable(&ht1, nd->fd1->sfile_name); //detele from naray yet to be done //making bitmap available //long a= nd->fd1->llocation_block_no; //bitmapUpdate(a, 0); } else { return 01; } return 10; } int unmount_VFS(char *uname) { if(MOUNTED == 0){ return 04; } //insufficient arguments if(strcmp(uname, "") == 0) { return 0; } //printf("uname: %s vfslabel: %s\n", uname, m1.sfile_system_label); if(strcmp(m1.sfile_system_label, uname) == 0){ //printf("\n--------------------Unmounting VFS\n"); fclose(fptr); //free(fl1.bitmap); //printf("\n--------------------VFS Unmounted\n"); MOUNTED = 0; return 10; } else { return 04; } } //file format check int fileformatcheck(char *path, char *modpath){ char *string; char *strtmpsrc; string = path; char *tokenPtr; tokenPtr = strtok( string, "." ); tokenPtr = (strtmpsrc = strtok( NULL, "." )) ? strtmpsrc : ""; char *string2; char *strtmp; string2 = modpath; char *tokenPtr2; tokenPtr2 = strtok( string2, "." ); tokenPtr2 = (strtmp = strtok( NULL, "." ))? strtmp : ""; if(strcmp(tokenPtr, tokenPtr2) == 0) {return 1;} else{return 0;} } //update edit file int update_File(char *filepath, char *src) { //vfs not mounted if(MOUNTED == 0){ return 06; } //insufficient arguments if(strcmp(filepath, "") == 0) { return 00; } //insufficient arguments if(strcmp(src, "") == 0) { return 00; } char ch,arr[1024] = ""; struct node *nd = searchBstFD(filepath); FILE *fp ; fp = fopen(src,"rb") ; //file format check if(fileformatcheck(filepath, src) == 0) { return 05; } if (nd != NULL) { //erase previous data fseek(fptr,m1.freeblock,SEEK_SET); long a= nd->fd1->llocation_block_no; fseek(fptr,a*sizeof(b1),SEEK_CUR); fwrite(&arr, sizeof(arr), 1, fptr); //write new data fseek(fptr,m1.freeblock,SEEK_SET); fseek(fptr,a*sizeof(b1),SEEK_CUR); if( fp == NULL ) { //printf("here %s", src); return 01; //source file not found } else { //printf("hereddd %s", src); //file size check fseek(fp, 0L, SEEK_END); long sz = ftell(fp); if(sz > sizeof(b1)) { return 04; } //file too large //file size check fseek(fp, 0L, SEEK_SET); fread(&arr, sizeof(arr), 1, fp); fclose(fp); //printf("\n%s\n", arr); } //Write files to the file system fwrite(&arr, sizeof(arr), 1, fptr); //Sending pointer to write at the first location of the FDescriptor //read old file descriptor fseek(fptr,m1.freedescriptor,SEEK_SET); fseek(fptr,a*sizeof(fd1),SEEK_CUR); struct File_Descriptor fdtemp; fread(&fdtemp, sizeof(fdtemp), 1, fptr); //write updated file descriptor fseek(fptr,m1.freedescriptor,SEEK_SET); fseek(fptr,a*sizeof(fd1),SEEK_CUR); strcpy(fd1.sfile_name, fdtemp.sfile_name); strcpy(fd1.slocation_full_path, fdtemp.slocation_full_path); fd1.lfile_size = sizeof(arr); fd1.llocation_block_no = a; fd1.sfile_type = 'f'; fwrite(&fd1, sizeof(fd1), 1, fptr); } else { return 02; //destination file not found } return 10; } int textfilecheck(char *path){ char *string; string = path; char *strtmpsrc; char *tokenPtr; tokenPtr = strtok( string, "." ); tokenPtr = (strtmpsrc = strtok( NULL, "." )) ? strtmpsrc : ""; if(!strcmp(tokenPtr,"txt")) {return 1;} else{return 0;} } //list file function int list_File(char *filepath, char *harddiskpath) { //vfs not mounted if(MOUNTED == 0){ return 06; } //insufficient arguments if(strcmp(filepath, "") == 0) { return 00; } //insufficient arguments if(strcmp(harddiskpath, "") == 0) { return 00; } //not a text file struct node *nd = searchBstFD(filepath); if(!textfilecheck(filepath)) { return 05; } else { if (nd != NULL) { fseek(fptr,m1.freeblock,SEEK_SET); long a = nd->fd1->llocation_block_no; fseek(fptr,a*sizeof(b1),SEEK_CUR); //strcat(harddiskpath, "/"); //strcat(harddiskpath, nd->fd1->sfile_name); FILE *fp = fopen (harddiskpath, "wt+" ) ; if ( fp == NULL ) { //perror ("cannot open file") ; return 02; //output file path not found } else { fread(&b1, sizeof(b1), 1, fptr); int i=0; while(b1.sfixed_size_buffer[i] != '\0') { fputc(b1.sfixed_size_buffer[i], fp); i++; } } fclose(fp); } else { //printf("path not found\n"); return 01; // source file path not found } } return 10; } //remove file function int remove_File(char *filepath) { //vfs not mounted if(MOUNTED == 0){ return 06; } //insufficient arguments if(strcmp(filepath, "") == 0) { return 00; } struct node *nd = searchBstFD(filepath); if (nd != NULL) { //deleting from BST deleteBstElm(filepath); //deleting from Hash Table deleteHashTable(&ht1, nd->fd1->sfile_name, nd->fd1->slocation_full_path); //detele from naray //delete_dir(filepath); //making bitmap available long a= nd->fd1->llocation_block_no; bitmapUpdate(a, 0); } else { return 01; } return 10; } //export_file function int export_File(char *filepath, char *outputfile) { //printf("above"); //vfs not mounted if(MOUNTED == 0){ return 07; } //source path missing if(strcmp(filepath, "") == 0) { return 00; } //destination path missing if(strcmp(outputfile, "") == 0) { return 00; } struct node *nd = searchBstFD(filepath); if (nd != NULL) { //can not export directory if( nd->fd1->sfile_type == 'd') { return 06; } fseek(fptr,m1.freeblock,SEEK_SET); long a= nd->fd1->llocation_block_no; //printf("%ld\n", a); //strcat(outputfile, "/"); //strcat(outputfile, nd->fd1->sfile_name); /*FILE *fptre = fopen(outputfile, "rb"); if(fptre != NULL) { return 05; }*/ fseek(fptr,a*sizeof(b1),SEEK_CUR); FILE *fp = fopen (outputfile, "wb+" ) ; if ( fp == NULL ) { //printf("here"); return 02; } else { fread(&b1, sizeof(b1), 1, fptr); int i=0; while(b1.sfixed_size_buffer[i] != '\0') { fputc(b1.sfixed_size_buffer[i], fp); i++; } } fclose(fp); } else { return 01; } return 10; } //move file int move_File(char *srcfilepath, char *destfilepathtmp) { //vfs not mounted if(MOUNTED == 0){ return 06; } char destfilepath[200] = ""; //insufficient arguments if(strcmp(srcfilepath, "") == 0) { return 00; } //insufficient arguments if(strcmp(destfilepathtmp, "") == 0) { return 00; } if(strcmp(destfilepathtmp,"/")!=0) { if(destfilepathtmp[strlen(destfilepathtmp)- 1] == '/') { //printf("Here\n"); strncpy(destfilepath, destfilepathtmp, strlen(destfilepathtmp) - 1); } else { strcpy(destfilepath, destfilepathtmp); } }else { strcpy(destfilepath, destfilepathtmp); } //source file exists or not struct node *ndsrc1 = searchBstFD(srcfilepath); if( ndsrc1 == NULL) { return 01; } //dest path exists or not struct node *ndsrc2 = searchBstFD(destfilepath); if( ndsrc2 == NULL) { return 02; } //dest is not a file struct node *ndsrc3 = searchBstFD(destfilepath); if( ndsrc3->fd1->sfile_type == 'f') { return 05; } //source is not dir struct node *ndsrc4 = searchBstFD(srcfilepath); if( ndsrc4->fd1->sfile_type == 'd') { return 01; } copy_File(srcfilepath, destfilepath); //giving error remove_File(srcfilepath); //printlist(ln1); //displayList(); return 10; } //copy file int copy_File(char *srcpath, char *destpath) { //vfs not mounted if(MOUNTED == 0){ return 07; } //source path missing if(strcmp(srcpath, "") == 0) { return 00; } //destination path missing if(strcmp(destpath, "") == 0) { return 00; } int fss = freeLocation(); if (fss == -1) { return 06; } char temparr[1024]; char full_path[100] = ""; //checking struct node *ndsrc = searchBstFD(srcpath); if (ndsrc != NULL) { if( ndsrc->fd1->sfile_type == 'd') { return 05; } fseek(fptr,m1.freeblock,SEEK_SET); long a = ndsrc->fd1->llocation_block_no; fseek(fptr,a*sizeof(b1),SEEK_CUR); fread(&b1, sizeof(b1), 1, fptr); int i=0; while(b1.sfixed_size_buffer[i] != '\0') { temparr[i] = b1.sfixed_size_buffer[i]; i++; } } else { return 01; } //printf("%ld\n", a); int tmp; if(strcmp(destpath,"/")!=0) { //strcpy(full_path,destpath); /*if(full_path[strlen(full_path-1)] !='/') { strcat(full_path,"/"); }*/ if(destpath[strlen(destpath) - 1] == '/') { //printf("Here\n"); strncpy(full_path, destpath, strlen(destpath) - 1); //dest[strlen(dest - 1)] = '\0'; //printf("%s\n",dest); } else{ strcpy(full_path, destpath); } //strcat(full_path,ndsrc->fd1->sfile_name); */ } /*else { if(full_path[strlen(full_path-1)] !='/') { strcat(full_path,"/"); } //strcat(full_path,ndsrc->fd1->sfile_name); }*/ tmp = searchBst(full_path); if (tmp == 0) { return 02; //cant find dest path } fseek(fptr, m1.freeblock,SEEK_SET); //printf("after seek"); //getting the first free location from the Bitmap long b = freeLocation(); fseek(fptr,b*sizeof(b1),SEEK_CUR); //Write files to the file system //printf("before write"); fwrite(&temparr, sizeof(temparr), 1, fptr); //Sending pointer to write at the first location of the FDescriptor fseek(fptr,m1.freedescriptor,SEEK_SET); fseek(fptr,b*sizeof(fd1),SEEK_CUR); strcpy(fd1.sfile_name, ndsrc->fd1->sfile_name); strcpy(fd1.slocation_full_path, full_path); //fd1.sfile_type; fd1.lfile_size = sizeof(temparr); fd1.llocation_block_no = b; fd1.sfile_type = 'f'; fwrite(&fd1, sizeof(fd1), 1, fptr); //printf("%ld", fd1.llocation_block_no); //Update bit map by passing block no. of occupied block bitmapUpdate(b, 1); //inserting into naray insert_node(&fd1,root); //inserting into hashtable insertHashTable(&ht1, &fd1); //inserting into BST insertBst(&fd1); //return 1; return 10; } //file search function int search_File(char *sname, char *outputfile) { //printlist(ln1); //creating list of file //output path missing //printf("%s\n",sname); //vfs not mounted if(MOUNTED == 0){ return 03; } if(strcmp(outputfile, "") == 0) { return 00; } if(strstr(sname, "/") != NULL) { return 02; } //printf("vfslabel: %s\n", m1.sfile_system_label); List_Node *start = searchHashTable(&ht1, sname); if(start == NULL) { return 04; } else { FILE *ft = fopen (outputfile, "w+" ) ; if ( ft == NULL ) { return 01; //cannot find specified output file } else { while(start != NULL) { fprintf(ft, "%s\t%s\n", start->data->sfile_name, start->data->slocation_full_path) ; start=start->next; } } fclose ( ft ) ; } return 10; } int add_File(char* dest, char* fname, char* src) { //vfs not mounted if(MOUNTED == 0){ return 07; } //printf("%s\n",dest); //insufficient arguments char destpurified[512] = ""; if(strcmp(dest, "") == 0) { return 00; } //insufficient arguments if(strcmp(fname, "") == 0) { return 00; } //insufficient arguments if(strcmp(src, "") == 0) { return 00; } //check for name validity if(strstr(fname, "/") != NULL) { return 02; } //printf("%s\n",dest); //printf("%d\n",strlen(dest) - 1); //purify argument //char desttmp[100] = ""; if(strcmp(dest,"/")!=0) { if(dest[strlen(dest) - 1] == '/') { //printf("Here\n"); strncpy(destpurified, dest, strlen(dest) - 1); //dest[strlen(dest - 1)] = '\0'; //printf("%s\n",destpurified); } else { strcpy(destpurified, dest); } } //printf("Here 1 \n"); char basefolder[512] = ""; char basename[80] = ""; //printf("%s\n", destpurified); //create directory if not exists if(strcmp(dest,"/")!=0) { struct node *nddest = searchBstFD(destpurified); if(nddest == NULL) { strcpy(basename, strrchr(destpurified, '/') + 1); //printf("before\n"); //printf("basename %s\n", basename); strncpy(basefolder, destpurified, strlen(destpurified) - strlen(basename) - 1); //printf("basefolder %s\n", basefolder); make_dir(basefolder, basename); } } //printf("after\n"); //printtree(root); //checking for file system space int fss = freeLocation(); if (fss == -1) { return 01; } else { //checking for file existence char full_path[512]; int tmp; if(strcmp(dest,"/")!=0) { strcpy(full_path,dest); if(dest[strlen(dest) - 1] != '/') { strcat(full_path,"/"); } strcat(full_path,fname); } else { strcat(full_path,"/"); strcat(full_path,fname); } tmp = searchBst(full_path); if (tmp == 1) { return 3; //file already exists } char ch,arr[1024]; int c; fseek(fptr,m1.freeblock,SEEK_SET); //printf("after seek"); //getting the first free location from the Bitmap long a = freeLocation(); fseek(fptr,a*sizeof(b1),SEEK_CUR); FILE *fp ; fp = fopen(src,"rb") ; //printf("here %s", src); if( fp == NULL ) { //perror ("cannot open file") ; return 05; //can not open specified data file } else{ //file size check fseek(fp, 0L, SEEK_END); long sz = ftell(fp); if(sz > sizeof(b1)) { return 06; } //file too large //file size check fseek(fp, 0L, SEEK_SET); int i; for(i=0;i<1024;i++) { arr[i]='\0'; } fread(&arr, sizeof(arr), 1, fp); fclose(fp); //printf("\n%s\n", arr); } //Write files to the file system //printf("before write"); fwrite(&arr, sizeof(arr), 1, fptr); //Sending pointer to write at the first location of the FDescriptor fseek(fptr,m1.freedescriptor,SEEK_SET); fseek(fptr,a*sizeof(fd1),SEEK_CUR); strcpy(fd1.sfile_name, fname); strcpy(fd1.slocation_full_path, destpurified); //fd1.sfile_type; fd1.lfile_size = sizeof(arr); fd1.llocation_block_no = a; fd1.sfile_type = 'f'; fwrite(&fd1, sizeof(fd1), 1, fptr); //printf("%ld", fd1.llocation_block_no); //Update bit map by passing block no. of occupied block bitmapUpdate(a, 1); //inserting into naray insert_node(&fd1,root); //inserting into hashtable insertHashTable(&ht1, &fd1); //inserting into BST insertBst(&fd1); return 10; } } /*writing code for bit map.*/ //Initializing bitmap to zero void bitMapInit() { long totalfiledescs = m1.ltotal_file_descriptors; fl1.bitmap = (char*)malloc(m1.ltotal_file_descriptors * sizeof(char)); long i; fseek(fptr,m1.freedescriptor,SEEK_SET); for(i=0;i < totalfiledescs; i++){ //fseek(fptr,i*sizeof(fd1),SEEK_CUR); fread(&fd1, sizeof(fd1), 1, fptr); if(fd1.llocation_block_no == -9999) fl1.bitmap[i] = 0; else fl1.bitmap[i] = 1; } } // returns free bitmap location long freeLocation() { long free_loc; //fl1.bitMap[0]=1; long j; for(j=0;j < m1.ltotal_file_descriptors;j++){ if(fl1.bitmap[j]==0){ free_loc = j; break; } } if(j==m1.ltotal_file_descriptors){ return -1; } return free_loc; } //updating occupied bit map void bitmapUpdate(long n, int flag){ if (flag ==1 ) // occupied fl1.bitmap[n]=1; else //empty fl1.bitmap[n]=0; } //statistics void stats() { printf("\nMount Label: %s", m1.sfile_system_label); printf("\nNext Free File Descriptor Location :%ld", m1.freedescriptor + sizeof(fd1) * (freeLocation())); printf("\nNext Free Block Location: %ld", m1.freeblock + sizeof(b1) * (freeLocation())); //printf("\nNext Free Block Location: %ld", m1.freeblock); printf("\nTotal File Blocks: %ld", m1.ltotal_file_blocks); printf("\nAvailable File Blocks: %ld", m1.ltotal_file_blocks - freeLocation()); printf("\nTotal File Descriptors: %ld", m1.ltotal_file_descriptors); printf("\nAvailable File Descriptors: %ld\n", m1.ltotal_file_descriptors - freeLocation()); //fclose(fptr); } void man(char* search_name){ if(!strcmp(search_name,"createvfs")){ printf("FUNCTION:\t createvfs (vfs_label,size)\n"); printf("Description:\nTo create a Virtual File System. <vfs_label> is the name of VFS. Size specified in kilobytes. Valid range is 1 to 1024 (inclusive)\n\n"); } else if(!strcmp(search_name,"mountvfs")){ printf("FUNCTION:\t mountvfs (vfs_label) \n"); printf("Description:\nTo Mount the VFS path on current directory. This involves loading the file/directory descriptors into various data structures\n\n"); } else if(!strcmp(search_name,"unmountvfs")){ printf("FUNCTION:\t unmountvfs (vfs_label)\n"); printf("Description:\nTo unmount the VFS. It involves saving index information and tree information back into the hard disk.\n\n"); } else if(!strcmp(search_name,"makedir")){ printf("FUNCTION:\t makedir (parent_path, dir_name) \n"); printf("Description:\nTo create a new directory whose name should be<dir_name> in path specified by <parent_path> where '/' is considered as 'root' directory.\n\n"); } else if(!strcmp(search_name,"deletedir")){ printf("FUNCTION:\t deletedir (path) \n"); printf("Description:\nTo remove a file or a directory as indicated by < name>\n\n"); } else if(!strcmp(search_name,"movedir")){ printf("FUNCTION:\t movedir (source_dir_path,dest_dir_path) \n"); printf("Description:\nTo move a sub-tree <source_dir_path> to <dest_dir_path> directory.\n\n"); } else if(!strcmp(search_name,"listdir")){ printf("FUNCTION:\t listdir (dir_name,flag, outputfile) \n"); printf("Description:\nList all the contents according to <flag> of the current directory i.e. specified by <dir_name>. Flag “-R” means recursive listing of the entire subtree. The output of listdir is saved in outputfile in the hard-disk.\n\n"); } else if(!strcmp(search_name,"addfile")){ printf("FUNCTION:\t addfile (dest_dir_name, file_name, data) \n"); printf("Description:\nCreate a new file named <file_name> with <data> as content. in path specified by <dest_dir_name>. “data” corresponds to an external file residing in the hard disk.\n\n"); } else if(!strcmp(search_name,"listfile")){ printf("FUNCTION:\t listfile (file_path, output_file) \n"); printf("Description:\nExtract the contents of a file specified by <file_path> and store in output file.\n\n"); } else if(!strcmp(search_name,"updatefile")){ printf("FUNCTION:\t updatefile (file_path, data) \n"); printf("Description:\nUpdate/Edit the contents of a file specified by <file_path> with <data>.\n\n"); } else if(!strcmp(search_name,"removefile")){ printf("FUNCTION:\t removefile (file_path) \n"); printf("Description:\nRemove a file specified by <file_path>.\n\n"); } else if(!strcmp(search_name,"exportfile")){ printf("FUNCTION:\t exportfile (vfs_file_path, hard_disk_path) \n"); printf("Description:\nExport the file from the file system into the hard disk\n\n"); } else if(!strcmp(search_name,"searchfile")){ printf("FUNCTION:\t searchfile (name, outputfile) \n"); printf("Description:\nRetrieves the full path of all the files/folders having the given name as part of its at the beginning of file/folder name (substring). The output is stored in outputfile.\n\n"); } else if(!strcmp(search_name,"copyfile")){ printf("FUNCTION:\t copyfile (source_file_path,dest_file_path) \n"); printf("Description:\nTo copy source file to destination specified. The destination includes full file path including file name. Overwrite the destination file if it already exists.\n\n"); } else if(!strcmp(search_name,"movefile")){ printf("FUNCTION:\t exportfile (vfs_file_path, hard_disk_path) \n"); printf("Description:\nRename <source_file_path> to <dest_file_path> file. The destination includes full file path including file name.Overwrite the destination file if it already exists.\n\n"); } } void cat(char *filepath) { struct node *nd = searchBstFD(filepath); if(!textfilecheck(filepath)) { printf("not a text file\n"); } else { if (nd != NULL) { fseek(fptr,m1.freeblock,SEEK_SET); long a = nd->fd1->llocation_block_no; fseek(fptr,a*sizeof(b1),SEEK_CUR); //strcat(harddiskpath, "/"); //strcat(harddiskpath, nd->fd1->sfile_name); fread(&b1, sizeof(b1), 1, fptr); int i=0; while(b1.sfixed_size_buffer[i] != '\0') { printf("%c",b1.sfixed_size_buffer[i]); i++; } } else { printf("path not found\n"); // source file path not found } } }
C
/* File: PrimeFactors.c Author: Mira Pohjola Description: Contains functions for finding largest prime factors for an array of long-type numbers. Prints the largest prime factor for each number. */ #include <stdio.h> #include <math.h> #include "PrimeFactors.h" void findPrimeFactors(long *numbers, long numbersAmount) { for (int i = 0; i < numbersAmount; i++){ long currentNumber = *(numbers+i); getLargestPrimeFactor(currentNumber); } } void getLargestPrimeFactor(long number) { long maxFactor = -1; long original = number; while (number % 2 == 0){ maxFactor = 2; number >>=1; } for (int i = 3; i <= sqrt(number); i+=2) { while(number % i == 0){ maxFactor = i; number /= i; } } if (number > 2) { maxFactor = number; } printf("\nLargest prime factor of %ld is %ld", original, maxFactor); }
C
// Girilen bir kelimenin uzunluunu bulur ve tersten yazdrr. #include <stdio.h> main () { char ayse[100]; int uzunluk = 0, i; printf ("Kelime giriniz: "); scanf ("%s", ayse); for (uzunluk = 0; ayse[uzunluk] != '\0'; uzunluk ++); for (i=uzunluk-1; i>=0; i--) printf ("%c", ayse[i]); getch (); }
C
#include <stdio.h> void avg(int n1,int n2) { float avg; avg= (float)(n1+n2)/2; printf("Average of %d and %d is: %.2f",n1,n2,avg); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> void f2(char *napis){ for(int i=0;napis[i]!='\0';i++){ if(napis[i]=='a'){ napis[i]='1'; if (napis[i+1]!='a') napis[i+1]='2'; if (napis[i+2]!='a') napis[i+2]='3'; } }} int main(){ char napis[10]={"apaszka"}; f2(napis); printf("%s",napis); }
C
#include<iostream> int main() { int a; int b; std::cout << "Írj egy számot: "; std::cin >> a; std::cout << "Írj egy másik számot: "; std::cin >> b; a = a * b; b = a / b; a = a / b; std::cout << "Felcserélve: " << a << " és " << b << '\n'; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* init_screen_size.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lnicosia <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/03/09 11:06:03 by lnicosia #+# #+# */ /* Updated: 2020/03/09 11:06:17 by lnicosia ### ########.fr */ /* */ /* ************************************************************************** */ #include "init.h" int init_screen_size(t_env *env) { env->screen_w[2] = 2560; env->screen_h[2] = 1440; env->screen_w[1] = 1920; env->screen_h[1] = 1080; env->screen_w[0] = 1600; env->screen_h[0] = 900; if (!(env->res[2] = ft_strdup("2560 x 1440"))) return (ft_perror("Could not malloc screen size 0")); if (!(env->res[1] = ft_strdup("1920 x 1080"))) return (ft_perror("Could not malloc screen size 1")); if (!(env->res[0] = ft_strdup("1600 x 900"))) return (ft_perror("Could not malloc screen size 2")); set_screen_size(env); return (0); } void set_screen_size(t_env *env) { env->w = env->screen_w[env->i]; env->h = env->screen_h[env->i]; env->h_w = env->w / 2; env->h_h = env->h / 2; }
C
#ifdef __linux #define _BSD_SOURCE #define _GNU_SOURCE #define _XOPEN_SOURCE 700 #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> int main(int argc, char const *argv[]) { // psignal psignal(SIGKILL, "SIGKILL"); psignal(SIGINT, "SIGINT"); psignal(SIGQUIT, "SIGQUIT"); printf("\n"); // strsignal printf("SIGKILL: %s\n", strsignal(SIGKILL)); printf("SIGINT: %s\n", strsignal(SIGINT)); printf("SIGQUIT: %s\n", strsignal(SIGQUIT)); return 0; }
C
#include "queue.h" void QInit(struct Queue* q, int size){ q->size = size; q->queueIn = q->queueOut = 0; //q->elems = (int*)malloc(size*sizeof(int)); } int QPut(struct Queue* q, int e){ if(q->queueIn == ((q->queueOut -1 + q->size) % q->size)){ return -1; //Queue full } q->elems[q->queueIn] = e; q->queueIn = (q->queueIn + 1) % q->size; return 0; } int QGet(struct Queue* q){ int e = q->elems[q->queueOut]; q->queueOut = (q->queueOut + 1) % q->size; return e; } void QDel(struct Queue* q){ //free(q->elems); } int QEmpty(struct Queue* q){ if(q->queueIn == q->queueOut) return 1; return 0; }
C
#include <stdio.h> #include <stdlib.h> // A linked list (LL) node to store a queue ent struct QNode { int key; int active; int ts; struct QNode* next; }; // The queue, front stores the front node of LL and rear stores the // last node of LL struct Queue { struct QNode *front, *rear; }; struct QNode* newNode(int k, int active, int ts); struct Queue* createQueue(); void enQueue(struct Queue* q, int k, int active, int ts);
C
#include <stdio.h> int ft_fibonacci(int index) { int answer; if (index < 0) return (-1); if (index <= 1) return (index); answer = ft_fibonacci(index - 1) + ft_fibonacci(index - 2); return (answer); } int main() { printf("%d", ft_fibonacci(7)); printf("%d", ft_fibonacci(2)); printf("%d", ft_fibonacci(1)); printf("%d", ft_fibonacci(0)); printf("%d", ft_fibonacci(-2)); return (0); }
C
#include<stdio.h> #include<stdlib.h> #include<math.h> #define input_Len 41 #define IIR_filter_Len 7 static double IIR_coeff_B[IIR_filter_Len] = {0.007585113,0.04551068,0.1137767,0.1517022,0.1137767,0.04551068,0.007585113}; static double IIR_coeff_A[IIR_filter_Len] = {1,-1.485052,1.603616,-0.9240610,0.3592332,-0.07561177,0.007322802}; void IIR_filter_floatPoint(const double *b, const double *a, size_t filterLength, const double *in, double *out, size_t length) { const double a0 = a[0]; const double *a_end = &a[filterLength-1]; const double *out_start = out; a++; out--; size_t m; for (m = 0; m < length; m++) { const double *b_macc = b; const double *in_macc = in; const double *a_macc = a; const double *out_macc = out; double b_tmp = (*in_macc--) * (*b_macc++); double a_tmp = 0; while (a_macc <= a_end && out_macc >= out_start) { b_tmp += (*in_macc--) * (*b_macc++); a_tmp += (*out_macc--) * (*a_macc++); } *++out = (b_tmp - a_tmp) / a0; in++; } } int main(){ double *sig = calloc(input_Len,sizeof(double)); double *IIR_sig = calloc(input_Len,sizeof(double)); printf("\n ------ input-----\n"); for (uint16_t k=0;k<input_Len;k++){ sig[k]=0.7*sin(0.15*M_PI*k)+0.1*sin(0.95*M_PI*k)+0.2*sin(0.77*M_PI*k); printf("sig[%d]=%f\n",k,*(sig+k)); //printf("%f\n",*(sig+k)); } IIR_filter_floatPoint(IIR_coeff_B, IIR_coeff_A, IIR_filter_Len, sig, IIR_sig, input_Len); printf("\n ------ IIR output-----\n"); for (uint16_t k;k<input_Len;k++){ printf("IIR_sig[%d]=%f\n",k,*(IIR_sig+k)); //printf("%f\n",*(IIR_sig+k)); } printf("sizeof(size_t)= %d\n",sizeof(size_t)); printf("sizeof(unsigned long)= %d\n",sizeof(unsigned long)); printf("sizeof(unsigned)= %d\n",sizeof(unsigned)); printf("sizeof(unsigned short)= %d\n",sizeof(unsigned short)); // size_t is an unsigned type. So, it cannot represent any negative values(<0). // You use it when you are counting something, and are sure that it cannot be negative. // For example, strlen() returns a size_t because the length of a string has to be at least 0. return 0 ; }
C
#ifndef __DLIST_H__ #define __DLIST_H__ #include <stdlib.h> #include <stddef.h> #include <stdio.h> #include <string.h> typedef struct _DNodo { void *dato; struct _DNodo *ant; struct _DNodo *sig; } DNodo; typedef struct { DNodo *primero; DNodo *ultimo; char *nombre; } DList; typedef void (*FuncionVisitar)(void *dato); typedef int (*FuncionComparar)(void *dato1, void *dato2); typedef int (*FuncionIguales)(void *dato1, void *dato2); // Devuelve una lista vacía. DList *dlist_crear(char *nombre); // Destruccion de la lista. void dlist_destruir(void *lista); // Agrega un elemento al final de la lista. void dlist_insertar_final(DList * lista, void *dato); // Imprime en pantalla el contenido de los nodos, segun la funcion dada. void dlist_imprimir(DList * lista, FuncionVisitar imprimir); // Dado el primer nodo de la lista, devuelve el nodo de la mitad de la lista, // y corta su ruta al anterior, dividiendo la lista en 2 partes. DNodo *dividir_lista(DNodo * primero); // Dado el primer nodo de la lista y el primer nodo de otra lista, // une las dos listas ordenadamente y devuelve el primer nodo de esta. DNodo *merge(DNodo * primero, DNodo * segundo, FuncionComparar comparar); // Dado el primer nodo de la lista, la ordena recursivamente y // devuelve el primer nodo de esta lista ordenada. DNodo *merge_sort(DNodo * primero, FuncionComparar comparar); // Dadas una dlist y una funcion de comparacion, // devuelve una dlist ordenada por merge sort y elimina los intervalos repetidos. void dlist_merge_sort(DList * lista, FuncionComparar comparar, FuncionIguales iguales); #endif /* __DLIST_H__ */
C
/* ** draw_map.c for draw_map in /home/danilo_d/rendu/MUL_2014_wolf3d ** ** Made by Danilov Dimitri ** Login <danilo_d@epitech.net> ** ** Started on Sat Dec 20 14:54:34 2014 Danilov Dimitri ** Last update Fri Dec 26 23:05:08 2014 Danilov Dimitri */ #include "my.h" void draw_map(t_tools *tool) { int i; int j; int coord_x; int coord_y; i = 0; coord_x = (HEIGHT / 2) + (HEIGHT / 4); while (i != tool->size_y) { j = 0; coord_y = 25; while (j != tool->size_y) { if (tool->tab[i][j] == 2) put_square(tool, coord_x, coord_y, 2); else if (tool->tab[i][j] == 0) put_square(tool, coord_x, coord_y, 0); else if (tool->tab[i][j] == 1) put_square(tool, coord_x, coord_y, 1); j++; coord_y += (HEIGHT / tool->size_y) / 4; } coord_x += HEIGHT / tool->size_y / 4; i++; } } void put_square(t_tools *tool, int coord_x, int coord_y, int flag) { int i; int j; int tmp; tmp = coord_y; i = 0; j = 0; while (j != HEIGHT / tool->size_y / 4) { i = 0; coord_y = tmp; while (i != HEIGHT / tool->size_y / 4) { if (flag == 0) put_white_pixel(tool, coord_y, coord_x); if (flag == 1) put_blue_pixel(tool, coord_y, coord_x); if (flag == 2) put_red_pixel(tool, coord_y, coord_x); coord_y++; i++; } j++; coord_x++; } }
C
#include "defs.h" int CheckResult(KASPAROV_BOARD *pos, char** msg) { ASSERT(CheckBoard(pos)); if (pos->fiftyMove >= 100) { *msg = "FIFTY MOVE DRAW"; // "50MV" return TRUE; } if (ThreeFoldRep(pos) >= 3) { *msg = "3-FOLD REPITITION DRAW"; // "3FLD" return TRUE; } if (DrawMaterial(pos) == TRUE) { *msg = "INSUFFICIENT MATERIAL DRAW"; // "MATD" return TRUE; } S_MOVELIST list[1]; GenerateAllMoves(pos, list); int found = 0; for (int MoveNum = 0; MoveNum < list->count; ++MoveNum) { if (!MakeMove(pos, list->moves[MoveNum].move)) { continue; } found++; TakeMove(pos); break; } if (found != 0) { *msg = "OK"; // "OK00" return FALSE; } int InCheck = SqAttacked(pos->KingSq[pos->side], pos->side ^ 1, pos); if (InCheck == TRUE) { if (pos->side == WHITE) { *msg = "BLACK MATES"; //"BLKM" return TRUE; } else { *msg = "WHITE MATES"; //"WHTM" return TRUE; } } else { *msg = "STALEMATE DRAW"; //"STLM" return TRUE; } } char* Game_Loop(KASPAROV_BOARD* pos, SEARCH_INFO* info) { setbuf(stdin, NULL); setbuf(stdout, NULL); int depth = MAXDEPTH, movetime = 5000; int engine = 0; int move; char* msg = ""; char inBuf[80], command[80]; ParseFen(START_FEN, pos); while (TRUE) { fflush(stdout); // Agent consultation requested! if (engine == 1) { if (CheckResult(pos, &msg) == FALSE) { info->starttime = GetTimeMs(); info->depth = depth; if (movetime != 0) { info->timeset = TRUE; info->stoptime = info->starttime + movetime; } printf("%s %s\n", SearchPosition(pos, info), msg); } else { return msg; } engine = 0; } PrintBoard(pos); printf("\nEnter > "); // Allocate space for user input and wait for it! fflush(stdout); memset(&inBuf[0], 0, sizeof(inBuf)); fflush(stdout); if (!fgets(inBuf, 80, stdin)) continue; sscanf(inBuf, "%s", command); if (!strcmp(command, "consult")) { engine = 1; continue; } if (!strcmp(command, "setboard")) { ParseFen(inBuf + 9, pos); continue; } if (!strcmp(command, "quit")) { info->quit = TRUE; break; } move = ParseMove(inBuf, pos); if (move == NOMOVE) { printf("Command unknown or illegal move: %s\n", inBuf); continue; } MakeMove(pos, move); pos->ply = 0; } return "USER ENDED GAME"; }
C
#include "minishell.h" int authorized_char(int c) { return (ft_isalnum(c) || c == '_'); } int is_special_char(int c) { return (c == '=' || c == '+' || c == ':' || c == ',' || c == '%' || c == '.' || c == '/' || c == ']' || c == '^' || c == '~' || c == '[' || c == '(' || c == ')' || c == '`' || c == '{' || c == '}'); } int is_symbol(int c) { return (c == '>' || c == '<' || c == ' ' || c == '\'' || c == '\"'); } int is_symbol_doll(int c) { return (c == '>' || c == '<' || c == ' ' || c == '\'' || c == '\"' || c == '$'); } int is_symbol_v2(int c) { return (c == '>' || c == '<' || c == ' '); }
C
/* version 4 of z = x + y same as version 3 but adds support for real numbers */ #include <stdio.h> int main() { float x, y, z; // read input scanf("%f %f",&x,&y); // compute addition z = x + y; // print result printf("result of %f + %f = %f\n", x, y, z); }
C
#include "matrice_lineaire.h" #include <stdlib.h> matrice allouer_matrice(int l, int c) { matrice m; /* A vous de jouer */ return m; } void liberer_matrice(matrice m) { /* A vous de jouer */ } int est_matrice_invalide(matrice m) { int resultat; /* A vous de jouer */ return resultat; } double *acces_matrice(matrice m, int i, int j) { double *resultat; /* A vous de jouer */ return resultat; } int nb_lignes_matrice(matrice m) { int resultat; /* A vous de jouer */ return resultat; } int nb_colonnes_matrice(matrice m) { int resultat; /* A vous de jouer */ return resultat; }
C
#include "../multilib.h" #include "../common.h" #include "../w_x.h" #define num 1024 #define top (1 << 31) //this is to verify all the inversing functions for w = 4 8 16 32 and 64; int main(int argc, char *argv[]) { unsigned int x, ans, i; unsigned char *c; int w = (1 << 8); uint64_t *y, yy; c = (unsigned char *) malloc (sizeof(unsigned char) * num); srand((unsigned) time(0)); for(i = 0; i < num; ++i) { x = rand() % top; ans = gf_inverse_w32(x); if(i < 10) { printf("x = %d, ans = %d, gf_inv = %d\n", x, ans, gf_inverse_w32(ans)); } if(x != gf_inverse_w32(ans)) { printf("failed testing gf_inverse_w8() with i = %d: %d != %d\n", i, x, gf_inverse_w32(ans)); exit(1); } } printf("testing w16 inverse BINGO!\n"); for(i = 0; i < num; ++i) { c[i] = rand() % w; } y = (uint64_t *) c; for(i = 0; i < num / 8; ++i) { yy = gf_shift_inverse_64(y[i]); if(y[i] != gf_shift_inverse_64(yy)) { printf("failed testing w = 64 with i = %d: %lu != %lu\n", i, y[i], gf_shift_inverse_64(yy)); exit(1); } } printf("testing w64 inverse BINGO!\n"); return 0; }
C
#include <stdio.h> typedef struct { float center[3]; float radius; } Sphere; typedef struct { char name[100]; float salary; } Employee; int getAge(); void solve(); Sphere makeSphere(float *c, float r); int main() { float centerVar[] = {1.0, 2.0, 3.0, 4.0}; float radiusVar = 9.0; Sphere ball = makeSphere(centerVar, radiusVar); printf("Ball: (x, y, z) = (%f, %f, %f); c = %f\n", ball.center[0], ball.center[1], ball.center[2], ball.radius); char* letter; char f = 'k'; letter = &f; printf("%c is always the same as %c\n", f, *letter); f = 'q'; printf("%c is always the same as %c\n", f, *letter); f = 't'; printf("%c is always the same as %c\n", f, *letter); char eldridge[] = "eldridge"; letter = &eldridge[0]; printf("%c is in %s\n", *letter, eldridge); ++letter; printf("%c is in %s\n", *letter, eldridge); ++letter; printf("%c is in %s\n", *letter, eldridge); ++letter; printf("%c is in %s\n", *letter, eldridge); ++letter; printf("%c is in %s\n", *letter, eldridge); ++letter; printf("%c is in %s\n", *letter, eldridge); ++letter; printf("%c is in %s\n", *letter, eldridge); ++letter; printf("%c is in %s\n", *letter, eldridge); float numbers[3] = {3.14156, 1.6180, 1.4142}; printf("%ld\n", sizeof(numbers)/sizeof(float)); int a = 9, b = 9; int c = ++a; int d = b++; printf("a %d c %d d %d\n", a, c, d); // insert code here... printf("Hi, tell me your name: "); char name[100]; scanf("%s", name); printf("Well done %s, tell me your age: ", name); int age = getAge(); printf("Dr. %s, you have %d years old.\n", name, age); printf("%f\n", numbers[0]); printf("%f\n", numbers[1]); printf("%f\n", numbers[2]); int i = 0; for(; i < 10; i++) printf("Hello Motherfucker\n"); solve(); return 0; } int getAge() { int age; scanf("%d", &age); return age; } void solve() { int n; scanf("%d", &n); int i = 0, flag = 0, sum = 0; for(; i < n; i++) { scanf("%d", &flag); sum += flag; } printf("%d\n", sum); } Sphere makeSphere(float *c, float r) { Sphere ans; ans.center[0] = c[0]; ans.center[1] = c[1]; ans.center[2] = c[2]; ans.radius = r; return ans; }
C
#include "binarySearch.h" int binarySearchRecurrsive(int *arr, int val, int lIdx, int rIdx) { if(lIdx > rIdx) { return INT_MIN; } //int mid = lIdx+((lIdx+rIdx)/2); int mid = ((lIdx+rIdx)/2); if(arr[mid] == val) { return mid; } else if(arr[mid] < val) { return binarySearchRecurrsive(arr,val,mid+1,rIdx); } else { return binarySearchRecurrsive(arr,val,lIdx,mid-1); } } int binarySearchIterative(int *arr, int val, int lIdx, int rIdx) { int mid; while(lIdx <= rIdx) { mid = (lIdx + rIdx)/2; if(arr[mid] == val) { return mid; } else if(arr[mid] < val) { lIdx = mid+1; rIdx = rIdx; } else { lIdx = lIdx; rIdx = mid-1; } } return INT_MIN; }
C
#include <stdio.h> void ft_is_negative(int n) { if (n >= 0) putchar('P'); else putchar('N'); } int main(int n) { ft_is_negative(56); return(0); }
C
#include "lib.h" void fillArrayIn(int* arrIn) { srand(time(0)); for (int i = 0; i < N; i++) { *(arrIn + i) = rand() % 6; } } bool checker(int* arr, int currentIndex, int value) { bool flag = false; for (int i = 0; i < currentIndex; i++) { if (*(arr + i) == value) { flag = true; } } return flag; } int countDuplicatingElements(int* arr, int len) { int count = 0; int lenTemp = len / 2; int k = 0; int* arrTemp = (int*)malloc(lenTemp * sizeof(int)); for (int i = 0; i < len; i++) { int value = *(arr + i); bool check = checker(arrTemp, k, value); for (int j = i + 1; j < len; j++) { if ((*(arr + j) == value) && (check == false)) { *(arrTemp + k) = value; count++; k++; break; } } } return count; } void writeDupElToResult(int* arrIn, int lenIn, int* arrOut, int lenOut) { int k = 0; for (int i = 0; i < lenIn; i++) { int value = *(arrIn + i); bool check = checker(arrOut, k, value); for (int j = i + 1; j < lenIn; j++) { if ((*(arrIn + j) == value) && (check == false)) { *(arrOut + k) = value; k += 2; break; } } } } void writeCountsToResult(int* arrIn, int lenIn, int* arrOut, int lenOut) { for (int i = 0; i < lenOut; i += 2) { int count = 0; for (int j = 0; j < lenIn; j++) { if (*(arrOut + i) == *(arrIn + j)) { count++; *(arrOut + i + 1) = count; } } } }
C
#include<stdio.h> int main(void) { //Vetores são variaveis compostas unidimensionais, em uma unica variavel podemos armazenar //diversos dados mas estes dados devem ser do mesmo tipo //Para declarar um vetor usamos int num[4]; //este vetor tem 4 elementos //para atribuir valores manualmente(vetores começam com indice 0) num[0] = 2; num[1] = 4; num[2] = 5; num[3] = 8; //este é o ultimo elemento //Só podemos mostrar um elemento por vez printf("%d ",num[0]); printf("%d ",num[1]); printf("%d ",num[2]); printf("%d \n",num[3]); printf("Estrutura de controle \n"); //Para percorrer estes valores de forma mais simples podemos usar uma estrututa de controle for(int i = 0; i < 4; i++) { //o indice começa em 0 e vai até 3 neste vetor printf("%d ",num[i]); } printf("\nEncerando..."); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "freelist.h" static int POINTERS_PER_BLOCK; void init_free_list(block_id head, block_count blocks) { if (blocks <= 0) { printf("Block count must be positive\n"); return; } POINTERS_PER_BLOCK = BLOCK_SIZE / sizeof(block_id); printf("\nBuilding Free List\n"); printf("======================\n"); block_id current = head, last = head + blocks - 1; block_id *pointers = malloc(BLOCK_SIZE); int i; while (current <= last) { for (i = POINTERS_PER_BLOCK - 1; i > 0; i--) { if (current == last) { break; } pointers[i] = last--; } if (current < last) { pointers[0] = current + 1; } else { while (i >= 0) { pointers[i--] = 0; } } for (i = 0; i < POINTERS_PER_BLOCK; i++) { printf("[Block %ld][%d] %ld\n", current, i, pointers[i]); } write_block(current, pointers, BLOCK_SIZE); current++; } free(pointers); } int check_free_list(block_id head, block_count blocks) { block_id current = head, count = 0; block_id *pointers = malloc(BLOCK_SIZE); while (TRUE) { read_block(current, pointers, BLOCK_SIZE); int i; for (i = 0; i < POINTERS_PER_BLOCK; i++) { if (pointers[i] > 0) { count++; } } if (pointers[0] > 0) { current = pointers[0]; } else { break; } } free(pointers); return blocks - count; } block_id allocate_block(block_id head) { block_id *pointers = malloc(BLOCK_SIZE); read_block(head, pointers, BLOCK_SIZE); int i; block_id allocation = 0; for (i = POINTERS_PER_BLOCK - 1; i > 0; i--) { if (pointers[i] > 0) { allocation = pointers[i]; pointers[i] = 0; write_block(head, pointers, BLOCK_SIZE); break; } } if (allocation == 0 && pointers[0] > 0) { allocation = pointers[0]; read_block(allocation, pointers, BLOCK_SIZE); write_block(head, pointers, BLOCK_SIZE); } free(pointers); return allocation; } void free_block(block_id head, block_id block) { if (block == 0) { printf("Invalid block address: 0\n"); return; } int done = 0; block_id *pointers = malloc(BLOCK_SIZE); read_block(head, pointers, BLOCK_SIZE); int i; for (i = 1; i < POINTERS_PER_BLOCK - 1; i++) { if (pointers[i] == 0) { pointers[i] = block; write_block(head, pointers, BLOCK_SIZE); done = 1; break; } } if (!done) { write_block(block, pointers, BLOCK_SIZE); pointers[0] = block; for (i = 1; i < POINTERS_PER_BLOCK - 1; i++) { pointers[i] = 0; } write_block(head, pointers, BLOCK_SIZE); } free(pointers); }
C
#include<stdio.h> void main() { printf("\nSkips the occurrence of numbers that are divisible by 7: \n\n"); for(int i=1;i<=100;i++) { if( i % 7 ==0 ) continue; printf("%d ",i); } printf("\n\n"); } /* Output : (base) mayuri@mayuri-PC:~/C2WT/Daily Flash/week 4/day 5/MySolutions/C$ cc Program3.c (base) mayuri@mayuri-PC:~/C2WT/Daily Flash/week 4/day 5/MySolutions/C$ ./a.out Skips the occurrence of numbers that are divisible by 7: 1 2 3 4 5 6 8 9 10 11 12 13 15 16 17 18 19 20 22 23 24 25 26 27 29 30 31 32 33 34 36 37 38 39 40 41 43 44 45 46 47 48 50 51 52 53 54 55 57 58 59 60 61 62 64 65 66 67 68 69 71 72 73 74 75 76 78 79 80 81 82 83 85 86 87 88 89 90 92 93 94 95 96 97 99 100 */
C
#include "header/collision_mng.h" void collision_mng_init(collision_mng* collision_mng) { collision_mng->colliders_list = dynarray_init(sizeof(collider_t*)); } void collision_mng_tick(collision_mng* collision_mng) { size_t num_colliders = dynarray_length(collision_mng->colliders_list); for (size_t i = 0; i < num_colliders; i++) { collider_t** first_collider = dynarray_get(collision_mng->colliders_list, i); for (size_t j = i+1 ; j < num_colliders; j++) { collider_t** second_collider = dynarray_get(collision_mng->colliders_list, j); if(SDL_HasIntersection(&(*first_collider)->rect, &(*second_collider)->rect)) { (*first_collider)->on_collision_ptr(*first_collider, *second_collider); (*second_collider)->on_collision_ptr(*second_collider, *first_collider); } } } } void collision_mng_add_collider(collision_mng* collision_mng, collider_t* collider) { collider_t** collider_ptr = dynarray_append(collision_mng->colliders_list); *collider_ptr = collider; collider_t* first_collider = dynarray_get(collision_mng->colliders_list, 0); }
C
#include <inttypes.h> #include <stdbool.h> #include "../../include/movement_manager.h" #include "../../include/range_sensors.h" #include "../../include/unused_param.h" #include "../../include/leds.h" #include "../../include/switch_direction.h" static uint8_t max = 0; static sensor_t max_sensor = R_SENSOR; static const int NOISE_THRESHOLD = 75; // Determined experimentally to work static void update_readings_running_avg(){ sensor_t sensor = 0; max = 0; for(sensor = 0; sensor < N_SENSORS; ++sensor){ uint16_t val = range_sensors_sensor_readings[sensor]; if(val > max){ max = val; max_sensor = sensor; } } } void handle_range_sensors(bool indicate){ update_readings_running_avg(); if(max > NOISE_THRESHOLD){ if(max_sensor == BR_SENSOR || max_sensor == BL_SENSOR){ // If it's at the back, switch directions and go towards it! movman_schedule_move(SWITCH_DIRECTION_THEN_MOVE_FORWARD, TO_SEEK, IMMEDIATELY_WITH_OVERWRITE); if(indicate){ led_toggle_orange(); } }else if(max_sensor == L_SENSOR){ if(current_front_is_good_front){ movman_schedule_move(ROTATE_90_LEFT_THEN_MOVE_FORWARD, TO_SEEK, IMMEDIATELY_WITH_OVERWRITE); }else{ movman_schedule_move(ROTATE_90_RIGHT_THEN_MOVE_FORWARD, TO_SEEK, IMMEDIATELY_WITH_OVERWRITE); } if(indicate){ led_toggle_white(); } }else if(max_sensor == R_SENSOR){ if(current_front_is_good_front){ movman_schedule_move(ROTATE_90_RIGHT_THEN_MOVE_FORWARD, TO_SEEK, IMMEDIATELY_WITH_OVERWRITE); }else{ movman_schedule_move(ROTATE_90_LEFT_THEN_MOVE_FORWARD, TO_SEEK, IMMEDIATELY_WITH_OVERWRITE); } if(indicate){ led_toggle_white(); } }else{ // If it's at the front, move towards it! // // We're not going to try to do any curving moves to align ourselves, we're just gonna go // all out. If we attack and miss, we still catch them on the side... movman_schedule_move(SMALL_MOVE_FORWARD, TO_SEEK, IMMEDIATELY_WITH_OVERWRITE); } } } static uint16_t left_accumulate = 0; static uint16_t right_accumulate = 0; void handle_range_sensors_accumulate(){ update_readings_running_avg(); left_accumulate += range_sensors_sensor_readings[L_SENSOR]; right_accumulate += range_sensors_sensor_readings[R_SENSOR]; } void handle_range_sensors_react_accumulate(){ if(left_accumulate > right_accumulate){ movman_schedule_move(ROTATE_90_LEFT_THEN_MOVE_FORWARD, TO_SEEK, IMMEDIATELY_WITH_OVERWRITE); }else{ movman_schedule_move(ROTATE_90_RIGHT_THEN_MOVE_FORWARD, TO_SEEK, IMMEDIATELY_WITH_OVERWRITE); } }
C
#include "my_lib.h" char * print_n_symb_in_line(char * line, int n) { int i; int len = strlen(line); int * have_space = (int *) malloc(len * sizeof(int)); for (i = 0; i < len; ++i) { if (line[i] == ' ' || line[i] == '\t') { have_space[i] = i; } else { have_space[i] = (i > 0) ? have_space[i - 1] : -1; } } char * result = (char * ) malloc(len * 3 + 1); int sz_result = 0; for (i = 0; i < len; ++i) { if(i + n >= len) { result[sz_result++] = line[i]; } else { int last; int j = i; if(have_space[i + n] < i) { last = i + n; i = i + n-1; } else { last = have_space[i+n]; i = have_space[i+n]; } for (; j < last; ++j) result[sz_result++] = line[j]; result[sz_result++] = '\n'; } } result = (char*)realloc(result, sz_result + 1); result[sz_result] = '\0'; return result; }
C
/** ** code.h ... P コードの 読み込み・生成・格納 **/ #ifndef _CODE_H_INCLUDED_ #define _CODE_H_INCLUDED_ /*----- 公開するデータ型 -----*/ struct Instruction { int type; int arg1; int arg2; }; typedef struct Instruction Instruction; /*----- 公開する定数 -----*/ enum InstructionType { ERR = -1, /* エラー処理用 */ LDC, LOD, LDA, ILD, STR, ISR, AOP, COP, WLN, RLN, STP, UJP, FJP, XST, MST, CAL, RET }; enum { UNKNOWN_ADDRESS = -1 }; /*----- 公開する関数 -----*/ int get_code_address(void); /* 格納中の最後の命令の番地を返す */ int append_instruction(int type, int arg1, int arg2); /* 命令 (type, arg1, arg2) を最後に追加し * エラーの有無を SUCCESS/FAILURE で返す */ int rewrite_instruction(int code_addr, int jump_addr); /* code_addr 番地に格納中の命令 (type, arg1, arg2) の arg2 を jump_addr に変え * エラーの有無を SUCCESS/FAILURE で返す */ Instruction *get_instruction(int addr); /* addr 番地に格納中の命令へのポインタを返す(無効な番地なら NULL を返す) */ void print_address(int addr); /* 番地 addr を表示 */ void print_instruction(const Instruction *insp); /* 命令 *insp を表示 */ void print_code(int visible_addr); /* 格納中の命令列を表示 * visible_addr が TRUE なら番地も表示 */ void read_code_or_exit(void); /* 使用中のファイルを読んで命令列を格納 * エラーがあれば強制終了 */ #endif /* _CODE_H_INCLUDED_ */