language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include "initiator.h"
void printList(ContentServerList** head)
{
// print the Content Server List (created by -s argument)
printf("===ContentServerList===\n");
ContentServerList* temp = *head;
while(temp!=NULL)
{
printf("[*] %s\n",temp->cs);
temp = temp->next;
}
printf("===End Of List===\n");
}
void decode_statistics(char* buff){
// decodes and prints the statistics
char* ip = strtok(buff,",");
char* port = strtok(NULL,",");
char* files = strtok(NULL,",");
char* bytes = strtok(NULL,",");
int connected = atoi(strtok(NULL,","));
if(connected)
{
printf("[*][Content Server %s:%s] files: %s bytes: %s \n",ip,port,files,bytes);
}
else
{
printf("[*][Content Server %s:%s] Couldn't Establish Connection \n",ip,port);
}
}
|
C
|
/*
* Copyright Ville Valkonen 2010 - 2016.
* Partly borroved from here:
* http://stackoverflow.com/questions/1636333/download-file-using-libcurl-in-c-c
* http://curl.haxx.se/libcurl/c/progressfunc.html
*/
#include <curl/curl.h>
#include <curl/easy.h>
#include <err.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "netfetch.h"
struct progress {
double lastrun;
CURL *curl;
};
int
netfetch(const char *fname)
{
FILE *fp;
CURL *curl;
CURLcode res = 0;
struct progress prog;
if ((curl = curl_easy_init()) == NULL) {
fprintf(stderr, "CURL initialization failed\n");
return 1;
}
if (strlen(fname) >= FILENAME_MAX) {
fprintf(stderr, "File name too long\n");
return 10;
}
prog.lastrun = 0;
prog.curl = curl;
fp = fopen(fname, "wb");
curl_easy_setopt(curl, CURLOPT_URL, URL);
curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &prog);
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
res = curl_easy_perform(curl);
if (res)
fprintf(stderr, "%s\n", curl_easy_strerror(res));
curl_easy_cleanup(curl);
if (fp)
fclose(fp);
return (int) res;
}
size_t
write_data(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
size_t written = 0;
written = fwrite(ptr, size, nmemb, stream);
return written;
}
int
progress(void *p, double dltotal, double dlnow, double ultotal, double ulnow)
{
double curtime = 0;
struct progress *prog;
CURL *curl;
prog = (struct progress *) p;
curl = prog->curl;
curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &curtime);
if ((curtime - prog->lastrun) >= MINPROGRESSTIME) {
prog->lastrun = curtime;
fprintf(stderr, "TOTALTIME: %f\r\n", curtime);
}
fprintf(stderr, "%.1f kiB / %.1f kiB [%.1f%%]\r",
dlnow / 1024, dltotal / 1024, PERCENTAGE(dlnow, dltotal));
fflush(stderr);
return 0;
}
|
C
|
/**
* Created by Pieter De Clercq.
*
* Project: huffman
*/
#ifndef HUFFMAN_IO_INPUT_BIT_INPUTSTREAM_H
#define HUFFMAN_IO_INPUT_BIT_INPUTSTREAM_H
#include "byte_input_stream.h"
/**
* An input stream for bits.
*/
struct bit_input_stream;
/**
* A function that reads a byte
*/
typedef byte (*_bit_input_feed_byte_function)(struct byte_input_stream *);
/**
* An input stream for bits.
*/
typedef struct bit_input_stream {
byte_input_stream *stream;
byte current_byte;
size_t current_cursor;
_bit_input_feed_byte_function feedFn;
} bit_input_stream;
/**
* Gets the amount of bits left in the current byte.
*
* @param bis
* @return
*/
#define bis_bits_left(bis) (BITS_IN_BYTE - (bis)->current_cursor)
/**
* Clears the current byte.
*
* @param bis the input stream
*/
void bis_clear_current_byte(bit_input_stream *bis);
/**
* Creates a new byte input stream.
*
* @param channel the encapsulated stream to feed off
* @param retain false to clear the buffer when full, true to expand it
* @return the created byte input stream
*/
bit_input_stream *bis_create(FILE *channel, bool retain);
/**
* Clears the entire input stream.
*
* @param bis the bit input stream
*/
void bis_flush(bit_input_stream *bis);
/**
* Frees the memory allocated by the bit input stream.
*
* @param bis the bit input stream
*/
void bis_free(bit_input_stream *bis);
/**
* Returns n bits from the buffer. Does not remove those bits from the buffer.
*
* @param bis the bit input stream
* @param n the amount of bits to retrieve
* @return n bits from the buffer
*/
#define bis_get_n_bits(bis, n) ((uint_fast8_t) ((bis)->current_byte << (bis)->current_cursor) >> (BITS_IN_BYTE-(n)))
/**
* Reads one bit from the bit input stream
*
* @param bis the bit input stream
* @return the bit
*/
bit bis_read_bit(bit_input_stream *bis);
/**
* Reads one byte from the bit input stream
*
* @param bis the bit input stream
* @return the byte
*/
byte bis_read_byte(bit_input_stream *bis);
/**
* Rewinds the internal cursor by n bits, cannot retrieve lost bytes.
*
* @param bis the bit input stream
* @param n the amount of bits to rewind
*/
#define bis_rewind(bis, n) ((bis)->current_cursor -= (n))
#endif /* HUFFMAN_IO_INPUT_BIT_INPUTSTREAM_H */
|
C
|
/*
* Filename: tavernAction.c
* Author: Charles Li
* Description: Prompts the player for their choice of action while in a tavern
* Date: Jun 30 2017
*/
#include "proj.h"
#include "projStrings.h"
void tavernAction( struct Player* player, struct InnKeep* keep ) {
long choice = 0;
char yesNo = 0;
while(1) {
char* drinkName;
printf(keep->actionPrompt);
printf(TAVERN_ACTIONS_STR);
choice = readInLong();
if(choice != ROOM && choice != DRINK && choice != RUMORS && choice != EXIT) { //if not one of 4 valid choices
printf(keep->invalidMsg); //print invalid message and reprompt
continue;
}
switch(choice) { //valid choice, switch depending on choice
case ROOM:
while(1) {
printf(keep->pricePrompt, ROOM_NAME, keep->roomPrice);
yesNo = readYesNo();
if(yesNo == 1) { //yes, wants room
if(player->money >= keep->roomPrice) { //enough money
player->money -= keep->roomPrice; //pay price
printf("* %i vaz remaining *", player->money);
printf(keep->roomConfirm); //print confirmation message
tavernSleep(player); //restore health and print message
}
else { //insufficient funds
printf(keep->insuffFunds);
break; //no need to reprompt room, loop back to reprompt action
}
}
else if(yesNo == 0) { //no, doesn't want room
break; //loop back to reprompt action
}
else { //invalid input, reprompt room
printf(keep->invalidMsg);
}
}
break; //room actions done, break from switch, reprompt for action choice
case DRINK:
while(1) { //allow player to continue drinking after first drink
printf(keep->drinkPrompt); //prompt for drink choice
printf(DRINKS_STR);
choice = readInLong;
if(choice == VIT || choice == STR || choice == FRT || choice == AGI) {
/* Save drink name according to selection */
if(choice == VIT) {
drinkName = VIT_BREW;
}
else if(choice == STR) {
drinkName = STR_BREW;
}
else if(choice == FRT) {
drinkName = FRT_BREW;
}
else if(choice == AGI) {
drinkName = AGI_BREW;
}
/* Prompt the player for money and check for funds */
printf(keep->pricePrompt, drinkName, keep->brewPrice);
yesNo = readYesNo();
if(yesNo == 1) { //yes, want the drink
if(player->money >= keep->brewPrice) { //enough money
player->money -= keep->brewPrice;
printf("* %i vaz remaining *", player->money);
printf(keep->drinkConfirm, drinkName); //print confirm message
/* Increase corresponding stat */
if(choice == VIT) {
player->maxHealth++;
player->currHealth++;
printf("\n* Vitality increased *\n");
}
else if(choice == STR) {
player->baseAtk++;
printf("\n* Strength increased *\n");
}
else if(choice == FRT) {
player->baseDef++;
printf("\n* Fortitude increased *\n");
}
else if(choice == AGI) {
player->baseSpd++;
printf("\n* Agility increased *\n");
}
}
else { //insufficient funds
printf(keep->insuffFunds);
break; //no need to keep prompting if no money
}
}
else { //don't want the drink or invalid input
continue; //reprompt for drink choice
}
}
else if(choice == DONE) { //no more drinks, break out of loop
break; //loop back for action choice
}
else { //invalid input, reprompt drink choice
printf(keep->invalidMsg);
}
}
break; //drink actions done, break from switch, reprompt for action choice
case RUMORS:
printf(keep->rumors);
break; //break from switch, reprompt for action choice
case EXIT:
printf(keep->exitMsg);
return;
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#define TAM 10
#define MAX 20
char ****associar3(int x, int y, int z, int w){
char ****p; //Matriz que recebe os Calloc
int i,j,k; //variveis da matriz
//aloca as linhas da matriz
p=(char****)calloc(x,sizeof(char***));
if (p==NULL){
printf("MEMRIA INSUFICIENTE!!!");
return(NULL);
}
//aloca colunas da matriz
for (i=0;i<x;i++){
p[i]=(char***)calloc(y,sizeof(char**));
if(p[i]==NULL){
printf("MEMRIA INSUFICIENTE!!!");
getche();
return(0);
}
}
//aloca a profundidade da matriz
for (i=0;i<x;i++){
for (j=0;j<y;j++){
p[i][j]=(char**)calloc(z,sizeof(char*));
if(p[i][j]==NULL){
printf("MEMRIA INSUFICIENTE!!!");
getche();
return(0);
}
}
}
for (i=0;i<x;i++){
for (j=0;j<y;j++){
for (k=0;k<z;k++){
p[i][j][k]=(char*)calloc((21),sizeof(char));
if(p[i][j][k]==NULL){
printf("MEMRIA INSUFICIENTE!!!");
getche();
return(0);
}
}
}
}
return(p);
}
int removestr (char*s, int p, int y){
int x, i, j;
x=strlen(s);
if (y==0) return(0);
if (!(p+y>x)){
for (i=p, j=p+y ; i<=x; i++, j++){
if (s[i]='\0')
break;
s[i]=s[j];
}
}
else s[p]='\0';
// Remove a string apartir do "j" da posio dcima de k
return(0);
}
void lernome(char*s){
printf("\ndigite uma palavra ( %d caracteres):\n", MAX);
scanf("%s", s);
s[MAX]='/0'; //assegura que termina aqui
}
void copiar (char****mat, char*m, int x, int y, int z, int w){
int i, j, k, l;
for (i=0;i<x;i++){
for (j=0;j<y;j++){
for (k=0;k<z;k++){
for (l=0;l<w;l++){
mat[i][j][k][l]=m[l];
}
}
}
}
}
// obrigado a deixar a funo Main embaixo das outras, pois a referncia de algumas
//variveis vem primeiro que a funo Main por conta do Calloc que aloca memria para
//a matriz [i][j][k][l]
int main(){
char s[MAX+1];
char****nomes;
int x, y, z, w, i, j, k, l;
nomes=associar3(TAM, TAM, TAM, MAX);
lernome (s);
// varivel "s" recebe nome que usurio digita
// Segue abaixo o lao para a matriz alocada receber a string
for (i=0;i<TAM;i++){
for (j=0;j<TAM;j++){
for (k=0;k<TAM;k++){
for (l=0;l<=MAX;l++){
nomes[i][j][k][l]=s[l];
}
}
}
}
printf("\nlala12");
for (i=0;i<TAM;i++){
for (j=0;j<TAM;j++){
for (k=0;k<TAM;k++){
removestr(nomes[i][j][k], k, j);
}
}
}
for (i=0;i<TAM;i++){
for (j=0;j<TAM;j++){
for (k=0;k<TAM;k++){
printf("\n %d %d %d %s", i, j, k, nomes[i][j][k]);
}
}
}
}
|
C
|
#include<stdio.h>
main()
{
int sum[200],i,test,input[200],output[200];
scanf("%d",&test);
for(i=0;i<test;i++)
{
scanf("%d",&input[i]);
sum[i]=summat(input[i]);
}
for(i=0;i<test;i++)
{
printf("%d\n",sum[i]);
}
}
int summat(int val)
{
int sum=0,r=0,div;
if(val%2==0)
{
div=1; r=1;
while(div<=(val/2))
{
r=val%div;
if(r==0)
{
sum+=div;
}
div++;
}
}
else
{
div=1; r=1;
while(div<(val/2))
{
r=val%div;
if(r==0)
{
sum+=div;
}
div+=2;
}
}
return sum;
}
|
C
|
/*
* Copyright (c) 2015 SINA Corporation, All Rights Reserved.
*
* stk_list.h: Yilong Zhao [email protected]
*
* simple tool kit: double list.
*/
#ifndef __STK_LIST_H
#define __STK_LIST_H
#include <stddef.h>
#if 0
#include <stdlib.h>
#endif
typedef struct stk_list_s stk_list_t;
struct stk_list_s {
struct stk_list_s *next;
struct stk_list_s *prev;
};
/* static define list */
#define STK_LIST_INIT(name) { &(name), &(name) }
#define STK_LIST_HEAD(name) \
stk_list_t name = STK_LIST_INIT(name)
static inline void stk_list_init(stk_list_t *list)
{
list->next = list;
list->prev = list;
}
static inline int stk_list_is_last(const stk_list_t *entry,
const stk_list_t *head)
{
return entry->prev == head;
}
static inline int stk_list_empty(const stk_list_t *head)
{
return head->next == head;
}
/* add a new entry between prev and next */
static inline void __list_add(stk_list_t *new,
stk_list_t *prev,
stk_list_t *next)
{
next->prev = new;
new->next = next;
new->prev = prev;
prev->next = new;
}
/* add a new entry after the specified head */
static inline void stk_list_add(stk_list_t *new, stk_list_t *head)
{
__list_add(new, head, head->next);
}
/* add a new entry at the end of the list */
static inline void stk_list_add_tail(stk_list_t *new, stk_list_t *head)
{
__list_add(new, head->prev, head);
}
static inline void __stk_list_del(stk_list_t *prev, stk_list_t *next)
{
prev->next = next;
next->prev = prev;
}
/* remove a entry from the list */
static inline void stk_list_del(stk_list_t *entry)
{
__stk_list_del(entry->prev, entry->next);
#if 0
entry->prev = NULL;
entry->next = NULL;
#endif
}
static inline stk_list_t *stk_list_pop(stk_list_t *head)
{
stk_list_t *entry = head->next;
stk_list_del(entry);
return entry;
}
#ifdef STK_DEBUG_OFFSET
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
#endif
/*
* stk_list_entry - get the struct for this entry
* @ptr: the &struct list_head pointer.
* @type: the type of the struct this is embedded in.
* @member: the name of the list_struct within the struct.
*/
#define stk_list_entry(ptr, type, member) \
((type *)( (unsigned char *)ptr - offsetof(type, member) ))
/*
* stk_list_pop_entry - get the struct for this entry
* @head: the head for your list.
* @type: the type of the struct this is embedded in.
* @member: the name of the list_struct within the struct.
*/
#define stk_list_pop_entry(head, type, member) \
({ \
type *entry; \
stk_list_t *ptr; \
if (stk_list_empty(head)) { \
entry = NULL; \
} else { \
ptr = stk_list_pop(head); \
entry = stk_list_entry(ptr, type, member); \
} \
entry; \
})
#define stk_list_first_entry(head, type, member) \
stk_list_entry((head)->next, type, member) \
#define stk_list_peek_head(head, type, member) \
({ \
type *entry; \
stk_list_t *ptr; \
if (stk_list_empty(head)) { \
entry = NULL; \
} else { \
ptr = (head)->next; \
entry = stk_list_entry(ptr, type, member); \
} \
entry; \
})
/*
* stk_list_for_each - iterate over a list
* @pos: the &struct list_head to use as a loop cursor.
* @head: the head for your list.
*/
#define stk_list_for_each(pos, head) \
for (pos = (head)->next; pos != (head); pos = pos->next)
/*
* stk_list_for_each_entry - iterate over list of given type
* @pos: the type * to use as a loop cursor.
* @head: the head for your list.
* @member: the name of the list_struct within the struct.
*/
#define stk_list_for_each_entry(pos, head, member) \
for (pos = stk_list_entry((head)->next, typeof(*pos), member); \
&(pos->member) != (head); \
pos = stk_list_entry(pos->member.next, typeof(*pos), member))
#endif /*__STK_LIST_H*/
|
C
|
/*
** EPITECH PROJECT, 2021
** B-CPP-300-MPL-3-1-CPPD03-cyril.grosjean
** File description:
** join
*/
#include "string.h"
void join_c(string_t *this, char delim, const char * const * tab)
{
char delimiter[1];
delimiter[0] = delim;
this->assign_c(this, tab[0]);
for (int i = 1; tab[i] != NULL; i += 1) {
this->append_c(this, delimiter);
this->append_c(this, tab[i]);
}
}
void join_s(string_t *this, char delim, const string_t * const * tab)
{
char delimiter[1];
delimiter[0] = delim;
this->assign_s(this, tab[0]);
for (int i = 1; tab[i] != NULL; i += 1) {
this->append_c(this, delimiter);
this->append_s(this, tab[i]);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "config.h"
int load_config(const char *path, struct cfg_info *cfg)
{
char *cfg_path = NULL;
int cfg_fd = 0;
char cfg_buf[1024];
FILE *cfg_file = NULL;
size_t len = 0;
ssize_t read_len = 0;
char *line = NULL;
char *vcfg = NULL;
// check config file path
if(path == NULL)
cfg_path = DEFAULT_CFG_PATH;
else
cfg_path = path;
if(cfg == NULL) {
fprintf(stderr, "exception. config info is null\n");
return -1;
}
cfg_file = fopen(cfg_path, "r");
if(cfg_file == NULL) {
perror("Failed to open config file");
return -1;
}
memset(cfg->host, '\0', sizeof(cfg->host));
memset(cfg->hosturl, '\0', sizeof(cfg->hosturl));
memset(cfg->hostparam, '\0', sizeof(cfg->hostparam));
cfg->port = 0;
while((read_len = getline(&line, &len, cfg_file)) != -1) {
if((vcfg =strchr(line, '#') == NULL)) {
//fprintf(stderr, "[debug] cfg_line: %s\n", line);
if((vcfg = strstr(line, "host=")) != NULL) {
strcpy(cfg->host, vcfg + strlen("host="));
}
else if((vcfg = strstr(line, "url=")) != NULL) {
strcpy(cfg->hosturl, vcfg + strlen("url="));
}
else if((vcfg = strstr(line, "param=")) != NULL) {
strcpy(cfg->hostparam, vcfg + strlen("param="));
}
else if((vcfg = strstr(line, "port=")) != NULL) {
cfg->port = atoi(vcfg + strlen("port="));
}
else if((vcfg = strstr(line, "length=")) != NULL) {
cfg->len = atoi(vcfg + strlen("length="));
}
else if((vcfg = strstr(line, "timestamp_format=")) != NULL) {
strcpy(cfg->timestamp_fmt, vcfg + strlen("timestamp_format="));
}
else if((vcfg = strstr(line, "interval=")) != NULL) {
cfg->str_int = atoi(vcfg + strlen("interval="));
}
else if((vcfg = strstr(line, "send_time=")) != NULL) {
cfg->send_int_time = atoi(vcfg + strlen("send_time="));
}
else if((vcfg = strstr(line, "send_count=")) != NULL) {
cfg->send_int_count = atoi(vcfg + strlen("send_count="));
}
}
}
//fprintf(stderr, "[debug] http info %s:%d\n", cfg->host, cfg->port);
fclose(cfg_file);
if(line)
free(line);
return 0;
}
|
C
|
#include <stdio.h>
#include "Headers/Stack.h"
Stack::Stack(){
start=NULL;
}
Stack::~Stack(){
List_of_Return_Addresses *p1=start;
List_of_Return_Addresses *p2;
while (p1!=NULL){
p2=p1->pointer;
delete p1;
p1=p2;
}
}
void Stack::Push(const int a){
if (start==NULL){
start=new List_of_Return_Addresses;
start->address=a;
start->pointer=NULL;
return;
}
List_of_Return_Addresses* p=start;
while(p->pointer!=NULL){
p=p->pointer;
}
p->pointer=new List_of_Return_Addresses;
p=p->pointer;
p->address=a;
p->pointer=NULL;
return;
}
void Stack::Pop(int & a){
if (start==NULL){
//printf("Stack is empty! Don't know where to go!\n");
//exit(0);
//exit(33);
a=-1;
return;
}
List_of_Return_Addresses* p=start;
List_of_Return_Addresses* p2=start;
int kol=0;
while(p->pointer!=NULL){
p2=p;
p=p->pointer;
kol++;
}
a=p->address;
delete p;
if (kol==0)
start=NULL;
else
p2->pointer=NULL;
return;
}
void Stack::Print(){
List_of_Return_Addresses* p=start;
while (p!=NULL){
//printf("Address=%d\n", p->address);
p=p->pointer;
}
}
|
C
|
#include <stdio.h>
/* Write a program to print all input lines that are longer
than 80 characters. */
#define MAXLINE 10000
int mygetline(char *, int);
int
main() {
int len;
char line[MAXLINE];
while ((len = mygetline(line, MAXLINE)) > 0) {
if (len > 80) {
printf("%s", line);
}
}
return 0;
}
int
mygetline(char *line, int lim) {
int c, i;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF; i++) {
line[i] = c;
if (c == '\n') {
i++;
break;
}
}
line[i] = '\0';
return i;
}
|
C
|
/*
* vmss_bitfields.c
* Lab2a
*
* Created by Alexey Streltsow on 3/30/10.
* Copyright 2010 Zila Networks LLC. All rights reserved.
*
*/
#include "vmss_bitfields.h"
#include <stdio.h>
const char* bits2string(INTFIELD* fld) {
static char sbits[128];
// sbits[0] = fld->bits[0].v ? '1' : '0';
// sbits[1] = ':';
char *bs = sbits;
int i;
for ( i=0; i<BIT_COUNT; ++i) {
*bs++ = fld->bits[i].v?'1':'0';
if (!( (i+1) % 4) && i != 0 ){
*bs++ = ' ';
}
}
*bs = 0;
return sbits;
}
void string2bits(const char* bitstring, INTFIELD* fld) {
int i=0;
const char* istr = bitstring;
while (*bitstring) {
if ( *bitstring == ' ' || *bitstring == '.' ) {
bitstring++;
continue;
}
fld->bits[++i].v = (*bitstring++ == '1') ? 1 : 0;
}
int count = BIT_COUNT - i;
while (--count > 0) {
shift_right(fld);
}
if (*istr == '-' ) {
fld->bits[0].v = 1;
}
}
void shift_left(INTFIELD* fld) {
int i;
for (i=0; i<BIT_COUNT-1; ++i) {
fld->bits[i].v = fld->bits[i+1].v;
}
fld->bits[BIT_COUNT-1].v=0;
}
void shift_right(INTFIELD* fld) {
int i;
for (i=BIT_COUNT-1; i>=0; --i) {
fld->bits[i].v = fld->bits[i-1].v;
}
fld->bits[0].v = 0;
}
void sum_bits(INTFIELD* b1, INTFIELD* b2, INTFIELD* res) {
int add = 0;
int i;
for (i=BIT_COUNT-1; i>=0; --i) {
if ( b1->bits[i].v == 0 && b2->bits[i].v == 0 ) {
res->bits[i].v = add;
add = 0;
}
else if ((b1->bits[i].v == 1 && b2->bits[i].v == 0) ||
(b1->bits[i].v == 0 && b2->bits[i].v == 1)) {
res->bits[i].v = !add;
}
else if ( b1->bits[i].v == 1 && b2->bits[i].v == 1 ) {
res->bits[i].v = add;
add = 1;
}
}
}
void subtract_bits(INTFIELD* b1, INTFIELD* b2, INTFIELD* res) {
int sub = 0;
int i;
for (i=BIT_COUNT-1; i>=0; --i) {
if ( b1->bits[i].v == 0 && b2->bits[i].v == 0 ) {
res->bits[i].v = sub;
}
else if ( b1->bits[i].v == 1 && b2->bits[i].v == 0 ) {
res->bits[i].v = !sub;
sub = 0;
}
else if ( b1->bits[i].v == 0 && b2->bits[i].v == 1 ) {
res->bits[i].v = !sub;
sub = 1;
}
else if ( b1->bits[i].v == 1 && b2->bits[i].v == 1 ) {
res->bits[i].v = sub;
//sub = 1;
}
}
}
void reverse_bits(INTFIELD* b, INTFIELD* res) {
int i;
for ( i=0; i<BIT_COUNT; i++ ) {
res->bits[i].v = !b->bits[i].v;
}
}
int bits2int(INTFIELD* b) {
int value = 0;
int i;
for (i=1; i<BIT_COUNT; i++) {
value |= (b->bits[i].v << (BIT_COUNT - i) );
}
//double fv = value / pow(10, b->p);
return value;
}
|
C
|
#include <stdio.h>
int main(int argc, char **argv){
if (argc!=3) {
fprintf(stderr,"USAGE: mv sourcefile destfile\n");
return 1;
}
if (rename(argv[1],argv[2])==-1){
perror("mv");
return 1;
}
return 0;
}
|
C
|
#include <stdio.h>
void main()
{
unsigned long long int n;
n = 7000000000;
n = n * 1.015;
printf("%llu withh be the population after x years", n);
}
|
C
|
/* C Program to Calculate Square of a Number */
#include<stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int number, Square;
char *a = argv[1];
// printf(" \n Please Enter any integer Value : ");
//scanf("%d", &number);
number = atoi(a);
Square = number * number;
printf("\n Square of a given number %d is = %d\n", number, Square);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define ROW 3
#define COL 4
void count(int A[][COL], int num_rows, int num_cols);
void fillRandom(int A[][COL], int num_rows, int num_cols);
void printArray(int A[][COL], int num_rows, int num_cols);
int main(){
int A[ROW][COL];
srand(time(NULL));
fillRandom(A, ROW, COL);
printArray(A, ROW, COL);
count(A, ROW, COL);
return 0;
}
void count(int A[][COL], int num_rows, int num_cols){
int i, j;
int count0=0, count1=0, count2=0, count3=0, count4=0;
for(i=0;i<num_rows; i++){
for(j=0;j<num_cols;j++){
if(A[i][j]==0){
count0++;
}
else if(A[i][j]==1){
count1++;
}
else if(A[i][j]==2){
count2++;
}
else if(A[i][j]==3){
count3++;
}
else if(A[i][j]==4){
count4++;
}
}
}
printf("number of 0's %d\n", count0);
printf("number of 1's %d\n", count1);
printf("number of 2's %d\n", count2);
printf("number of 3's %d\n", count3);
printf("number of 4's %d\n", count4);
}
void fillRandom(int A[][COL], int num_rows, int num_cols){
int i, j;
for(i=0;i<num_rows;i++){
for(j=0;j<num_cols;j++){
A[i][j]=(rand() % 5);
}
}
}
void printArray(int A[][COL], int num_rows, int num_cols){
int i, j;
for(i=0;i<num_rows;i++){
for(j=0;j<num_cols;j++){
printf("%d ", A[i][j]);
}
printf("\n");
}
}
|
C
|
#include <stdio.h>
/**
* main - get biggest prime factor of given number
* do it like stack overflow 24166478
* no need for sieve
* Return: 0
*/
int main(void)
{
long int d, n;
n = 612852475143;
d = 2;
while (d < n)
{
if ((n % d) == 0)
{
n = n / d;
d--;
}
d++;
}
printf("%li\n", n);
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int i=0, meter;
while (i<3)
{
meter = i * 1609;
printf("%d %d Դϴ.\n", i, meter);
i++;
}
return 0;
}
|
C
|
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, string argv[])
{
if(argc!=2)
{
printf("Enter one Key\n");
return 1;
}
else
{
int k=atoi(argv[1]);
string text = GetString();
for(int i=0,n=strlen(text); i<n; i++)
{
char letter=text[i];
int ciphertext;
if(isupper(letter))
{
ciphertext=(letter-65+key)%26+65;
}
else if(islower(letter))
{
ciphertext=(letter-97+key)%26+97;
}
else
{
ciphertext=letter;
}
printf("%c",ciphertext);
}
printf("\n");
}
}
|
C
|
#include <stdio.h>
#include <omp.h>
int main()
{
//#pragma omp parallel
#pragma omp critical
{ printf("Bonjour je suis le thread numero %i!\n",omp_get_thread_num);
//#pragma omp barrier
printf("Au revoir je le thread numero! %i\n",omp_get_thread_num);}
return 0;
}
|
C
|
/***************************
File: Multilookup
Nick Trierweiler
**************************/
#include "util.h"
#include "queue.h"
#include "multilookup.h"
char * OUTPUT_FILE;
char errorstr[SBUFSIZE];
int NUM_FILES;
int num_queued;
int num_resolved;
queue q;
pthread_mutex_t output_lock;
pthread_mutex_t queue_lock;
void * read_file(void * f){
//printf("inside read_file\n");
FILE * file = fopen((char*) f, "r");
if(!file){
sprintf(errorstr, "Error Opening Input File: %s", (char*)f);
return NULL;
}
char hostname[MAX_NAME_LENGTH];
char * hostname_ptr; //if i dont do this then hostname gets turned into a pointer
while(fscanf(file, INPUTFS, hostname) > 0){
pthread_mutex_lock(&queue_lock); //LOCK
while(queue_is_full(&q)){
pthread_mutex_unlock(&queue_lock);
usleep(rand()%100);
pthread_mutex_lock(&queue_lock);
}
hostname_ptr = malloc(sizeof(hostname));
strcpy(hostname_ptr, hostname);
queue_push(&q, hostname_ptr);
num_queued++;
//printf("pushed to queue: %s\n", hostname_ptr);
pthread_mutex_unlock(&queue_lock); //UNLOCK
}
fclose(file);
return NULL;
}
void * write_file(void * outputfp){
char firstipstr[INET6_ADDRSTRLEN];
char* hostname;
usleep(100); //delay resolver threads
while(1){
if(num_resolved == num_queued){ //are we done?
printf("num_queued: %d, num_resolved: %d\n", num_queued, num_resolved);
return(NULL);
}
while(!queue_is_empty(&q)){
pthread_mutex_lock(&queue_lock); //LOCK
hostname = (char*) queue_pop(&q);
num_resolved++;
pthread_mutex_unlock(&queue_lock);
/* from lookup.c */
if(dnslookup(hostname, firstipstr, sizeof(firstipstr)) == UTIL_FAILURE)
{
fprintf(stderr, "dnslookup error:, HOSTNAME %s\n", hostname); //alert user when hostname not found
strncpy(firstipstr, "", sizeof(firstipstr));
}
/* Write to Output File */
//printf("writing %s,%s to file\n", hostname, firstipstr);
if (hostname != NULL){
pthread_mutex_lock(&output_lock);
fprintf(outputfp, "%s,%s\n", hostname, firstipstr);
//printf("writing to file: %s,%s\n", hostname, firstipstr);
pthread_mutex_unlock(&output_lock);
}
free(hostname); //fixes valgrind direct loss
}
}
return NULL;
}
//credit to stackoverflow.com/questions/19232957/pthread-create-passing-an-integer-as-the-last-argument
//also stackoverflow.com/questions/32487579/why-does-a-function-accept-a-void-pointer
void * request_pool(void * argv){
/* create a thread pool*/
pthread_t request_threads[NUM_FILES];
char ** files = (char**) argv;
/* assign a thread to each file pointer */
int i;
for(i = 1; i < NUM_FILES+1; i++){
pthread_create(&request_threads[i], NULL, read_file, (void*) files[i]);
}
for(i = 0; i< NUM_FILES; i++){
pthread_join(request_threads[i], NULL);
}
return NULL;
}
void * resolve_pool(void* outputfp){
pthread_t resolve_threads[NUM_FILES];
int i = 0;
for(i = 0; i < NUM_FILES; i++){
pthread_create(&resolve_threads[i], NULL, write_file, outputfp);
pthread_join(resolve_threads[i], NULL);
}
return NULL;
}
int main(int argc, char* argv[]){
queue_init(&q, 10);
pthread_mutex_init(&output_lock, NULL);
pthread_mutex_init(&queue_lock, NULL);
/* seed random generator */
srand(time(NULL));
/* Local Vars */
//FILE* inputfp = NULL;
//char hostname[MAX_NAME_LENGTH]; moved to read_file
char errorstr[MAX_NAME_LENGTH];
//char firstipstr[INET6_ADDRSTRLEN];
int i;
/* Setup Local Vars for threads*/
// pthread_t threads[NUM_THREADS];
// int rc;
// long t;
// long cpyt[NUM_THREADS];
/* Check Arguments */
if(argc < MINARGS){
fprintf(stderr, "Not enough arguments: %d\n", (argc - 1));
fprintf(stderr, "Usage:\n %s %s\n", argv[0], USAGE);
return EXIT_FAILURE;
}
/* from lookup.c */
OUTPUT_FILE = argv[argc -1];
FILE* outputfp = fopen(OUTPUT_FILE, "w");
if (!outputfp) {
fprintf(stderr, "Error opening output file \n");
return EXIT_FAILURE;
}
NUM_FILES = argc - 2;
//printf("numfiles: %d", NUM_FILES); working
for(i=1; i<(argc-1); i++){
/* Get Input File Names for request */
printf("file %s\n", argv[i]);
if(!argv[i])
{
sprintf(errorstr, "Error Grabbing Name of Input File: %s", argv[i]);
perror(errorstr);
break;
}
}
//credit to code example cis.poly.edu/cs3224a/Code/ProducerConsumerUsingPthreads.c
pthread_t pro, con;
pthread_create(&pro, NULL, request_pool, (void *) argv);
pthread_create(&con, NULL, resolve_pool, (void *) outputfp);
/* wait for pro and con threads to terminate before exiting */
pthread_join(pro, NULL);
pthread_join(con, NULL);
/*close file*/
fclose(outputfp);
/* clean up to prevent memory leak: locks, allocated memory */
pthread_mutex_destroy(&queue_lock);
pthread_mutex_destroy(&output_lock);
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
// Gustavo Jimenez Torres
//Ejemplo de aplicacion del diseo descendente a un problema \\
//Escribe un programa que dibuje la siguiente piramide utilizando unicamente los simbolos O y X
//usando la salida estandar en modo texto de pantalla. Generaliza el programa para una piramide de n lineas
//(donde n sera menor que 24 lineas que es la capacidad del modo texto normal.)
int main()
{
int i,j;
int n=5;
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i;j++)
printf("O");
for(j=1;j<=2*i-1;j++)
printf("X");
printf("\n");
}
system("pause");
}
|
C
|
/*H*
*
* FILENAME: exception.c
* DESCRIPTION: Functions for throwing Herbrand errors
* AUTHORS: José Antonio Riaza Valverde
* UPDATED: 16.11.2019
*
*H*/
#include "exception.h"
/**
*
* This function generates an instantiation error returning a
* pointer to a newly initialized Term struct.
*
**/
Term *exception_instantiation_error(wchar_t *level) {
Term *list, *error, *ins_error, *level_term;
error = term_init_atom(L"error");
ins_error = term_init_atom(L"instantiation_error");
// Level term
level_term = term_alloc();
level_term->type = TYPE_ATOM;
term_set_string(level_term, level == NULL ? L"top_level" : level);
// Error term
list = term_list_empty();
term_list_add_element(list, error);
term_list_add_element(list, ins_error);
term_list_add_element(list, level_term);
return list;
}
/**
*
* This function generates a type error returning a pointer
* to a newly initialized Term struct.
*
**/
Term *exception_type_error(Term *type, Term *found, wchar_t *level) {
Term *list, *list_type, *list_expected, *list_given, *error, *type_error, *expected, *given, *level_term;
error = term_init_atom(L"error");
type_error = term_init_atom(L"type_error");
// Level term
level_term = term_alloc();
level_term->type = TYPE_ATOM;
term_set_string(level_term, level == NULL ? L"top_level" : level);
// Found term
term_increase_references(found);
term_increase_references(type);
// Given type
given = tc_get_type_expr(found);
// Error term
list_expected = term_list_empty();
term_list_add_element(list_expected, term_init_atom(L"expected"));
term_list_add_element(list_expected, type);
list_given = term_list_empty();
term_list_add_element(list_given, term_init_atom(L"found"));
term_list_add_element(list_given, given);
list_type = term_list_empty();
term_list_add_element(list_type, type_error);
term_list_add_element(list_type, list_expected);
term_list_add_element(list_type, list_given);
term_list_add_element(list_type, found);
list = term_list_empty();
term_list_add_element(list, error);
term_list_add_element(list, list_type);
term_list_add_element(list, level_term);
return list;
}
/**
*
* This function generates a domain error returning a pointer
* to a newly initialized Term struct.
*
**/
Term *exception_domain_error(wchar_t *domain, Term *found, wchar_t *level) {
Term *list, *list_domain, *error, *domain_error, *expected, *level_term;
error = term_init_atom(L"error");
domain_error = term_init_atom(L"domain_error");
expected = term_init_atom(domain);
// Level term
level_term = term_alloc();
level_term->type = TYPE_ATOM;
term_set_string(level_term, level == NULL ? L"top_level" : level);
// Found term
term_increase_references(found);
// Error term
list_domain = term_list_empty();
term_list_add_element(list_domain, domain_error);
term_list_add_element(list_domain, expected);
term_list_add_element(list_domain, found);
list = term_list_empty();
term_list_add_element(list, error);
term_list_add_element(list, list_domain);
term_list_add_element(list, level_term);
return list;
}
/**
*
* This function generates an existence error returning a
* pointer to a newly initialized Term struct.
*
**/
Term *exception_existence_error(wchar_t *source, Term *found, wchar_t *level) {
Term *list, *list_existence, *error, *existence_error, *source_term, *level_term;
error = term_init_atom(L"error");
existence_error = term_init_atom(L"existence_error");
source_term = term_init_atom(source);
// Level term
level_term = term_alloc();
level_term->type = TYPE_ATOM;
term_set_string(level_term, level == NULL ? L"top_level" : level);
// Found term
term_increase_references(found);
// Error term
list_existence = term_list_empty();
term_list_add_element(list_existence, existence_error);
term_list_add_element(list_existence, source_term);
term_list_add_element(list_existence, found);
list = term_list_empty();
term_list_add_element(list, error);
term_list_add_element(list, list_existence);
term_list_add_element(list, level_term);
return list;
}
/**
*
* This function generates an arity error returning a
* pointer to a newly initialized Term struct.
*
**/
Term *exception_arity_error(int arity, int given, Term *found, wchar_t *level) {
Term *list, *list_arity, *list_given, *list_expected, *error, *arity_error,
*expected_term, *given_term, *expected_n, *given_n, *level_term;
error = term_init_atom(L"error");
arity_error = term_init_atom(L"arity_error");
expected_term = term_init_atom(L"expected");
given_term = term_init_atom(L"given");
expected_n = term_init_numeral(arity);
given_n = term_init_numeral(given);
// (expected Arity)
list_expected = term_list_empty();
term_list_add_element(list_expected, expected_term);
term_list_add_element(list_expected, expected_n);
// (given Length)
list_given = term_list_empty();
term_list_add_element(list_given, given_term);
term_list_add_element(list_given, given_n);
// Level term
level_term = term_alloc();
level_term->type = TYPE_ATOM;
term_set_string(level_term, level == NULL ? L"top_level" : level);
// Found term
term_increase_references(found);
// Error term
list_arity = term_list_empty();
term_list_add_element(list_arity, arity_error);
term_list_add_element(list_arity, list_expected);
term_list_add_element(list_arity, list_given);
term_list_add_element(list_arity, found);
list = term_list_empty();
term_list_add_element(list, error);
term_list_add_element(list, list_arity);
term_list_add_element(list, level_term);
return list;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<math.h>
long int fatorial(long int arg){
long long int resposta = 1;
for(int i = 1;i<=arg;i++){
resposta *=i;
}
return resposta;
}
int main(void){
printf("fatorial:%ld\n",fatorial(10));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <limits.h>
struct Edge{
int y;//end point
int c;//capacity
int f;//flow
struct Edge *next;
};//C type for edge
typedef struct Edge edge;
struct Vertex{
int x;//id
int n;//need
edge *p;
};//C type for vertex
typedef struct Vertex vertex;
struct Graph{
int v;//#vertices
int e;//#edges
vertex *h;//Array
};//C type for graph
typedef struct Graph graph;
/*All helper functions*/
graph *ReadGraph(char *fname);
void PrintGraph(graph *g);
void PrintGraph2(graph *g);
void addLinkResGraph(graph *g, int x, int y, int c);
int augmentFlow(graph *g, graph *resG, int s, int t);
graph * computeResidualGraph(graph *g);
void ComputeMaxFlow(graph *g, int s, int t);
void NeedBasedFlow(graph *g);
graph *getGraph(int n, int m, int *need);
void addLink(graph *g, int x, int y, int c);
edge *getEdge(int y, int c);
int min(int a, int b);
int main()
{
char *inputFile = (char *)malloc(21*sizeof(char));
printf("Enter the name of the input File : ");
scanf("%s", inputFile);
graph *g = ReadGraph(inputFile);
printf("The graph entered is : \n");
PrintGraph(g);
printf("\n**********************Max Flow Computation**********************\n\n");
int s, t;
printf("Enter the Source and Sink vertex : ");
scanf("%d %d", &s, &t);//Input of source and sink
ComputeMaxFlow(g, s, t);//Max Flow s-->t
printf("\nThe final graph with flows assigned is : \n");
PrintGraph(g);//Printing the final flow assigned graph
g = ReadGraph(inputFile);//Reading graph again
printf("\n******************Need Based Flow Computation*******************\n\n");
NeedBasedFlow(g);//Need based Max Flow
}
graph *ReadGraph(char *fname)
{
FILE *fp = fopen(fname, "r");
int n, m;
fscanf(fp, "%d %d", &n, &m);//Vertices and edges
int *need = (int *)malloc((n+1)*sizeof(int));
for(int i = 1; i<=n; i++)
{
fscanf(fp, "%d", &need[i]);
}//Input of need
graph *g = getGraph(n, m, need);
for(int i = 0; i<m; i++)
{
int x, y, c;
fscanf(fp, "%d %d %d", &x, &y, &c);//Input of edges
addLink(g, x, y, c);
}
fclose(fp);
return g;
}
graph *getGraph(int n, int m, int *need)
{
graph *g = (graph *)malloc(sizeof(graph));
g->v = n;
g->e = m;
g->h = (vertex *)malloc((n+2)*sizeof(vertex ));
for(int i = 0; i<=n+1; i++)
{
g->h[i].x = i;
g->h[i].n = need[i];
g->h[i].p = (edge *)malloc(sizeof(edge));
g->h[i].p = NULL;
}
return g;
}/*Function to initialise an empty graph*/
void addLink(graph *g, int x, int y, int c)
{
edge *p = getEdge(y, c);
p->next = g->h[x].p;
g->h[x].p = p;
}/*Add an edge to the graph*/
edge *getEdge(int y, int c)
{
edge *new = (edge *)malloc(sizeof(edge));
new->y = y;
new->c = c;
new->f = 0;
new->next = (edge *)malloc(sizeof(edge));
new->next = NULL;
return new;
}/*Get a new edge*/
void PrintGraph(graph *g)
{
int n = g->v;
for(int i=1; i<=n; i++)
{
printf("%d ", i);
edge *e = g->h[i].p;
while(e!=NULL)
{
if(e->y!=0&&e->y!=(n+1))
printf("-> (%d, %d, %d) ", e->y, e->c, e->f);
e = e->next;
}
printf("\n");
}
}/*Function to print the graph*/
void NeedBasedFlow(graph *g)
{
int n = g->v;
int pos = 0, neg = 0;
/*The vertex is a producer if need<0 and consumer if need>0
So we take 2 extra vertices 0 and n+1. Connect 0 to all the producers
and n+1 to all the consumers. The 0 becomes the source and n+1 becoes
the sink in subsequent maxFlow computation*/
for(int i = 1; i<=n; i++)
{
int need = g->h[i].n;
if(need<0)
{
neg = neg - need;
addLink(g, 0, i, -1*need);
}
else if(need>0)
{
pos = pos + need;
addLink(g, i, n+1, need);
}
}
if(pos!=neg)//Total flow produced necessarily= Total flow consumed
{
printf("Need based flow assignment meeting the constraints not possible\n");
}
else
{
int maxFlow = 0;
ComputeMaxFlow(g, 0, n+1);
edge *e = g->h[0].p;
while(e!=NULL)
{
maxFlow += e->f;
e = e->next;
}
if(maxFlow==pos)//Condition for feasibility of flow assignment as per constraints
{
printf("Need based flow assignment meeting the constraints possible\n");
printf("The final need based flow assigned graph is : \n");
PrintGraph(g);
}
else
{
printf("Need based flow assignment meeting the constraints not possible\n");
}
}
}
void ComputeMaxFlow(graph *g, int s, int t)
{
int add = 1;
int maxFlow = 0;
while(add!=0)//While augmented flow != 0
{
graph *resG = computeResidualGraph(g);
add = augmentFlow(g, resG, s, t);
maxFlow += add;
}
if(s!=0)
printf("The maximum flow from %d to %d is: %d\n", s, t, maxFlow);
else
printf("The need based flow in the graph is: %d\n", maxFlow);
}
graph * computeResidualGraph(graph *g)
{
/*Initialising empty residual graph*/
graph *resG = (graph *)malloc(sizeof(graph));
resG->v = g->v;
int n = g->v;
resG->h = (vertex *)malloc((n+2)*sizeof(vertex ));
for(int i = 0; i<=n+1; i++)
{
resG->h[i].x = i;
resG->h[i].p = (edge *)malloc(sizeof(edge));
resG->h[i].p = NULL;
}
for(int i = 0; i<=n+1; i++)
{
edge *e = g->h[i].p;
while(e!=NULL)
{
int source = i;
int dest = e->y;
int cap = e->c;
int flow = e->f;
if(flow>0)//If current flow>0 add an edge from dest->source of capacity flow
{
addLinkResGraph(resG, dest, source, flow);
if(flow<cap)
addLinkResGraph(resG, source, dest, cap-flow);
//If flow<capacity add an edge dest->source of capacity cap-flow
}
else
{//If flow = 0 simply replicate the edge as in original graph
addLinkResGraph(resG, source, dest, cap);
}
e = e->next;
}
}
return resG;
}
void addLinkResGraph(graph *g, int x, int y, int c)
{
/*If edge x to y exists, increase its cap by c
If edge x to y does not exist, add a new edge x->y of cap c*/
edge *e = g->h[x].p;
int exists = 0;
while(e!=NULL)
{
int end = e->y;
if(end==y)//Edge exists, increase capacity of existing edge
{
exists = 1;
e->c = e->c + c;
break;
}
e = e->next;
}
if(!exists)//Edge does not exist, add a new edge
{
edge *p = getEdge(y, c);
p->next = g->h[x].p;
g->h[x].p = p;
}
}
int augmentFlow(graph *g, graph *resG, int s, int t)
{
int n = g->v;
int *dist = (int *)malloc((n+2)*sizeof(int ));
int *parent = (int *)malloc((n+2)*sizeof(int ));
int *colour = (int *)malloc((n+2)*sizeof(int ));
int *minCap = (int *)malloc((n+2)*sizeof(int ));
for(int i=0; i<=n+1; i++)
{
minCap[i] = 0;
dist[i] = n+3;
parent[i] = -1;
colour[i] = 0;//0->Unvisited, 1->in Queue, 2->Popped from queue
}
int *queue = (int *)malloc((n+2)*sizeof(int ));
int start = -1, end = -1;
queue[0] = s;
start = 0;
end = 0;
dist[s] = 0;
parent[s] = -1;
minCap[s] = INT_MAX;
//Modified BFS to find the required augmenting path
while(start<=end)
{
int source = queue[start%(n+2)];
start++;
colour[source] = 2;
edge *e = resG->h[source].p;
while(e!=NULL)
{
int dest = e->y;
if(colour[dest]==0)
{
queue[(end+1)%(n+2)] = dest;
end++;
colour[dest] = 1;
dist[dest] = 1 + dist[source];
parent[dest] = source;
minCap[dest] = min(minCap[source], e->c);
}
else if(colour[dest]==1)
{
if(dist[dest]==(1+dist[source]))
{
if(minCap[dest]<min(minCap[source], e->c))
{
minCap[dest] = min(minCap[source], e->c);
parent[dest] = source;
}
}
}
e = e->next;
}
if(dist[source]>dist[t])//Already reached a level below the level of sink
break;
}
int augFlow = minCap[t];//augmenting flow
int child = t;
int par = parent[child];
while(par!=-1)//Adding the augmenting flows to the edges of the augmenting path
{
int p = parent[1];
int remFlow = augFlow;
edge *e = g->h[par].p;
int count = 0;
while(e!=NULL)//First trying to push the maximum possible flow along the source->dest edge
{
int dest = e->y;
if(dest==child)
{
int currFlow = e->f;
int capacity = e->c;
e->f = e->f + min(remFlow, capacity-currFlow);
remFlow = remFlow - min(remFlow, capacity-currFlow);
break;
}
count++;
e = e->next;
}
edge *e2 = g->h[child].p;
while(e2!=NULL)//If not enough remaining capacity, push negative flow along dest->source (effectively flow along sourcce->dest)
{
int dest = e2->y;
if(dest==par)
{
e2->f = e2->f - remFlow;
break;
}
e2 = e2->next;
}
child = par;
par = parent[child];
}
return augFlow;
}
int min(int a, int b)//Function to find minimum of 2 integers
{
return ((a<b)?a:b);
}
|
C
|
/* Adjecancy list using array of linked list */
#include <stdio.h>
#include <stdlib.h>
struct node{
int info;
struct node *next;
};
typedef struct node NODE;
NODE *first_edge(NODE *start[], int a, int b)
{
NODE *tmp;
tmp = (NODE *)malloc(sizeof(NODE));
tmp -> info = b;
tmp -> next = start[a];
start[a] = tmp;
return start[a];
}
NODE *insert_edge(NODE *start[], int a, int b,int n)
{
int flag=0;
NODE *tmp,*p;
p = start[a];
if(a>n || b>n)
{
printf("Enter a valid edge\n");
return start[a];
}
if(p == NULL)
{
start[a] = first_edge(start,a,b);
return start[a];
}
tmp = (NODE *)malloc(sizeof(NODE));
tmp -> info = b;
tmp -> next = NULL;
while(p->next!=NULL)
{
if(p->info == b)
{
printf("Edge already exist\n");
flag = 1;
break;
}
p = p->next;
}
if(flag == 0)
p->next = tmp;
return start[a];
}
NODE *delete_edge(NODE *start[], int a, int b)
{
NODE *p;
p = start[a];
if(p==NULL)
{
printf("No edges\n");
return start[a];
}
else if (p->info == b)
{
NODE *tmp;
tmp = p;
start[a] = p->next;
free(tmp);
return start[a];
}
else
{
while(p->next != NULL)
{
if(p->next->info == b)
{
NODE *tmp;
tmp = p->next;
p->next = p->next->next;
free(tmp);
return start[a];
}
}
}
printf("NO such edge exist\n");
}
void show_graph(NODE *start[], int n)
{
int i;
for(i=1;i<=n;i++)
{
NODE *p;
p = start[i];
printf("%d -> ",i);
if(p!=NULL)
{
while(p->next != NULL)
{
printf("%d ",p->info);
p = p->next;
}
printf("%d ",p->info);
}
printf("\n");
}
}
int main()
{
int n,i,a,b,choice;
printf("Enter the number of vertex: ");
scanf("%d",&n);
NODE *start[n+1];
for(i=1;i<=n;i++)
start[i] = NULL;
while(1)
{
printf("\n1. Enter edge\n");
printf("2. Delete a edge\n");
printf("3. Show graph\n");
scanf("%d",&choice);
if(choice == 1)
{
printf("Enter origin and destination: ");
scanf("%d %d",&a,&b);
start[a] = insert_edge(start,a,b,n);
}
else if(choice == 2)
{
printf("Enter a origin and destination to be deleted: ");
scanf("%d %d",&a,&b);
start[a] = delete_edge(start,a,b);
}
else if(choice == 3)
{
show_graph(start,n);
}
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strrev.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: glafitte <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/09/17 18:28:12 by glafitte #+# #+# */
/* Updated: 2014/09/17 18:46:23 by glafitte ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
void ft_putchar(char c)
{
write(1, &c, 1);
}
int ft_strlen(char *str)
{
int i;
i = 0;
while (str[i])
i++;
return (i);
}
void ft_putstr(char *str)
{
int counter;
counter = 0;
while (str[counter])
{
ft_putchar(str[counter]);
counter++;
}
}
char *ft_strrev(char *str)
{
char *str2;
int i;
int j;
int tmp;
i = 0;
j = ft_strlen(str);
tmp = j;
while (i < tmp)
str2[i++] = str[j--];
str2[i] = '\0';
return (str2);
}
char *ft_strrev(char *str);
int main (void)
{
char str[]= "coucou tous le monde";
char *str_ptr;
str_ptr = str;
printf("%s\n", ft_strrev(str_ptr));
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct wrongAns{ //Structure containing wrong answers and relative operations
char *ans[100];
}wrongAns;
wrongAns wAns[10];
float findTotal(int n, float* operands, int* operators); //function that computes the total
char findOp(int m); //function matching an integer in [0,3] to a sign
int main(int argc, char* argv[])
{
srand(time(NULL)); //initializing rand function
if(argc!=2){
printf("Invalid input\n"); //making sure the input is in the correct form
return 0;
}
//generate vectors with dynamic allocation
int n= atoi(argv[1]); //n is the command line input from the user
int* operators = (int*) malloc ((n-1)*sizeof(int));
float* operands = (float*) malloc (n*sizeof(float));
//initializing counter for wrong answers
int wrong = 0;
for(int k=0;k<10;k++){
for(int i=0; i<n; i++){
operands[i]=(rand()%100)+1; //generating random numbers n times
}
for(int i=0; i<n-1; i++){
operators[i]=rand()%4; //generating n-1 operations
}
for(int i=0; i<n; i++){ //printing on screen the operations
printf("%.0f ",operands[i]);
if(i!=n-1){
if(operators[i]==0){
printf("+ ");
}
if(operators[i]==1){
printf( "- ");
}
if(operators[i]==2){
printf( "* ");
}
if(operators[i]==3){
printf("/ ");
}
}
}
printf("= ");
float uTot;
scanf("%f", &uTot);
float tot = findTotal(n, operands, operators); //computing total
float Dtot = uTot - tot; //checking answer
if (Dtot>0.05||Dtot<-0.05){ //Check if answer is outside of tolerance
switch(n){ //Saving wrong answers and relative operations as strings in structure
case 3: sprintf(wAns[wrong].ans, "%.0f %c %.0f %c %.0f = %.2f\n", operands[0], findOp(operators[0]), operands[1], findOp(operators[1]), operands[2], tot);
break;
case 4: sprintf(wAns[wrong].ans, "%.0f %c %.0f %c %.0f %c %.0f = %.2f\n", operands[0], findOp(operators[0]), operands[1], findOp(operators[1]), operands[2], findOp(operators[2]), operands[3], tot);
break;
case 5: sprintf(wAns[wrong].ans, "%.0f %c %.0f %c %.0f %c %.0f %c %.0f = %.2f\n", operands[0], findOp(operators[0]), operands[1], findOp(operators[1]), operands[2], findOp(operators[2]), operands[3], findOp(operators[3]), operands[4], tot);
break;
default: printf("Error");
break;
}
wrong++;
}
} //end of 10 inputs
printf("\n\nYou got %d answers wrong.\n\n", wrong);
for(int i=0; i<wrong; i++){
printf("%s\n", wAns[i].ans);
}
return 0;
}
//function calculating result of operation
float findTotal(int n, float* operands, int* operators){
float tot = operands[0];
for(int i=0; i<n; i++){
if (operators[i]==0){
tot= tot+ operands[i+1];
}
if (operators[i]==1){
tot= tot- operands[i+1];
}
if (operators[i]==2){
tot= tot* operands[i+1];
}
if (operators[i]==3){
tot= tot/ operands[i+1];
}
}
return tot;
}
//to determine operations the function takes as input a number between 0 and 3 and assign an operation to each value
char findOp(int m){
switch(m){
case 0:
return '+';
case 1:
return '-';
case 2:
return '*';
case 3:
return '/';
default:
exit(EXIT_FAILURE);
}
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
char *s;
printf("enter the string : ");
scanf("%s",s);
printf("you entered %s\n", s);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int ex8()
{
int i,j;
char *str[13] = {"ab","cd","ef","gh","ij","kl","mn","op","qr","st","uv","wx","yz"};
for (i = 0; i <= 12; i++)
{
for (j = 0; j <= 1; j++)
{
printf(" *str=%p\n", (*(str + i) + j));
printf(" **str=%c\n", *(*(str + i) + j));
}
}
}
|
C
|
#ifndef AOC2020_H
#define AOC2020_H
#define INPUT_NULL_CHECK \
if(input == NULL) \
{ \
printf("Error: Could not read file.\n"); \
} \
size_t removeDupes(void * array, size_t arraySize, size_t elemSize, int(*cmpfunc)(const void * a, const void * b));
size_t countCharacterInFile(FILE * input, char ch);
void printArray(void *array, size_t arraySize, size_t elemSize, void (*printfunc)(const void * a));
void rewindFile(FILE * input);
char peek(FILE * fp);
int max(int a, int b);
#endif
|
C
|
/*
Function to calculate the neighbour j of the k site given a
square lattice of side L and size N (N = L*L).
The neighbours are chosen by the j value as especified below:
j = 0 right neighbour;
j = 1 upper neighbour;
j = 2 left neighbour;
j = 3 below neighbour;
*/
int nbr(int j, int k, int L)
{
int N = L*L;
int n;
if (j ==0)
{
if(k%L == L-1)
{
n = k+1-L;
}
else n = k+1;
}
if (j == 1)
{
n = (k+L)%N;
}
if (j == 2)
{
if(k%L == 0)
{
n = k-1+L;
}
else n = k-1;
}
if (j == 3)
{
n = (k-L+N)%N
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool check(char c)
{
return ('A' <= c && c <= 'Z') ||
('a' <= c && c <= 'z');
}
int main(int argc, char *argv[])
{
int count = 0;
bool current = false;
char c;
while ((c = getchar()) != EOF) {
if (c == '\n') {
printf("%d\n", count);
count = 0;
current = false;
} else if (check(c)) {
if (!current) {
current = true;
count++;
}
} else {
current = false;
}
}
return 0;
}
|
C
|
/*
** blit_tektext.c for in /home/tek/rendu/gfx_tekgui
**
** Made by
** Login <[email protected]>
**
** Started on Sat Feb 27 08:53:16 2016
** Last update Sat Feb 27 08:53:37 2016
*/
#include "tekgui.h"
unsigned int get_pixel(t_bunny_pixelarray *buffer,
int x,
int y)
{
unsigned int color;
unsigned int i;
i = buffer->clipable.clip_width * y + x;
if (x >= 0 && x <= buffer->clipable.clip_width &&
y >= 0 && y <= buffer->clipable.clip_height)
return (color = (((t_color*)buffer->pixels)[i].full));
return (color = 0);
}
void blit_tektext(t_bunny_pixelarray *background,
t_bunny_pixelarray *buffer,
t_bunny_position *pos)
{
t_bunny_position pos_rela;
unsigned int color;
pos_rela.y = pos->y;
while (pos_rela.y < 7 + pos->y)
{
pos_rela.x = pos->x;
while (pos_rela.x < 5 + pos->x)
{
color = get_pixel(buffer, pos_rela.x +
buffer->clipable.clip_x_position - pos->x,
pos_rela.y + buffer->clipable.clip_y_position
- pos->y);
if (color != 0)
tekpixel(background, &pos_rela, color);
pos_rela.x++;
}
pos_rela.y++;
}
}
|
C
|
#include <LPC214x.h>
unsigned long int x=0x00000000;
int main(){
unsigned int i=0;
unsigned int j=0;
PINSEL1=0x00000000;
IO0DIR=0x00FF0000;
while(1)
{
//Increasing ramp
for(i=0;i!=0xFF;i++){ //Loop between min value and max value(0xFF)
x=i; // 8 bit to 32 bit conversion
x=x<<16; //We only want value from 16 to 23
IO0PIN=x;
for(j=0;j<=90000;j++); //No delay in actual program, we need a smooth graph
}
//Decreasing ramp
for(i=0xFF;i!=0;i--){ //Start decrementing till we reach min value i.e 0x00
x=i;
x=x<<16;
IO0PIN=x;
for(j=0;j<=90000;j++);
}
}
}
|
C
|
/*RESULTS.c
* **USES RESULTS.h
*
* BRIEF:
* Source file for initializing and accessing
* a structure --- USED TO STORE TIME AND SCORE
*/
#include <stdio.h>
#include <stdlib.h>
#include "RESULTS.h"
#include "string.h"
//initializes time and score array elements to 0 and returns the structure
//ex: StoreResults s = RESULTS_Init();
//result: s->time == {0 0 0 0 0 0 0 0 0 0}
// s->score == {0 0 0 0 0 0 0 0 0 0}
StoreResults RESULTS_Init()
{
int i = 0;
StoreResults s;
for (i = 0; i < SIZE; i++) {
s.time[i] = 2;
s.score[i] = 2;
}
strcpy(s.prompt[0], "null");
strcpy(s.prompt[1], "null");
strcpy(s.prompt[2], "null");
strcpy(s.prompt[3], "null");
strcpy(s.prompt[4], "null");
strcpy(s.prompt[5], "null");
strcpy(s.prompt[6], "null");
strcpy(s.prompt[7], "null");
strcpy(s.prompt[8], "null");
strcpy(s.prompt[9], "null");
strcpy(s.response[0], "null");
strcpy(s.response[1], "null");
strcpy(s.response[2], "null");
strcpy(s.response[3], "null");
strcpy(s.response[4], "null");
strcpy(s.response[5], "null");
strcpy(s.response[6], "null");
strcpy(s.response[7], "null");
strcpy(s.response[8], "null");
strcpy(s.response[9], "null");
return s;
}
//adds a time value to an open (0) element in the array
//args: RESULTS_NewTime(StoreResults* s, unsigned int NewTime)
//StoreResults *s = pointer to a struct
//unsigned int NewTime = time value
//ex: StoreResults s = RESULTS_Init();
// RESULTS_NewTime(&s, 8);
//result: s->time = {8 0 0 0 0 0 0 0 0 0}
void RESULTS_NewTime(StoreResults* s, unsigned int NewTime)
{
int i = 0;
for (i = 0; i < SIZE; i++) {
if ((i == (SIZE)) && ((*s).time[SIZE] != 0)) {
printf("ARRAY FULL!\r\n");
break;
}
if ((*s).time[i] == 2) {
(*s).time[i] = NewTime;
break;
}
}
}
//adds a score value to an open (0) element in the array
//args: RESULTS_NewScore(StoreResults* s, unsigned int NewScore)
//StoreResults *s = pointer to a struct
//unsigned int NewScore = score value
//ex: StoreResults s = RESULTS_Init();
// RESULTS_NewScore(&s, 8);
//result: s->score = {8 0 0 0 0 0 0 0 0 0}
void RESULTS_NewScore(StoreResults *s, unsigned int NewScore)
{
int i = 0;
for (i = 0; i < SIZE; i++) {
if ((i == (SIZE)) && ((*s).score[SIZE] != 0)) {
printf("ARRAY FULL!\r\n");
break;
}
if ((*s).score[i] == 2) {
(*s).score[i] = NewScore;
break;
}
}
}
void RESULTS_Prompt(StoreResults* s, unsigned int counter)
{
strcpy((*s).prompt[counter], (*s).combo[0]);
printf("Prompt: %s\n", (*s).prompt[counter]);
}
void RESULTS_Response(StoreResults* s, unsigned int counter, unsigned int color, unsigned int response)
{
if (color == 1) {
if (response == 0) {//GRBRBG
strcpy((*s).response[counter], "GT");
} else if (response == 1) {
strcpy((*s).response[counter], "RS");
} else if (response == 2) {
strcpy((*s).response[counter], "BC");
} else if (response == 3) {
strcpy((*s).response[counter], "RT");
} else if (response == 4) {
strcpy((*s).response[counter], "BS");
} else if (response == 5) {
strcpy((*s).response[counter], "GC");
}
} else if (color == 2) {
if (response == 0) {//GRBBGR
strcpy((*s).response[counter], "GT");
} else if (response == 1) {
strcpy((*s).response[counter], "RS");
} else if (response == 2) {
strcpy((*s).response[counter], "BC");
} else if (response == 3) {
strcpy((*s).response[counter], "BT");
} else if (response == 4) {
strcpy((*s).response[counter], "GS");
} else if (response == 5) {
strcpy((*s).response[counter], "RC");
}
} else if (color == 3) {
if (response == 0) {//GBRRGB
strcpy((*s).response[counter], "GT");
} else if (response == 1) {
strcpy((*s).response[counter], "BS");
} else if (response == 2) {
strcpy((*s).response[counter], "RC");
} else if (response == 3) {
strcpy((*s).response[counter], "RT");
} else if (response == 4) {
strcpy((*s).response[counter], "GS");
} else if (response == 5) {
strcpy((*s).response[counter], "BC");
}
} else if (color == 4) {
if (response == 0) {//GBRBRG
strcpy((*s).response[counter], "GT");
} else if (response == 1) {
strcpy((*s).response[counter], "BS");
} else if (response == 2) {
strcpy((*s).response[counter], "RC");
} else if (response == 3) {
strcpy((*s).response[counter], "BT");
} else if (response == 4) {
strcpy((*s).response[counter], "RS");
} else if (response == 5) {
strcpy((*s).response[counter], "GC");
}
} else if (color == 5) {//RGBGBR
if (response == 0) {
strcpy((*s).response[counter], "RT");
} else if (response == 1) {
strcpy((*s).response[counter], "GS");
} else if (response == 2) {
strcpy((*s).response[counter], "BC");
} else if (response == 3) {
strcpy((*s).response[counter], "GT");
} else if (response == 4) {
strcpy((*s).response[counter], "BS");
} else if (response == 5) {
strcpy((*s).response[counter], "RC");
}
} else if (color == 6) {
if (response == 0) {//RGBBRG
strcpy((*s).response[counter], "RT");
} else if (response == 1) {
strcpy((*s).response[counter], "GS");
} else if (response == 2) {
strcpy((*s).response[counter], "BC");
} else if (response == 3) {
strcpy((*s).response[counter], "BT");
} else if (response == 4) {
strcpy((*s).response[counter], "RS");
} else if (response == 5) {
strcpy((*s).response[counter], "GC");
}
} else if (color == 7) {
if (response == 0) {//RBGGRB
strcpy((*s).response[counter], "RT");
} else if (response == 1) {
strcpy((*s).response[counter], "BS");
} else if (response == 2) {
strcpy((*s).response[counter], "GC");
} else if (response == 3) {
strcpy((*s).response[counter], "GT");
} else if (response == 4) {
strcpy((*s).response[counter], "RS");
} else if (response == 5) {
strcpy((*s).response[counter], "BC");
}
} else if (color == 8) {
if (response == 0) {//RBGBGR
strcpy((*s).response[counter], "RT");
} else if (response == 1) {
strcpy((*s).response[counter], "BS");
} else if (response == 2) {
strcpy((*s).response[counter], "GC");
} else if (response == 3) {
strcpy((*s).response[counter], "BT");
} else if (response == 4) {
strcpy((*s).response[counter], "GS");
} else if (response == 5) {
strcpy((*s).response[counter], "RC");
}
} else if (color == 9) {
if (response == 0) {//BGRGRB
strcpy((*s).response[counter], "BT");
} else if (response == 1) {
strcpy((*s).response[counter], "GS");
} else if (response == 2) {
strcpy((*s).response[counter], "RC");
} else if (response == 3) {
strcpy((*s).response[counter], "GT");
} else if (response == 4) {
strcpy((*s).response[counter], "RS");
} else if (response == 5) {
strcpy((*s).response[counter], "BC");
}
} else if (color == 10) {
if (response == 0) {//BGRRBG
strcpy((*s).response[counter], "BT");
} else if (response == 1) {
strcpy((*s).response[counter], "GS");
} else if (response == 2) {
strcpy((*s).response[counter], "RC");
} else if (response == 3) {
strcpy((*s).response[counter], "RT");
} else if (response == 4) {
strcpy((*s).response[counter], "BS");
} else if (response == 5) {
strcpy((*s).response[counter], "GC");
}
} else if (color == 11) {
if (response == 0) {//BRGGBR
strcpy((*s).response[counter], "BT");
} else if (response == 1) {
strcpy((*s).response[counter], "RS");
} else if (response == 2) {
strcpy((*s).response[counter], "GC");
} else if (response == 3) {
strcpy((*s).response[counter], "GT");
} else if (response == 4) {
strcpy((*s).response[counter], "BS");
} else if (response == 5) {
strcpy((*s).response[counter], "RC");
}
} else if (color == 12) {
if (response == 0) {//BRGRGB
strcpy((*s).response[counter], "BT");
} else if (response == 1) {
strcpy((*s).response[counter], "RS");
} else if (response == 2) {
strcpy((*s).response[counter], "GC");
} else if (response == 3) {
strcpy((*s).response[counter], "RT");
} else if (response == 4) {
strcpy((*s).response[counter], "GS");
} else if (response == 5) {
strcpy((*s).response[counter], "BC");
}
}
printf("Response: %s\n", (*s).response[counter]);
}
unsigned int *RESULTS_GetTimes(StoreResults *s)//returns time array from struct
{
return (*s).time;
}
unsigned int *RESULTS_GetScores(StoreResults *s)//returns score array from struct
{
return (*s).score;
}
void RESULTS_PrintScore(StoreResults *s)
{
int right = 0;
int wrong = 0;
int i;
for (i = 0; i < SIZE; i++) {
if ((*s).score[i] == 1) {
right++;
} else /*if ((*s).score[i] == 0)*/ {
wrong++;
}
}
printf("Correct: %i\n", right);
printf("Incorrect: %i\n", wrong);
}
void RESULTS_PrintTimeArray(StoreResults *s)
{
int i;
printf("Time (ms): ");
for (i = 0; i < SIZE; i++) {
printf("%i", (*s).time[i]);
if (i != SIZE - 1) {
printf(", ");
}
}
printf("\n");
}
void RESULTS_PrintScoreArray(StoreResults *s)
{
int i;
printf("Score: ");
for (i = 0; i < SIZE; i++) {
printf("%i", (*s).score[i]);
if (i != SIZE - 1) {
printf(", ");
}
}
printf("\n");
}
void RESULTS_PrintTotalTime(StoreResults *s)
{
int i;
int total;
for (i = 0; i < SIZE; i++) {
total += (*s).time[i];
}
printf("Total Time (ms): %i\n", total);
}
void RESULTS_PrintPromptArray(StoreResults *s)
{
int i;
printf("Prompt: ");
for (i = 0; i < SIZE; i++) {
printf("%s", (*s).prompt[i]);
if (i != SIZE - 1) {
printf(", ");
}
}
printf("\n");
}
void RESULTS_PrintResponseArray(StoreResults *s)
{
int i;
printf("Response: ");
for (i = 0; i < SIZE; i++) {
printf("%s", (*s).response[i]);
if (i != SIZE - 1) {
printf(", ");
}
}
printf("\n");
}
|
C
|
//program which accept directory name and file name from user and check whether that file is present in that directory or not
/*
Write a program which accept directory name and file name from user and check whether that file is available in that directory or not.
*/
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include<string.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
DIR *dir;
struct dirent *entry;
if(argc != 3)
{
printf("Error: Not sufficeient arguments\n");
return -1;
}
// Open the specified directory
if ((dir = opendir(argv[1])) == NULL)
{
printf("Unable to open specified directory\n");
return -1;
}
// Traverse directory
while ((entry = readdir(dir)) != NULL)
{
if(strcmp(argv[2],(char*)entry->d_name)==0)
{
printf("%s file is present in directory\n",argv[2]);
break;
}
}
// close that opened directory
closedir(dir);
return 0;
}
|
C
|
#include "mips_interpreter.h"
// runs through all MIPS commands inside a string
void run_from_string(mips_state* registers, char* input)
{
// infinite loop- until we run out of commands to process.
while (input != NULL)
{
// first, skip all whitespace before the next command
input = skip_over_whitespace(input);
// now we need to parse the non-whitespace text.
// if could be and opcode, label, or section specifier
// first we check if its an opcode.
// we do this by scanning through the array of stored instruction names, and memcmping the current text
for (int i = 0; i < INSTRUCTION_COUNT; i++)
{
int instruction_name_length = strlen(INSTRUCTION_NAMES[i]);
if (memcmp(INSTRUCTION_NAMES[i], input, instruction_name_length) == 0)
{
// make sure there is at least one character of whitespace after the command.
// if we don't check this, we might get false positives- add will trigger addi, etc..
if (!is_whitespace(input + instruction_name_length))
continue;
// we got a match!
// look up the function in the implementation array
instruction_function opcode_func = INSTRUCTION_IMPLEMENTATION[i];
// skip over the instruction name
input += instruction_name_length;
// call that bad boy
opcode_func(registers, input);
}
}
// we didn't find any matching opcode name. maybe it's a section specifier?
break;
}
}
void run_from_data(char* input)
{
// infinite loop- until we run out of commands to process.
while (input != NULL)
{
// first, skip all whitespace before the next command
input = skip_over_whitespace(input);
// now we need to parse the non-whitespace text.
// if could be and opcode, label, or section specifier
// first we check if its an opcode.
// we do this by scanning through the array of stored instruction names, and memcmping the current text
for (int i = 0; i < INSTRUCTION_COUNT; i++)
{
int instruction_name_length = strlen(INSTRUCTION_NAMES[i]);
if (memcmp(INSTRUCTION_NAMES[i], input, instruction_name_length) == 0)
{
// make sure there is at least one character of whitespace after the command.
// if we don't check this, we might get false positives- add will trigger addi, etc..
if (!is_whitespace(input + instruction_name_length))
continue;
// we got a match!
// look up the function in the implementation array
instruction_function opcode_func = INSTRUCTION_IMPLEMENTATION[i];
// skip over the instruction name
input += instruction_name_length;
// call that bad boy
opcode_func(registers, input);
}
}
// we didn't find any matching opcode name. maybe it's a section specifier?
break;
}
}
|
C
|
#pragma once
#include "polyNTT.h"
struct FactorialNTT {
// High order first
static vector<int> multiplySlow(const vector<int>& left, const vector<int>& right, int mod) {
vector<int> res(left.size() + right.size() - 1);
for (int i = 0; i < int(right.size()); i++) {
for (int j = 0; j < int(left.size()); j++) {
res[i + j] = int((res[i + j] + 1ll * left[j] * right[i]) % mod);
}
}
return res;
}
// It works when M <= 998244353 (119 * 2^23 + 1, primitive root = 3)
// (x + a)(x + a + 1)(x + a + 2)...(x + k)
// left = a, right = k
// High order first
static vector<int> multiplyRisingFactorialSmall(int left, int right, int mod, int root) {
int n = right - left + 1;
if (n < 128) {
vector<int> res = vector<int>{ 1, left };
for (int i = left + 1; i <= right; i++)
res = multiplySlow(res, vector<int>{ 1, i }, mod);
return res;
}
vector<vector<int>> poly;
NTT ntt(mod, root);
poly.push_back(vector<int>{ 1, left });
for (int i = left + 1; i <= right; i++) {
int j = 0;
while (j < int(poly.size()) && !(poly[j].size() & (poly[j].size() - 1)))
j++;
if (j >= int(poly.size()))
poly.push_back(vector<int>{ 1, i });
else
poly[j] = multiplySlow(poly[j], vector<int>{ 1, i }, mod);
// apply FFT
while (j > 0 && poly[j].size() == poly[j - 1].size()
&& (poly[j].size() & (poly[j].size() - 1)) == 0) {
if (poly[j].size() < 128)
poly[j - 1] = multiplySlow(poly[j - 1], poly[j], mod);
else
poly[j - 1] = ntt.multiply(poly[j - 1], poly[j]);
poly.erase(poly.begin() + j);
j--;
}
}
vector<int> res = poly.back();
for (int i = int(poly.size()) - 2; i >= 0; i--)
res = ntt.multiply(res, poly[i]);
return res;
}
// (x + a)(x + a + 1)(x + a + 2)...(x + k)
// left = a, right = k
// High order first
static vector<int> multiplyRisingFactorial(int left, int right, int mod) {
int n = right - left + 1;
if (n < 128) {
vector<int> res = vector<int>{ 1, left };
for (int i = left + 1; i <= right; i++)
res = multiplySlow(res, vector<int>{ 1, i }, mod);
return res;
}
vector<vector<int>> poly;
poly.push_back(vector<int>{ 1, left });
for (int i = left + 1; i <= right; i++) {
int j = 0;
while (j < int(poly.size()) && !(poly[j].size() & (poly[j].size() - 1)))
j++;
if (j >= int(poly.size()))
poly.push_back(vector<int>{ 1, i });
else
poly[j] = multiplySlow(poly[j], vector<int>{ 1, i }, mod);
// apply FFT
while (j > 0 && poly[j].size() == poly[j - 1].size()
&& (poly[j].size() & (poly[j].size() - 1)) == 0) {
if (poly[j].size() < 128)
poly[j - 1] = multiplySlow(poly[j - 1], poly[j], mod);
else
poly[j - 1] = PolyNTT::multiplyFast(poly[j - 1], poly[j], mod);
poly.erase(poly.begin() + j);
j--;
}
}
vector<int> res = poly.back();
for (int i = int(poly.size()) - 2; i >= 0; i--)
res = PolyNTT::multiplyFast(res, poly[i], mod);
return res;
}
};
|
C
|
#include <stdio.h>
int main(void)
{
int cup, ounce, tablespoon, teaspoon;
float pint;
printf("Enter the number of cups: ");
scanf("%d", &cup);
pint = cup / 2.0;
ounce = cup * 8;
tablespoon = ounce * 2;
teaspoon = tablespoon * 3;
printf("%d cups is %.2f pints.\n", cup, pint);
printf("%d cups is %d ounces.\n", cup, ounce);
printf("%d cups is %d tablespoons.\n", cup, tablespoon);
printf("%d cups is %d teaspoons.\n", cup, teaspoon);
return 0;
}
|
C
|
/*
Parallel and Distributed Computing Class
OpenMP
Practice 6 : Matrix * Matrix
Name : Obed N Munoz
*/
#include <stdio.h>
#include <omp.h>
#define ROWS_A 200
#define ROWS_B 200
#define COLS_A 200
#define COLS_B 200
int main ()
{
// Counters
int i, j, k;
float sum;
// Working matrix and vectors
float matrix_a[ROWS_A][COLS_B], matrix_b[ROWS_B][COLS_B], matrix_c[ROWS_A][COLS_B];
// Initializing Matrix and Vector
printf("\nInitializing Matrixes A[%d][%d] , B[%d][%d] ...\n", ROWS_A,COLS_A,ROWS_B,COLS_B);
for (i=0; i<ROWS_A; i++)
for (j=0; j<COLS_A; j++)
matrix_a[i][j] = j * i % 100;
for (i=0; i<ROWS_B; i++)
for(j=0; j<COLS_B; j++)
matrix_b[i][j] = j * i %100;
printf("\nStarting Multiplication MatrixA * MatrixB ...\n");
double start = omp_get_wtime();
// Parallelizing dot product for each column
#pragma omp parallel shared(matrix_a,matrix_b,matrix_c) private(i,j,k)
{
for ( i = 0 ; i < ROWS_A ; i++ )
for ( j = 0 ; j < COLS_B ; j++) {
for ( k = 0 ; k < ROWS_B ; k++)
sum = sum + matrix_a[i][k]*matrix_b[k][j];
matrix_c[i][j] = sum;
sum = 0;
}
}
double end = omp_get_wtime();
printf("\nMultiplication Vector * Matrix has FINISHED\n");
printf("\nExecution Time = %f\n",end - start);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
//Server includes
#include <sys/socket.h>
#include <netinet/in.h>
//HTML parsing library
//#include "gumbo.h"
#include <sys/stat.h>
//connection port
#define PORT 8080
#define IP "127.0.0.1"
static void read_file(FILE *fp, char **output, int *length);
int main(void) {
int serverSocket = 0;
//Creating a socket, AF_INET is for IPv4
if ((serverSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("Error in socket");
exit(EXIT_FAILURE);
}
//setting address
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_port = htons(PORT); //htons() is for converting TCP/IP network byte order.
address.sin_addr.s_addr = INADDR_ANY;//inet_addr(IP); //possible to use INADDR_ANY in order to access any incoming connections
memset(&address.sin_zero, 0, sizeof(address.sin_zero)); //IMPORTANT to clear sin_zero because of unexpected behavior!
//binding server
if (bind(serverSocket, (struct sockaddr*)&address, sizeof(address)) < 0) {
perror("Error in bind");
exit(EXIT_FAILURE);
}
//setting listen
if (listen(serverSocket, 10) < 0) {
perror("Error in listen");
exit(EXIT_FAILURE);
}
long valRead = 0;
int newSocket = 0;
int addrLen = sizeof(address);
//getHTML
const char *filename = "index.html";
FILE *fp = NULL;
fp = fopen(filename, "r");
if (!fp) {
perror("Error in file opening");
exit(EXIT_FAILURE);
}
char *input;
int input_length;
read_file(fp, &input, &input_length);
size_t size = 0;
fseek(fp, 0L, SEEK_END);
size = ftell(fp);
char *sizeStr = (char *)malloc(1000 * sizeof(char));
sprintf(sizeStr, "%ld", size);
printf("%s\n", sizeStr);
char *send = malloc(1000 * sizeof(char));
stpcpy(send, "HTTP/1.1 200 OK\nContent-Type: text/html;charset=UTF-8\nContent-Length: ");
strcat(send, sizeStr);
strcat(send, "\n\n");
strcat(send, input);
while(1) {
printf("Waiting for a connection.\n");
if ((newSocket = accept(serverSocket, (struct sockaddr*)&address, (socklen_t*)&addrLen)) < 0) {
perror("Error in accept");
exit(EXIT_FAILURE);
}
printf("Connection accepted.\n");
char buffer[30000] = {0};
valRead = read(newSocket, buffer , sizeof(buffer));
printf("%s\n", buffer);
write(newSocket, send, strlen(send));
printf("Sent\n");
if (close(newSocket) < 0) {
perror("Error in close");
exit(EXIT_FAILURE);
}
printf("Connection closed.\n");
exit(EXIT_SUCCESS);
}
return 0;
}
static void read_file(FILE *fp, char **output, int *length) {
struct stat filestats;
int fd = fileno(fp);
fstat(fd, &filestats);
*length = filestats.st_size;
*output = malloc((*length) + 1);
int start = 0;
int bytes_read;
while ((bytes_read = fread(*output + start, 1, *length - start, fp))) {
start += bytes_read;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <stdarg.h>
#include "instructions.h"
#include "stack.h"
#include "table.h"
// "Private" methods to break up our work here.
static void readInstructions(FILE * fp);
static void discardline(FILE * fp);
static void execute();
int main(int argc, char * argv[]){
//First things first. Open the input file.
FILE *fp;
int i = 0;
if (argc != 2 || (fp = fopen(argv[1], "r")) == NULL) {
printf("File open failed.\nUsage: %s <input file>\n",argv[0]);
exit(1);
}
// initialize the symbol table, jump table and stack to 0
// method will be in instructions.c
initialize();
// read the input file and prepare structures
readInstructions(fp);
// Close the file.
fclose(fp);
// Begin to interpret
execute();
// debugging purposes...
printTables();
printf("\nProgram halted\n");
}
void readInstructions(FILE * fp)
{
int address = 0;
char opcode[OPCODE_SIZE];
char operand[OPERAND_SIZE];
printf("\n** Output **\n\n");
while(fscanf(fp, "%s", opcode) != EOF){
// operand check(read into operand var)
if(hasOperand(opcode)){
fscanf(fp, "%s", operand);
} else{
operand[0] = 0;
}
// insert the instruction into the instruction table
insertInstruction(address, opcode, operand);
address++;
// discard any possible comments on current line
discardline(fp);
}
}
void execute()
{
//printInstructionTable();
int pc = 0;
char opcode[OPCODE_SIZE];
char operand[OPERAND_SIZE];
while(strcmp(opcode, "halt")){
fetchInstruction(pc, opcode, operand);
// execution of current instruction
if(strcmp(opcode, "nop") == 0){pc = nop(pc);}
else if(strcmp(opcode, "add") == 0){pc = add(pc);}
else if(strcmp(opcode, "sub") == 0){pc = sub(pc);}
else if(strcmp(opcode, "mul") == 0){pc = mul(pc);}
else if(strcmp(opcode, "divide") == 0){pc = divide(pc);}
else if(strcmp(opcode, "get") == 0){pc = get(pc, operand);}
else if(strcmp(opcode, "put") == 0){pc = put(pc, operand);}
else if(strcmp(opcode, "push") == 0){pc = push(pc, operand);}
else if(strcmp(opcode, "pop") == 0){pc = pop(pc, operand);}
else if(strcmp(opcode, "not") == 0){pc = not(pc);}
else if(strcmp(opcode, "and") == 0){pc = and(pc);}
else if(strcmp(opcode, "or") == 0){pc = or(pc);}
else if(strcmp(opcode, "testeq") == 0){pc = testeq(pc);}
else if(strcmp(opcode, "testne") == 0){pc = testne(pc);}
else if(strcmp(opcode, "testlt") == 0){pc = testlt(pc);}
else if(strcmp(opcode, "testle") == 0){pc = testle(pc);}
else if(strcmp(opcode, "testgt") == 0){pc = testgt(pc);}
else if(strcmp(opcode, "testge") == 0){pc = testge(pc);}
else if(strcmp(opcode, "jump") == 0){pc = jump(pc, operand);}
else if(strcmp(opcode, "jf") == 0){pc = jf(pc, operand);}
}
}
// discard rest of line (good for comments)
void discardline(FILE * fp)
{
int newline;
do
{
newline = fgetc(fp);
} while ((char)newline != '\n' && (newline != EOF));
}
|
C
|
#ifndef MOD_INVERSE_ALG_IMPORTED
#include "extended_grade_common_devider_alg.h"
#define MOD_INVERSE_ALG_IMPORTED
// Function to find modulo inverse of a
int mod_inverse(int a, int m)
{
int x, y;
int g = ext_gcd(a, m, &x, &y);
if (g != 1)
return -1; // Error: it`s impossible to find inverse value, -1 not in [0, m-1] so impossible value
else
{
// m is added to handle negative x
int res = (x%m + m) % m;
return res;
}
}
// Driver Program
/* int main(void) { */
/* int a = 3; */
/* int b = 7; */
/* printf("Mod invers of %d by %d is %d", a, b, mod_inverse(a, b)); */
/* return 0; */
/* } */
#endif
|
C
|
#include <stdio.h>
/**
* main -Entry point
* Descripcion:
* Return: 0
*/
int main(void)
{
int i;
long int na = 0;
long int ne = 1;
long int fibo;
for (i = 0; i < 50; i++)
{
fibo = ne + na;
na = ne;
ne = fibo;
if (i != 49)
{
printf("%ld, ", fibo);
}
else
{
printf("%ld\n", fibo);
}
}
return (0);
}
|
C
|
/**
******************************************************************************
* main.c
* Matt Saiki
* Session 6 - Morse Code Headlight
*
******************************************************************************
*/
#include "comp494.h"
#include "gpio.h"
#include "morse.h"
#define DLY_CNT_TICK 10000
int main(void)
{
int TickDlyCnt;
//Initialize the hardware, turn on the LED
GpioInit();
GPIO_LED_ENA();
//Wait for the button to be pressed
while(!GPIO_PB_IS_PRESSED())
;
//Turn off the LED
GPIO_LED_DIS();
// Initialize the Morse Code state machine with the string to be sent
// Passing the address of the string
// Char * in init
MorseStateMachineInit("USD 2017");
//Main loop
while(TRUE)
{
// Pace the tick timer
for(TickDlyCnt = 0; TickDlyCnt < DLY_CNT_TICK; TickDlyCnt++)
;
// Clock the state machine
MorseStateMachineClock();
//If the string has been sent, resend it
if (MorseStateMachineIsIdle())
{
MorseStateMachineInit("USD 2017");
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int tribonacci(int number){
if (number == 0 || number == 1)
return 0;
if (number == 2)
return 1;
return tribonacci(number -1) + tribonacci(number - 2) + tribonacci(number - 3);
}
int main(){
printf("%d", tribonacci(8));
return 0;
}
|
C
|
#include<stdio.h>
int main(){
int i,j;
for(i=1;i<=4;i++){
char a='A';
for(j=1;j<=7;j++){
if(j>=5-i+1 && j<=2+i){
printf(" ");
if(j==4)
a--;
}else{
printf("%c",a);
j<4?a++:a--;
}
}
printf("\n");
}
return 0;
}
/*
ABCDCBA
ABC CBA
AB BA
A A
*/
|
C
|
/* cbits
* $ gcc -fPIC -shared cbits.c -o cbits.so
* $ clang -fPIC -shared cbits.c -o cbits.so
* */
#include "stdio.h"
double printPretty(double x) {
putchar((char) x);
fflush(stdout);
return 0;
}
|
C
|
#include "checkend.h"
int checkend(int diff)
{
int i = 0;
int j = 0;
int sumend = 0;
for(i=1;i<heigh+1;i+=1)
{
for(j=1;j<width+1;j+=1)
{
sumend += ntable[i][j];
}
}
if((500-diff)==sumend)
return 1;
else return 0;
}
|
C
|
#include "sh.h"
t_token *get_last_token(t_token *t)
{
t_token *r;
r = t;
while (r->next != NULL)
r = r->next;
return (r);
}
int right_row(t_token *t)
{
t_token *first;
first = t;
while (first->next)
{
if (first->type == first->next->type)
return (0);
first = first->next;
}
return (1);
}
int get_priority(char *s)
{
//if (ft_strcmp(s, BK) == 0)
//return ()
if (ft_strcmp(s, OR) == 0)
return (2);
if (ft_strcmp(s, AND) == 0)
return (2);
if (ft_strcmp(s, PIPE) == 0)
return (3);
if (ft_strcmp(s, SC) == 0)
return (1);
}
int is_tokens_true(t_token *t)
{
t_token *tmp;
tmp = t;
while (t)
{
if (ft_strcmp(t->data, BK) == 0 ||
ft_strcmp(t->data, OR) == 0 ||
ft_strcmp(t->data, AND) == 0 ||
ft_strcmp(t->data, PIPE) == 0 ||
ft_strcmp(t->data, SC) == 0)
{
t->type = cmd;
t->priority = get_priority(t->data);
}
else
t->type = ext;
t = t->next;
}
if (right_row(tmp))
return (1);
else
return (0);
}
t_token *init_token(void)
{
t_token *new;
if(!(new = (t_token *)malloc(sizeof(t_token))))
return (NULL);
new->data = NULL;
new->priority = 0;
new->next = NULL;
new->prev = NULL;
return (new);
}
|
C
|
// move forwards or backwards
if ((keyDown[38]) || (keyPress[38]))
upArrowKeyPressed = TRUE;
if ((keyDown[40]) || (keyPress[40]))
downArrowKeyPressed = TRUE;
if ((keyUp[38]) && (!keyPress[38]))
upArrowKeyPressed = FALSE;
if ((keyUp[40]) && (!keyPress[40]))
downArrowKeyPressed = FALSE;
if ((upArrowKeyPressed) && (!downArrowKeyPressed))
{
upArrowKeyFirst = TRUE;
downArrowKeyFirst = FALSE;
}
if ((!upArrowKeyPressed) && (downArrowKeyPressed))
{
upArrowKeyFirst = FALSE;
downArrowKeyFirst = TRUE;
}
// toggle forwards or backwards depending on which was pressed first
forwardBackwardToggle = 0;
forward = 0;
backward = 0;
if ((upArrowKeyPressed) && (downArrowKeyPressed))
{
if (upArrowKeyFirst)
forwardBackwardToggle = 1;
if (downArrowKeyFirst)
forwardBackwardToggle = 2;
}
if (forwardBackwardToggle != 1)
if (upArrowKeyPressed)
{
forward = 12.0;
backward = 0;
}
if (forwardBackwardToggle != 2)
if (downArrowKeyPressed)
{
forward = 0;
backward = -12.0;
}
// turn left or right
if ((keyDown[37]) || (keyPress[37]))
leftArrowKeyPressed = TRUE;
if ((keyDown[39]) || (keyPress[39]))
rightArrowKeyPressed = TRUE;
if ((keyUp[37]) && (keyPress[37]))
leftArrowKeyPressed = FALSE;
if ((keyUp[39]) && (keyPress[39]))
rightArrowKeyPressed = FALSE;
if ((leftArrowKeyPressed) && (!rightArrowKeyPressed))
{
leftArrowKeyFirst = TRUE;
rightArrowKeyFirst = FALSE;
}
if ((!leftArrowKeyPressed) && (rightArrowKeyPressed))
{
leftArrowKeyFirst = FALSE;
rightArrowKeyFirst = TRUE;
}
// toggle left or right depending on which was pressed first
leftRightToggle = 0;
turnLeft = 0;
turnRight = 0;
if ((leftArrowKeyPressed) && (rightArrowKeyPressed))
{
if (leftArrowKeyFirst)
leftRightToggle = 1;
if (rightArrowKeyFirst)
leftRightToggle = 2;
}
if (forward)
{
if (leftRightToggle != 1)
if (leftArrowKeyPressed)
turnLeft = 6;
if (leftRightToggle != 2)
if (rightArrowKeyPressed)
turnRight = -6;
}
if (backward)
{
if (leftRightToggle != 1)
if (leftArrowKeyPressed)
turnLeft = -6;
if (leftRightToggle != 2)
if (rightArrowKeyPressed)
turnRight = 6;
}
if ((!forward) && (!backward))
{
if (leftRightToggle != 1)
if (leftArrowKeyPressed)
turnLeft = 6;
if (leftRightToggle != 2)
if (rightArrowKeyPressed)
turnRight = -6;
}
turnLeftRight += turnLeft + turnRight;
// jump
if ((keyDown[32]) || (keyPress[32]))// space key
jumpUp = TRUE;
// end jump
if ((keyUp[32]) && (!keyPress[32]))// space key
{
alreadyJumped = FALSE;
jumpUp = FALSE;
}
// lift up or put down object
if (keyPress[88])// x key
liftPutDownObj = TRUE;
// move camera
if (keyDown[33])// page up key
moveCloser = TRUE;
if (keyDown[34])// page down key
moveAway = TRUE;
if (!keyDown[33])// page up key
moveCloser = FALSE;
if (!keyDown[34])// page down key
moveAway = FALSE;
if (keyPress[27])// Esc
{
// exit from the game scene first
if ((viewMainMenu) && (sceneNumber == 0))
{
exitMsg = 1;
}
else
{
sceneNumber = 0;
viewMainMenu = 1;
viewControls = 0;
viewOptions = 0;
resetScene = TRUE;
}
}
|
C
|
/*-------------------------------------------------------
ԶİʱȡĿͼFFT㷨
ܣԶгȲ2Ĵݵĩβ0Ϊ2Ĵݵijȣ
ȻʹðʱȡDITĿͼFFT㷨DFT任
أźŴ
ʱ䣺2014-12-05
ģ2014-12-27 ӳģ
-------------------------------------------------------
ģ飺
1帴ĽṹӺ
2
2.1
2.2ı䳤ȣʹ֮2ĴݣIJ
2.3ʼ任
2.4ַ,λ
2.5
2.6
3Ӻ
2.1
2.2
2.3ʼ任
2.4ַ,λ
2.5
2.6
2.7㡢˷
4
--------------------------------------------------------
еıԼȫֱ
1
(1)size_x=0 //еĴСʼΪ0;
(2)Len_x //еij;
(3)pow2_Len //г2ΪĶ;
(4)complexrealimg;//ʵ鲿
2
(1)N //Ϊ궨壬в
--------------------------------------------------------
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define N 1024
/*帴*/
typedef struct {
double real;
double img;
} complex;
complex x[N], *W; /*,任*/
/*Ӻ*/
int inputdata(size_x);//
void changeLen(size_x, Len_x);/*ı䳤ȣʹ֮2ĴݣIJ*/
void fft(Len_x); /*ٸҶ任*/
void initW(Len_x); /*ʼ任*/
void bit_reversed_order(Len_x); /*ַ,λ*/
void output(Len_x);/**/
void add(complex a, complex b, complex *c); /*ӷ*/
void multiply(complex a, complex b, complex *c); /*˷*/
void sub(complex a, complex b, complex *c); /**/
//---------------------------------------------------------
/* */
void main() {
int size_x = 0;/*еĴС*/
int pow2_Len, Len_x = 0;
size_x = inputdata();
pow2_Len = (int)(ceil(log(size_x) / log(2)) + 0.5);//г2ΪĶ
Len_x = (int)(pow(2, pow2_Len) + 0.5);//еij
if ((Len_x - size_x) != 0)changeLen((size_x, Len_x));//
initW(Len_x);//ʼ任
bit_reversed_order(Len_x);//λ
fft(Len_x);//μ
output(Len_x);//
system("pause");
}
//---------------------------------------------------------
//ֵõӺ
/*뺯*/
int inputdata() {
char c = 'y';//ַʼֵΪy
int size_x = 0, i = 0;
printf("ԭʼxijȣ");
scanf_s("%d", &size_x);//ԭʼеij
getchar();//ջس
printf("\nǷΪ?(Y/N) ");//ʵУ붼0鲿鷳һifж
scanf_s("%c", &c, 1);//ַcжǷΪʵ
if ((c == 'Y') || (c == 'y')) { //Ǹ
printf("\nԭʼx[N]ʵ鲿:\n");
for (i = 0; i < size_x; i++)
scanf_s("%lf%lf", &x[i].real, &x[i].img);
}//ֱʵ鲿
else { //ʵ
printf("\nԭʼx[N]ʵ:\n");//ֱʵ
for (i = 0; i < size_x; i++) {
scanf_s("%lf", &x[i].real);//ʵ
x[i].img = 0.0000;
}//鲿ֵΪ0
}
return size_x;//ԭʼеij
}
/*㣺ı䳤ȣʹ֮2ĴݣIJ*/
void changeLen(size_x, Len_x) {
int i;
for (i = size_x; i < Len_x; i++) { //ʣLen_x-size_xԪظֵΪ0
x[i].real = 0.0000;
x[i].img = 0.0000;
}
}
//-------------------------------------------------------
/*
˵
(1)η
FFTΪpow2_Len(1=0...pow2_Len-1)
iΪ(Len_x/2L)飬ÿһ2L=2*(2^i)Ԫأ
ÿһLҪLε㣬ͬʱÿһ±ҲL
ڵiУ
j=j+2LȷÿһĵһԪص±꣬kʾĵkε
(2)
õ֮ǰĸӺ
*/
void fft(Len_x) { //ԭĽİʱȡFFT㷨αP444
int i = 0, j = 0, k = 0, L = 0;
complex up, down, product;//мֵ
for (i = 0; i < log(Len_x) / log(2); i++) { //һ,Ϊi
L = 1 << i;//ʹL=pow(2,i)ԴﵽͬЧǽλҪת
for (j = 0; j < Len_x; j = j + 2 * L) { //һ㣬j,ÿLε㣬ÿӦԪ2L
for (k = 0; k < L; k++) { //һ,±
multiply(x[j + k + L], W[Len_x*k / 2 / L], &product);//һοP444ͼ11.23
add(x[j + k], product, &up);
sub(x[j + k], product, &down);
x[j + k] = up;//νǸDzοͼ11.23
x[j + k + L] = down;//εĽ±L
}
}
}
}
//-------------------------------------------------------
/*ʼ任*/
void initW(Len_x) {
int i;
double PI;
PI = atan(1) * 4;//Բ,ȻҲú궨壬ֱӸֵ
W = (complex *)malloc(sizeof(complex) * Len_x);/*ٴСsizeof(complex)Len_xڴռ,
<stdlib.h>*/
for (i = 0; i < Len_x; i++) {
W[i].real = cos(2 * PI / Len_x * i);//任ӵʵ
W[i].img = -1 * sin(2 * PI / Len_x * i);//任ӵ鲿
}
}
//--------------------------------------------------------
/*
ܣַ㣬x(n)λ
˵תΪƺλıʵְλҾ
ʹλɣԭ±iĶưλƺͶ1㣬
ȻõƵһjУ±תɣ
ʹһõ±ݽΪгȵһ
*/
void bit_reversed_order(Len_x) {
complex temp;
unsigned short i = 0, j = 0, k = 0;
double t = 0;
for (i = 0; i < Len_x; i++) { //±iתj
k = i;//iֵkΪλkֵб仯iʱʹ
j = 0;
t = (log(Len_x) / log(2));//±תɶƺtλҪtλ
while ((t--) > 0) {
j = j << 1;//ڱλ
j = j | (k & 1);// k1λ㣬j(k & 1)λ
k = k >> 1;//λȡɵ͵ߵĸ
}
if (j > i) { //ijj>iŽDZ֤±ӦԪزᱻ
temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}//for
}
//------------------------------------------------------------
/*Ҷ任Ľ*/
void output(Len_x) {
int i;
printf("\nFFT任Ϊ\n");
for (i = 0; i < Len_x; i++) {
printf("%.4f", x[i].real);
if (x[i].img >= 0.0001)
printf("+%.4fj\n", x[i].img);//鲿0.0001+鲿
else
if (fabs(x[i].img) < 0.0001)printf("\n");// fabs:xľֵ
else printf("%.4fj\n", x[i].img);//鲿С0.0001ֱԴţ
}
}
//----------------------------------------------------------------
/*
ܣ帴
˵ ָͨ뱣עﲻκֵΪȫֱ
*/
//帴ӷĺ
void add(complex a, complex b, complex *c)
{
c->real = a.real + b.real;
c->img = a.img + b.img;
}
//帴˷ĺ
void multiply(complex a, complex b, complex *c)
{
c->real = a.real*b.real - a.img*b.img;
c->img = a.real*b.img + a.img*b.real;
}
//帴ĺ
void sub(complex a, complex b, complex *c)
{
c->real = a.real - b.real;
c->img = a.img - b.img;//ṹָp->Աȼڣ*p.Ա
}
|
C
|
#include <stdio.h>
#include <cs50.h>
int main(void)
{
char x = 'a';
char y = 'z';
char z = 'A';
char u = 'Z';
printf("%i, %i, %i, %i", x,y,z,u);
string s = "HELLO";
printf("%c", s[1]);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,h,m,s,i,dia[2],hora[2],minuto[2],segundo[2];
char li[3],xo[3];
printf("Dia ");
scanf("%d",&n);
scanf("%d%s%d%s%d\n",&h,&li,&m,&xo,&s);
dia[0]=n;
hora[0]=h;
minuto[0]=m;
segundo[0]=s;
printf("Dia ");
scanf("%d",&n);
scanf("%d%s%d%s%d",&h,&li,&m,&xo,&s);
dia[1]=n;
hora[1]=h;
minuto[1]=m;
segundo[1]=s;
if(hora[0]<=hora[1] && minuto[0]<=minuto[1] && segundo[0]<=segundo[1]){
printf("%d dia(s)\n",dia[1]-dia[0]);
}else{
if(hora[0]<=hora[1] && minuto[0]<=minuto[1] && segundo[0]<=segundo[1]){
printf("%d dia(s)\n",dia[1]-dia[0]-1);
}else{
if(hora[0]>=hora[1] && minuto[0]<=minuto[1] && segundo[0]<=segundo[1]){
printf("%d dia(s)\n",dia[1]+30-dia[0]);
}else{
printf("%d dia(s)\n",dia[1]+30-dia[0]-1);
}
}
}
if(hora[0]<=hora[1] && minuto[0]<=minuto[1] && segundo[0]<=segundo[1]){
printf("%d hora(s)\n",hora[1]-hora[0]);
}else{
if(hora[0]>=hora[1] && minuto[0]<=minuto[1] && segundo[0]<=segundo[1]){
printf("%d hora(s)\n",(hora[1]+24)-hora[0]);
}else{
if(hora[0]<=hora[1] && minuto[0]>=minuto[1]){
printf("%d hora(s)\n",hora[1]-hora[0]-1);
}else{
printf("%d hora(s)\n",(hora[1]+24)-hora[0]-1);
}
}
}
if(minuto[0]<=minuto[1] && segundo[0]<=segundo[1]){
printf("%d minuto(s)\n",minuto[1]-minuto[0]);
}else{
if(minuto[0]<=minuto[1] && segundo[0]>=segundo[1]){
printf("%d minuto(s)\n",minuto[1]-minuto[0]-1);
}else{
if(minuto[0]>=minuto[1] && segundo[0]<=segundo[1]){
printf("%d minuto(s)\n",(minuto[1]+60)-minuto[0]);
}else{
printf("%d minuto(s)\n",(minuto[1]+60)-minuto[0]-1);
}
}
}
if(segundo[0]<=segundo[1]){
printf("%d segundo(s)\n",segundo[1]-segundo[0]);
}else{
printf("%d segundo(s)\n",(segundo[1]+60)-segundo[0]);
}
return 0;
}
|
C
|
#include <poll.h>
#include <stdio.h>
static void choose(int *po1, int *po2)
{
struct pollfd as[2];
as[0].fd = *po1;
as[0].events = POLLIN;
as[1].fd = *po2;
as[1].events = POLLIN;
if (poll(as, 2, 5*1000) < 0)
perror("poll");
if ((as[0].revents&POLLIN) == 0)
*po1 = -1;
if ((as[1].revents&POLLIN) == 0)
*po2 = -1;
}
|
C
|
/*********************************
Description:
**********************************/
#include <stdio.h>
#include <errno.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <signal.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/shm.h>
#include <time.h>
#include "messageType.h"
#include "sharedIds.h"
#include "constants.h"
#include "pcbType.h"
#define SIMPID 1
#define PCBIND 2
void sigquit_handler (int sig);
void attachShmMsg();
int rcvMsg();
void sendMsg(int, const char *);
int getRandBetween(int ,int );
int getRequestType();
int getProbability();
void freePcb(int);
int msqid, activeCounterId, sharedClockId, pcbsId;
int * sharedIds;
int * activeCounter, * sharedClock;
pcb_t * pcbs;
int main( int argc, char * argv[]) {
int address, pcbLoc, simpid, i;
int * waitQueue = (int*) calloc(MAX_PROCESSES, sizeof(int)); // stores indecies of processes in the process table
signal(SIGQUIT, sigquit_handler);
// signal handler to catch sigquit sent from oss.
attachShmMsg();
// setup the message queue and the shared memory.
pcbLoc = atoi(argv[PCBIND]);
simpid = atoi(argv[SIMPID]);
// get the index of the pcb also get the simpid
pcbs[pcbLoc].simpid = simpid;
pcbs[pcbLoc].pid = getpid();
// get the simulated pid to the pcb location.
for(i = 0; i < PAGE_SIZE; i++ ) {
if(getProbability()) {
// address should be valid 75% of the time.
address = getRandBetween(0, PAGE_SIZE);
// will be an integer between 0 and the limit of process memory (2^15)
} else {
// page fault should happen
address = 999999999;
// guarentee a page fault will happen since this process only has 2^15 valid frame locations
}
if( getRequestType()) { // 50/50 chance of being either a request or a write.
// handle a read request here
char msg[MAX_MSG];
sprintf(msg, "Process %d is requesting to read address %d at time %d:%d", getpid(), address,sharedClock[CLOCK_SEC], sharedClock[CLOCK_NS] );
sendMsg(REQ_READ, msg);
} else {
// handle a write here.
char msg[MAX_MSG];
sprintf(msg, "Process %d is requesting write of address %d at time %d:%d", getpid(), address,sharedClock[CLOCK_SEC], sharedClock[CLOCK_NS]);
sendMsg(REQ_WRITE, msg);
}
if( rcvMsg() == -1 ) break;
// wait to receive a message
// will terminate the process if a pagefault is returned..
}
freePcb(pcbLoc);
// release the pcb.
shmdt(activeCounter);
shmdt(sharedClock);
shmdt(pcbs);
return 0;
}
void freePcb(int i) {
// replace the pcb in the process table
pcb_t newPcb;
pcbs[i] = newPcb;
}
int getPcbInd(char * simpid) {
int i = -1;
int assigned = 0;
printf("here from userProc\n");
int simpidInt = atoi(simpid);
for(; i< MAX_PROCESSES; i++) {
if(pcbs[i].simpid == simpidInt) break;
if ( i == MAX_PROCESSES && !assigned) i = 0;
}
return i;
}
int getRequestType() {
// 50% chance of a 0 or a 1
// 1 indicates you should send a request and 0 a write.
return rand() & 1;
}
int getProbability() {
// probability will either be 0 or 1.
// The chance that a 1 will be sent is 75% and 0 is 25%
// 1 indicates a to get a valid, and 0 indicates a an invalid address.
srand(time(NULL) * getpid());
return (rand() & 1) | (rand() & 1);
}
int rcvMsg() {
struct msg_t messageData;
msgrcv(msqid, &messageData, sizeof(messageData), 0, MSG_NOERROR);
// wait for a message to come back from a child proces.
switch(messageData.msgType) {
case GRANTED: { return 1;}
case PAGE_FAULT: {return -1;}
}
return 0;
}
void sendMsg(int msgType, const char * message) {
// wrapper function to send a message to oss.
struct msg_t messageData;
messageData.msgType = msgType;
// assign the type of message to be sent.
strcpy(messageData.message, message);
// cpy the message to the structure.
if ( msgsnd(msqid, (void*)&messageData, MAX_MSG, 0) == -1) {
// check that the message sent.
perror("User_proc: sendMsg");
if(errno == EIDRM) printf("errno = EIDRM");
exit(0);
}
}
void sigquit_handler (int sig){
// handle cleanup section by removing any remaining shared memory, or message queues.
shmdt(activeCounter);
shmdt(sharedClock);
exit(0);
}
void attachShmMsg() {
key_t sharedIdKey;
int sharedIdsId;
sharedIdKey = ftok("userProcess.c", 'Z');
sharedIdsId = shmget(sharedIdKey, 5* sizeof(int), IPC_CREAT | 0644);
sharedIds = (int * ) shmat(sharedIdsId, NULL, 0);
// setup shared memory.
if(sharedIdKey == -1) {
// check for all valid keys.
perror("Error: User Process: ftok failed ");
exit(1);
}
if(sharedIdsId == -1){
// check that all ids were valid.
perror("Error: User Process: invalid shared id ");
exit(1);
}
if (sharedIds == NULL){
// check for errors attaching to shared memory.
perror("Error: User Process: not attached to valid shared memory. ");
exit(1);
}
msqid = sharedIds[MSGQ_IND];
activeCounterId = sharedIds[ACTIVE_IND];
sharedClockId = sharedIds[CLOCK_IND];
pcbsId = sharedIds[PCB_IND];
// set globals ids from shared ids.
sharedClock = (int*) shmat(sharedClockId, NULL, 0);
// get the active counter shared memory.
pcbs = (pcb_t*) shmat(pcbsId, NULL,0);
// attach to the process table.
}
int getRandBetween(int min, int max) {
srand(getpid()*max);
return (rand() % (max - min + 1)) + min;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
int root(int n)
{
return (int)sqrt((float)n);
}
void f_Prime6(int n)
{
int i = 0;
int j = 0;
int k = 0;
int count = 0;
int*p = (int*)malloc(sizeof(int)*(n + 1));
// ʼÿһԪض1
for (i = 0; i < n + 1; i++)
{
p[i] = 1;
}
//printf("prime = 2\n");
count = 1;
// С2Դ2ʼÿһıΪ0.һΪ0Ϊ
for (i = 2; i <= n; i = k)
{
for (j = 2; i*j <= n; j++)
{
p[i*j] = 0;
}
// һΪ0Ϊ
for (k = i + 1; k <= n; k++)
{
if (1 == p[k])
{
//printf("prime = %d\n", k);
count++;
break;
}
}
}
printf("f_prime6 = %d\n",count);
}
int f_isPrime5(int n)
{
int i = 0;
if (n < 2)
{
return 0;
}
if ((0 == n % 2) && (n != 2))
{
return 0;
}
if ((0 == n % 3) && (n != 3))
{
return 0;
}
if ((0 == n % 5) && (n != 5))
{
return 0;
}
for (i = 2; i*i<=n; i++)
{
if (0 == n % i)
{
return 0;
}
}
return 1;
}
int f_isPrime4(int n)
{
int i = 0;
int m = 0;
if (n < 2)
{
return 0;
}
if ((0 == n % 2) && (n != 2))
{
return 0;
}
if ((0 == n % 3) && (n != 3))
{
return 0;
}
if ((0 == n % 5) && (n != 5))
{
return 0;
}
m = root(n);
for (i = 2; i <= m; i++)
{
if (0 == n % i)
{
return 0;
}
}
return 1;
}
int f_isPrime3(int n)
{
int i = 0;
int m = 0;
if (n < 2)
{
return 0;
}
m = root(n);
for (i = 2; i <= m; i++)
{
if (0 == n % i)
{
return 0;
}
}
return 1;
}
int f_isPrime2(int n)
{
int i = 0;
if (n < 2)
{
return 0;
}
for (i = 2; i <= root(n); i++)
{
if (0 == n % i)
{
return 0;
}
}
return 1;
}
int f_isPrime1(int n)
{
int i = 0;
if (n < 2)
{
return 0;
}
for (i = 2; i < n; i++)
{
if (0 == n % i)
{
return 0;
}
}
return 1;
}
int main()
{
int i = 0;
int j = 0;
int n = 10000;
int count[6] = {0};
for (i = 2; i <= n; i++)
{
if (1 == f_isPrime1(i))
{
//printf("%d\n", i);
count[0]++;
}
if (1 == f_isPrime2(i))
{
//printf("%d\n", i);
count[1]++;
}
if (1 == f_isPrime3(i))
{
//printf("%d\n", i);
count[2]++;
}
if (1 == f_isPrime4(i))
{
//printf("%d\n", i);
count[3]++;
}
if (1 == f_isPrime5(i))
{
//printf("%d\n", i);
count[4]++;
}
}
for (j = 0; j < 5; j++)
{
printf("f_prime%d = %d\n", j+1, count[j]);
}
f_Prime6(n);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>
#include<string.h>
#include<stdarg.h>
BOOL create_child_process(const char *cmd_str, const char* current_directory);
BOOL load_config(const char* path, char* command, size_t size);
void Error(const char* error_str);
void basename(const char *path, char *name);
void basename_noext(const char *path, char *name);
BOOL file_exists(const char *path);
const char* rprintf(const char* fmt, ...);
int main(int argc, char *argv[])
{
char name[FILENAME_MAX];
basename_noext(argv[0], name);
const char *lua_start_file = "starter\\start.lua";
if (!file_exists(lua_start_file)) {
Error(rprintf(": ûҵluaļ\n"
"鷳һ£ %s\n", lua_start_file));
}
int is_ok;
char command[MAX_PATH];
sprintf(command, "starter\\lua\\wlua5.1.exe %s %s", lua_start_file, name);
/* int is_ok = load_config(config_path, command, MAX_PATH); */
/* if (!is_ok) { */
/* Error(rprintf(": ûҵļ\n" */
/* "鷳һ£ %s\n", config_path)); */
/* return 0; */
/* } */
is_ok = create_child_process(command, NULL);
if (!is_ok) {
Error(rprintf("(%s)ʧܡ\n"
"ţע·exeļġ\n", command));
}
return 0;
}
BOOL load_config(const char* path, char* command, size_t size)
{
FILE* config_file = fopen(path, "r");
if (config_file == NULL) {
command[0] = '\0';
return FALSE;
}
fgets(command, size, config_file);
if (command[strlen(command) - 1] == '\n')
command[strlen(command) - 1] = '\0';
return TRUE;
}
void Error(const char* error_str)
{
MessageBox(NULL, TEXT(error_str), TEXT(""), MB_OK);
}
/*
һ̡
cmd_str ̵·ҪעԱstarterǰĿ¼·
current_directory ӽ̵ĵǰĿ¼NULL̳и̵á
*/
BOOL create_child_process(const char *cmd_str, const char* current_directory)
{
STARTUPINFO start_info;
PROCESS_INFORMATION process_info;
ZeroMemory(&start_info, sizeof(start_info)); // Ϣṹ ( ൱ memset 0, Чʸ )
start_info.cb = sizeof(start_info); // ýṹСcbӦΪṹĴС
ZeroMemory(&process_info, sizeof(process_info)); // Ϣṹ
// תΪ·
char path[MAX_PATH];
GetFullPathName(current_directory, MAX_PATH, path, NULL);
// ˵CreateProcessĵڶֻڴ
char* cmd_str_ = malloc(strlen(cmd_str) + 1);
strcpy(cmd_str_, cmd_str);
BOOL is_ok = CreateProcess(
NULL, // ·, ʹ
cmd_str_, //
NULL, // ̳н̾(Ĭ)
NULL, // ̳߳̾(Ĭ)
FALSE, // ̳о(Ĭ)
0, // ûд־(Ĭ)
NULL, // ʹĬϻ
current_directory == NULL? NULL : path, // ַǴŵľ·ΪNULLʹø̵Ŀ¼
&start_info, // STARTUPINFO ṹ
&process_info );// PROCESS_INFORMATION Ϣ
free(cmd_str_);
if (!is_ok)
{
// ʧ
/* printf( "Error: δҵ (%d).\n", GetLastError() ); */
return FALSE;
}
// ȴӽ̽
// ʹõͨ PROCESS_INFORMATION ṹȡӽ̵ľ hProcess
WaitForSingleObject(process_info.hProcess, INFINITE);
// رս̾߳̾
CloseHandle(process_info.hProcess);
CloseHandle(process_info.hThread);
return TRUE;
}
void basename(const char *path, char *name)
{
int name_top = 0;
for (int i = (int)strlen(path) - 1; i >= 0 && path[i] != '/' && path[i] != '\\'; i--) {
if (path[i] != '\0' ) {
name[name_top++] = path[i];
}
}
int name_size = name_top;
for (int i = 0; i < name_size / 2; i++) {
char tmp = name[i];
name[i] = name[name_size - i - 1];
name[name_size - i - 1] = tmp;
}
name[name_size] = '\0';
}
void basename_noext(const char *path, char *name)
{
basename(path, name);
int i;
for (i = strlen(name) - 1; i >= 0 && name[i] != '.'; i--) {
name[i] = '\0';
}
if (i >= 0 && name[i] == '.')
name[i] = '\0';
}
BOOL file_exists(const char *path)
{
FILE* fp = fopen(path, "r");
if (fp == NULL) {
return FALSE;
} else {
fclose(fp);
return TRUE;
}
}
// û
const char* rprintf(const char* fmt, ...)
{
static char res[2048];
va_list ap;
va_start(ap, fmt);
char* p_res = res;
const char* p_fmt;
for (p_fmt = fmt; *p_fmt != '\0'; p_fmt++) {
if (*p_fmt != '%') {
*(p_res++) = *p_fmt;
} else {
size_t size;
int int_val;
double double_val;
char* str_val;
p_fmt++;
switch (*p_fmt) {
case 'd':
int_val = va_arg(ap, int);
size = sprintf(p_res, "%d", int_val);
p_res += size;
break;
case 'g':
double_val = va_arg(ap, double);
size = sprintf(p_res, "%g", double_val);
p_res += size;
break;
case 's':
str_val = va_arg(ap, char*);
size = sprintf(p_res, "%s", str_val);
p_res += size;
break;
case '%':
default:
*(p_res++) = *p_fmt;
break;
}
}
}
*(p_res++) = '\0';
va_end(ap);
return res;
}
/* οϣ
·תΪ·http://blog.csdn.net/nocky/article/details/6056717
δӽ̣http://www.lellansin.com/windows-api%E6%95%99%E7%A8%8B%EF%BC%88%E5%9B%9B%EF%BC%89-%E8%BF%9B%E7%A8%8B%E7%BC%96%E7%A8%8B.html
*/
|
C
|
#include<stdio.h>
int main()
{
int a = 545;
// print value and size of an int variable
printf("int a value: %d and size: %lu bytes\n", a, sizeof(a));
char c = 'a';
//print value and size of an char variable
printf("char c value: %c and size %lu bytes\n", c, sizeof(c));
float f = 1.11;
//print value and size of an float variable
printf("float f value: %f and size %lu bytes\n", f, sizeof(f));
double d = 12.3453;
//print value and size of an double variable
printf("double d value: %f and size %lu bytes\n", d, sizeof(d));
unsigned int i = 7;
//print value and size of an unsigned int
printf("unsigned int i value: %d and size %lu bytes\n", i, sizeof(i));
short int j = 5;
//print value and size of an short int
printf("short int j value: %d and size %lu bytes\n", j, sizeof(j));
}
|
C
|
#include <cs50.h>
#include <stdio.h>
int main(void)
{
void swap(int *a, int *b);
int x = 1;
int y = 2;
printf("Unswapped : %i is x and %i is y\n",x,y);
swap(&x, &y);
printf("Swapped : %i is x and %i is y\n",x,y);
}
void swap(int *a, int *b)
{
printf("Unswapped : %i is a and %i is b\n",*a,*b);
int tmp = *a;
*a = *b;
*b = tmp;
printf("Swapped : %i is a and %i is b\n",*a,*b);
}
|
C
|
#include "buffer.h"
void rs_buffer_init(RSBuffer *buf, long len, double fill)
{
int i;
buf->ptr = ALLOC_N(double, len);
buf->len = len;
buf->offset = 0;
for (i=0; i<len; i++) {
buf->ptr[i] = fill;
}
}
void rs_buffer_resize(RSBuffer *buf, long len)
{
long i;
long old_len = buf->len;
long offset = buf->offset;
double *ptr = buf->ptr;
double *dst, *src;
double fill;
if (len < old_len) {
if (offset < len) {
dst = ptr + offset;
src = ptr + offset + old_len - len;
memmove(dst, src, (len - offset) * sizeof(double));
}
else {
dst = ptr;
src = ptr + offset - len;
offset = 0;
memmove(dst, src, len * sizeof(double));
}
REALLOC_N(ptr, double, len);
// ## maybe better: don't release space, just use less of it
}
else if (len > old_len) {
REALLOC_N(ptr, double, len);
fill = ptr[offset];
dst = ptr + offset + len - old_len;
src = ptr + offset;
memmove(dst, src, (old_len - offset) * sizeof(double));
for (i = 0; i < len - old_len; i++) {
ptr[offset + i] = fill;
}
}
else
return;
buf->len = len;
buf->offset = offset;
buf->ptr = ptr;
}
void rs_buffer_inhale_array(RSBuffer *buf, VALUE ary)
{
int size, i;
Check_Type(ary, T_ARRAY);
size = RARRAY_LEN(ary);
if (buf->ptr) {
REALLOC_N(buf->ptr, double, size);
}
else {
buf->ptr = ALLOC_N(double, size);
}
buf->len = size;
buf->offset = 0;
for (i = 0; i < size; i++) {
buf->ptr[i] = NUM2DBL(RARRAY_PTR(ary)[i]);
}
}
VALUE rs_buffer_exhale_array(RSBuffer *buf)
{
VALUE ary;
int i;
int j;
int size;
size = buf->len;
ary = rb_ary_new2(size);
if (size > 0) {
rb_ary_store(ary, size-1, Qnil);
}
for (i = buf->offset, j=0; i < size; i++, j++) {
RARRAY_PTR(ary)[j] = rb_float_new(buf->ptr[i]);
}
for (i = 0; i < buf->offset; i++, j++) {
RARRAY_PTR(ary)[j] = rb_float_new(buf->ptr[i]);
}
return ary;
}
void
Init_buffer()
{
}
|
C
|
/*
* PeerChat - a simple linux commandline Client - client chat
* Author: Tarun kumar yadav
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdbool.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#include "chatroom_utils.h"
#define MAX_CLIENTS 4
int PORTS = 1111;
void initialize_server(connection_info *server_info, int port)
{
if((server_info->socket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("Failed to create socket");
exit(1);
}
server_info->address.sin_family = AF_INET;
server_info->address.sin_addr.s_addr = INADDR_ANY;
server_info->address.sin_port = htons(port);
if(bind(server_info->socket, (struct sockaddr *)&server_info->address, sizeof(server_info->address)) < 0)
{
perror("Binding failed");
exit(1);
}
const int optVal = 1;
const socklen_t optLen = sizeof(optVal);
if(setsockopt(server_info->socket, SOL_SOCKET, SO_REUSEADDR, (void*) &optVal, optLen) < 0)
{
perror("Set socket option failed");
exit(1);
}
if(listen(server_info->socket, 3) < 0) {
perror("Listen failed");
exit(1);
}
//Accept and incoming connection
printf("Waiting for incoming connections...\n");
}
void send_public_message(connection_info clients[], int sender, char *group_name, char *message_text)
{
message msg;
msg.type = PUBLIC_MESSAGE;
strncpy(msg.username, clients[sender].username, 20);
strncpy(msg.data, message_text, 256);
char line[512], *member;
FILE *f= fopen("groups.txt", "r");
while (fgets(line,sizeof(line), f)) {
if(strcmp(strtok(line," "), group_name) == 0) {
member = strtok(NULL, " ");
while(member != NULL) {
if (member[strlen(member) - 1] == '\n') {
member[strlen(member) - 1] = '\0';
}
int i = 0;
for(i = 0; i < MAX_CLIENTS; i++)
{
if(i != sender && clients[i].socket != 0 && strcmp(clients[i].username, member)==0)
{
if(send(clients[i].socket, &msg, sizeof(msg), 0) < 0)
{
perror("Send failed");
exit(1);
}
}
}
member = strtok(NULL, " ");
}
}
}
}
void send_private_message(connection_info clients[], int sender,
char *username, char *message_text)
{
message msg;
msg.type = PRIVATE_MESSAGE;
strcpy(msg.username, clients[sender].username);
sprintf(msg.data, "%d", PORTS);
//puts(msg.data);
PORTS = PORTS + 1;
int i;
for(i = 0; i < MAX_CLIENTS; i++)
{
if(i != sender && clients[i].socket != 0
&& strcmp(clients[i].username, username) == 0)
{
if(send(clients[i].socket, &msg, sizeof(msg), 0) < 0)
{
perror("Send failed");
exit(1);
}
if(send(clients[sender].socket, &msg, sizeof(msg), 0) < 0)
{
perror("Send failed");
exit(1);
}
return;
}
}
msg.type = USERNAME_ERROR;
sprintf(msg.data, "Username \"%s\" does not exist or is not logged in.", username);
if(send(clients[sender].socket, &msg, sizeof(msg), 0) < 0)
{
perror("Send failed");
exit(1);
}
}
void send_file(connection_info clients[], int sender,
char *username, char *message_text)
{
char *fileType = strtok(message_text, " ");
size_t size = atoi(strtok(NULL,""));
printf("Reading Picture Byte Array %d\n", (int)size);
int arraySize = 1026;
char p_array[arraySize];
size_t readSize = 0;
printf("KAKAKA\n");
char str[30];
int i;
for (i = 0;; ++i) {
strcpy(str, username);
sprintf(str, "%s%d", str, i);
strcat(str, ".");
strcat(str, fileType);
if( access( str, F_OK ) != -1 ) {
// file exists
} else {
break;
}
}
FILE *image;
image = fopen(str, "w");
while (readSize < size) {
ssize_t result = read(clients[sender].socket, p_array, arraySize);
if (0 >= result)
{
if (0 == result)
{
fprintf(stderr, "The other end gracefully shut down the connection.\n");
break;
}
else
{
if (EINTR == errno) /* got interrupted, start over */
{
continue;
}
if (EAGAIN == errno) /* in case reading from a non-blocking socket: no data available, start over */
{
continue;
}
/* Something went wrong unrecoverable. */
perror("read() failed");
break;
}
}
else
{
readSize += result;
if(0 == fwrite(p_array, 1, result, image)) {
perror("Error while copying file\n");
}
}
}
fclose(image);
message msg;
msg.type = SEND_FILE;
strcpy(msg.data, "File successfully sent.");
if(send(clients[sender].socket, &msg, sizeof(msg), 0) < 0)
{
perror("Send failed");
exit(1);
}
}
void receive_file(connection_info clients[], int sender) // client receives file
{
message msg;
msg.type = RECEIVE_FILE;
char username[20];
strcpy(username, clients[sender].username);
char str[30];
char temp[30];
int i = 0;
while(true) {
strcpy(str, clients[sender].username); // str is file Name on Server
sprintf(str, "%s%d", str, i);
strcat(str, ".");
//strcat(str, "png");
strcpy(temp, str);
bool found = false;
strcat(temp, "png");
if(found && access( temp, F_OK ) != -1 ) {
strcpy(str, temp);
found = true;
}
strcpy(temp, str);
strcat(temp, "jpg");
if(found && access( temp, F_OK ) != -1 ) {
strcpy(str, temp);
}
strcpy(temp, str);
strcat(temp, "jpeg");
if(found && access( temp, F_OK ) != -1 ) {
strcpy(str, temp);
}
strcpy(temp, str);
strcat(temp, "pdf");
if(found && access( temp, F_OK ) != -1 ) {
strcpy(str, temp);
}
strcpy(temp, str);
strcat(temp, "mkv");
if(found && access( temp, F_OK ) != -1 ) {
strcpy(str, temp);
}
if( access( str, F_OK ) != -1 ) {
// file exists
} else {
break;
}
char temp[30];
strcpy(temp, str);
strtok(temp,".");
char *fileType = strtok(NULL,"");
//Get Picture Size
printf("Getting file Size %s\n", str);
FILE *picture;
picture = fopen(str, "r");
int size;
fseek(picture, 0, SEEK_END);
size = ftell(picture);
fseek(picture, 0, SEEK_SET);
//Send Picture Size
printf("Getting file Size\n");
sprintf(msg.data, "%s %d",fileType, size);
strncpy(msg.username, username, 20);
if(send(clients[sender].socket, &msg, sizeof(message), 0) < 0)
{
perror("Send failed");
exit(1);
}
//Send Picture as Byte Array
printf("Sending file as Byte Array\n");
char send_buffer[1026];
int c=0;
while(!feof(picture)) {
fread(send_buffer, 1, 1026, picture);
write(clients[sender].socket, send_buffer, 1026);
bzero(send_buffer, 1026);
++c;
}
++i;
remove(str);
}
}
void create_group(connection_info clients[], int sender,
char *username, char *message_text)
{
message msg;
msg.type = CREATE_GROUP;
FILE *f = fopen("groups.txt", "a");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
fprintf(f, "%s %s %s\n", username, clients[sender].username, message_text);
fclose(f);
strncpy(msg.username, clients[sender].username, 20);
strncpy(msg.data, message_text, 256);
msg.type = CREATE_GROUP;
sprintf(msg.data, "Group name \"%s\" successfully created with members: \"%s\"", username, message_text);
if(send(clients[sender].socket, &msg, sizeof(msg), 0) < 0)
{
perror("Send failed");
exit(1);
}
}
void join_group(connection_info clients[], int sender, char *groupname)
{
message msg;
msg.type = JOIN_GROUP;
FILE *original_file, *temporary_file;
char *original_file_name = "groups.txt";
char *temporary_file_name = "dummy.txt";
original_file = fopen("groups.txt", "r");
temporary_file = fopen(temporary_file_name, "w");
char line[500], temp[500], *member;
while (fgets(line,sizeof(line), original_file))
{
if (line[strlen(line) - 1] == '\n') {
line[strlen(line) - 1] = '\0';
}
strcpy(temp, line);
if(strcmp(strtok(temp," "), groupname) == 0) {
member = strtok(NULL, " ");
while(member != NULL) {
if(strcmp(member, clients[sender].username) == 0) { // if already in group, dont add
fclose(temporary_file);
fclose(original_file);
remove(temporary_file_name);
sprintf(msg.data, "You are already a member of: \"%s\"", groupname);
if(send(clients[sender].socket, &msg, sizeof(msg), 0) < 0)
{
perror("Send failed");
exit(1);
}
return;
}
member = strtok(NULL, " ");
}
strcat(line, " ");
strcat(line, clients[sender].username);
strcat(line, "\n");
} else {
strcat(line, "\n");
}
fputs(line, temporary_file);
}
fclose(temporary_file);
fclose(original_file);
rename(temporary_file_name, original_file_name);
sprintf(msg.data, "You are now a member of: \"%s\"", groupname);
if(send(clients[sender].socket, &msg, sizeof(msg), 0) < 0)
{
perror("Send failed");
exit(1);
}
}
void send_connect_message(connection_info *clients, int sender, int login)
{
//puts("hey");
message msg;
msg.type = SUCCESS;
strncpy(msg.username, clients[sender].username, 21);
int i = 0;
printf("LOGIN %d", login);
for(i = 0; i <= MAX_CLIENTS; i++)
{
if(clients[i].socket != 0)
{
if(i == sender)
{if (login == 1) {
strcpy(msg.data, "1");
} else{
strcpy(msg.data, "0");
}
if(send(clients[i].socket, &msg, sizeof(msg), 0) < 0)
{
perror("Send failed");
exit(1);
}
}
}
}
}
void send_disconnect_message(connection_info *clients, char *username)
{
message msg;
msg.type = DISCONNECT;
strncpy(msg.username, username, 21);
int i = 0;
for(i = 0; i < MAX_CLIENTS; i++)
{
if(clients[i].socket != 0)
{
if(send(clients[i].socket, &msg, sizeof(msg), 0) < 0)
{
perror("Send failed");
exit(1);
}
}
}
}
void send_user_list(connection_info *clients, int receiver) {
message msg;
msg.type = GET_USERS;
char *list = msg.data;
int i;
for(i = 0; i < MAX_CLIENTS; i++)
{
if(clients[i].socket != 0)
{
list = stpcpy(list, clients[i].username);
list = stpcpy(list, "\n");
}
}
if(send(clients[receiver].socket, &msg, sizeof(msg), 0) < 0)
{
perror("Send failed");
exit(1);
}
}
void send_too_full_message(int socket)
{
message too_full_message;
too_full_message.type = TOO_FULL;
strcpy(too_full_message.data, "FULL");
if(send(socket, &too_full_message, sizeof(too_full_message), 0) < 0)
{
perror("Send failed");
exit(1);
}
close(socket);
}
//close all the sockets before exiting
void stop_server(connection_info connection[])
{
int i;
for(i = 0; i < MAX_CLIENTS; i++)
{
//send();
close(connection[i].socket);
}
exit(0);
}
void login(connection_info *clients, int sender, char* loginDetails) {
FILE *f = fopen("registeredUsers.txt", "r");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
char *username = strtok(loginDetails, " ");
char * password = strtok(NULL, "");
password[strlen(password)-1] = '\0';
printf("ss%sss", username);
printf("kk%skk", password);
char uname[50], pass[50];
int login = 0;
while(fscanf(f, "%s %s\n", uname, pass) > 0) {
if (strcmp(username, uname)==0 && strcmp(password, pass) == 0) {
login = 1;
break;
}
}
fclose(f);
strcpy(clients[sender].username, username);
printf("\nUser connected: %s\n", clients[sender].username);
send_connect_message(clients, sender, login);
//puts("mml");
if (login != 1) {
close(clients[sender].socket);
clients[sender].socket = 0;
}
}
void handle_client_message(connection_info clients[], int sender)
{
int read_size;
message msg;
if((read_size = recv(clients[sender].socket, &msg, sizeof(message), 0)) == 0)
{
printf("User disconnected: %s.\n", clients[sender].username);
close(clients[sender].socket);
clients[sender].socket = 0;
send_disconnect_message(clients, clients[sender].username);
} else {
switch(msg.type)
{
case GET_USERS:
send_user_list(clients, sender);
break;
case SET_USERNAME:
login(clients, sender, msg.username);
break;
case PUBLIC_MESSAGE:
send_public_message(clients, sender, msg.username, msg.data);
break;
case PRIVATE_MESSAGE:
send_private_message(clients, sender, msg.username, msg.data);
break;
case CREATE_GROUP:
create_group(clients, sender, msg.username, msg.data);
break;
case JOIN_GROUP:
join_group(clients, sender, msg.username);
break;
case SEND_FILE:
send_file(clients, sender, msg.username, msg.data);
break;
case RECEIVE_FILE:
receive_file(clients, sender);
break;
default:
fprintf(stderr, "Unknown message type received.\n");
break;
}
}
}
int construct_fd_set(fd_set *set, connection_info *server_info,
connection_info clients[])
{
FD_ZERO(set);
FD_SET(STDIN_FILENO, set);
FD_SET(server_info->socket, set);
int max_fd = server_info->socket;
int i;
for(i = 0; i < MAX_CLIENTS; i++)
{
if(clients[i].socket > 0)
{
FD_SET(clients[i].socket, set);
if(clients[i].socket > max_fd)
{
max_fd = clients[i].socket;
}
}
}
return max_fd;
}
void handle_new_connection(connection_info *server_info, connection_info clients[])
{
int new_socket;
int address_len;
new_socket = accept(server_info->socket, (struct sockaddr*)&server_info->address, (socklen_t*)&address_len);
if (new_socket < 0)
{
perror("Accept Failed");
exit(1);
}
int i;
for(i = 0; i < MAX_CLIENTS; i++)
{
if(clients[i].socket == 0) {
clients[i].socket = new_socket;
break;
} else if (i == MAX_CLIENTS -1) // if we can accept no more clients
{
send_too_full_message(new_socket);
}
}
}
void handle_user_input(connection_info clients[])
{
char input[255];
fgets(input, sizeof(input), stdin);
trim_newline(input);
if(input[0] == 'q') {
stop_server(clients);
}
}
int main(int argc, char *argv[])
{
puts("Starting server.");
fd_set file_descriptors;
connection_info server_info;
connection_info clients[MAX_CLIENTS];
int i;
for(i = 0; i < MAX_CLIENTS; i++)
{
clients[i].socket = 0;
}
if (argc != 2)
{
fprintf(stderr, "Usage: %s <port>\n", argv[0]);
exit(1);
}
initialize_server(&server_info, atoi(argv[1]));
while(true)
{
int max_fd = construct_fd_set(&file_descriptors, &server_info, clients);
if(select(max_fd+1, &file_descriptors, NULL, NULL, NULL) < 0)
{
perror("Select Failed");
stop_server(clients);
}
if(FD_ISSET(STDIN_FILENO, &file_descriptors))
{
handle_user_input(clients);
}
if(FD_ISSET(server_info.socket, &file_descriptors))
{
handle_new_connection(&server_info, clients);
}
for(i = 0; i < MAX_CLIENTS; i++)
{
if(clients[i].socket > 0 && FD_ISSET(clients[i].socket, &file_descriptors))
{
handle_client_message(clients, i);
}
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void randnum (int *array11)
{
srand (time (0));
for (int i = 0; i < 25; i++)
{
array11[i] = rand () % 100;
}
for (int f = 0; f < 25; f++)
{
printf ("%d ", array11[f]);
}
}
void reverse (int *array22)
{
int cache = 0;
int j = 0;
for (int h = 24; h >= 12; h-- && j++)
{
cache = array22[h];
array22[h] = array22[j];
array22[j] = cache;
}
printf ("\nZahlen umgedreht:\n");
for (int u = 0; u < 25; u++)
{
printf ("%d ", array22[u]);
}
}
void arithmetical_mean(int * array33)
{
int median = 0;
for(int i = 0;i<25;i++)
{
median+=array33[i];
}
median /= 25;
printf("\n\nMedian: %d\n\nAlle Abweichungen von +-20\%% mit Median ausgetauscht: \n",median);
for(int i = 0;i<25;i++)
{
if(array33[i] < median * 0.80 || array33[i] > median * 1.20)
{
array33[i] = median;
}
printf("%d ",array33[i]);
}
}
void min_max(int * array44)
{
int min = array44[0];
int max = array44[0];
for(int i = 0;i<25;i++)
{
if(min > array44[i])
{
min = array44[i];
}
if(max < array44[i])
{
max = array44[i];
}
}
printf("\n\nMin: %d\n",min);
printf("\nMax: %d",max);
}
void count_12(int * array55)
{
int one = 0;
int two = 0;
int three = 0;
for(int i = 0;i<25;i++)
{
if(array55[i]<10)
{
one++;
}
if(array55[i]>=10 && array55[i] < 100)
{
two++;
}
if(array55[i] == 100)
{
three++;
}
}
printf("\n\nEinstellig: %d \n\nZweistellig: %d \n\nDreistellig: %d",one,two,three);
}
int main ()
{
int array[25];
int array2[25];
int array3[25];
randnum (array);
printf ("\n");
for (int g = 0; g < 25; g++)
{
array2[g] = array[g];
}
reverse (array2);
for (int g = 0; g < 25; g++)
{
array3[g] = array[g];
}
arithmetical_mean(array3);
min_max(array);
count_12(array);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Elemento{
int indice;
int d;
}Elemento;
typedef struct Heap{
struct Elemento *array;
int tamanho;
}Heap;
int parent(int i);
int left(int i);
void heap_decrease_key(Heap *heap, int indice, int key);
int right(int i);
Heap* inicializa_heap(int t);
void min_heapify(Heap* heap, int i);
void adiciona_heap(Heap* heap, int i, int d, int indice);
void build_min_heap(Heap* heap);
/*
void heapsort(Heap* heap){
int i, aux;
for(i = heap->tamanho; >=2;i--){
aux = heap->array[i];
heap->array[i] = heap->array[1];
heap->array[1] = aux;
heap->tamanho--;
min_heapify(heap, 1);
}
}*/
int extract_min(Heap *heap);
void libera_heap(Heap* heap);
void print_heap(Heap *heap);
|
C
|
#include <stdio.h>
// Patrick Korianski Homework 1
// All print statements other than the bottom one that shows the final result, were used for testing and seeing the correct number of steps per trial.
int main()
{
int a, b, x, final, lgsteps;
lgsteps = 0;
printf( "Enter a: ");
scanf("%d", &a);
printf( "Enter b: ");
scanf("%d", &b);
long steps, prod;
x = a;
// My Collatz Recurrence method.
// In the while it looks for if the number is even or odd and then puts it in the right equ.
// The last if statement determines if the current x's amount of steps is greater than the current max steps
void collatz(int n){
prod = x;
steps = 1;
printf("\n");
while(prod != 1 && prod != 0){
if(prod % 2 ==0){
long eSum = prod/2;
printf("x= %d at step %d equals %d\n", x, steps, eSum);
prod = eSum;
steps++;
}
else{
long oSum = (3*prod)+1;
printf("x=%d at step %d equals %d\n", x, steps, oSum);
prod = oSum;
steps++;
}
}
if(steps > lgsteps){
lgsteps = steps;
final = x;
}
}
// Runs the method and checks for if the numbers entered are positive numbers and if a>b or a<b
if(a <= 0 || b <= 0){
printf("\nThe number entered is not a postive number for a or b\n");
final = 0;
}
else if(a < b){
while(x != b+1){
while(x <= b){
collatz(x);
printf("-----------------------------\n");
x++;
}
}
}
else{
while(x != b-1){
while(x >= b){
collatz(x);
printf("-----------------------------\n");
x--;
}
}
}
// Kept track of max steps in variable 'final' and at the end of the code made x equal to final
x = final;
// Prints final result
printf("\nLongest Collatz chain starts at %d\n\n", x );
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "holberton.h"
/**
* _calloc - reallocates a memory block using malloc and free.
* @ptr: pointer
* @old_size: size of ptr
* @new_size: new size of memory block.
* Return: s
**/
void *_realloc(void *ptr, unsigned int old_size, unsigned int new_size)
{
void *p;
if (new_size == old_size)
return (ptr);
if (ptr == NULL)
return (malloc(new_size));
if ((new_size == 0) && (ptr != NULL))
{
free(ptr);
return NULL;
}
p = malloc(new_size * sizeof(int));
p = ptr;
if (p == NULL)
{
free(ptr);
return (NULL);
}
free (ptr);
return (p);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* print_characters.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: afarapon <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/01/04 21:27:56 by afarapon #+# #+# */
/* Updated: 2018/01/08 12:36:37 by afarapon ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int ft_print_null(char chr, t_all_flags all_flags)
{
char *res;
int counter;
counter = 1;
all_flags.width--;
if (all_flags.f_minus)
{
write(1, &chr, 1);
res = ft_make_width_char(ft_strnew(1), all_flags);
counter += (int)write(1, res, ft_strlen(res));
}
else
{
res = ft_make_width_char(ft_strnew(1), all_flags);
counter += (int)write(1, res, ft_strlen(res));
write(1, &chr, 1);
}
free(res);
return (counter);
}
int ft_print_characters(char **f, t_all_flags all_flags, va_list list)
{
int chr;
char *res;
int result;
if (**f == 'C' && MB_CUR_MAX == 4)
return (ft_print_u_characters(f, all_flags, list));
chr = va_arg(list, int);
(*f)++;
if (chr)
{
res = ft_strnew(1);
res[0] = (char)chr;
res = ft_make_width_char(res, all_flags);
result = (int)write(1, res, ft_strlen(res));
free(res);
return (result);
}
else
result = ft_print_null((char)chr, all_flags);
return (result);
}
char *ft_make_width_char(char *src, t_all_flags all)
{
wchar_t sign;
intmax_t len;
char *result;
char *width;
len = (int)ft_strlen(src);
if (len >= all.width)
return (src);
if (all.f_minus)
sign = ' ';
else
sign = (char)(all.f_zero == 1 ? '0' : ' ');
len = all.width - (int)ft_strlen(src);
width = ft_strnew((size_t)len);
if (len > 0 && width)
ft_memset(width, sign, (size_t)len);
if (all.f_minus)
result = ft_strjoin(src, width);
else
result = ft_strjoin(width, src);
free(src);
free(width);
return (result);
}
|
C
|
#ifndef _UTIL_LIST_H_
#define _UTIL_LIST_H_ 1
#include <stdlib.h>
#include <memory.h>
#include "private/list.h"
static struct list_node* new_list_node(void *val, size_t val_t)
{
const size_t mem_t = sizeof(struct list_node) + val_t;
struct list_node *node = (struct list_node*) malloc(mem_t);
if (node == NULL) {
return NULL;
}
node->value = val;
node->prev = node->next = NULL;
if (val_t != 0) {
node->value = node + 1;
memcpy(node->value, val, val_t);
}
return node;
}
struct list_node* add_list_head(struct list *list, void *val, size_t val_t)
{
struct list_node *node;
if (list == NULL || (node = new_list_node(val, val_t)) == NULL) {
return NULL;
}
if (list->ls_head == NULL) {
list->ls_tail = node;
}
else {
list->ls_head->prev = node;
node->next = list->ls_head;
}
list->ls_size ++;
list->ls_head = node;
return node;
}
struct list_node* add_list_tail(struct list *list, void *val, size_t val_t)
{
struct list_node *node;
if (list == NULL || (node = new_list_node(val, val_t)) == NULL) {
return NULL;
}
if (list->ls_tail == NULL) {
list->ls_head = node;
}
else {
list->ls_tail->next = node;
node->prev = list->ls_tail;
}
list->ls_size ++;
list->ls_tail = node;
return node;
}
struct list_node* remove_list_head(struct list *list)
{
if (list == NULL || list->ls_head == NULL) {
return NULL;
}
struct list_node *node = list->ls_head;
if (node->next != NULL) {
node->next->prev = NULL;
}
else {
list->ls_tail = NULL;
}
list->ls_head = node->next;
list->ls_size --;
node->next = NULL;
return node;
}
struct list_node* remove_list_tail(struct list *list)
{
if (list == NULL || list->ls_tail == NULL) {
return NULL;
}
struct list_node *node = list->ls_tail;
if (node->prev != NULL) {
node->prev->next = NULL;
}
else {
list->ls_head = NULL;
}
list->ls_tail = node->prev;
node->prev = NULL;
list->ls_size --;
return node;
}
void free_list(struct list *list)
{
if (list == NULL)
return;
struct list_node *next, *node = list->ls_head;
while (node != NULL) {
next = node->next;
free(node);
node = next;
}
memset(list, 0, sizeof(struct list));
}
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* init_fractals.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vsosevic <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/10/29 19:16:55 by vsosevic #+# #+# */
/* Updated: 2017/10/29 19:16:57 by vsosevic ### ########.fr */
/* */
/* ************************************************************************** */
#include "fractol.h"
int ft_print_controls(t_fractal *f)
{
char **output_text;
int i;
int x;
int y;
output_text = (char**)malloc(sizeof(*output_text) * 100);
output_text[0] = "- anykey: START";
output_text[1] = "- W and S: Vertical movement";
output_text[2] = "- A and D: Horizontal movement";
output_text[3] = "- Q and E: Increase or decrease precision";
output_text[4] = "- Z and X: Zoom";
output_text[5] = "- 1 and 2: Change COLOR";
output_text[6] = "- Space: Return to default";
output_text[7] = "- ESC: EXIT";
i = 0;
x = 300;
y = 100;
mlx_string_put(f->init_mlx, f->window, 350, 100, 0xcc0033, "INSTRUCTION");
while (i <= 6)
{
mlx_string_put(f->init_mlx, f->window, x, y += 100, 0xffff00,
output_text[i]);
i++;
}
return (0);
}
void init_mandelbrot_fractal(t_fractal *f)
{
f->change_x = W / 2;
f->change_y = H / 2;
f->color = 1;
f->z = 270;
f->max_iteration = 30;
f->i = 0;
f->go_x = -0.46;
f->go_y = 0;
ft_print_controls(f);
mandelbrot(f);
}
void init_julya_fractal(t_fractal *f)
{
f->change_x = 400;
f->change_y = 500;
f->point_real = -0.285;
f->point_imagine = -0.01;
f->z = 250;
f->max_iteration = 45;
f->go_x = -0.26;
f->go_y = 0;
ft_print_controls(f);
julya(f);
}
void init_burningship_fractal(t_fractal *f)
{
f->change_x = W / 2;
f->change_y = H / 2;
f->z = 250;
f->max_iteration = 20;
f->go_x = 0;
f->go_y = 0;
ft_print_controls(f);
burning_ship(f);
}
|
C
|
#ifndef PARSER_UTIL
#define PARSER_UTIL
#include "bool.h"
#include "util.h"
#include "context.h"
typedef enum{
UNKNOWN,
STRING,
NO_TYPE
} token_type;
typedef struct{
char *string;
token_type type;
char last_char;
} token_t;
bool token_init(token_t *this, const char *string, token_type type, char last_char);
void token_init_null(token_t *this);
token_t token_get_null();
void token_dispose(token_t *this);
bool token_equals(const token_t *t1, const token_t *t2);
bool token_null(const token_t *t);
void free_command_tokens(token_t *tokens);
/**
* Tokenizes the given command string
* @param command - command string(segment of the user input)
* @return tokenized command
*/
token_t *tokenize_command(const char *command);
/**
* Replaces all the variables and aliases with their definitions
* @param tokens - tokenized command
* @param c - context
* @return True, if success
*/
bool replace_variables(token_t *tokens, context *c);
/**
* Searches for a string in the list that equal to the first parameter
* @param string - target string
* @param list - list of the strings (NULL terminated)
* @return True, if found
*/
bool string_in_list(const char *string, const char **list);
const char **STRING_START_ENDS;
const char **COMMAND_DELIMITERS;
const char **WHITE_SPACES;
const string_pair *COMMAND_COMMENTS;
#endif
|
C
|
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include "my_ls.h"
#include <ctype.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#define STRMAX 1024
char * compare_mode(char c){
switch(c){
case '0':
return (char*)"---";
case '1':
return (char*)"--x";
case '2':
return (char*)"-w-";
case '3':
return (char*)"-wx";
case '4':
return (char*)"r--";
case '5':
return (char*)"r-x";
case '6':
return (char*)"rw-";
case '7':
return (char*)"rwx";
default:
return NULL;
}
}
void indent(int track){
int i;
for(i=0;i<track;i++)
printf("\t");
}
/**EXCEEDS 5 LINES BY 2**/
char * change_mode(int mode,int filetype){
char mode_in_string[BUFSIZ], *temp=malloc(BUFSIZ);
int i;
temp[0]=filetype==0?'d':'-';
temp[1]='\0';
sprintf(mode_in_string,"%o",mode & 07777);
for(i=0;i<3;i++)
strcat(temp,compare_mode(mode_in_string[i]));
return temp;
}
void free_memory(char *mode, char *pathname_file, char *modification_time,int require_path){
free(mode);
if(require_path!=0)
free(pathname_file);
free(modification_time);;
}
void print_directory_name(char * argument){
if(argument[0]!='/')
printf("/");
printf("%s\n",argument);
}
/**EXCEEDS 5 LINES BY 3**/
void print_info(char *argument,char *filename,int filetype, int track,int require_path){
struct stat buf;
char *modification_time=malloc(BUFSIZ), *pathname_file=require_path==0?argument:pathname(argument,filename);
indent(track);
if(stat(pathname_file,&buf)!=-1){
char *mode=change_mode(buf.st_mode,filetype);
strftime(modification_time,18,"%b %d %H:%M",localtime(&buf.st_mtime));
printf("%5s %3lu %5s %5s %10lu %7s %10s",mode,buf.st_nlink,getUserName(buf.st_uid),getGroupName(buf.st_gid),buf.st_size,modification_time,filename);
print_directory_name(argument);
free_memory(mode,pathname_file,modification_time,require_path);
}
}
int check_if_file(char *path){
struct stat buf;
stat(path,&buf);
return S_ISREG(buf.st_mode);
}
char * pathname(char *path, char *filename){
char * temp =malloc(BUFSIZ);
strcpy(temp,path);
strcat(temp,"/");
strcat(temp,filename);
return temp;
}
char *getUserName(uid_t uid){
struct passwd *pw=getpwuid(uid);
return pw->pw_name?pw->pw_name:(char*)"";
}
char *getGroupName(gid_t gid){
struct group *grp=getgrgid(gid);
return grp->gr_name?grp->gr_name:(char*)"";
}
void directory_recursion(char *temp,int track, char *directory_name){
indent(track);
printf("%s/\n",directory_name);
do_ls(temp,track);
}
void check_for_recursion(char *argument, char *filename, int track){
char *temp=pathname(argument,filename);
print_info(argument,filename,check_if_file(temp),track,1);
if(check_if_file(temp)==0)
directory_recursion(temp,++track, filename);
free(temp);
}
void ls_directory(char *argument,DIR *dirp,int track){
struct dirent *direntp;
while((direntp=readdir(dirp))){
if((strcmp(direntp->d_name,".")!=0)&&(strcmp(direntp->d_name,"..")!=0))
check_for_recursion(argument,direntp->d_name,track);
}
track--;
}
void do_ls(char *argument, int track){
DIR *dirp;
if((!(dirp=opendir(argument))))
return;
else
ls_directory(argument,dirp,track);
closedir(dirp);
}
|
C
|
int
futex_wait(struct futex * f, int val, struct timespec * reltime) {
ret = 0;
Mark process as INTERRUPTIBLE
Hash ("struct page *" + offset) -> index [i] into hash table
chain "struct futex_q" to tail of hashtable[i]
typedef struct futex_q {
process * prptr;
struct page * p;
offset o;
} futex_q;
Map into low memory (kernel) if in high memory
Read futex value -> valread
Unmap (if mapped before)
if ( valread != val )
ret = -EWOULDBLOCK;
else {
if ( reltime != NULL ) sleep(reltime);
else sleep(INDEFINITELY);
if ( timeout )
ret = ETIMEDOUT;
else
ret = EINTR;
}
Try to remove our "struct futex_q" from the hash table
if ( already removed )
return 0;
else
return ret;
}
int
futex_wake(struct futex * f, int val, struct timespec * reltime) {
for ( int i = 0; i < val; i++ ) {
attempt to wake next process in appropriate hash bucket
}
return number of processes actually woken;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include<math.h>
int main()
{
int i;double s;double p;double a[4];
int flag=0;
a[3]=0;
for(i=0;i<=2;i++)
printf("α߳:"),scanf("%lf",&a[i]),a[3]+=a[i];
p=a[3]/2.0;
for(i=0;i<=2;i++)
if(a[3]>2*a[i])flag++;
if(flag==3) s=sqrt(p*(p-a[0])*(p-a[1])*(p-a[2])),printf("%lf",s);
else printf("ܹ");
return 0;
}
|
C
|
#define _XOPEN_SOURCE 700
#define _DEFAULT_SOURCE
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include <time.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <limits.h>
#include <unistd.h>
#include <time.h>
#include <ftw.h>
// format daty którą podajemy w argumencie
const char format[] = "%d.%m.%Y %H:%M:%S";
//zmienne globalne dla funkcji display_info
const char *nftwoperant;
time_t nftwDate;
pid_t child_pid = 1;
void getFileInfo(const char *path, const struct stat *file){
printf("Proces rodzica: Proces rodzica ma pid:%d\n", (int)getpid());
printf("\nFile path\t%s\n", path);
printf("File size:\t%ld\n", file->st_size);
printf("Permission: \t");
printf( (S_ISDIR(file->st_mode)) ? "d" : "-");
printf( (file->st_mode & S_IRUSR) ? "r" : "-");
printf( (file->st_mode & S_IWUSR) ? "w" : "-");
printf( (file->st_mode & S_IXUSR) ? "x" : "-");
printf( (file->st_mode & S_IRGRP) ? "r" : "-");
printf( (file->st_mode & S_IWGRP) ? "w" : "-");
printf( (file->st_mode & S_IXGRP) ? "x" : "-");
printf( (file->st_mode & S_IROTH) ? "r" : "-");
printf( (file->st_mode & S_IWOTH) ? "w" : "-");
printf( (file->st_mode & S_IXOTH) ? "x" : "-");
printf("\n");
printf("Data of last modification \t%s\n", ctime(&(file->st_mtime)));
}
int display_info(const char *fpath, const struct stat *fileStat, int tflag, struct FTW *ftwbuf){
if(tflag != FTW_F ){
child_pid = vfork();
return 0;
}
time_t date = fileStat->st_mtime;
char operant = nftwoperant[0];
switch(operant)
{
case '=':
if(difftime(date, nftwDate) == 0){
getFileInfo(fpath,fileStat);
return 0;
}
break;
case '>':
if(difftime(date, nftwDate) > 0){
getFileInfo(fpath,fileStat);
return 0;
}
break;
case '<':
if(difftime(date, nftwDate) < 0)
{
getFileInfo(fpath,fileStat);
return 0;
}
break;
default:
return 0;
break;
}
if(child_pid != 0){
//scanDIR(newPath, sign, date);
return 0;
exit(0);
}
return 0; // continue jak return 0
}
void scanDIR(char *path, char sign, time_t date){
struct dirent * file;
DIR * folder = opendir(path);
struct stat buf;
char newPath[PATH_MAX];
if(folder == NULL){
printf("ERROR");
}
while((file = readdir(folder)) != NULL){
strcpy(newPath, path);
strcat(newPath, "/");
strcat(newPath, file->d_name);
if(lstat(newPath, &buf) == -1)
{
continue;
}
// pomiń takie pliki
if(strcmp(file->d_name, "..") == 0 || strcmp(file->d_name, ".") == 0)
{
continue;
}
//rekursja gdy folder
if (S_ISDIR(buf.st_mode) != 0) {
pid_t child_pid = vfork();
if(child_pid == 0){
scanDIR(newPath, sign, date);
exit(0);
}
}
// jeśli plik to pokaż informacje
if(S_ISREG(buf.st_mode) != 0){
int operant = (int) sign;
switch(operant)
{
case '=':{
if(difftime(buf.st_mtime, date) == 0){
getFileInfo(newPath,&buf);
}
}
break;
case '>':{
if(difftime(buf.st_mtime, date) > 0){
getFileInfo(newPath,&buf);
}
}
break;
case '<':{
if(difftime(buf.st_mtime, date) < 0)
{
getFileInfo(newPath,&buf);
}
}
break;
default:
printf("Error with operants, incorrect operants.");
break;
}
}
}
closedir(folder);
}
int main(int argc,char* argv[])
{
struct tm *timeptr;
if(argc > 3)
{
//odczyt daty, konwersja z tablicy char na strukture tm
timeptr = malloc(sizeof(struct tm));
memset(timeptr, 0, sizeof(struct tm));
strptime(argv[3], format, timeptr);
//Dzięki temu zabiegowi poniżej nie dodaje 1 godziny do daty ;)
timeptr->tm_isdst = -1;
// konwersja na time_t z struktury tm
time_t date = timelocal (timeptr);
// scieżka bezwględna do folderu (argumentu)
char buf[PATH_MAX];
realpath(argv[1], buf);
//wywołanie funkcji dla 1 sposobu implementacji
scanDIR(buf,argv[2][0], date);
printf("\n ---NFTW--- \n");
//dane potrzebne do drugiej implementacji
nftwoperant = argv[2];
nftwDate = date;
//wywolanie funkcji dla 2 implementacji
nftw(buf, display_info, 10, FTW_PHYS);
//exit(0);
}else{
printf("Error, not enough arguments for program.");
exit(0);
}
return 0;
}
|
C
|
//
// Created by black.dragon74 on 4/23/18.
// Code is poetry.
//
#include <stdio.h>
// A void method that simply prints an empty line using the escape character "\n"
void printEmptyLine(){
printf("\n");
}
int main() {
int* ptest; // A pointer that will point to the address of a variable of type int
int test; // Normal var test with int data type.
/*
* We have assigned the pointer ptest to the address of the test variable.
* We can't use pointers to alter values unless we bind it to some variable like in the line below.
*/
ptest = &test; // The pointer ptest is now binded the the address of the variable test.
/*
* While dealing with pointers a pointer variable of a datatype can only be assigned to it's address
* The address of a variable is given by a reference operator (&)
* In the above declaration. ptest = test; would have given errors at the time of compilation.
*
* We can use a pointer to alter the variable's value at runtime.
* The value of a pointer is given by a dereference operator (*)
*/
// Now we will be printing a few statements to understand the pointers
/*
* We will now assign some value to the variable test like test = 10
* We will be printing the values of the variables test and ptest.
* We will also pe printing the address of the variables test and ptest.
*
* Now, you have to notice, the address of test and ptest must be same as ptest is a pointer to the address of test.
* The value of the variable test and val of the pointer ptest will also be same as pointer is reading from the same address.
*/
test = 10; // We have assigned some value to the variable test.
printf("The value of the variable test is: %d\n", test);
printf("The address of the variable test is: %u\n", &test);
printEmptyLine();
printf("The value of pointer ptest is: %d\n", *ptest);
printf("The address of pointer ptest is: %u\n", ptest);
printEmptyLine();
/*
* Now we will alter the value of pointer ptest using dereference operator (*)
* You will notice that the value of the variable test will also change as we modified it's value in the memory address.
*/
*ptest = 20; // It is same as test = 20; Note: *ptest will return value not the address
printf("The value of the variable test is: %d\n", test);
printf("The address of the variable test is: %u\n", &test);
printEmptyLine();
printf("The value of pointer ptest is: %d\n", *ptest);
printf("The address of pointer ptest is: %u\n", ptest);
printEmptyLine();
/*
* To recap:
* "&" also known as the reference operator is used to get the mem address of a variable.
* "*" also known as the dereference operator is used to get a value from the pointer's mem address.
*
* A pointer points to the address of a variable and can only be defined to it like:
* int* someint; someint = &someothervar.
* In the above line, a pointer someint is created with datatype int. It is then assigned to the address(&) of some other var.
*
* When dereference operator is used on a pointer it will return the value of the variable to which pointer is assigned.
* Like, printf("Value of someint is: %d", *someint); will print the value of "someothervar" as someint = value of "someothervar"
*/
// Return 0 if the execution is successful
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
pthread_t tid1 , tid2;
pthread_mutex_t g_mutex1 = PTHREAD_MUTEX_INITIALIZER
, g_mutex2 = PTHREAD_MUTEX_INITIALIZER;
void *ret1;
void *ret2;
void* thread1(void *x)
{
//deadlock
/*
pthread_mutex_lock(&g_mutex1);
sleep(1);
pthread_mutex_lock(&g_mutex2);
for (size_t i = 0; i < 5; i++)
{
printf("Thread 1\n");
}
pthread_mutex_unlock(&g_mutex1);
pthread_mutex_unlock(&g_mutex2);*/
//cozum
pthread_mutex_lock(&g_mutex1);
sleep(1);
pthread_mutex_lock(&g_mutex2);
for (size_t i = 0; i < 5; i++)
{
printf("Thread 1\n");
}
pthread_mutex_unlock(&g_mutex1);
pthread_mutex_unlock(&g_mutex2);
return (void*)100;
}
void* thread2(void *x)
{
//deadlock
/*
pthread_mutex_lock(&g_mutex2);
pthread_mutex_lock(&g_mutex1);
for (size_t i = 0; i < 5; i++)
{
printf("Thread 2\n");
}
pthread_mutex_unlock(&g_mutex2);
pthread_mutex_unlock(&g_mutex1);*/
//cozum
pthread_mutex_lock(&g_mutex1);
pthread_mutex_lock(&g_mutex2);
for (size_t i = 0; i < 5; i++)
{
printf("Thread 2\n");
}
pthread_mutex_unlock(&g_mutex1);
pthread_mutex_unlock(&g_mutex2);
return (void*)150;
}
int main()
{
if(pthread_create(&tid1,NULL,thread1,NULL) != 0)
{
printf("Create Error\n");
exit(EXIT_FAILURE);
}
if(pthread_create(&tid2,NULL,thread2,NULL) != 0)
{
printf("Create Error\n");
exit(EXIT_FAILURE);
}
pthread_join(tid1,&ret1);
pthread_join(tid2,&ret2);
if(ret1 == (void*)100) printf("Thread1 Succes\n");
if(ret2 == (void*)150) printf("Thread2 Succes\n");
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include "jobs.h"
typedef struct job_node {
pid_t pid;
char* display_name;
job_node* next;
job_node* prev;
} job_node;
job_node* job_create(pid_t pid, char* name) {
job_node* new_job = malloc(sizeof(job_node));
new_job->pid = pid;
new_job->display_name = name;
new_job->prev = NULL;
new_job->next = NULL;
return new_job;
}
void job_free(job_node* node) {
free(node->display_name);
free(node);
}
job_node* prune_jobs(job_node* head) {
job_node* cursor = head;
int status;
while (cursor != NULL) {
pid_t waitres = waitpid(cursor->pid, &status, WNOHANG);
if (waitres <= 0) { // job still running or error
cursor = cursor->next;
continue;
}
int exit_status;
if (!WIFEXITED(status) && (exit_status = WEXITSTATUS(status)) != 0 ) {
fprintf(stderr, "job %d (%s) didn't exit normally with status %d\n", cursor->pid, cursor->display_name, exit_status);
}
if (cursor->prev != NULL) {
cursor->prev->next = cursor->next;
}
else {
head = cursor->next;
}
if (cursor->next != NULL) {
cursor->next->prev = cursor->prev;
}
job_node* old_cursor = cursor;
cursor = cursor->next;
job_free(old_cursor);
}
return head;
}
job_node* job_add(job_node* head, pid_t pid, char* name) {
job_node* new = job_create(pid, name);
if (head == NULL) {
return new;
}
new->next = head;
head->prev = new;
return new;
}
job_node* job_next(job_node* node) {
return node->next;
}
pid_t job_pid(job_node* node) {
return node->pid;
}
char* job_name(job_node* node) {
return node->display_name;
}
|
C
|
/**
* @file
* Implementation of the SPSPS library.
*
* @verbatim
* SPSPS
* Stacy's Pathetically Simple Parsing System
* https://github.com/sprowell/spsps
*
* Copyright (c) 2014, Stacy Prowell
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* @endverbatim
*/
#include "parser.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <wchar.h>
//======================================================================
// Definition of the parser struct.
//======================================================================
struct spsps_parser_ {
/// Whether the parser has consumed the end of file.
bool at_eof;
/// The current zero-based block index.
uint8_t block;
/// The blocks.
SPSPS_CHAR blocks[2][SPSPS_LOOK];
/// How many times we have consumed the EOF.
uint16_t eof_count;
/// How many times we have peeked without consuming.
uint16_t look_count;
/// The name of the source.
char * name;
/// The next entry in the current block.
size_t next;
/// The stream providing characters.
FILE * stream;
/// The current column number.
uint32_t column;
/// The current line number.
uint32_t line;
/// The most recent error code.
spsps_errno errno;
/// Whether the buffer been initialized the first time
bool initialized;
};
//======================================================================
// Helper functions.
//======================================================================
SPSPS_CHAR chbuf[30]; // U+002e (.) and U+0000002e.
char * spsps_printchar(SPSPS_CHAR xch) {
unsigned SPSPS_CHAR ch = (unsigned SPSPS_CHAR) xch;
if (isprint(ch)) {
sprintf(chbuf, "U+%04x (%1c)", ch, ch);
} else {
sprintf(chbuf, "U+%04x", ch);
}
return chbuf;
}
void
spsps_read_other_(Parser parser) {
// Allocation: Nothing is allocated or deallocated by this method.
size_t count = fread(parser->blocks[parser->block^1], sizeof(SPSPS_CHAR),
SPSPS_LOOK, parser->stream);
if (count < SPSPS_LOOK) {
if (sizeof(SPSPS_CHAR) == 1) {
memset(parser->blocks[parser->block^1] + count, SPSPS_EOF,
SPSPS_LOOK - count);
} else {
for (; count < SPSPS_LOOK; ++count) {
parser->blocks[parser->block^1][count] = SPSPS_EOF;
} // Clear the remainder of the block.
}
}
}
void spsps_initialize_parser_(Parser parser){
spsps_read_other_(parser);
parser->block ^= 1;
parser->initialized = true;
}
//======================================================================
// Primitives.
//======================================================================
char *
spsps_loc_to_string(Loc * loc) {
if (loc == NULL) {
// Return something the caller can deallocate.
char * ret = (char *) malloc(1);
ret[0] = 0;
return ret;
}
// Generate the string. An unsigned 32 bit integer can produce (with no
// bugs) a value up to 2^32-1. This is 4*2^30-1, or roughly 4*10^9. We
// allocate 12 digits for each number (which is sufficient), two for
// colons, and one for the terminating null. This is 27. We then add the
// strlen of the name.
size_t mlen = 27 + strlen(loc->name);
char * buf = (char *) malloc(mlen);
sprintf(buf, "%s:%d:%d", loc->name, loc->line, loc->column);
if (strlen(buf) > mlen) {
// This should never, never, never happen.
fprintf(stderr, "Internal error in loc string construction.\n");
exit(1);
}
return buf;
}
SPSPS_CHAR
spsps_look_(Parser parser, size_t n) {
// Allocation: Nothing is allocated or deallocated by this method.
if (n >= SPSPS_LOOK) {
// Lookahead too large.
parser->errno = LOOKAHEAD_TOO_LARGE;
return 0;
}
// If we look too long without progressing, the parser may be stalled.
parser->look_count++;
if (parser->look_count > 1000) {
// Stalled.
parser->errno = STALLED;
return SPSPS_EOF;
}
if(!parser->initialized){
spsps_initialize_parser_(parser);
}
// Look in the correct block.
if (n + parser->next < SPSPS_LOOK) {
return parser->blocks[parser->block][n + parser->next];
} else {
return parser->blocks[parser->block^1][n + parser->next - SPSPS_LOOK];
}
}
//======================================================================
// Implementation of public interface.
//======================================================================
Parser
spsps_new(char * name, FILE * stream) {
// Allocate a new parser. Duplicate the name.
Parser parser = (Parser) calloc(1, sizeof(struct spsps_parser_));
parser->at_eof = false;
parser->block = 0;
parser->eof_count = 0;
parser->look_count = 0;
if (name != NULL) parser->name = strdup(name);
else parser->name = strdup("(unknown)");
parser->next = 0;
if (stream != NULL) parser->stream = stream;
else parser->stream = stdin;
parser->column = 1;
parser->line = 1;
parser->errno = OK;
parser->initialized = false;
return parser;
}
void
spsps_free(Parser parser) {
// Free the parser name and the parser itself.
free(parser->name);
parser->at_eof = true;
parser->name = NULL;
parser->stream = NULL;
free(parser);
}
SPSPS_CHAR
spsps_consume(Parser parser) {
// Nothing is allocated or deallocated by this method.
SPSPS_CHAR ch = spsps_look_(parser, 0);
spsps_consume_n(parser, 1);
parser->errno = OK;
return ch;
}
void
spsps_consume_n(Parser parser, size_t n) {
// Nothing is allocated or deallocated by this method.
if (n >= SPSPS_LOOK) {
// Lookahead too large.
parser->errno = LOOKAHEAD_TOO_LARGE;
return;
}
if(!parser->initialized){
spsps_initialize_parser_(parser);
}
parser->errno = OK;
parser->look_count = 0;
if (parser->at_eof) {
parser->eof_count++;
if (parser->eof_count > 1000) {
// Stalled at EOF.
parser->errno = STALLED_AT_EOF;
return;
}
}
for (size_t count = 0; count < n; ++count) {
if (parser->blocks[parser->block][parser->next] == SPSPS_EOF) {
parser->at_eof = true;
return;
}
parser->column++;
if (parser->blocks[parser->block][parser->next] == '\n') {
parser->line++;
parser->column = 1;
}
parser->next++;
if (parser->next >= SPSPS_LOOK) {
parser->next -= SPSPS_LOOK;
parser->block ^= 1;
spsps_read_other_(parser);
}
} // Loop to consume characters.
}
void
spsps_consume_whitespace(Parser parser) {
// Nothing is allocated or deallocated by this method.
while (strchr(" \t\r\n", spsps_peek(parser)) != NULL)
spsps_consume(parser);
parser->errno = OK;
}
bool
spsps_eof(Parser parser) {
// Nothing is allocated or deallocated by this method.
parser->errno = OK;
return parser->at_eof;
}
Loc *
spsps_loc(Parser parser) {
// A loc instance is allocated by this method.
parser->errno = OK;
Loc * loc = (Loc *) malloc(sizeof(struct spsps_loc_));
loc->name = parser->name;
loc->line = parser->line;
loc->column = parser->column;
return loc;
}
SPSPS_CHAR
spsps_peek(Parser parser) {
// Nothing is allocated or deallocated by this method.
parser->errno = OK;
return spsps_look_(parser, 0);
}
char *
spsps_peek_n(Parser parser, size_t n) {
// Allocates and returns a fixed-length string.
if (n >= SPSPS_LOOK) {
// Lookahead too large.
parser->errno = LOOKAHEAD_TOO_LARGE;
return "";
}
parser->errno = OK;
SPSPS_CHAR * buf = (SPSPS_CHAR *) malloc(sizeof(SPSPS_CHAR) * n);
for (size_t index = 0; index < n; ++index) {
buf[index] = spsps_look_(parser, index);
} // Read characters into buffer.
return buf;
}
bool
spsps_peek_str(Parser parser, char * next) {
// Nothing is allocated or deallocated by this method.
size_t n = strlen(next);
if (n >= SPSPS_LOOK) {
// Lookahead too large.
parser->errno = LOOKAHEAD_TOO_LARGE;
return false;
}
parser->errno = OK;
for (size_t index = 0; index < n; ++index) {
if (next[index] != spsps_look_(parser, index)) return false;
} // Check all characters.
return true;
}
bool
spsps_peek_and_consume(Parser parser, char * next) {
// Nothing is allocated or deallocated by this method.
parser->errno = OK;
if (spsps_peek_str(parser, next)) {
spsps_consume_n(parser, strlen(next));
return true;
} else {
return false;
}
}
|
C
|
// simple.c
// Drew Bies
// project 2
// CPSC 346 02
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/slab.h>
typedef struct person
{
int month;
int day;
int year;
struct person *next;
} node;
node* pptr;
// makes node with head ptr
void makeNode(node** ptr)
{
node* newNode = (node*) kmalloc(sizeof(node),GFP_USER);
newNode -> month = 10;
newNode -> day = 8;
newNode -> year = 2019;
newNode -> next = NULL;
*ptr = newNode;
}
// prints node from ptr
void printNode(node* ptr)
{
if(ptr != NULL)
{
printk(KERN_INFO "month: %d\n", ptr -> month);
printk(KERN_INFO "day: %d\n", ptr -> day);
printk(KERN_INFO "year: %d\n", ptr -> year);
printk(KERN_INFO "next: NULL\n");
}else{
printk(KERN_INFO "ptr = NULL\n");
}
}
/* This function is called when the module is loaded. */
int simple_init(void)
{
printk(KERN_INFO "Loading Module\n");
makeNode(&pptr);
printNode(pptr);
return 0;
}
/* This function is called when the module is removed. */
void simple_exit(void)
{
printk(KERN_INFO "Removing Module\n");
pptr = NULL;
printNode(pptr);
}
/* Macros for registering module entry and exit points. */
module_init( simple_init );
module_exit( simple_exit );
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Simple Module");
MODULE_AUTHOR("SGG");
|
C
|
#include "utilities.h"
const int mounthLUTny[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; // days in non leap year
const int mounthLUTly[] = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }; // days in leap year
const int mounthDays[] = { 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // days in a mounth
void utils_convert_counter_2_hms( uint32 counter, uint8 *phour, uint8 *pminute, uint8 *psecond)
{
counter = (counter>>1) % (3600*24); // get the hour of day
if ( phour )
*phour = counter / 3600;
counter = counter % 3600;
if ( pminute )
*pminute = counter / 60;
if ( psecond )
*psecond = counter % 60;
}
void utils_convert_counter_2_ymd( uint32 counter, uint16 *pyear, uint8 *pmounth, uint8 *pday )
{
uint32 year;
uint32 mounth;
uint32 day;
const int *mounthLUT;
int i;
counter = (counter>>1) / (3600*24); // get the day nr from YEAR_START
year = (counter * 100 + 99) / 36525; // calculate the year
counter -= ((year * 36525) / 100); // leave only the days from year
// find the mouth
if ( (year+1) % 4 )
mounthLUT = mounthLUTny;
else
mounthLUT = mounthLUTly;
for (i=11; i>=0; i--)
{
if ( mounthLUT[i] <= counter )
break;
}
mounth = i;
// find the day
day = counter - mounthLUT[i];
if ( pday )
*pday = day+1;
if ( pmounth )
*pmounth = mounth+1;
if ( pyear )
*pyear = year+YEAR_START;
}
uint32 utils_convert_date_2_counter( datestruct *pdate, timestruct *ptime )
{
uint32 counter = 0;
uint32 myear;
uint32 days;
if ( pdate->year < YEAR_START)
return 0;
if ( pdate->mounth > 12 )
return 0;
myear = pdate->year - YEAR_START; // starting with leap year
// add the time
if ( ptime )
counter = (ptime->hour*3600 + ptime->minute*60 + ptime->second);
// add the days
days = (pdate->day-1);
// add the mounths
if ( (myear+1) % 4 )
days = days + mounthLUTny[pdate->mounth-1]; // add the days of the elapsed mounths considering leap year
else
days = days + mounthLUTly[pdate->mounth-1]; // add the days of the elapsed mounths considering non-leap year
// add the years
days = days + ((myear * 36525) / 100); // the rounding takes care of leap year +1 day addition
counter = counter + days * 24 * 3600;
return (counter<<1);
}
uint32 utils_maximum_days_in_mounth( datestruct *pdate )
{
uint32 days;
days = mounthDays[pdate->mounth-1];
if ( days == 0 )
{
uint32 myear;
myear = pdate->year - YEAR_START; // starting with leap year
if ( (myear+1) % 4 )
return 28;
else
return 29;
}
return days;
}
uint32 utils_day_of_week( uint32 counter )
{
uint32 dow;
dow = (counter >> 1) / (3600*24); // gives back the days;
dow = (dow + WEEK_START) % 7;
return dow; // return 0 based value (0 means monday)
}
uint32 utils_week_of_year( uint32 counter )
{
uint32 woy;
uint32 days_yearstart;
uint32 days_thisday;
days_thisday = (counter >> 1) / (3600*24); // total days till this day
// calculate the start day of this year ( yearX_Ian_01 )
woy = (days_thisday * 100 + 99) / 36525; // calculate the year
days_yearstart = ((woy * 36525) / 100); // days till beginning of this year - the rounding takes care of leap year +1 day addition
days_thisday = (days_thisday + WEEK_START) / 7; // this amount of weeks till the current day
days_yearstart = ( days_yearstart + WEEK_START ) / 7; // this amount of weeks till the current year
woy = days_thisday - days_yearstart;
return woy;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct node Node;
typedef int boolean;
#define true 1
#define false 2
struct node{
int data;
struct node *next;
}; //structure to node
void deleteNode(Node *node){ free(node); } //free the memory location of a node
Node* createNewNode(int value){
Node *node = (Node*) malloc(sizeof(Node));
node->data = value;
node->next = NULL;
return node; //returns a new node[ node(data:value,next:NULL) ]
}
boolean isEmpty(Node* start) { return start == NULL; } //retruns list is empty or not
Node* insert_end(Node *start,int value){
Node *newNode = createNewNode(value); //create a new node with value
Node *ptr;
if(start == NULL) start = newNode;
else{
ptr = start;
while(ptr->next != NULL) ptr = ptr->next;
ptr->next = newNode;
}
return start;
}
Node* insert_begin(Node *start,int value){
Node *newNode = createNewNode(value);
if(start == NULL) start = newNode;
else{
newNode->next = start;
start = newNode;
}
return start;
}
Node* insert_before(Node *start,int value,int before){
if (isEmpty(start)){
printf("Error:underflow!\n");
return start;
}
if (start->data == before) return insert_begin(start,value);
Node *newNode = createNewNode(value),*ptr,*preptr;
ptr = start;
preptr = ptr;
while(ptr->data != before){
preptr = ptr;
ptr = ptr->next;
if(preptr->next == NULL){
printf("Error:%d is not found!\n",before);
return start;
}
}
newNode->next = ptr;
preptr->next = newNode;
return start;
}
Node* insert_after(Node* start,int value,int after){
if (isEmpty(start)){
printf("Error:underflow!\n");
return start;
}
Node *ptr,*preptr;
ptr = start;
preptr = ptr;
Node *newNode = createNewNode(value);
if(preptr->data == after){
ptr = preptr->next;
newNode->next = ptr;
preptr->next = newNode;
return start;
}
while(preptr->data != after){
preptr = ptr;
ptr = ptr->next;
if(preptr->next==NULL) {
if (preptr->data == after) return insert_end(start,value);
printf("Error:%d is not found!\n",after);
return start;
}
}
newNode->next = ptr;
preptr->next = newNode;
return start;
}
int readValue(){
printf("Enter a value: ");
int n;
scanf("%d",&n);
return n;
}
Node* delete_begin(Node *start){
if (isEmpty(start)){
printf("Error:underflow!\n");
return start;
}
Node *tmp;
tmp = start;
start = start->next;
deleteNode(tmp);
return start;
}
Node* delete_end(Node *start){
if (isEmpty(start)){
printf("Error:underflow!\n");
return start;
}
Node *ptr = start,*preptr = start;
while(ptr->next != NULL){
preptr = ptr;
ptr = ptr->next;
}
preptr->next = NULL;
deleteNode(ptr);
return start;
}
Node* delete_node(Node *start,int value){
if (isEmpty(start)){
printf("Error:underflow!\n");
return start;
}
if (start->data == value) return delete_begin(start);
Node *ptr,*preptr;
ptr = preptr = start;
while(ptr->data != value){
if (ptr->next == NULL) {
printf("Error:%d is not found!\n",value);
return start;
}
preptr = ptr;
ptr = ptr->next;
}
preptr->next = ptr->next;
deleteNode(ptr);
return start;
}
Node* delete_after(Node* start,int after){
if (isEmpty(start)){
printf("Error:underflow!\n");
return start;
}
Node *ptr,*preptr;
ptr = preptr = start;
if(preptr->data == after){
ptr = preptr->next;
preptr->next = ptr->next;
deleteNode(ptr);
return start;
}
while(preptr->data != after){
if (preptr->next == NULL){
printf("Error:%d is not found!\n",after);
return start;
}
preptr = ptr;
ptr = ptr->next;
}
if (preptr->next==NULL){
printf("Error:no value found after %d!\n",after);
return start;
}
preptr->next = ptr->next;
deleteNode(ptr);
return start;
}
Node* delete_before(Node* start,int before){
if (isEmpty(start)){
printf("Error:underflow!\n");
return start;
}
if(start->data == before){
printf("Error:no value before %d!\n" , before);
return start;
}
Node *ptr,*preptr,*ppretr;
ppretr= preptr = ptr = start;
if(preptr->next->data == before){
start = preptr->next;
deleteNode(ptr);
return start;
}
while(ptr->data != before){
if(ptr->next == NULL){
printf("Error:%d is not found!\n",before);
return start;
}
ppretr = preptr;
preptr = ptr;
ptr = ptr->next;
}
ppretr->next = ptr;
deleteNode(preptr);
return start;
}
Node* delete_list(Node* start){
while(start!= NULL) start = delete_begin(start);
return start;
}
void displayList(Node *start){
if (isEmpty(start)){
printf("Error:list is empty!\n");
return;
}
Node *ptr = start;
while(ptr->next != NULL){
printf("%d, ", ptr->data);
ptr = ptr->next;
}
printf("%d\n", ptr->data);
}
Node* sort_list(Node* start){
if (isEmpty(start)){
printf("Error:can't sort.list is empty!\n");
return start;
}
Node *ptr1,*ptr2;
int temp;
ptr1 = start;
while(ptr1 != NULL){
ptr2 = ptr1->next;
while(ptr2 != NULL){
if(ptr1->data>ptr2->data){
temp = ptr1 -> data;
ptr1->data = ptr2->data;
ptr2->data = temp;
}
ptr2 = ptr2->next;
}
ptr1 = ptr1->next;
}
return start;
}
int main(){
printf("\n*** Linked List Implementation ***\n\n");
Node *start1 = NULL; //start point for new list
printf("%s\n", isEmpty(start1) ? "list is empty!" : "list is not empty!" ); //cheak list empty or not
//now list is empty.but I try to delete values from list.
start1 = delete_begin(start1); //deleting 1st node
start1 = delete_end(start1); //deleting last node
start1 = delete_node(start1,56); //deleting a value
start1 = delete_before(start1,45); //deleting node before a value
start1 = delete_after(start1,67); //deleting node after value
start1 = delete_list(start1); //deleting all list.nothing except
//fine! all got Error:underflow!
displayList(start1); //printing the list
printf("---------------------------------------\n\n");
//cheak insert_before and insert_after at under flow condition
start1 = insert_before(start1,5,6); //inserting 5 before 6
start1 = insert_after(start1,5,6); //inserting 5 after 6
//fine! both got Error:underflow!
displayList(start1); //printing the list
printf("---------------------------------------\n\n");
//cheaking insert_begin Function:this will insert items to front
start1 = insert_begin(start1,5); //inserting 5 -> 5 : at NULL
displayList(start1);
start1 = insert_begin(start1,6); //inserting 6 -> 6,5
displayList(start1);
start1 = insert_begin(start1,7); //inserting 7 -> 7,6,5
displayList(start1);
//works fine :)
printf("---------------------------------------\n\n");
//deleting all list to cheack insert_after Function
start1 = delete_list(start1);
displayList(start1);
//success! : deleteing list works fine!
printf("---------------------------------------\n\n");
//cheaking insert_end Function:this will insert items to end
start1 = insert_end(start1,5); //inserting 5 -> 5 : at NULL
displayList(start1);
start1 = insert_end(start1,6); //inserting 6 -> 5,6
displayList(start1);
start1 = insert_end(start1,7); //inserting 7 -> 5,6,7
displayList(start1);
//works fine :)
printf("---------------------------------------\n\n");
//adding more dummy data
start1 = insert_end(start1,8);
start1 = insert_end(start1,9);
start1 = insert_end(start1,10);
start1 = insert_end(start1,11);
start1 = insert_end(start1,12);
start1 = insert_end(start1,13);
start1 = insert_end(start1,14);
start1 = insert_end(start1,15);
start1 = insert_end(start1,16);
start1 = insert_end(start1,17);
start1 = insert_end(start1,18);
start1 = insert_end(start1,19);
start1 = insert_end(start1,20);
displayList(start1);
//done!
printf("---------------------------------------\n\n");
//cheaking insert_before Function insert_before(list,value,target)
start1 = insert_before(start1,76,5); //insert before 1st value
displayList(start1); //success!
start1 = insert_before(start1,77,12); //insert before a middle value
displayList(start1); //success!
start1 = insert_before(start1,78,20); //insert before last value
displayList(start1); //success!
start1 = insert_before(start1,79,100); //insert before not related value
//got the error:not found
displayList(start1); //success!
//works fine for all possibilities.
printf("---------------------------------------\n\n");
//checking insert_after Function insert_before(list,value,target)
start1 = insert_after(start1,80,76); //insert after 1st value
displayList(start1); //success!
start1 = insert_after(start1,80,13); //insert after a middle value
displayList(start1); //success!
start1 = insert_after(start1,82,20); //insert after last value
displayList(start1); //success!
start1 = insert_after(start1,83,100); //insert after not related value
//got the error:not found
displayList(start1); //success!
//works fine for all possibilities.
printf("---------------------------------------\n\n");
//checking deleting funtions
start1 = delete_begin(start1); //deleting 1st element
displayList(start1);
start1 = delete_end(start1); //deleting last element
displayList(start1);
start1 = delete_node(start1,13); //deleting 1st element
displayList(start1);
//they are working
printf("---------------------------------------\n\n");
//checking delete_after function
start1 = delete_after(start1,80); //1st element
displayList(start1);
start1 = delete_after(start1,12); //a middle element
displayList(start1);
start1 = delete_after(start1,20); //last element
displayList(start1);
start1 = delete_after(start1,100); //not related element
displayList(start1);
//nice worked :D
printf("---------------------------------------\n\n");
//checking delete_before function
start1 = delete_before(start1,80); //1st element
displayList(start1);
start1 = delete_before(start1,77); //middle element
displayList(start1);
start1 = delete_before(start1,20); //last element
displayList(start1);
start1 = delete_before(start1,100); //not leated element
displayList(start1);
//gg working
printf("---------------------------------------\n\n");
//check sorting list
printf("Sorted list!\n");
sort_list(start1); //sorting
displayList(start1);
//worked
printf("---------------------------------------\n\n");
//removing all list
start1 = delete_list(start1); //empty list again
displayList(start1);
//working
printf("---------------------------------------\n\n");
//add 2 element and test sort function
start1 = insert_end(start1,9);
start1 = insert_end(start1,6);
sort_list(start1);
displayList(start1);
//worked
//check it for 1 element
start1 = delete_node(start1,9);
sort_list(start1);
displayList(start1);
//worked
//now im going to sort empty list :D
start1 = delete_node(start1,6);
sort_list(start1);
displayList(start1);
return 0;
}
|
C
|
/***************************************************************************************************
ExploreEmbedded
****************************************************************************************************
* File: eeprom.c
* Version: 15.0
* Author: ExploreEmbedded
* Website: http://www.exploreembedded.com/wiki
* Description: Contains the library routines for Eeprom Read-Write
The libraries have been tested on ExploreEmbedded development boards. We strongly believe that the
library works on any of development boards for respective controllers. However, ExploreEmbedded
disclaims any kind of hardware failure resulting out of usage of libraries, directly or indirectly.
Files may be subject to change without prior notice. The revision history contains the information
related to updates.
GNU GENERAL PUBLIC LICENSE:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Errors and omissions should be reported to [email protected]
***************************************************************************************************/
/***************************************************************************************************
Revision History
****************************************************************************************************
15.0: Initial version
***************************************************************************************************/
#include "eeprom.h"
#include "delay.h"
#include "xc.h"
extern void eeprom_write(unsigned char addr, unsigned char value);
extern unsigned char eeprom_read(unsigned char addr);
/***************************************************************************************************
void EEPROM_WriteByte(uint16_t v_eepromAddress_u16, uint8_t v_eepromData_u8)
***************************************************************************************************
* I/P Arguments: uint16_t: eeprom_address at which eeprom_data is to be written
uint8_t: byte of data to be to be written in eeprom.
* Return value : none
* description: This function is used to write the data at specified EEPROM_address..
**************************************************************************************************/
void EEPROM_WriteByte(uint16_t v_eepromAddress_u16, uint8_t v_eepromData_u8)
{
eeprom_write(v_eepromAddress_u16,v_eepromData_u8);
/* unsigned char gie_Status;
while(WR); // check the WR bit to see if a WR is in progress
EEADR=eepromAddress; // Write the address to EEADR.
EEDATA=eepromData; // load the 8-bit data value to be written in the EEDATA register.
WREN=1; // Set the WREN bit to enable eeprom operation.
gie_Status = GIE; // Store the Interrupts enable/disable state
GIE = 0; // Disable the interrupts
EECON2=0x55; // Execute the special instruction sequence
EECON2=0xaa; // Refer the datasheet for more info
WR=1; // Set the WR bit to trigger the eeprom write operation.
GIE = gie_Status; // Restore the interrupts
WREN=0; // Disable the EepromWrite
*/
}
/***************************************************************************************************
uint8_t EEPROM_ReadByte(uint16_t v_eepromAddress_u16)
***************************************************************************************************
* I/P Arguments: uint16_t: eeprom_address from where eeprom_data is to be read.
* Return value : uint8_t: data read from Eeprom.
* description: This function is used to read the data from specified EEPROM_address.
***************************************************************************************************/
uint8_t EEPROM_ReadByte(uint16_t v_eepromAddress_u16)
{
while(RD || WR); // check the WR&RD bit to see if a RD/WR is in progress
EEADR=v_eepromAddress_u16; // Write the address to EEADR.
// Make sure that the address is not larger than the memory size
RD = 1; // Set the WR bit to trigger the eeprom read operation.
return(EEDATA); // Return the data read form eeprom.
}
/***************************************************************************************************
void EEPROM_WriteNBytes(uint16_t v_eepromAddress_u16, uint8_t *ptr_ramAddress_u8, uint16_t v_numOfBytes_u16)
***************************************************************************************************
* I/P Arguments: uint16_t,: eeprom_address from where the N-bytes are to be written.
uint8_t*: Buffer(Pointer) containing the N-Bytes of data to be written in Eeprom.
uint16_t : Number of bytes to be written
* Return value : none
* description:
This function is used to write N-bytes of data at specified EEPROM_address.
***************************************************************************************************/
#if ( ENABLE_EEPROM_WriteNBytes == 1)
void EEPROM_WriteNBytes(uint16_t v_eepromAddress_u16, uint8_t *ptr_ramAddress_u8, uint16_t v_numOfBytes_u16)
{
while(v_numOfBytes_u16 != 0)
{
EEPROM_WriteByte(v_eepromAddress_u16,*ptr_ramAddress_u8); //Write a byte from RAM to EEPROM
v_eepromAddress_u16++; //Increment the Eeprom Address
ptr_ramAddress_u8++; //Increment the RAM Address
v_numOfBytes_u16--; //Decrement NoOfBytes after writing each Byte
}
}
#endif
/***************************************************************************************************
void EEPROM_ReadNBytes(uint16_t EepromAddr, uint8_t *RamAddr, uint16_t NoOfBytes)
***************************************************************************************************
* I/P Arguments: uint16_t,: eeprom_address from where the N-bytes is to be read.
uint8_t*: Pointer to copy the N-bytes read from Eeprom.
uint16_t : Number of bytes to be Read
* Return value : none
* description:
This function is used to Read N-bytes of data from specified EEPROM_address.
The data read from the eeprom will be copied into the specified RamAddress.
##Note: Care should be taken to allocate enough buffer to read the data.
***************************************************************************************************/
#if ( ENABLE_EEPROM_ReadNBytes == 1)
void EEPROM_ReadNBytes(uint16_t v_eepromAddress_16, uint8_t *ptr_ramAddress_u8, uint16_t v_numOfBytes_u16)
{
while(v_numOfBytes_u16 != 0)
{
*ptr_ramAddress_u8 = EEPROM_ReadByte(v_eepromAddress_16);//Read a byte from EEPROM to RAM
v_eepromAddress_16++; //Increment the EEPROM Address
ptr_ramAddress_u8++; //Increment the RAM Address
v_numOfBytes_u16--; //Decrement NoOfBytes after Reading each Byte
}
}
#endif
/***************************************************************************************************
void EEPROM_WriteString(uint16_t v_eepromAddress_u16, char *ptr_stringPointer_u8)
***************************************************************************************************
* I/P Arguments: uint16_t,: eeprom_address where the String is to be written.
char*: Pointer to String which has to be written.
* Return value : none
* description:This function is used to Write a String at specified EEPROM_address.
NOTE: Null char is also written into the eeprom.
***************************************************************************************************/
#if ( ENABLE_EEPROM_WriteString == 1)
void EEPROM_WriteString(uint16_t v_eepromAddress_u16, char *ptr_stringPointer_u8)
{
do
{
EEPROM_WriteByte(v_eepromAddress_u16,*ptr_stringPointer_u8); //Write a byte from RAM to EEPROM
ptr_stringPointer_u8++; //Increment the RAM Address
v_eepromAddress_u16++; //Increment the Eeprom Address
}while(*(ptr_stringPointer_u8-1) !=0);
}
#endif
/***************************************************************************************************
void EEPROM_ReadString(uint16_t v_eepromAddress_u16, char *ptr_destStringAddress_u8)
***************************************************************************************************
* I/P Arguments: uint16_t,: eeprom_address from where the String is to be read.
char*: Pointer into which the String is to be read.
* Return value : none
* description:This function is used to Read a String from specified EEPROM_address.
The string read from eeprom will be copied to specified buffer along with NULL character
***************************************************************************************************/
#if ( ENABLE_EEPROM_ReadString == 1)
void EEPROM_ReadString(uint16_t v_eepromAddress_u16, char *ptr_destStringAddress_u8)
{
char eeprom_data;
do
{
eeprom_data = EEPROM_ReadByte(v_eepromAddress_u16); //Read a byte from EEPROM to RAM
*ptr_destStringAddress_u8 = eeprom_data; //Copy the data into String Buffer
ptr_destStringAddress_u8++; //Increment the RAM Address
v_eepromAddress_u16++; //Increment the Eeprom Address
}while(eeprom_data!=0);
}
#endif
/***************************************************************************************************
void EEPROM_Erase()
***************************************************************************************************
* I/P Arguments: none
* Return value : none
* description: This function is used to erase the entire Eeprom memory.
Complete Eeprom(C_MaxEepromSize_U16) is filled with 0xFF to accomplish the Eeprom Erase.
***************************************************************************************************/
#if ( ENABLE_EEPROM_Erase == 1)
void EEPROM_Erase()
{
uint16_t v_eepromAddress_u16;
for(v_eepromAddress_u16=0;v_eepromAddress_u16<C_MaxEepromSize_U16;v_eepromAddress_u16++)
{
EEPROM_WriteByte(v_eepromAddress_u16,0xffu); // Write Each memory location with OxFF
}
}
#endif
|
C
|
#include <cs50.h>
#include <stdio.h>
int get_positive_int(string message, int minimum, int max);
int main(void)
{
int minimum = 1;
int max = 8;
int height = get_positive_int("Write a number from %i to %i: ", 1, 8);
for (int i = 1; i <= height; i++)
{
for (int j = 1; j <= height; j++)
{
int max_spaces_to_print = height - i;
if (j <= max_spaces_to_print)
{
printf(" ");
}
else
{
printf("#");
}
}
printf("\n");
}
}
int get_positive_int(string message, int minimum, int max)
{
int n;
do
{
n = get_int(message, minimum, max);
}
while (n < minimum || n > max);
return n;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "tela.h"
#include "linhas.h"
#define MALLOC(x) ((x *) malloc (sizeof(x)))
/***********************************************************************************************************************************/
/***********************************************************************************************************************************/
ListaDeLinhas* createLinhas(ListaDeLinhas *listaDeLinhas)
{
//No *novo;
//listaDeLinhas = MALLOC(ListaDeLinhas);
listaDeLinhas = (ListaDeLinhas*)malloc(sizeof(ListaDeLinhas));
listaDeLinhas->tamanho = 0;
listaDeLinhas->inicio = NULL;
listaDeLinhas->fim = NULL;
return listaDeLinhas;
}
void writeLinhas (ListaDeLinhas *listaDeLinhas, int ind, Lista *c)
{
Linha *novo;
novo = (Linha*)malloc(sizeof(Linha));
novo->info = c;
if (ind == 0 || listaDeLinhas->tamanho == 0)
{
novo->anterior = NULL;
if (listaDeLinhas->tamanho == 0)
{
novo->proximo = NULL;
listaDeLinhas->inicio = listaDeLinhas->fim = novo;
}
else
{
novo->proximo = listaDeLinhas->inicio;
listaDeLinhas->inicio = novo;
}
}
else if ((ind >= listaDeLinhas->tamanho))
{
novo->proximo = NULL;
novo->anterior = listaDeLinhas->fim;
listaDeLinhas->fim->proximo = novo;
listaDeLinhas->fim = novo;
}
else
{
int i;
Linha *percorre;
percorre = listaDeLinhas->inicio;
for (i = 0 ; i < ind-1 ; i++)
percorre = percorre->proximo;
Linha *aux;
aux = percorre->proximo;
percorre->proximo = novo;
novo->anterior = percorre;
novo->proximo = aux;
aux->anterior = novo;
}
listaDeLinhas->tamanho++;
};
Lista* readLinhas (ListaDeLinhas *listaDeLinhas, int ind)
{
int i;
Linha *percorre;
percorre = listaDeLinhas->inicio;
for (i = 0 ; i < ind ; i++)
percorre = percorre->proximo;
return percorre->info;
};
Lista* eraseLinhas (ListaDeLinhas *listaDeLinhas, int ind)
{
Lista* retorno;
if ((ind == 0) && (listaDeLinhas->tamanho == 1))
free(listaDeLinhas->inicio);
else if (ind == 0)
{
Linha *aux;
aux = listaDeLinhas->inicio;
retorno = listaDeLinhas->inicio->info;
listaDeLinhas->inicio = listaDeLinhas->inicio->proximo;
free(aux);
}
else if (ind >= listaDeLinhas->tamanho-1)
{
Linha *aux;
aux = listaDeLinhas->fim;
retorno = listaDeLinhas->fim;
listaDeLinhas->fim = listaDeLinhas->fim->anterior;
free(aux);
}
else
{
int i;
Linha *percorre;
percorre = listaDeLinhas->inicio;
for (i = 0 ; i < ind ; i++)
percorre = percorre->proximo;
retorno = percorre->info;
Linha *ant, *prox;
ant = percorre->anterior;
prox = percorre->proximo;
ant->proximo = prox;
prox->anterior = ant;
free(percorre);
}
listaDeLinhas->tamanho--;
return retorno;
};
void verificarLinhas(ListaDeLinhas *listaDeLinhas)
{
Linha *percorre;
percorre = listaDeLinhas->inicio;
while (percorre != NULL)
{
//printf("\n\n\n\n ant:%p atual:%p pro:%p" , percorre->anterior , percorre , percorre->proximo);
if (percorre->info->tamanho == 101)
{
if (percorre == listaDeLinhas->fim)
{
Lista *novaLinha;
novaLinha = create(novaLinha);
writeLinhas(listaDeLinhas, listaDeLinhas->tamanho+1 , novaLinha);
//printf("\n\n\n\n\n\n\n\n\n ! %p" , listaDeLinhas->fim->info);
char letra = erase( listaDeLinhas->fim->anterior->info , listaDeLinhas->fim->anterior->info->tamanho);
writeC(
listaDeLinhas->fim->info,
0 ,
letra);
//printf("\n\n\n\n\n\n\n\n\n criou nova Linha :%p !" , listaDeLinhas->fim);
//printf("\n! %c" , letra);
}
else
{
//printf("\n\n\n\n\n\n\n Linha :%p !" , listaDeLinhas->fim);
//printf("\n\n\n\n\n\n\n Linha :%c !" , listaDeLinhas->fim->anterior->anterior->info->fim->info);
if (percorre->info != NULL)
writeC(
percorre->proximo->info ,
0 ,
erase(percorre->info , percorre->info->tamanho));
}
}
percorre = percorre->proximo;
}
}
int getTamanhoL(ListaDeLinhas *listaDeLinhas)
{
return listaDeLinhas->tamanho;
};
|
C
|
#include "sudoku.h"
#include <stdio.h>
#include <stdlib.h>
Position* fromGrid(char grid[9][9])
{
int i,j; //za setanje po matrici
Position *mySudoku = (Position*)malloc(sizeof(Position)); //alociraj mem oblika strukture Position (predstavlja sudoku)
mySudoku->load=0;
for (i=0;i<9;i++)
{
for (j=0;j<9;j++)
{
mySudoku->grid[i][j] = grid[i][j]; //prekopiraj broj na poziciju
if (grid[i][j] > 0 && grid[i][j] < 10) //ako je u dozvoljenom intervalu
(mySudoku->load)++; //povecaj broj upisanih brojeva
else if (grid[i][j] > 9 || grid[i][j]<0) //ako neko pobogu neispravno zada grid
{
printf("Error: Number at position [%d][%d] out of interval (0-9)",i,j);
return NULL;
}
}
}
return mySudoku;
}
void printPosition(Position *p)
{
int i,j;
printf("-----------------\n"); //uljepsavanja
for (i=0;i<9;i++)
{ //
for (j=0;j<9;j++) //setaj po poljima
{
printf("%d", p->grid[i][j]);
if (j==2 || j==5 ||j==8) //uljepsavanje
printf(" | ");
if (j==8) //novi red kad si dosa do kraja reda
printf("\n");
}
if (i==2 || i==5 || i==8) //uljepsavanje
printf("-----------------\n");
}
}
int legalMoves(Position *p, Move moves[1000])
{
int a,b; //ova dva su koordinate za setanje po sudokuu
int m,n; //jedan je za provjeravat broj, drugi je za provjeravat redak i stupac
int k=0; //ovog vracam, broji poteze
int flag = 1; //sluzi za provjerit jeli potez legalan
for (a=0;a<9;a++)
{
for (b=0;b<9;b++) //
{ //
if (p->grid[a][b]==0) // setanje po sudoku
{
for (m=1;m<10;m++) //broj za usporedjivanje
{
for (n=0;n<9;n++) //za redak i stupac trenutne pozicije
{
if (p->grid[a][n]==m) //uvik isti redak, minja se stupac
{
flag=0;
break;
}
if (p->grid[n][b]==m) //uvik isti stupac, minja se redak
{
flag=0;
break;
}
}
if (!flag)
{
flag = 1;
continue;
}
if ((p->grid[((a/3)*3)+((a+1)%3)][((b/3)*3)+((b+1)%3)] == m) || (p->grid[((a/3)*3)+((a+1)%3)][((b/3)*3)+((b+2)%3)] == m)
|| (p->grid[((a/3)*3)+((a+2)%3)][((b/3)*3)+((b+1)%3)] == m) || (p->grid[((a/3)*3)+((a+2)%3)][((b/3)*3)+((b+2)%3)] == m))
flag=0; //ovo je sve jedan ogromni praseci if, uglavnom, pokriva pozicije koje nisu provjerene
//sa ova gornja dva if-a
if (flag && n==9) //mislin da mi ovi flag ode mozda niti ne triba, mogu stavit continue u gornji if
{
moves[k].i=a; //koordinata x je a
moves[k].j=b; //koordinata y je b
moves[k].input=m; //broj koji moze na tu poziciju je onaj koji je prosa sve zadane provjere
//printf("%d. (%d,%d) -> %d\n",k,moves[k].i,moves[k].j,m);
k++; //inkrementiraj broj koji ces vratit
}
flag=1;
}
}
}
}
return k;
}
void makeMove(Position *p, Move m)
{
p->grid[m.i][m.j]=m.input;
(p->load)++;
}
void undoMove(Position *p, Move m)
{
p->grid[m.i][m.j]=0;
(p->load)--;
}
int ncnt = 0;
int solveSudoku(Position *p)
{
int i,k;
Move moves[1000];
k = legalMoves(p,moves);
ncnt++;
if(ncnt % 10000 == 0) //ovo broji rekurzivne pozive
{
printf("%d rekurzivnih poziva\n",ncnt);
printf("%d ispunjeno\n",p->load);
}
if (p->load==81) //ako je load 81 znaci da je sudoku ispunjen
{
printf("81 ispunjeno\n SUCCESS !!\n");
return 1;
}
for (i=0;i<k;i++)
{
makeMove(p,moves[i]); //napravi potez
if (solveSudoku(p)) //rukurzivni poziv
{
return 1;
}
undoMove(p,moves[i]); //kad ovaj gornji poziv ne dodje do kraja, ponisti taj potez koji si napravija
}
return 0;
}
/*void sortMoves(Move moves[1000], int n)
{
}*/
|
C
|
#include "monty.h"
/**
* add - function that adds the top two elements of the stack.
* @stack: top pointer of a doubly linked list.
* @line_number: number of line in file where we found the command.
* Return: nothing.
*/
void add(stack_t **stack, unsigned int line_number)
{
stack_t *aux1 = *stack;
(void) line_number;
*stack = (*stack)->prev;
(*stack)->n = ((*stack)->n) + (aux1->n);
(*stack)->next = NULL;
free(aux1);
}
/**
* nop - function that doesn’t do anything.
* @stack: top pointer of a doubly linked list.
* @line_number: number of line in file where we found the command.
* Return: nothing.
*/
void nop(stack_t **stack, unsigned int line_number)
{
(void) line_number;
(void) stack;
}
/**
* sub - function that subtracts the top element of the stack
* from the second top element of the stack.
* @stack: top pointer of a doubly linked list.
* @line_number: number of line in file where we found the command.
* Return: nothing.
*/
void sub(stack_t **stack, unsigned int line_number)
{
stack_t *aux1 = *stack;
(void) line_number;
*stack = (*stack)->prev;
(*stack)->n = ((*stack)->n) - (aux1->n);
(*stack)->next = NULL;
free(aux1);
}
/**
* _div - function that divides the second top element of the stack
* by the top element of the stack.
* @stack: top pointer of a doubly linked list.
* @line_number: number of line in file where we found the command.
* Return: nothing.
*/
void _div(stack_t **stack, unsigned int line_number)
{
stack_t *aux1 = *stack;
(void) line_number;
*stack = (*stack)->prev;
(*stack)->n = ((*stack)->n) / (aux1->n);
(*stack)->next = NULL;
free(aux1);
}
/**
* mul - function that multiplies the top two elements of the stack.
* @stack: top pointer of a doubly linked list.
* @line_number: number of line in file where we found the command.
* Return: nothing.
*/
void mul(stack_t **stack, unsigned int line_number)
{
stack_t *aux1 = *stack;
(void) line_number;
*stack = (*stack)->prev;
(*stack)->n = ((*stack)->n) * (aux1->n);
(*stack)->next = NULL;
free(aux1);
}
|
C
|
#include "Position.h"
#include "Error.h"
#include <stdlib.h>
#include <assert.h>
Component_Type POSITION_COMPONENT = "Position";
struct Position
{
Component info;
double x, y;
};
Position* Position_create(double x, double y)
{
Position* self = malloc(sizeof(Position));
if(!self)
error(ERROR_ALLOC);
self->info.type = String_create(POSITION_COMPONENT);
self->x = x;
self->y = y;
return self;
}
void Position_destroy(Position** p_component)
{
assert(p_component && (*p_component));
String_destroy(&(*p_component)->info.type);
free((*p_component));
(*p_component) = NULL;
}
double Position_get_x(const Position* self)
{
assert(self);
return self->x;
}
double Position_get_y(const Position* self)
{
assert(self);
return self->y;
}
void Position_set_x(Position* self, double x)
{
assert(self);
self->x = x;
}
void Position_set_y(Position* self, double y)
{
assert(self);
self->y = y;
}
|
C
|
#include "csapp.h"
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
int main()
{
pid_t pid = fork();
if (pid == 0)
printf("\n Hi from the child - my pid = %d \n", pid);
else
printf("hello from parent - pid = %d \n", pid);
return 0;
}
|
C
|
//
// main.c
// Exercise 3
//
// Created by Changheng Chen on 11/17/16.
// Copyright © 2016 Changheng Chen. All rights reserved.
//
/* Predict what will be printed on the screen */
#include <stdio.h>
#define PRD(a) printf("%d", (a) ) // Print decimal
#define NL printf("\n"); // Print new line
// Create and initialize array
int a[]={0, 1, 2, 3, 4};
int main()
{
int i;
int* p;
// Print a from a[0] to a[4]
for (i=0; i<=4; i++) PRD(a[i]); // 1: 0 1 2 3 4
NL;
// p gets address a[0] first, then a[0], a[1],...,a[4]
for (p=&a[0]; p<=&a[4]; p++) PRD(*p); // 2: 0 1 2 3 4
NL;
NL;
// p gets address a[0] first, then the adress increases with i
for (p=&a[0], i=0; i<=4; i++) PRD(p[i]); // 3: 0 1 2 3 4
NL;
// p gets address a[0] by receiving the array name 'a'
// *(p+i) points to a[0], a[3], a[5] subsequently
// a+4 is the address a[4]
for (p=a, i=0; p+i<=a+4; p++, i++) PRD(*(p+i)); // 4: 0 2 4
NL;
NL;
// p points to a[4] first, then jumps back to a[0] one array element a time
for (p=a+4; p>=a; p--) PRD(*p); // 5: 4 3 2 1 0
NL;
// p points to a[4] first, then decreases to a[3], a[2], a[1], a[0]
for (p=a+4, i=0; i<=4; i++) PRD(p[-i]); // 6: 4 3 2 1 0
NL;
// p points to a[5] first, p-a changes from 4, 3, 2, 1 to 0
for (p=a+4; p>=a; p--) PRD(a[p-a]); // 7: 4 3 2 1 0
NL;
return 0;
}
|
C
|
#include "lists.h"
#include <stdlib.h>
/**
* delete_dnodeint_at_index - inserts a node at position
* @h: double pointer to the head
* @index: index to insert new node
* Return: 1 or - 1
*/
int delete_dnodeint_at_index(dlistint_t **h, unsigned int index)
{
dlistint_t *temp = NULL;
unsigned int i = 0;
if (!h || !(*h))
{
return (-1);
}
else
{
temp = *h;
while (index != i++ && temp)
temp = temp->next;
if (!temp)
return (-1);
if (temp->next)
temp->next->prev = temp->prev;
if (index == 0)
*h = temp->next;
else
temp->prev->next = temp->next;
free(temp);
return (1);
}
return (-1);
}
|
C
|
/*
Johannes Schneemann
November 26, 2019
*****************************************************
This C program compares the performance of the LRU
and the Optimal page replacement algorithms.
*****************************************************
Description:
The program will take a reference string and the number of frames as inputs.
The maximum length of a reference string is 20 and there are 5 diffent pages from
page 1 to page 5. The reference string can be randomly generated and the number of
frames (max. 5) is entered through the keyboard. For example, the system generates a reference
string 2 1 3 4 5 2 3 ...5 and you enter the number of frames 3.
Compare the number of page faults generated by the Optimal and LRU algorithms.
Print out the page replacement process and you can see
how LRU differs from the optimal.
Note: Ties are not addressed!
*/
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int inMemory(int reference, int memory[], int numberFrames);
void displayMemory(int memory[], int numberFrames);
int min(int a, int b);
int max(int a, int b);
int pageFaults = 0;
int main(){
int numberFrames = -1, refStringLength = -1;
int memory[5], referenceString[20];
for(;;){
printf("Please enter the length of the reference string (max 20):");
scanf(" %d", &refStringLength);
printf("Please enter the number of frames to use (max 5):");
scanf(" %d", &numberFrames);
if(refStringLength >= 1 && refStringLength <= 20 &&
numberFrames >= 1 && numberFrames <= 5){
srand(time(NULL));
//initialize all frames to zero
for(int i = 0; i < numberFrames; i++){
memory[i] = 0;
}
//random reference string
for(int i = 0; i < refStringLength; i++){
int randomInt = ((rand() % 5) + 1);
if(randomInt != referenceString[i - 1]){
referenceString[i] = randomInt;
}else{
i--;
}
}
if(refStringLength != 20){
referenceString[refStringLength] = -1;
}
//Display reference string
printf("\nThe generated reference string is:\n");
int i = 0;
while((referenceString[i] != -1) && (i < 20)){
printf("%d ", referenceString[i]);
i++;
}
printf("\n");
/*
* Optimal Algorithm
* If there is an empty frame & reference is not in the list,
* load a page into it. Variable i iterates through the frames
* and variable j iterates through the reference string.
*/
printf("\n<----------*** OPTIMAL ALRORITHM ***---------->\n");
i = 0;
int j = 0;
for(j = 0; i < numberFrames; j++){
if(referenceString[j] == -1){
break;
}else if(!inMemory(referenceString[j], memory, numberFrames)){
memory[i] = referenceString[j];
i++;
displayMemory(memory, numberFrames);
}else{
printf("%d is in memory\n", referenceString[j]);
}
}
while(j < refStringLength){
int out = 0;
if(inMemory(referenceString[j], memory, numberFrames)){
printf("%d is in memory\n", referenceString[j]);
}else{
/*
* Page replacement section for Optimal begins
*/
int replacementIndex = 0;
int found = 0;
for(int m = 0; m < numberFrames; m++){
found = 0;
int frameValue = memory[m];
for(int n = j; n < refStringLength; n++){
if(frameValue == referenceString[n]){
found = 1;
if(m == 0)
replacementIndex = n;
else{
replacementIndex = max(replacementIndex, n);
}
break;
}
}
if(!found) {
out = frameValue;
break;
}
}
if(found)
out = referenceString[replacementIndex];
for(int n = 0; n < numberFrames; n++) {
if (memory[n] == out) {
memory[n] = referenceString[j];
break;
}
}
displayMemory(memory, numberFrames);
}
j++;
}
printf("NUMBER OF PAGE FAULTS: %d\n", pageFaults);
/*
* LRU Algorithm
* If there is an empty frame & reference is not in the list,
* load a page into it. Variable i iterates through the frames
* and variable j iterates through the reference string.
*/
printf("\n<----------*** LRU ALGORITHM ***-------------->\n");
//initialize all frames to zero and reset page fault counter
for(int i = 0; i < numberFrames; i++)
memory[i] = 0;
pageFaults = 0;
i = 0;
j = 0;
for(j = 0; i < numberFrames; j++){
if(referenceString[j] == -1)
break;
else if(!inMemory(referenceString[j], memory, numberFrames)){
memory[i] = referenceString[j];
i++;
displayMemory(memory, numberFrames);
}else{
printf("%d is in memory\n", referenceString[j]);
}
}
while(j < refStringLength){
int _replacementIndex;
int _out;
if(inMemory(referenceString[j], memory, numberFrames)){
printf("%d is in memory\n", referenceString[j]);
}else{
/*
* Page replacement section for LRU begins
* Move from the end to get LRU and determines
* LRU by getting most previous reference string call
*/
_replacementIndex = 20;
int _frameValue = -1;
for(int m = 0; m < numberFrames; m++){
_frameValue = memory[m];
for(int n = (j-1); n >= 0; n--){
if(_frameValue == referenceString[n]){
_replacementIndex = min(_replacementIndex, n);
break;
}
}
}
_out = referenceString[_replacementIndex];
for(int n = 0; n < numberFrames; n++){
if(memory[n] == _out){
memory[n] = referenceString[j];
break;
}
}
displayMemory(memory, numberFrames);
}
j++;
}
printf("NUMBER OF PAGE FAULTS: %d\n\n", pageFaults);
break;
}
printf("Invalid selection, choose again.\n");
}
return 0;
}
int inMemory(int reference, int memory[], int numberFrames){
int loaded = 0;
for(int i = 0; i < numberFrames; i++){
if(reference == memory[i]){
loaded = 1;
break;
}
}
return loaded;
}
void displayMemory(int memory[], int numberFrames){
for(int i = 0; i < numberFrames; i++)
printf("%d ", memory[i]);
printf("\n");
pageFaults++;
}
int min(int a, int b){
if(a < b)
return a;
return b;
}
int max(int a, int b){
if(a > b)
return a;
return b;
}
|
C
|
#include <stdio.h>
int fun(int n)
{
if (n == 2 || n == 3)
return 1;
if (n == 1)
return 0;
else
return fun (n - 2) + fun(n - 3);
}
int main()
{
int n;
//int sum = 0;
while (scanf("%d", &n) != EOF) {
printf("%d\n", fun(n));
}
return 0;
}
|
C
|
/*
** calc_k.c for raytracer in /home/cheval_y//raytracer/sources/intersection
**
** Made by franck chevallier
** Login <[email protected]>
**
** Started on Thu Apr 11 11:18:04 2013 franck chevallier
** Last update Fri Jun 7 18:16:04 2013 antoine simon
*/
#include "raytracer.h"
int calc_k(t_discriminant disc, double *k1, double *k2)
{
if (disc.delta > 0)
{
(*k1) = (- disc.b - sqrt(disc.delta)) / (2 * disc.a);
(*k2) = (- disc.b + sqrt(disc.delta)) / (2 * disc.a);
return (0);
}
if (disc.delta == 0)
{
(*k1) = (disc.b * - 1) / 2 * disc.a;
(*k2) = (*k1);
return (0);
}
return (1);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* Dados trs nmeros verificar se eles podem representar as medidas dos lados de um
tringulo e, se puderem, classificar o tringulo em equiltero, issceles ou escaleno.
Para codificar o programa, devemos lembrar das seguintes definies:
Para que trs nmeros representem os lados de um tringulo necessrio que cada um deles seja menor que a
soma dos outros dois.
Um tringulo equiltero se tem os trs lados iguais, issceles se tem
apenas dois lados iguais e escaleno se tem todos os lados distintos. */
int main()
{
float a,b,c;
printf("Informe os lados de um triangulo (Digitos separados por espao)\n");
scanf("%f %f %f",&a,&b,&c);
if(a<=b+c && b<=a+c && c<=b+a){
printf("Valores correspondem a um tringulo\n");
if(a==b && b==c)
printf("Triangulo equilatero\n");
else
if(a!=b && b!=c && a!=c)
printf("Triangulo escaleno\n");
else
printf("Triangulo isosceles\n"); //if (a==b || a==c || b==c)
}
else
printf("Valores no correspondem a um tringulo\n");
system("PAUSE");
return 0;
}
|
C
|
#include "main.h"
#include "arg.h"
/********************************************************************/
/* */
/* ALTERNATYWNA DO PRZEDSTAWIONEJ NA WYKLADZIE WERSJA OPRACOWANIA */
/* PARAMETROW WYWOLANIA PROGRAMU UWZGLEDNIAJACA OPCJE Z PARAMETRAMI */
/* Z ODPOWIEDNIO ZAPROPONOWANYMI STRUKTURAMI DANYCH PRZEKAZUJACYMI */
/* WCZYTANE USTAWIENIA */
/* COPYRIGHT (c) 2007-2013 ZPCiR */
/* */
/* Autorzy udzielaja kazdemu prawa do kopiowania tego programu */
/* w calosci lub czesci i wykorzystania go w dowolnym celu, pod */
/* warunkiem zacytowania zrodla */
/* */
/********************************************************************/
/************************************************************************/
/* Funkcja rozpoznaje opcje wywolania programu zapisane w tablicy argv */
/* i zapisuje je w strukturze wybor */
/* Skladnia opcji wywolania programu */
/* program {[-i nazwa] [-o nazwa] [-p liczba] [-n] [-r] [-d] } */
/* Argumenty funkcji: */
/* argc - liczba argumentow wywolania wraz z nazwa programu */
/* argv - tablica argumentow wywolania */
/* wybor - struktura z informacjami o wywolanych opcjach */
/* PRE: */
/* brak */
/* POST: */
/* funkcja otwiera odpowiednie pliki, zwraca uchwyty do nich */
/* w strukturze wybor, do tego ustawia na 1 pola, ktore */
/* poprawnie wystapily w linii wywolania programu, */
/* pola opcji nie wystepujacych w wywolaniu ustawione sa na 0; */
/* zwraca wartosc W_OK, gdy wywolanie bylo poprawne */
/* lub kod bledu zdefiniowany stalymi B_* (<0) */
/* UWAGA: */
/* funkcja nie sprawdza istnienia i praw dostepu do plikow */
/* w takich przypadkach zwracane uchwyty maja wartosc NULL */
/************************************************************************/
int przetwarzaj_opcje(int argc, char **argv, w_opcje *wybor) {
int i,k,kolejna=0;
/*Zaalokowanie pamieci na tablice obslugujaca opcje*/
char *nazwa_pliku_we, *nazwa_pliku_wy;
wybor->opcje=malloc(argc*sizeof(int));
wyzeruj_opcje(wybor,argc);
wybor->plik_wy=stdout; /* na wypadek gdy nie podano opcji "-o" */
for (i=1; i<argc; i++) {
if (argv[i][0] != '-'){ /* blad: to nie jest opcja - brak znaku "-" */
fprintf(stderr,"Plik: arg.c Funkcja: Przetwarzaj_opcje\nArgument %s ",argv[i]);
return B_NIEPOPRAWNAOPCJA;
};
switch (argv[i][1]) {
case 'i': { /* opcja z nazwa pliku wejsciowego */
if (++i<argc) { /* wczytujemy kolejny argument jako nazwe pliku */
nazwa_pliku_we=argv[i];
if (strcmp(nazwa_pliku_we,"-")==0){ /* gdy nazwa jest "-" */
wybor->plik_we=stdin; /* ustwiamy wejscie na stdin */
}else{ /* otwieramy wskazany plik */
if(argv[i][0]!='-'){
wybor->plik_we=fopen(nazwa_pliku_we,"r");
}else{
};
};
}else{
fprintf(stderr,"Plik: arg.c Funkcja: Przetwarzaj_opcje\nArgument %s ",argv[--i]);
return B_BRAKNAZWY; /* blad: brak nazwy pliku */
};
break;
}
case 'o': { /* opcja z nazwa pliku wyjsciowego */
if (++i<argc) { /* wczytujemy kolejny argument jako nazwe pliku */
nazwa_pliku_wy=argv[i];
if (strcmp(nazwa_pliku_wy,"-")==0){/* gdy nazwa jest "-" */
wybor->plik_wy=stdout; /* ustwiamy wyjscie na stdout */
}else{ /* otwieramy wskazany plik */
wybor->plik_wy=fopen(nazwa_pliku_wy,"w");
};
}else{
fprintf(stderr,"Plik: arg.c Funkcja: Przetwarzaj_opcje\nArgument %s ",argv[--i]);
return B_BRAKNAZWY; /* blad: brak nazwy pliku */
};
break;
}
case 'p': {
if (++i<argc) { /* wczytujemy kolejny argument jako wartosc progu */
if (sscanf(argv[i],"%d",&wybor->prog)==1){
wybor->opcje[kolejna]=PROGOWANIE;
kolejna++;
}else{
fprintf(stderr,"Plik: arg.c Funkcja: Przetwarzaj_opcje\nArgument %s ",argv[i]);
return B_BLEDNAWARTOSCI; /* blad: niepoprawna wartosc progu */
};
}else{
fprintf(stderr,"Plik: arg.c Funkcja: Przetwarzaj_opcje\nArgument %s ",argv[--i]);
return B_BRAKWARTOSCI;
}; /* blad: brak wartosci progu */
break;
}
case 'n': { /* mamy wykonac negatyw */
wybor->opcje[kolejna]=NEGATYW;
kolejna++;
break;
}
case 'k': { /* mamy wykonac konturowanie */
wybor->opcje[kolejna]=KONTUROWANIE;
kolejna++;
break;
}
case 'd': { /* mamy wyswietlic obraz */
wybor->opcje[kolejna]=WYSWIETLENIE;
kolejna++;
break;
}
case 'h': { /* mamy wyswietlic instrukcje obslugi */
wybor->pomoc=1;
break;
}
case 'r':{
if(argv[i][2]=='y'){
wybor->opcje[kolejna]=ROZMYCIEY;
kolejna++;
}else if(argv[i][2]=='x'){
wybor->opcje[kolejna]=ROZMYCIEX;
kolejna++;
}else{
fprintf(stderr,"Plik: arg.c Funkcja: Przetwarzaj_opcje\nArgument %s",argv[i]);
return B_NIEPOPRAWNAOPCJA;
};
if (++i<argc){ /* wczytujemy kolejny argument jako wartosc progu */
if (sscanf(argv[i],"%d",&wybor->promien)!=1){
fprintf(stderr,"Plik: arg.c Funkcja: Przetwarzaj_opcje\nArgument %s",argv[i]);
return B_BLEDNAWARTOSCI; /* blad: niepoprawna wartosc promienia */
};
}else{
fprintf(stderr,"Plik: arg.c Funkcja: Przetwarzaj_opcje\nArgument %s ",argv[--i]);
return B_BRAKWARTOSCI;
}; /* blad: brak wartosci promienia */
break;
}
case 's':{ /* mamy wykonac konwersje do szarosci*/
wybor->konwersja=1;
break;
}
case 'e':{ /* mamy wykonac rozciaganie histogramu*/
wybor->opcje[kolejna]=HISTOGRAM;
kolejna++;
break;
}
case 'z': { /* Wykonamy zamiane poziomow czerni i bieli*/
wybor->opcje[kolejna]=ZAMIANA;
kolejna++;
if (++i<argc) { /* wczytujemy kolejny argument jako wartosc czerni*/
if (sscanf(argv[i],"%d",&wybor->czern)!=1) {
fprintf(stderr,"Plik: arg.c Funkcja: Przetwarzaj_opcje\nArgument %s %s ",argv[i-1],argv[i]);
return B_BLEDNAWARTOSCI;}; /* blad: niepoprawna wartosc */
} else {
fprintf(stderr,"Plik: arg.c Funkcja: Przetwarzaj_opcje\nArgument %s ",argv[--i]);
return B_BRAKWARTOSCI; /* blad: brak wartosci*/
};
if (++i<argc) { /* wczytujemy kolejny argument jako wartosc bieli*/
if (sscanf(argv[i],"%d",&wybor->biel)!=1) {
fprintf(stderr,"Plik: arg.c Funkcja: Przetwarzaj_opcje\nArgument %s %s ",argv[i-2],argv[i]);
return B_BLEDNAWARTOSCI;}; /* blad: niepoprawna wartosc */
} else {
fprintf(stderr,"Plik: arg.c Funkcja: Przetwarzaj_opcje\nArgument %s ",argv[i-2]);
return B_BRAKWARTOSCI; /* blad: brak wartosci*/
};
break;
}
case 'm': { /* Operacja przetwarzania macierza*/
wybor->opcje[kolejna]=MASKA;
kolejna++;
for(k=0;k<WSP_MASKI;k++){
if (++i<argc) { /* wczytujemy kolejne wspolczynniki*/
if (sscanf(argv[i],"%d",&wybor->wspolczynniki[k])!=1) {
fprintf(stderr,"Plik: arg.c Funkcja: Przetwarzaj_opcje\nArgument %s %s",argv[i-k-1],argv[i]);
return B_BLEDNAWARTOSCI;
}; /* blad: niepoprawna wartosc */
}else {
fprintf(stderr,"Plik: arg.c Funkcja: Przetwarzaj_opcje\nArgument %s ",argv[i-k-1]);
return B_BRAKWARTOSCI; /* blad: brak wartosci*/
};
};
break;
}
case '?': /*Gdy podano nieprawidlowe opcje*/
printf("Dostepne opcje:\n");
printf("-i [nazwa_pliku]- wczytanie pliku wejsciowego\n");
printf("-o [nazwa_pliku]- zapis do pliku wyjsciowego\n");
printf("-d - wyswietlenie programem display\n");
printf("-n - negatyw\n");
printf("-k - konturowanie\n");
printf("-s - konwersja obrazu kolorowego do szarosci\n");
printf("-z [czern] [biel] - zamiana poziomow czerni i bieli\n");
printf("-rx [promien] - rozmycie poziome\n");
printf("-ry [promien] - rozmycie pionowe\n");
printf("-e - rozciaganie histogramu\n");
printf("-p [prog] - progowanie\n");
printf("-m <w1-w9> - przetwarzanie macierza konwolucji o wsp w1-w9");
printf("-h - pomoc, wyswietla pelna instrukcje obslugi programu\n");
printf("\n");
break;
default: /* nierozpoznana opcja */
fprintf(stderr,"Plik: arg.c Funkcja: Przetwarzaj_opcje\nArgument %s",argv[i]);
return B_NIEPOPRAWNAOPCJA;
}; /*koniec switch */
}; /* koniec for */
return WSZYSTKO_OK;
}
/********************************************
* Funkcja alokuje pamiec dynamiczna *
* *
* Wejscie: *
* wymx, wymy - wymiary tablicy *
* *
* Wyjscie *
* wskaznik na zaalokowana pamiec *
* *
* *
* Brak warunkow PRE i POST *
* *
* Poprawnosc alokacji pamieci sprawdzana *
* jest w miejscach uzycia funkcji alokuj *
* ze wzgledu na lokalna komunikacje bledow *
* *
********************************************/
int **alokuj(int wymx, int wymy){
int **tablica=NULL;
tablica = malloc(wymy*sizeof(int*));
/* Jesli uda sie zaalokowac pamiec to alokuj dalej*/
if(tablica!=NULL){
for(int y=0; y<wymy;y++){
tablica[y]=malloc(wymx*sizeof(int));
/*Jesli nie udalo sie zaalokowac calej potrzebnej pamieci
To zwolnij wszystko co udalo Ci sie zaalokowac i zwroc NULL*/
if(tablica[y]==NULL){
zwolnij(tablica,wymy);
return NULL;
};
};
};
return tablica;
}
/********************************************
* Funkcja zwalnia pamiec dynamiczna *
* *
* Brak warunkow PRE i POST *
* *
********************************************/
void zwolnij(int **tablica, int wymy){
if(tablica!=NULL){
for(int y=0; y<wymy;y++){
/* Tylko gdy dana pamiec byla poprawnie zaalokowana to ja zwolnij*/
if((tablica[y])!=NULL){
free(tablica[y]);
};
};
free(tablica);
};
}
/********************************************
* Funkcja inicjuje strukture danych. *
* *
* PRE: *
* prawidlowo zainicjowana zmienna *obraz *
* *
* POST: zainicjowana struktura *
********************************************/
void inicjuj_obraz(t_obraz *obraz){
obraz->wymx=0;
obraz->wymy=0;
obraz->szarosci=0;
for(int i=0; i<WYBOR; i++){obraz->wariant[i]='\0';};
obraz->piksele=NULL;
}
/********************************************
* Funkcja kopiuje tablice pikseli *
* *
* Wejscie: *
* tab - wskaznik na kopie *
* obraz - oryginalny obraz *
* *
* Brak warunkow PRE *
* *
* POST - kopiuje oryginalna tablice *
* *
********************************************/
void kopiuj_tab(int **tab,t_obraz obraz){
int wymx;
if(obraz.wariant[1]=='3'){wymx=KOLOR*obraz.wymx;}else{wymx=obraz.wymx;};
for (int i=0; i<obraz.wymy; i++){ /*kopiowanie tablicy*/
for(int j=0; j<wymx; j++){
tab[i][j]=obraz.piksele[i][j];
};
};
}
/*******************************************************/
/* Funkcja inicjuje strukture wskazywana przez wybor */
/* PRE: */
/* poprawnie zainicjowany argument wybor (!=NULL) */
/* POST: */
/* "wyzerowana" struktura wybor wybranych opcji */
/*******************************************************/
void wyzeruj_opcje(w_opcje * wybor, int ile) {
int k;
wybor->plik_we=NULL; /*i*/
wybor->plik_wy=NULL; /*o*/
wybor->pomoc=0;
wybor->prog=0;
wybor->konwersja=0;
wybor->promien=0;
wybor->czern=0;
wybor->biel=0;
for(int k=0;k<WSP_MASKI;k++){wybor->wspolczynniki[k]=0;};
for(k=0;k<ile;k++){wybor->opcje[k]=0;};
}
/*******************************************************/
/* Funkcja zwalnia pamiec dynamiczna programu, */
/* a nastepnie wyswietla komunikat bledu. */
/* */
/* Wejscie: */
/* - numer bledu ktory wystapil */
/* - wskaznik do struktury obrazu */
/* - wskaznik do tablicy z opcjami */
/* */
/* */
/* POST: */
/* zwalnia pamiec i wyswietla komunikat bledu */
/*******************************************************/
void komunikat(int blad, t_obraz *obraz, int *opcje){
/* Najpierw zwalniamy pamiec dynamiczna*/
if(obraz->piksele!=NULL){zwolnij(obraz->piksele,obraz->wymy);};
if(opcje!=NULL){free(opcje);};
/* Teraz rozpoznamy blad i poinformujemy o nim uzytkownika.
Przekazujemy tylko informacje o rodzaju bledu, poniewaz jego
lokalizacja wyswietla sie lokalnie wewnatrz funkcji */
switch (blad) {
case HELP:
fprintf(stderr,"Mam ogromna nadzieje, ze udalo mi sie pomoc ;) \nKomunikat %d\n",blad);
break;
case B_NIEPOPRAWNAOPCJA:
fprintf(stderr,"Niepoprawna opcja \nError %d\n",blad);
break;
case B_BRAKNAZWY:
fprintf(stderr,"Brak nazwy pliku \nError %d\n",blad);
break;
case B_BRAKWARTOSCI:
fprintf(stderr,"Brak wymaganej wartosci \nError %d\n",blad);
break;
case B_BLEDNAWARTOSCI:
fprintf(stderr," Bledna wartosc argumentu \nError %d\n",blad);
break;
case ZLY_FORMAT:
fprintf(stderr,"Niepoprawny format obrazu! \nError %d\n",blad);
break;
case PUSTY_PLIK:
fprintf(stderr,"Plik, ktory probujesz wczytac jest pusty! \nError %d\n",blad);
break;
case BRAK_UCHWYTU:
fprintf(stderr,"Niepoprawne dowiazanie do pliku! Nie udalo sie go otworzyc. \nError %d\n",blad);
break;
case BLAD_PAMIECI:
fprintf(stderr,"Nie udalo sie zaalokowac poprawnie pamieci! \nError %d\n",blad);
break;
}
}
/*******************************************************/
/* Funkcja wyswietla tresc pomocy dla uzytkownika */
/* */
/* Wejscie: */
/* Otrzymuje nazwe programu glownego. */
/* */
/* POST: */
/* wyswietla instrukcje obslugi programu */
/*******************************************************/
void pomoc(char *nazwa){
fprintf(stderr," \n\
______________________________________\n\
| |\n\
| Instrukcja obslugi programu |\n\
|______________________________________|\n\n");
fprintf(stderr,"Przedstawiony program dokonuje operacji edycji na obrazach w formacie .pgm {P2 i P5}.\n\
Umozliwia on rowniez wczytywanie i zapis obrazow kolorowych o formacie .ppm {P3}.\n\
Natomiast mozliwosc edycji obrazow kolorowych jest niedostepna. \n\
Program dokona wtedy konwersji obrazow kolorowych do skali szarosci.\n\n\
WZOR WYWOLANIA: %s -i <arg> -o <arg> [opcje] \n\n\
__________________________________\n\
| |\n\
| OPCJE URUCHAMIANIA PROGRAMU |\n\
|__________________________________|\n\n\
-i ('-'|<nazwa_pliku>) -> WYMAGANA! Ustawienie pliku zrodlowego obrazu. \
Argument '-' oznacza czytanie z stdin.\n\n\
-o ('-'|<nazwa_pliku>) -> WYMAGANA! Ustawienie pliku wynikowego obrazu. \
Argument '-' oznacza wypisanie na stdout.\n\n\
-d -> Wyswietla obraz przed zapisaniem przy uzyciu programu display.\n\n\
-h -> Wyswietla instrukcje obslugi programu ;) \
Powoduje zignorowanie wszystkich innych opcji.\n\n\
____________________________\n\
| |\n\
| OPCJE EDYCJI OBRAZU |\n\
|____________________________|\n\n\
****** !! UWAGA !! ******\nOperacje edycji przedstawione ponizej wykonywane \
beda tylko na obrazach w odcieniach szarosci. \nDlatego tez przy probie edycji obrazu kolorowego zostanie on automatycznie skonwertowany do szarosci.\n\n\
-s -> Dokonuje konwersji obrazy kolorowego .ppm do obrazu w odcieniach szarosci .pgm.\n\n\
-z <czern> <biel> -> Wykonuje na obrazie operacje zamiany poziomow czerni i bieli. \
Wartosci wymagane w argumentach tej opcji to wartosc procentowa nowego \
poziomu czerni i bieli w odniesieniu do wartosci maksymalnej szarosci piksela obrazu.\n\
WARUNEK KONIECZNY : 0 < czern < biel <= 100 oraz czern i biel musza byc liczbami calkowitymi\n\n\
-p <prog> -> Wykonuje operacje progowania obrazu względem zadanej wartosci progu.\n\
WARUNEK KONIECZNY : 0 < prog < 100 oraz prog musi byc liczba calkowita\n\n\
-r(x|y) <promien> -> Wykonuje operacje rozmycia poziomego(dla x) lub pionowego \
(dla y) o wartosci zadanej jako promien rozmycia.\n\
WARUNEK KONIECZNY : 0 < promien < 10 oraz promien musi byc liczba calkowita\n\n\
-k -> Wykonuje operacje konturowania obrazu.\n\n\
-n -> Wykonuje operacje obliczenia negatywu obrazu.\n\n\
-m <w1> <w2> <w3> <w4> <w5> <w6> <w7> <w8> <w9> -> Wykonuje operacje \
przetwarzania obrazu macierza konwolucji. \nWspolczynniki w1-w9 sluza do okreslenia\
filtru maski, ktory ma byc wykonany w operacji. \nWspolczynniki musza być liczbami całkowitymi.\n\n\
",nazwa);
}
|
C
|
/* print a table of squares and cubes */
#include <stdio.h>
double square(double);
double cube(double);
int main(void)
{
int how_many = 0 , i, j;
printf("I want square and cube for 1 to n where n is: ");
scanf("%d", &how_many);
printf("\n square and cubes by interval of .1\n");
for (i=1; i <= how_many; i++)
{
for (j=0; j < 10; j++)
{
printf("\n%lf\t %lf\t%lf",
i + j/10.0, square(i + j/10.0), cube(i + j/10.0));
};
};
printf("\n\n");
return 0;
};
double square(double x)
{
return (x * x);
};
double cube(double x)
{
return (x * x * x);
};
|
C
|
// base2.c
#include <stdlib.h>
#include <stdio.h>
#include "quack.h"
#include <ctype.h>
int check_valid_input(char * x){
fputs("checking if the input is a number...\n", stdout);
while(*x){
printf("%c", *x);
if (!isdigit(*x)){
fprintf(stderr, "\nnot all input are digits!\n");
exit(EXIT_FAILURE);
}
puts("...OK...");
x ++;
}
fputs("input is a number!\n", stdout);
return EXIT_SUCCESS;
}
int main(int argc, char ** argv){
int n, b;
if (argc != 3){
fprintf(stderr, "Usage: ./base number base\n");
return EXIT_FAILURE;
}
printf("you have entered number %s, base %s.\n", *(argv + 1), *(argv + 2));
// check if it is valid
check_valid_input(*(argv + 1));
check_valid_input(*(argv + 2));
sscanf(*(argv + 1), "%d", &n);
b = atoi(*(argv + 2));
printf("converting number to an integer using sscanf... %d\n", n);
printf("converting base to an integer using atoi... %d\n", b);
// setting up quack
Quack t = NULL;
t = createQuack();
fputs("start of loop\n", stdout);
while (n > 0){
printf("push %d %% %d ==> %d\n", n, b, n%b);
if (n%b == 10){
push('a', t);
}
else if (n%b == 11){
push('b', t);
}
else if (n%b == 12){
push('c', t);
}
else if (n%b == 13){
push('d', t);
}
else if (n%b == 14){
push('e', t);
}
else if (n%b == 15){
push('f', t);
}
else if (n%b == 16){
push('g', t);
}
else {
push(n%b + '0', t);
}
showQuack(t);
printf("n = %d/%d\n", n, b);
n = n / b;
}
puts("popping...\n");
while(!isEmptyQuack(t)){
printf("%c", pop(t));
}
puts("\n");
return EXIT_SUCCESS;
}
|
C
|
#include "func.h"
int Cd(char* buf)//进入相对应的目录
{
//printf("cd: %s\n",buf);
char func[100]={0};
int i=2,j=0;
while(buf[i]!='\0')
{
if(buf[i]!=' ') func[j++]=buf[i];
i++;
}
func[j]='\0';
//printf("func=%s\n",func);
if(strcmp(main_pwd,getcwd(NULL,0))==0)
{
if(strcmp(func,"..")==0)
{
printf("cd error\n");
return -1;
}
}
chdir(func);
return 0;
}
int Ls(char *path,File_Info *fileinfo ,int *num)
{
DIR *dir;
dir=opendir(path);
if(dir==NULL)
{
perror("opendir error ");
return -1;
}
int ret;
struct dirent *p;
struct stat buf;
int i=0;
while( (p=readdir(dir))!=NULL ) //每readdir一次,指向下一个文件
{
if(strcmp(p->d_name,".")==0||strcmp(p->d_name,"..")==0) continue;
ret=stat(p->d_name,&buf);//获取每个文件信息,存储在stat结构体中
if(ret==-1)
{
perror("stat");
return -1;
}
if(buf.st_mode/4096==4) fileinfo[i].type='d'; //文件类型,d为目录
else fileinfo[i].type='-';
strcpy(fileinfo[i].name,p->d_name);
fileinfo[i].size=buf.st_size;
i++;
//printf(" %20s",p->d_name); //文件名
//printf(" %10ld字节\n",buf.st_size); //文件大小
}
*num=i;
//printf("ls发送成功\n");
return 0;
}
int Puts(int sfd)
{
int len;
char buf[1000]={0};
int ret;
//接收文件名
ret=recv(sfd,&len,sizeof(len),0);
if(ret==-1)
{
printf("server close\n");
goto end;
}
ret=recv(sfd,buf,len,0);
if(ret==-1)
{
printf("server close\n");
goto end;
}
//puts(buf);
//接收MD5码
char *md5=NULL;
md5=(char *)malloc(32*sizeof(char));
recv(sfd,md5,32,0); //接收MD5
// Connect_Mysql();
// if(strcmp(md5,row[ md5 ])==0)
// {
// row[link]++;
// }
//
//
//接收文件大小
off_t f_size;
ret=recv(sfd,&len,sizeof(len),0);
if(ret==-1)
{
printf("server close\n");
goto end;
}
ret=recv(sfd,&f_size,sizeof(f_size),0);
if(ret==-1)
{
printf("server close\n");
goto end;
}
printf("%ld\n",f_size);
int fd=open(buf,O_RDWR|O_CREAT,0666); //以接收到的文件名为名字创建文件
float total=0;
//float f=f_size*100;
time_t now,last;
now=time(NULL);
last=now;
//以时间打百分比
while(1)
{
ret=recv_n(sfd,(char*)&len,sizeof(len));
if(ret==-1)
{
printf("%5.2f%s\n",total/f_size*100,"%");
break;
}
else if(len>0)
{
total+=len;
time(&now);
if(now-last>=1)
{
printf("%5.2f%s\r",total/f_size*100,"%");
fflush(stdout);//若不刷新缓冲,高速循环中,不能实时打印,只有循环结束才打印
last=now;
}
ret=recv_n(sfd,buf,len);
write(fd,buf,len);
if(ret==-1)
{
printf("%5.2f%s\n",total/f_size*100,"%");
break;
}
}
else
{
printf(" \r");
printf("%s\n","100%");
break;
}
}
end:
close(fd);
return 0;
}
//给客户端发送文件
int Gets(char *buf,int new_fd)
{
//printf("正在发送文件\n");
char fname[100]={0};
int i=4,j=0;
while(buf[i]!='\0')
{
if(buf[i]!=' ') fname[j++]=buf[i];
i++;
}
//fname[j]='\0';
printf("fname=%s\n",fname);
int ret=tran_file(new_fd,fname); //发送文件
if(ret==-1) printf("发送文件失败\n");
else printf("发送文件完成\n");
return 0;
}
int Remove(char *buf)
{
char fname[100]={0};
int i=2,j=0;
while(buf[i]!='\0')
{
if(buf[i]!=' ') fname[j++]=buf[i];
i++;
}
//puts(fname);
int ret=remove(fname);
if(ret==-1) printf("删除失败\n");
else printf("删除成功\n");
return 0;
}
char* Pwd()
{
return getcwd(NULL,0);
}
int Connect_Mysql(char *md5)
{
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char* server="localhost";
char* user="root";
char* password="ran123";
char* database="ranchunfu_1";//要访问的数据库名称
char query[300]="select * from Account";
//puts(query);
int t;
conn=mysql_init(NULL);
if(!mysql_real_connect(conn,server,user,password,database,0,NULL,0))
{
printf("Error connecting to database:%s\n",mysql_error(conn));
}else{
// printf("连接数据库成功,table:Account\n");
}
t=mysql_query(conn,query);
if(t)
{
printf("Error making query:%s\n",mysql_error(conn));
mysql_close(conn);
return -1;
}
res=mysql_use_result(conn);
if(res)
{
while( (row=mysql_fetch_row(res))!=NULL)
{
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "generationCode.h"
// Création fonction choix
void choix (int Num)
{
// Création du fichier param.h
FILE *fichier = NULL;
fichier = fopen("coeur\\param.h", "w+");
// Retourner la valeur saisie dans le fichier créé
fprintf(fichier, "int parametre(){return %d;}", Num);
// Fermer le fichier
fclose(fichier);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.