language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | #include<stdio.h>
int main()
{
int l,b,area,perimeter;
printf("\n enter values of l,b");
scanf("\n%d%d",&l,&b);
area=(l*b);
perimeter=(l*b)+(l*b);
printf("\narea=%d,perimeter=%d",area,perimeter);
}
|
C | #define __REENTRANT
#include <pthread.h>
#include <stdio.h>
void *threadhello(void *unused)
{
printf("Hello, world!\n");
return 0;
}
int main() {
pthread_t thready;
pthread_create(&thready, NULL, &threadhello, NULL);
usleep(10);
}
|
C |
#ifndef Enum_h
#define Enum_h
#include <stdio.h>
/**
Two enums for easy usage of register names and assembly operations
*/
typedef enum reg{
ZERO= 0x0,
AT = 0x1,
V0 = 0x2,
A0 = 0x3,
A1 = 0x4,
T0 = 0x5,
T1 = 0x6,
T2 = 0x7,
T3 = 0x8,
S0 = 0x9,
S1 = 0xa,
S2 = 0xb,
GP = 0xc,
SP = 0xd,
FP = 0xe,
RA = 0xf
} reg;
typedef enum instrucion{
ADD = 0x0,
SUB = 0x1,
AND = 0x2,
OR = 0x3,
SLL = 0x4,
SRA = 0x5,
MAC = 0x6,
BRANCH = 0x7,
RES1 = 0x8,
RES2 = 0x9,
RES3 = 0xa,
JAL = 0xb,
LW = 0xc,
SW = 0xd,
JR = 0xe,
HALT = 0xf
}inst;
#endif /* Enum_h */
|
C | #include <stdio.h>
#include <stdlib.h>
void BubbleSort(int A[], int n)
{
int sorted = 0;
int i;
while (!sorted)
{
sorted = 1;
for (i = 0; i < n; i++)
if (A[i] > A[i + 1])
{
sorted = 0;
int aux = A[i];
A[i] = A[i + 1];
A[i + 1] = aux;
}
}
}
int main()
{
int n, i, A[1000];
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d", &A[i]);
BubbleSort(A, n);
for (i = 0; i < n; i++)
printf("%d ", A[i]);
return 0;
}
|
C | #include "RTC.h"
/*
Read RTC time(Hour, Min, Sec) from CMOS
*/
void kReadRTCTime(BYTE* pbHour, BYTE* pbMinute, BYTE* pbSecond)
{
BYTE bData;
kOutPortByte(RTC_CMOSADDRESS, RTC_ADDRESS_HOUR);
bData = kInPortByte(RTC_CMOSDATA);
*pbHour = RTC_BCDTOBINARY(bData);
kOutPortByte(RTC_CMOSADDRESS, RTC_ADDRESS_MINUTE);
bData = kInPortByte(RTC_CMOSDATA);
*pbMinute = RTC_BCDTOBINARY(bData);
kOutPortByte(RTC_CMOSADDRESS, RTC_ADDRESS_SECOND);
bData = kInPortByte(RTC_CMOSDATA);
*pbSecond = RTC_BCDTOBINARY(bData);
}
/*
Read RTC date(Year, Month, DayOfMonth, DayOfWeek) from CMOS
*/
void kReadRTCDate(WORD* pwYear, BYTE* pbMonth, BYTE* pbDayOfMonth,
BYTE* pbDayOfWeek)
{
BYTE bData;
kOutPortByte(RTC_CMOSADDRESS, RTC_ADDRESS_YEAR);
bData = kInPortByte(RTC_CMOSDATA);
*pwYear = RTC_BCDTOBINARY(bData) + 2000;
kOutPortByte(RTC_CMOSADDRESS, RTC_ADDRESS_MONTH);
bData = kInPortByte(RTC_CMOSDATA);
*pbMonth = RTC_BCDTOBINARY(bData);
kOutPortByte(RTC_CMOSADDRESS, RTC_ADDRESS_DAYOFMONTH);
bData = kInPortByte(RTC_CMOSDATA);
*pbDayOfMonth = RTC_BCDTOBINARY(bData);
kOutPortByte(RTC_CMOSADDRESS, RTC_ADDRESS_DAYOFWEEK);
bData = kInPortByte(RTC_CMOSDATA);
*pbDayOfWeek = RTC_BCDTOBINARY(bData);
}
/*
convert dayofWeek value to string
*/
char* kConvertDayOfWeekToString(BYTE bDayOfWeek)
{
static char* vpcDayOfWeekString[8] = { "Error", "Sunday", "Monday",
"Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
// invalid value
if (bDayOfWeek >= 8)
{
return vpcDayOfWeekString[0];
}
// return string
return vpcDayOfWeekString[bDayOfWeek];
}
|
C | #include <stdio.h>
#define NAME_LEN 20
int main(void)
{
struct {
int number;
char name[NAME_LEN + 1];
int on_hand;
} part1 = {528, "Disk drive", 10},
part2 = {914, "Printer cable", 5};
printf("Part number:\t%d\n", part1.number);
printf("Part name:\t%s\n", part1.name);
printf("Qty on hand:\t%d\n", part1.on_hand);
typedef struct
int number;
char name[NAME_LEN + 1];
int on_hand;
} Part;
return 0;
} |
C | /*
** EPITECH PROJECT, 2019
** corewar
** File description:
** aff.c
*/
#include "corewar.h"
#include <criterion/criterion.h>
#include <criterion/redirect.h>
champion_t *ini_champ(machine_t *machine);
Test(Corewar, aff_i, .init = redirect_all_std)
{
machine_t machine;
machine.champion[0] = ini_champ(&machine);
machine.champion[0]->process->pc = 0;
machine.champion[0]->process->registers[0] = 'i';
f_aff(&machine, machine.champion[0]);
cr_expect_stdout_eq_str("i");
cr_expect_eq(machine.champion[0]->process->pc, 3);
}
Test(Corewar, aff_i_with_modulo, .init = redirect_all_std)
{
machine_t machine;
machine.champion[0] = ini_champ(&machine);
machine.champion[0]->process->pc = 0;
machine.champion[0]->process->registers[0] = 'i' + (256 * 2);
f_aff(&machine, machine.champion[0]);
cr_expect_stdout_eq_str("i");
cr_expect_eq(machine.champion[0]->process->pc, 3);
}
|
C | #include <stdio.h>
#define LENGTH_OF_ARRAY(array) \
(sizeof(array) / sizeof(*array))
int sum(int* array, size_t length_of_array);
int array[] = {1,2,3,4,5,6,7,8,9,10};
int main(int argc, char** argv)
{
int index;
printf("Array: ");
for(index = 0; index < LENGTH_OF_ARRAY(array); index++)
{
printf("%s ", array[index]);
}
printf("\nSum: %i\n", sum(array, LENGTH_OF_ARRAY(array)) );
}
int sum(int* array, size_t length_of_array)
{
int sum = 0;
int index;
for(index = 0; index < length_of_array; index++)
{
sum += array[index];
}
return sum;
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include "seqpair.h"
int main(int argc, char ** argv)
{
if (argc != 3)
{
fprintf(stderr, "not proper amount of inputs\n");
return EXIT_FAILURE;
}
FILE * infptr = fopen(argv[1], "r");
if (infptr == NULL)
{
fprintf(stderr, "Input file failed to open or doesn't exist\n");
return EXIT_FAILURE;
}
listnode ** hcg = NULL;
listnode ** vcg = NULL;
double * widths = NULL;
double * heights = NULL;
int size = parseInputData(infptr, &hcg, &vcg, &widths, &heights);
fclose(infptr);
double * x = calculate_x(hcg, widths, size);
double * y = calculate_y(vcg, heights, size);
FILE * outfptr = fopen(argv[2], "w");
if (outfptr == NULL)
{
fprintf(stderr, "Output file failed to open or doesn't exist\n");
return EXIT_FAILURE;
}
writeOuput(outfptr, x, y, size);
fclose(outfptr);
destroyGraph(hcg, size);
destroyGraph(vcg, size);
free(widths);
free(heights);
free(x);
free(y);
return EXIT_SUCCESS;
}
|
C | #include "unity/src/unity.h"
#include "common.h"
# define ENTRY 1
/*
* Rules:
* ENTRY = "0"*
* Input:
* ""
* Output:
* NULL
*/
P4_PRIVATE(void) test_match_zeroormore_at_least_zero(void) {
P4_Grammar* grammar = P4_CreateGrammar();
TEST_ASSERT_NOT_NULL(grammar);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_AddZeroOrMore(grammar, ENTRY, P4_CreateLiteral("0", true))
);
P4_Source* source = P4_CreateSource("", ENTRY);
TEST_ASSERT_NOT_NULL(source);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_Parse(grammar, source)
);
TEST_ASSERT_EQUAL(0, P4_GetSourcePosition(source));
P4_Token* token = P4_GetSourceAst(source);
TEST_ASSERT_NULL(token);
P4_DeleteSource(source);
P4_DeleteGrammar(grammar);
}
/*
* Rules:
* ENTRY = "0"*
* Input:
* "00000"
* Output:
* ENTRY: "00000"
*/
P4_PRIVATE(void) test_match_zeroormore_multiple_times(void) {
P4_Grammar* grammar = P4_CreateGrammar();
TEST_ASSERT_NOT_NULL(grammar);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_AddZeroOrMore(grammar, ENTRY, P4_CreateLiteral("0", true))
);
P4_Source* source = P4_CreateSource("00000", ENTRY);
TEST_ASSERT_NOT_NULL(source);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_Parse(grammar, source)
);
TEST_ASSERT_EQUAL(5, P4_GetSourcePosition(source));
P4_Token* token = P4_GetSourceAst(source);
TEST_ASSERT_NOT_NULL(token);
TEST_ASSERT_EQUAL_TOKEN_STRING("00000", token);
TEST_ASSERT_EQUAL_TOKEN_RULE(ENTRY, token);
TEST_ASSERT_NULL(token->next);
TEST_ASSERT_NULL(token->head);
TEST_ASSERT_NULL(token->tail);
P4_DeleteSource(source);
P4_DeleteGrammar(grammar);
}
/*
* Rules:
* ENTRY = "0"+
* Input:
* "0"
* Output:
* ENTRY: "0"
*/
P4_PRIVATE(void) test_match_onceormore_at_least_once(void) {
P4_Grammar* grammar = P4_CreateGrammar();
TEST_ASSERT_NOT_NULL(grammar);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_AddOnceOrMore(grammar, ENTRY, P4_CreateLiteral("0", true))
);
P4_Source* source = P4_CreateSource("0", ENTRY);
TEST_ASSERT_NOT_NULL(source);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_Parse(grammar, source)
);
TEST_ASSERT_EQUAL(1, P4_GetSourcePosition(source));
P4_Token* token = P4_GetSourceAst(source);
TEST_ASSERT_NOT_NULL(token);
TEST_ASSERT_EQUAL_TOKEN_RULE(ENTRY, token);
TEST_ASSERT_EQUAL_TOKEN_STRING("0", token);
TEST_ASSERT_NULL(token->next);
TEST_ASSERT_NULL(token->head);
TEST_ASSERT_NULL(token->tail);
P4_DeleteSource(source);
P4_DeleteGrammar(grammar);
}
/*
* Rules:
* ENTRY = "0"+
* Input:
* "00000"
* Output:
* ENTRY: "00000"
*/
P4_PRIVATE(void) test_match_onceormore_multiple_times(void) {
P4_Grammar* grammar = P4_CreateGrammar();
TEST_ASSERT_NOT_NULL(grammar);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_AddOnceOrMore(grammar, ENTRY, P4_CreateLiteral("0", true))
);
P4_Source* source = P4_CreateSource("00000", ENTRY);
TEST_ASSERT_NOT_NULL(source);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_Parse(grammar, source)
);
TEST_ASSERT_EQUAL(5, P4_GetSourcePosition(source));
P4_Token* token = P4_GetSourceAst(source);
TEST_ASSERT_NOT_NULL(token);
TEST_ASSERT_EQUAL_TOKEN_RULE(ENTRY, token);
TEST_ASSERT_EQUAL_TOKEN_STRING("00000", token);
TEST_ASSERT_NULL(token->next);
TEST_ASSERT_NULL(token->head);
TEST_ASSERT_NULL(token->tail);
P4_DeleteSource(source);
P4_DeleteGrammar(grammar);
}
/*
* Rules:
* ENTRY = "0"+
* Input:
* "1"
* Error:
* P4_MatchError
* Output:
* NULL
*/
P4_PRIVATE(void) test_match_onceormore_zero_raise_match_error(void) {
P4_Grammar* grammar = P4_CreateGrammar();
TEST_ASSERT_NOT_NULL(grammar);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_AddOnceOrMore(grammar, ENTRY, P4_CreateLiteral("0", true))
);
P4_Source* source = P4_CreateSource("1", ENTRY);
TEST_ASSERT_NOT_NULL(source);
TEST_ASSERT_EQUAL(
P4_MatchError,
P4_Parse(grammar, source)
);
TEST_ASSERT_EQUAL(0, P4_GetSourcePosition(source));
P4_Token* token = P4_GetSourceAst(source);
TEST_ASSERT_NULL(token);
P4_DeleteSource(source);
P4_DeleteGrammar(grammar);
}
/*
* Rules:
* ENTRY = "0"?
* Input:
* ""
* Output:
* NULL
*/
P4_PRIVATE(void) test_match_zerooronce_match_empty(void) {
P4_Grammar* grammar = P4_CreateGrammar();
TEST_ASSERT_NOT_NULL(grammar);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_AddZeroOrOnce(grammar, ENTRY, P4_CreateLiteral("0", true))
);
P4_Source* source = P4_CreateSource("", ENTRY);
TEST_ASSERT_NOT_NULL(source);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_Parse(grammar, source)
);
TEST_ASSERT_EQUAL(0, P4_GetSourcePosition(source));
P4_Token* token = P4_GetSourceAst(source);
TEST_ASSERT_NULL(token);
P4_DeleteSource(source);
P4_DeleteGrammar(grammar);
}
/*
* Rules:
* ENTRY = "0"?
* Input:
* "0"
* Output:
* ENTRY: "0"
*/
P4_PRIVATE(void) test_match_zerooronce_exact_once(void) {
P4_Grammar* grammar = P4_CreateGrammar();
TEST_ASSERT_NOT_NULL(grammar);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_AddZeroOrOnce(grammar, ENTRY, P4_CreateLiteral("0", true))
);
P4_Source* source = P4_CreateSource("0", ENTRY);
TEST_ASSERT_NOT_NULL(source);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_Parse(grammar, source)
);
TEST_ASSERT_EQUAL(1, P4_GetSourcePosition(source));
P4_Token* token = P4_GetSourceAst(source);
TEST_ASSERT_NOT_NULL(token);
TEST_ASSERT_EQUAL_TOKEN_STRING("0", token);
TEST_ASSERT_EQUAL_TOKEN_RULE(ENTRY, token);
TEST_ASSERT_NULL(token->next);
TEST_ASSERT_NULL(token->head);
TEST_ASSERT_NULL(token->tail);
P4_DeleteSource(source);
P4_DeleteGrammar(grammar);
}
/*
* Rules:
* ENTRY = "0"?
* Input:
* "00000"
* Output:
* ENTRY: "0"
*/
P4_PRIVATE(void) test_match_zerooronce_at_most_once(void) {
P4_Grammar* grammar = P4_CreateGrammar();
TEST_ASSERT_NOT_NULL(grammar);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_AddZeroOrOnce(grammar, ENTRY, P4_CreateLiteral("0", true))
);
P4_Source* source = P4_CreateSource("00000", ENTRY);
TEST_ASSERT_NOT_NULL(source);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_Parse(grammar, source)
);
TEST_ASSERT_EQUAL(1, P4_GetSourcePosition(source));
P4_Token* token = P4_GetSourceAst(source);
TEST_ASSERT_NOT_NULL(token);
TEST_ASSERT_EQUAL_TOKEN_STRING("0", token);
TEST_ASSERT_EQUAL_TOKEN_RULE(ENTRY, token);
TEST_ASSERT_NULL(token->next);
TEST_ASSERT_NULL(token->head);
TEST_ASSERT_NULL(token->tail);
P4_DeleteSource(source);
P4_DeleteGrammar(grammar);
}
/*
* Rules:
* ENTRY = "0"{5}
* Input:
* "00000"
* Output:
* ENTRY: "00000"
*/
P4_PRIVATE(void) test_match_repeat_exact_successfully(void) {
P4_Grammar* grammar = P4_CreateGrammar();
TEST_ASSERT_NOT_NULL(grammar);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_AddRepeatExact(grammar, ENTRY, P4_CreateLiteral("0", true), 5)
);
P4_Source* source = P4_CreateSource("00000", ENTRY);
TEST_ASSERT_NOT_NULL(source);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_Parse(grammar, source)
);
TEST_ASSERT_EQUAL(5, P4_GetSourcePosition(source));
P4_Token* token = P4_GetSourceAst(source);
TEST_ASSERT_NOT_NULL(token);
TEST_ASSERT_EQUAL_TOKEN_STRING("00000", token);
TEST_ASSERT_EQUAL_TOKEN_RULE(ENTRY, token);
TEST_ASSERT_NULL(token->next);
TEST_ASSERT_NULL(token->head);
TEST_ASSERT_NULL(token->tail);
P4_DeleteSource(source);
P4_DeleteGrammar(grammar);
}
/*
* Rules:
* ENTRY = "0"{5}
* Input:
* "0000"
* Error:
* P4_MatchError
* Output:
* NULL
*/
P4_PRIVATE(void) test_match_repeat_exact_no_less(void) {
P4_Grammar* grammar = P4_CreateGrammar();
TEST_ASSERT_NOT_NULL(grammar);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_AddRepeatExact(grammar, ENTRY, P4_CreateLiteral("0", true), 5)
);
P4_Source* source = P4_CreateSource("0000", ENTRY);
TEST_ASSERT_NOT_NULL(source);
TEST_ASSERT_EQUAL(
P4_MatchError,
P4_Parse(grammar, source)
);
TEST_ASSERT_EQUAL(0, P4_GetSourcePosition(source));
P4_Token* token = P4_GetSourceAst(source);
TEST_ASSERT_NULL(token);
P4_DeleteSource(source);
P4_DeleteGrammar(grammar);
}
/*
* Rules:
* ENTRY = "0"{5}
* Input:
* "00001"
* Error:
* P4_MatchError
* Output:
* NULL
*/
P4_PRIVATE(void) test_match_repeat_exact_insufficient_attaching_unmatch(void) {
P4_Grammar* grammar = P4_CreateGrammar();
TEST_ASSERT_NOT_NULL(grammar);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_AddRepeatExact(grammar, ENTRY, P4_CreateLiteral("0", true), 5)
);
P4_Source* source = P4_CreateSource("00001", ENTRY);
TEST_ASSERT_NOT_NULL(source);
TEST_ASSERT_EQUAL(
P4_MatchError,
P4_Parse(grammar, source)
);
TEST_ASSERT_EQUAL(0, P4_GetSourcePosition(source));
P4_Token* token = P4_GetSourceAst(source);
TEST_ASSERT_NULL(token);
P4_DeleteSource(source);
P4_DeleteGrammar(grammar);
}
/*
* Rules:
* ENTRY = "0"{5}
* Input:
* "000000"
* Output:
* ENTRY: "00000"
*/
P4_PRIVATE(void) test_match_repeat_exact_no_more(void) {
P4_Grammar* grammar = P4_CreateGrammar();
TEST_ASSERT_NOT_NULL(grammar);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_AddRepeatExact(grammar, ENTRY, P4_CreateLiteral("0", true), 5)
);
P4_Source* source = P4_CreateSource("000000", ENTRY);
TEST_ASSERT_NOT_NULL(source);
TEST_ASSERT_EQUAL(
P4_Ok,
P4_Parse(grammar, source)
);
TEST_ASSERT_EQUAL(5, P4_GetSourcePosition(source));
P4_Token* token = P4_GetSourceAst(source);
TEST_ASSERT_NOT_NULL(token);
TEST_ASSERT_EQUAL_TOKEN_STRING("00000", token);
TEST_ASSERT_EQUAL_TOKEN_RULE(ENTRY, token);
TEST_ASSERT_NULL(token->next);
TEST_ASSERT_NULL(token->head);
TEST_ASSERT_NULL(token->tail);
P4_DeleteSource(source);
P4_DeleteGrammar(grammar);
}
int main(void) {
UNITY_BEGIN();
RUN_TEST(test_match_zeroormore_at_least_zero);
RUN_TEST(test_match_zeroormore_multiple_times);
RUN_TEST(test_match_onceormore_at_least_once);
RUN_TEST(test_match_onceormore_multiple_times);
RUN_TEST(test_match_onceormore_zero_raise_match_error);
RUN_TEST(test_match_zerooronce_match_empty);
RUN_TEST(test_match_zerooronce_exact_once);
RUN_TEST(test_match_zerooronce_at_most_once);
RUN_TEST(test_match_repeat_exact_successfully);
RUN_TEST(test_match_repeat_exact_no_less);
RUN_TEST(test_match_repeat_exact_insufficient_attaching_unmatch);
RUN_TEST(test_match_repeat_exact_no_more);
return UNITY_END();
}
|
C | #include <stddef.h> // For NULL
#include <stdlib.h> // For malloc()
#include <string.h>
#include <stdio.h>
#include <sys/stat.h> // For stat
#include "printer.h"
#include "arguements.h"
#include "directory.h"
#include "list.h"
#include "sort.h"
static void freeItem(void *item) {
free(item);
};
int main(int numArgs, char *args[]) {
// Declaring a struct to record to handle the arguements
struct Options options = {false, false, false, NULL};
// Handling the arguements
int firstLocationArg = arguements_handler(&options, numArgs, args);
// Defining a dummy struct to hold the max lengths of the lstat values. I don't actually need it, but I need to pass it
Sizes dummySizes = {-1, -1,-1,-1,-1, false};
// Reading the directory
if (options.path == NULL) {
// Printing the current path if we want recursion. (Doing this to mimick ls)
if (options.R) {
printf(".:\n");
}
// If no path argument was passed
read_directory(".", &options, &dummySizes);
} else if ((numArgs - firstLocationArg) > 1){
// If multiple path arguements were passed
// Defining a struct to hold the max lengths of the lstat values
Sizes argsSizes = {0, 0,0,0,0};
// Creating a list to hold regular arguements, so that they can be sorted
List argsList = {0 , NULL, NULL, NULL};
// Creating a list to hold arguements that are paths
List directoryList = {0 , NULL, NULL, NULL};
for (int i = firstLocationArg; i < numArgs; ++i) {
char *arg = (char *) malloc(strlen(args[i]) + 1);
strcpy(arg, args[i]);
struct stat sb;
if (isDirectory(arg)) {
if (lstat(arg, &sb) == -1) {
perror("lstat");
}
// Testing if a directory is a soft link, if yes and l is an arguement, we print it with the files.
// Otherwise we print it with the directories. Doing this to mimic ls
if (S_ISLNK(sb.st_mode) && options.l) {
getSizes(arg, &options, &argsSizes);
addNode(&argsList, arg);
} else {
// Extracting any directories to be printed after
addNode(&directoryList, arg);
}
} else {
// Testing if the file exists so it won't get put on the list
if (lstat(arg, &sb) == -1) {
perror("lstat");
free(arg);
continue;
}
getSizes(arg, &options, &argsSizes);
addNode(&argsList, arg);
}
}
if (argsList.size > 0) {
// Sorting the arguements that are files
selectionSort(&argsList);
Node *current = argsList.head;
do {
read_directory(current->item, &options, &argsSizes);
current = current->next;
} while (current != NULL);
listFree(&argsList, freeItem);
printf("\n");
}
// If there are any directories, we'll send them to be read now
if (directoryList.size > 0) {
// Sorting the arguements that are directories
selectionSort(&directoryList);
Node *current = directoryList.head;
do {
// Testing if quotes need to wrap the directory name
if (quotesNeeded(current->item)) {
printf("\'%s\':\n", (char *) current->item);
} else {
printf("%s:\n", (char *) current->item);
}
read_directory(current->item, &options, &dummySizes);
printf("\n");
current = current->next;
} while (current != NULL);
listFree(&directoryList, freeItem);
}
} else {
read_directory(args[firstLocationArg], &options, &dummySizes);
}
return 0;
}
|
C | #include <stdio.h>
int main() {
int n,a,b,c;
scanf("%d", &n);
for(int i=0; i<n; i++) {
scanf(" %d %d %d", &a, &b, &c);
if(a+b == c || a-b == c || b-a == c || a*b == c || ((a/b == c) && (a%b == 0)) || ((b/a == c) && (b%a == 0))) {
char string [] = "Possible";
puts(string);
}
else {
char string [] = "Impossible";
puts(string);
}
}
return 0;
}
|
C | #include<stdio.h>
int main()
{
int n,nn,sm;
while(scanf("%d",&n)==1&&n!=0) {
nn=n;
while(nn/10>0) {
sm=0;
while(n) {
sm=sm+n%10;
n=n/10;
}
nn=sm;
n=nn;
}
printf("%d\n",nn);
}
return 0;
}
|
C | #include "libmx.h"
void mx_print_arr(int *arr, int n, char *delim) {
if (!arr) {
return;
}
for (int i = 0; i < n; i++) {
mx_printint(arr[i]);
mx_printstr(delim);
}
mx_printchar('\n');
}
|
C | #include <stdlib.h>
#include <stdio.h>
typedef char *data;
typedef int keyType;
struct tree{
keyType key;
data info;
struct tree *left;
struct tree *right;
};
void insertKey(keyType key, data x, struct tree **T);
void deleteKey(keyType key, struct tree **T);
struct tree *search(keyType key, struct tree *T);
struct tree *findMin(struct tree *T);
void printTree(struct tree *T);
int main(){
struct tree *T = NULL;
int i;
/* Insert 10 random key */
for (i = 0; i < 10; i++) {
int ikey = (rand() % 20) + 1;
printf("Insert key %d \n", ikey);
insertKey(ikey, "someinfo", &T);
}
printf("Tree: ");
printTree(T);
printf("\n");
return 0;
}
struct tree *search(keyType key, struct tree *T){
if (NULL == T) return NULL;
else if (key < T->key) return search(key, T->left);
else if (key > T->key) return search(key, T->right);
else return T;
}
void insertKey(keyType key, data x, struct tree **T){
if(*T==NULL){
*T=(struct tree *)malloc(sizeof(**T));
(*T)->key=key;
(*T)->left=NULL;
(*T)->right=NULL;
}
else if((*T)->key<key){
insertKey(key,x,&(*T)->left);
}
else if((*T)->key>key){
insertKey(key,x,&(*T)->right);
}
else fprintf(stderr,"This key alredy exist");
}
struct tree *findMin(struct tree *T)
{
while (NULL != T->left) T = T->left;
return T;
}
void deleteKey(keyType key, struct tree **T){
if(*T==NULL){
fprintf(stderr,"Is not exist");
}
else {
if(key < (*T)->key){
deleteKey(key,&(*T)->left);
}
else if(key > (*T)->key){
deleteKey(key,&(*T)->right);
}
else // Element from delete is okey
if((*T)->left && (*T)->right){
struct tree *replace= findMin((*T)->right);
(*T)->key = replace->key;
(*T)->info = replace->info;
deleteKey((*T)->key,&(*T)->right);
}
else {
struct tree *temp = *T;
if ((*T)->left)
*T = (*T)->left;
else
*T = (*T)->right;
free(temp);
}
}
}
void printTree(struct tree *T)
{
if (NULL == T) return;
printf("%d ", T->key);
printTree(T->left);
printf(" ");
printTree(T->right);
}
|
C | #pragma once
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
static bool g_stop = false;
//SIGTERMźŴʱеѭ
static void handle_term(int sig)
{
g_stop = true;
}
void blacklog_test(int argc, char* argv[])
{
signal(SIGTERM, handle_term); //עźŴ
if (argc < 3) {
printf("usage: %s ip_address port_number backlog\n",
basename(argv[0])); //basenameͷļ<string.h>ȡ·һ/
return;
}
const char *ip = argv[1];
uint16_t port = static_cast<uint16_t>(atoi(argv[2]));
int backlog = atoi(argv[3]);
int sock = socket( //socket
PF_INET, //ײЭ壬PF_INETʾIPv4PF_INET6ʾIPv6PF_UNIXʾUNIXЭ
SOCK_STREAM, //ͣSOCK_STREAMʾTCPSOCK_DGRAMʾUDP
0); //ǰɵЭ鼯£ѡһЭ飬ͨΪ0ʾĬЭ
assert(sock >= 0); //socketʧܷ-1errno
struct sockaddr_in address; //sockaddr_inרIPv4ַsockaddr_in6רIPv6ַ
bzero(&address, sizeof(address)); //addressʼΪ0
address.sin_family = AF_INET; //ַ壬AF_INET=PF_INETAF_INET6=PF_INET6AF_UNIX=PF_UNIX
inet_pton(AF_INET, ip, &address.sin_addr); //ַIPַתֽʾIPַ
address.sin_port = htons(port); //ֽתֽ
int ret = bind( //socketҲΪsocketڷ
sock, //Ҫsocket
(struct sockaddr*)&address, //Ҫĵַ
sizeof(address)); //ַ
assert(ret != -1); //ɹ0ʧܷ-1errno
ret = listen( //
sock, //Ҫsocket
backlog); //ں˼еȣbacklog
assert(ret != -1); //ɹ0ʧܷ-1errno
while (!g_stop) {
sleep(1);
}
close(sock); //رsocketرգǼü
//ҪرգԵshutdown
}
|
C | #include"gauss.h"
Matrix permuter(Matrix m, int row1,int row2){
E *tmp_ligne=m->mat[row1];
m->mat[row1]=m->mat[row2];
m->mat[row2]=tmp_ligne;
return m;
}
Matrix multLigne(Matrix m,int row,float scalar){
int j;
for(j=0;j<m->nb_columns;j++){
m->mat[row][j]*=scalar;
}
return m;
}
Matrix addMultLigne(Matrix m,int row1,int row2,float scalar){
int j;
for(j=0;j<m->nb_columns;j++){
m->mat[row1][j]+=m->mat[row2][j]*scalar;
}
return m;
}
int Pivot_Gauss(Matrix m){
int i,j,k,l;
int rows=m->nb_rows;
int columns=m->nb_columns;
int row_max;
float pivot;
float coeff;
int signe=0;
for(k=0;k<rows;k++){
/*Choix du pivot et verification si la matrice est inversible*/
row_max=k;
for(l=k;l<rows;l++){
if(m->mat[k][k]<m->mat[l][k])
row_max=l;
}
permuter(m,row_max,k);
/*Lors d'un permutation on garde la puissance du coefficient (-1) pour avoir le bon signe du determinant*/
if(row_max!=k)
signe+=row_max+k;
pivot=m->mat[k][k];
/*Descente du pivot de gauss*/
for(i=k+1;i<rows;i++){
coeff=(float) ((float) m->mat[i][k]/(float) pivot);
for(j=k;j<columns;j++){
m->mat[i][j]-=(float) (m->mat[k][j]*coeff);
}
}
}
for(i=0;i<rows;i++){
for(j=0;j<i;j++){
m->mat[i][j]=0;
}
}
return signe;
}
int m_determinant(Matrix m){
int i;
int signe=0;
int det=1;
if(m->nb_rows==2 && m->nb_columns==2)
return (m->mat[0][0]*m->mat[1][1])-(m->mat[0][1]*m->mat[1][0]);
signe=Pivot_Gauss(m);
for(i=0;i<m->nb_rows;i++){
det*=m->mat[i][i];
}
if(signe%2==1)
det*=-1;
return det;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool prime(int n) {
int i = 2;
for(; i < n / 2; i++)
if(n % i == 0)
return false;
return true;
}
int main(int argc, char const *argv[]) {
int TC, n, i, count;
int* a;
int* b;
scanf("%d", &TC);
while(TC--) {
scanf("%d", &n);
count = 0;
a = (int*) malloc(sizeof(int) * n);
b = (int*) malloc(sizeof(int) * n);
for (i = 2; i < (n / 2) + 1; i++) {
if(prime(i) && prime(n - i)) {
a[count] = i;
b[count] = n - i;
count++;
}
}
printf("%d has %d representation(s)\n", n, count);
for(i = 0; i < count; i++)
printf("%d+%d\n", a[i], b[i]);
printf("\n");
}
return 0;
} |
C | #include "ps2simulator.h"
void ps2sim_init(unsigned char* datapin, unsigned char databit, unsigned char* clockpin, unsigned char clockbit) {
// gather data_pin and clock_pin
data_pin = datapin;
data_bit = databit;
clock_pin = clockpin;
clock_bit = clockbit;
// default them to high
ps2sim_setclock(1);
ps2sim_setdata(1);
}
void ps2sim_send(unsigned char buffer) {
// put the clock and the data down
ps2sim_setclock(1);
ps2sim_setdata(0);
delay_us(CLOCK_LENGTH_2);
ps2sim_setclock(0);
ps2sim_setdata(0);
delay_us(CLOCK_LENGTH_2);
// start sending bits
i = 0;
parity = 0xFF;
while (i < 8) {
// set clock up
ps2sim_setclock(1);
// getting the right bit
tempbit = buffer & (1 << i);
parity = tempbit ? ~parity : parity;
ps2sim_setdata(tempbit);
delay_us(CLOCK_LENGTH_2);
// down
ps2sim_setclock(0);
delay_us(CLOCK_LENGTH_2);
// increment
i++;
}
// parity bit
ps2sim_setclock(1);
ps2sim_setdata(parity);
delay_us(CLOCK_LENGTH_2);
ps2sim_setclock(0);
delay_us(CLOCK_LENGTH_2);
// end
ps2sim_setclock(1);
ps2sim_setdata(1);
delay_us(CLOCK_LENGTH_2);
ps2sim_setclock(0);
ps2sim_setdata(1);
delay_us(CLOCK_LENGTH_2);
// put line back to high
ps2sim_setclock(1);
ps2sim_setdata(1);
}
static void ps2sim_setdata(unsigned char value) {
if (value) {
*data_pin |= 1 << data_bit;
} else {
*data_pin &= ~(1 << data_bit);
}
}
static void ps2sim_setclock(unsigned char value) {
if (value) {
*clock_pin |= 1 << clock_bit;
} else {
*clock_pin &= ~(1 << clock_bit);
}
delay_us(5);
} |
C | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_4__ TYPE_1__ ;
/* Type definitions */
typedef int uint32_t ;
struct TYPE_4__ {int exceptions; } ;
typedef TYPE_1__ t_Qm ;
typedef int /*<<< orphan*/ t_Error ;
typedef int /*<<< orphan*/ e_QmExceptions ;
/* Variables and functions */
int /*<<< orphan*/ ASSERT_COND (TYPE_1__*) ;
int /*<<< orphan*/ E_INVALID_VALUE ;
int /*<<< orphan*/ E_OK ;
int /*<<< orphan*/ GET_EXCEPTION_FLAG (int,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ MAJOR ;
int /*<<< orphan*/ RETURN_ERROR (int /*<<< orphan*/ ,int /*<<< orphan*/ ,char*) ;
__attribute__((used)) static __inline__ t_Error SetException(t_Qm *p_Qm, e_QmExceptions exception, bool enable)
{
uint32_t bitMask = 0;
ASSERT_COND(p_Qm);
GET_EXCEPTION_FLAG(bitMask, exception);
if(bitMask)
{
if (enable)
p_Qm->exceptions |= bitMask;
else
p_Qm->exceptions &= ~bitMask;
}
else
RETURN_ERROR(MAJOR, E_INVALID_VALUE, ("Undefined exception"));
return E_OK;
} |
C | #include "search_algos.h"
/**
* print_array - Prints an array
* @array: Target array
* @l: Left index of @array
* @r: Right index of @array
*/
void print_array(int *array, size_t l, size_t r)
{
size_t i = 0;
printf("Searching in array: ");
for (i = l; i <= r; i++)
{
printf("%d", array[i]);
if (i == r)
printf("\n");
else
printf(", ");
}
}
/**
* binary_search - function that searches for a value in a
* sorted array of integers using the Binary search algorithm
* @array: is a pointer to the first element of the array to search
* @size: is the number of elements in array
* @value: is the value to search
* Return: return the first index where value is located
*/
int binary_search(int *array, size_t size, int value)
{
size_t r = 0, l = 0, m = 0;
if (!array || size == 0)
return (-1);
bubble_sort(array, size);
r = size - 1;
while (l <= r)
{
print_array(array, l, r);
m = (l + r) / 2;
if (array[m] < value)
l = m + 1;
else if (array[m] > value)
r = m - 1;
else
return (m);
}
return (-1);
}
/**
*bubble_sort - sort bubble
*@array: array of numbers to sort
*@size: size of array
*/
void bubble_sort(int *array, size_t size)
{
unsigned int swaps = 1, i;
int tmp;
if (array != NULL && size > 1)
while (swaps != 0)
{
swaps = 0;
for (i = 0; i < (size - 1); i++)
{
if (array[i] > array[i + 1])
{
tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
swaps = 1;
}
}
}
}
/**
* selection_sort - function that sort a list of number wuth selection
* @array: given array
* @size: size of array
*/
void selection_sort(int *array, size_t size)
{
unsigned int i = 0, j, k;
int tmp;
if (array != NULL && size > 1)
{
while (i <= (size - 2))
{
tmp = array[i];
k = i;
for (j = i + 1; j < size; j++)
{
if (tmp > array[j])
{
tmp = array[j];
k = j;
}
}
array[k] = array[i];
array[i] = tmp;
i++;
}
}
}
|
C | #include "checker.h"
int is_sorted(t_stack **a)
{
int i;
t_stack *tmp;
tmp = *a;
i = 0;
while (i < list_size(*a) - 1)
{
if (tmp->number > tmp->next->number)
return (0);
tmp = tmp->next;
i++;
}
return (1);
}
int up_number_position(t_stack **a, int a_size, int min, int max)
{
t_stack *tmp;
int position;
tmp = *a;
position = 0;
while (position < a_size)
{
if (min <= tmp->number && tmp->number <= max)
{
return (position);
}
tmp = tmp->next;
position++;
}
return (position);
}
int bottom_number_position(t_stack **a, int a_size, int min, int max)
{
t_stack *tmp;
int i;
int position;
tmp = *a;
position = 0;
i = 0;
while (i < a_size)
{
if (min <= tmp->number && tmp->number <= max)
{
position = i;
}
tmp = tmp->next;
i++;
}
return (position);
}
void push_to_b(t_stack **a, t_stack **b, int min, int max)
{
int up_position;
int bottom_position;
int a_size;
a_size = list_size(*a);
up_position = up_number_position(a, a_size, min, max);
bottom_position = a_size - bottom_number_position(a, a_size, min, max);
if (up_position < bottom_position)
{
while (up_position-- > 0)
{
printf("ra\n");
ra_rb(a);
}
}
else
{
while (bottom_position-- > 0)
{
printf("rra\n");
rra_rrb(a);
}
}
printf("pb\n");
pa_pb(a, b);
}
void push_swap_sorter(t_stack **a, t_stack **b, int min, int max)
{
int block;
int block_size;
int i;
block_size = ((max - min) / 10) + 1;
block = 0;
while (*a && block < 10)
{
i = 0;
while (i < block_size)
{
push_to_b(a, b, min * block * block_size + min, min * (block + 1) * block_size);
order_b(b);
i++;
}
block++;
}
while (*b)
{
order_b(b);
pa_pb(b, a);
printf("pa\n");
}
}
|
C | /***********************************************
Author: Vibishan Wigneswaran
Date: 8/2/2020
Purpose: Create a program that uses top down approach and utilizes stub functions
Time Spent: 5 minutes
***********************************************/
#include <stdio.h>
int convert_length (int num);
int convert_weight (int num);
int main(int argc, char *argv[]) {
int choice; //stores choice
int num;
printf("1. convert lengths\n2. convert weights\n3. Exit\nPlease choose from (1, 2, 0):"); //initialprompt
scanf("%d", &choice); //record prompt
while (choice != 0) {
switch(choice) {
case 0: break;
//Exit
case 1: printf("1. convert lengths \n"); scanf("%d", &choice);
int convert_length (int num);
case 2: printf("2. convert weights \n"); scanf("%d", &choice);
int convert_weight (int num);
}
}
printf("User chose to Exit \n"); //prompt caused by exiting
return 0;
}
int convert_length (int num) {
printf("converts length");
}
int convert_weight (int num) {
printf("converts weight");
}
|
C | #include "simple_insertion.h"
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
// Declaration in simple_insertion.h
typedef struct list_node
{
struct list_node* next;
struct list_node* back;
unsigned int value;
} list_node_t;
list_t* create_list()
{
list_t* newList = malloc(sizeof(list_t));
newList->top = NULL;
newList->length = 0; // We actually don't need this, do we?
return newList;
}
void delete_list(list_t* list)
{
// Delete all of them soon
list_node_t* chaser = list->top;
list_node_t* temporary_node;
while (chaser != NULL)
{
temporary_node = chaser;
chaser = chaser->next;
free(temporary_node);
}
free(list);
}
void list_insert(list_t* list, unsigned int value)
{
list_node_t* newNode = malloc(sizeof(list_node_t));
// Insert at top
newNode->value = value;
newNode->back = NULL;
newNode->next = list->top;
list->top = newNode;
if (list->top->next != NULL)
{
list->top->next->back = list->top;
}
}
// Helper Function for the function below
void put_into_place(
list_node_t* toBeSorted,
list_node_t* alreadySorted,
unsigned int* assignments,
unsigned int* comparisons
)
{
// I'm not counting null comparisons as a comparison;
// After all, seeing if a for loop has ended isn't counted
// as a comparison in an array implementation
// Note that I put the comparison increment in the while loop
// so will count the value being compared, but won't count if
// if short circuiting occurs, but will occur if the comparison
// returns false.
// ++x returns x + 1, and since x is only zero or greated, it will
// always resolve to true.
while (alreadySorted != NULL &&
++(*comparisons) &&
alreadySorted->value > toBeSorted->value
)
{
// It is clearer to group the assignments
++(*assignments);
++(*assignments);
++(*assignments);
unsigned int temp = toBeSorted->value;
toBeSorted->value = alreadySorted->value;
alreadySorted->value = temp;
++(*assignments);
++(*assignments);
alreadySorted = alreadySorted->back;
toBeSorted = toBeSorted->back;
}
}
results_t list_insertion_sort(list_t* list)
{
unsigned int assignments = 0;
unsigned int comparisons = 0;
if (list->top != NULL)
{
++assignments;
++assignments;
list_node_t* toBeSorted = list->top->next;
list_node_t* alreadySorted = list->top;
while (toBeSorted != NULL)
{
put_into_place(toBeSorted,
alreadySorted,
&assignments,
&comparisons
);
toBeSorted = toBeSorted->next;
alreadySorted = alreadySorted->next;
}
}
results_t results;
results.assignments = assignments;
results.comparisons = comparisons;
return results;
}
// Returns false if value was not found in the list,
// and therefore was not removed
bool list_remove(list_t* list, unsigned int value)
{
return false;
}
void print_whole_list(list_t* list)
{
list_node_t* chaser = list->top;
unsigned int depth = 0;
while (chaser != NULL)
{
++depth;
printf("%u: %u\n", depth, chaser->value);
chaser = chaser->next;
}
} |
C | /* display.c -- draw azimuth, elevation, and roll displays *
* All functions assume a coordinate system of (0.0,0.0) to (1.0,1.0)
*/
#include <math.h>
#include <GL/glut.h>
#include "display.h"
#include "fsim.h"
static void drawRoundDisplay();
static void drawAxes();
static void drawMeter(float min, float max, float value, float angle);
/* Draws a circle with ticks for use with drawMeter and friends */
static void drawRoundDisplay() {
int j;
float tmp, sintmp, costmp;
/* Draw a circle */
glBegin(GL_LINE_LOOP);
for(j = 0; j < 360; j++) {
tmp = j * 2 * M_PI / 360.0;
glVertex2f(0.5 + 0.5*cos(tmp), 0.5 + 0.5*sin(tmp));
}
glEnd();
/* Draw tick marks at every 30 degrees */
glBegin(GL_LINES);
for(j = 0; j < 360; j += 30) {
tmp = j * 2 * M_PI / 360.0;
costmp = cos(tmp); sintmp = sin(tmp);
glVertex2f(0.5 + 0.5*costmp, 0.5 + 0.5*sintmp);
glVertex2f(0.5 + 0.45*costmp, 0.5 + 0.45*sintmp);
}
glEnd();
}
/* Draws axes along the middle of the window
* for use with drawAEGraph()
*/
static void drawAxes() {
int j;
glBegin(GL_LINES);
/* Draw coordinate axes */
glVertex2f(0.5, 0.0);
glVertex2f(0.5, 1.0);
glVertex2f(0.0, 0.5);
glVertex2f(1.0, 0.5);
/* Draw tick marks */
for(j = 1; j < 10; j++) {
glVertex2f(0.5, 0.1 * j);
glVertex2f(0.55, 0.1 * j);
glVertex2f(0.1 * j, 0.5);
glVertex2f(0.1 * j, 0.55);
}
glEnd();
}
static void drawMeter(float min, float max, float value, float angle) {
float tmp = 2*M_PI*((value - min)/max),
costmp = cos(tmp),
sintmp = sin(tmp);
glColor3f(1.0, 1.0, 1.0);
drawRoundDisplay();
glBegin(GL_LINES);
/* Draw north arrow in red */
glColor3f(1.0, 0.0, 0.0);
glVertex2f(0.5, 0.5);
glVertex2f(0.5 + 0.3*costmp, 0.5 + 0.3*sintmp);
/* Draw south arrow in grey */
glColor3f(0.5, 0.5, 0.5);
glVertex2f(0.5, 0.5);
glVertex2f(0.5 - 0.3*costmp, 0.5 - 0.3*sintmp);
glEnd();
}
void drawAltimeter(float min_height, float max_height, float height) {
drawMeter(min_height, max_height, height, 0.0);
}
void drawCompass(float angle) {
drawMeter(0.0, 360.0, angle, 90.0);
}
#define ELEV_MIN -90.0
#define ELEV_MAX 90.0
/* Local var elevation must be scaled to within [0.0, 1.0] so that the
parameter may take on any values between ELEV_MIN and ELEV_MAX. */
void drawAEGraph(float azimuth, float elevation) {
elevation = (elevation - ELEV_MIN) / (ELEV_MAX - ELEV_MIN);
glLineWidth(4.0);
glBegin(GL_LINES);
/* Draw azimuth */
glColor3f(1.0, 0.0, 0.0);
glVertex2f(azimuth/360.0 + 0.5, 0.0);
glVertex2f(azimuth/360.0 + 0.5, 1.0);
/* Draw elevation */
glColor3f(0.0, 1.0, 0.0);
glVertex2f(0.0, elevation);
glVertex2f(1.0, elevation);
glEnd();
glColor3f(1.0, 1.0, 1.0);
glLineWidth(1.0);
drawAxes();
}
|
C | #include <stdio.h>
//求今年有多少个黑色星期五 13
//统计年份
int is_year(int year)
{
if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0)
return 1;
return 0;
}
int count_year_days(int sy, int ey)
{
int days = 0;
int i;
for (i = sy; i < ey; i++)
{
days += 365 + is_year(i);
}
return days;
}
int count_month_days(int month, int year)
{
int days = 0;
int i;
for (i = 1; i < month; i++)
{
if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10)
{
days += 31;
}
if (i == 2)
{
days += 28 + is_year(year);
}
if (i == 4 || i == 6 || i == 9 || i == 11)
{
days += 30;
}
}
return days;
}
int main(void)
{
int year = 2016, month, day;
int i, days = 0;
printf("please input year : ");
scanf("%d", &year);
//统计年总天数
days += count_year_days(1990, year) + 13;
/*printf("days = %d\n", days);*/
int d;
for (i = 1; i <= 12; i++)
{
d = days + count_month_days(i, year);
/*printf("%d : days = %d\n", i, days);*/
if (d % 7 == 5)
{
printf("%d月13日是黑色星期五!\n", i);
}
}
printf("===================\n");
while (1)
{
printf("plesea input year : month : day : ");
scanf("%d:%d:%d", &year, &month, &day);
days = count_year_days(2000, year) + count_month_days(month, year) + day - 1;
if (days % 5 < 3)
{
printf("打鱼!\n");
}
else
{
printf("晒网!\n");
}
}
return 0;
}
|
C | #include <stdio.h>
#include<math.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
double sum=0.0;
int num_threads;
int size, error;
void* calculate(void* threadid){
int* tid = (int*)threadid;
int i;
int rank = *tid;
double x2;
double result=0.0;
int N=1000000;
for (i=rank; i<N; i+=num_threads)
{
x2=(double)i*(double)i/((double)N*(double)N);
result+=sqrt(1-x2)/N;
}
pthread_mutex_lock(&mutex);
sum+=result;
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main (int argc, char* argv[])
{
double pi=0.0;
num_threads = atoi(argv[1]);
// size = atoi(argv[2]);
pthread_t threads[num_threads];
int ID[num_threads];
int t;
for (t = 0; t < num_threads; t++) {
ID[t] = t;
int rc = pthread_create(&threads[t], NULL, calculate, (void*)&ID[t]);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
for(t=0;t<num_threads;t++)
pthread_join(threads[t], NULL);
pi=4*sum;
printf("%f",pi);
return 0;
}
|
C | #include <func.h>
void sigFunc(int signum){
printf("before sleep,signal %d is coming!\n",signum);
sleep(3);
printf("after sleep,signal %d is coming!\n",signum);
}
int main(){
if(signal(SIGINT,sigFunc)==SIG_ERR){
perror("signal");
return -1;
}
if(signal(SIGQUIT,sigFunc)==SIG_ERR)
{
perror("signal");
return -1;
}
while(1);
}
|
C | #include<omp.h>
#include<stdio.h>
#include<stdlib.h>
int vecsize = 1000000;
int vecsum_odd(int *vec_a, int vecsize)
{
int i;
int sum = 0;
#pragma omp parallel for reduction(+ : sum)
for(i=0; i<vecsize; i++)
if((i+1) % 2 != 0){
sum += vec_a[i];
}
return sum;
}
int main(int argc, char *argv[])
{
double startapp = omp_get_wtime();
int * vec1 = malloc(vecsize * sizeof(int *));
for (int i=0; i < vecsize; i++)
vec1[i] = i + 1;
int sum_par = 0;
omp_set_num_threads(atoi(argv[1]));
int thid;
double startpar = omp_get_wtime();
#pragma omp parallel sections
{
thid = omp_get_num_threads();
#pragma omp section
vecsum_odd(vec1, vecsize/2);
#pragma omp section
sum_par = vecsum_odd(vec1+vecsize/2, vecsize);
}
double endpar = omp_get_wtime();
printf("[PARALLEL]:: start = %.16g\nend = %.16g\ndiff = %.16g\n",
startpar, endpar, endpar-startpar);
double timepar = endpar - startpar;
double endapp = omp_get_wtime();
printf("[APP TIME]:: start = %.16g\nend = %.16g\ndiff = %.16g\n", startapp,
endapp, endapp-startapp);
double timeapp = endapp - startapp;
printf("Elements: %d\n", vecsize);
printf("Threads: %d\n", thid);
printf("Calulated time: %f\n", timeapp / timepar);
}
|
C | // A demonstration of creating threads.
#include <stdio.h>
#include <pthread.h>
#define NUM_OF_THREADS 10
// Function to carry out inside each thread.
void * hello(void * tID) {
printf("Hello from thread %d!\n", * ((int *) tID));
pthread_exit(NULL);
}
int main() {
// Use a fixed array of thread IDs instead of an incrementing temporary value as thread arguments.
// Otherwise the threads will refer to a changing or invalid value in the main thread.
int tIDs[NUM_OF_THREADS] = {0};
for (int i = 0; i < NUM_OF_THREADS; i++) {
tIDs[i] = i;
}
// Create threads.
pthread_t threads[NUM_OF_THREADS];
for (int i = 0; i < NUM_OF_THREADS; i++) {
if (pthread_create(&threads[i], NULL, hello, (void *) &tIDs[i]) != 0) {
printf("Failed to create thread %d.\n", i);
return 0;
}
}
// Tell the main thread to wait for all threads to finish.
for (int i = 0; i < NUM_OF_THREADS; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
|
C | /*
* mm-naive.c - The fastest, least memory-efficient malloc package.
*
* In this naive approach, a block is allocated by simply incrementing
* the brk pointer. A block is pure payload. There are no headers or
* footers. Blocks are never coalesced or reused. Realloc is
* implemented directly using mm_malloc and mm_free.
*
* NOTE TO STUDENTS: Replace this header comment with your own header
* comment that gives a high level description of your solution.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include "mm.h"
#include "memlib.h"
/*********************************************************
* NOTE TO STUDENTS: Before you do anything else, please
* provide your team information in the following struct.
********************************************************/
team_t team = {
/* Team name */
"ateam",
/* First member's full name */
"Choi Min Yeop",
/* First member's email address */
"[email protected]",
/* Second member's full name (leave blank if none) */
"",
/* Second member's email address (leave blank if none) */
""
};
/* single word (4) or double word (8) alignment */
#define ALIGNMENT 8
/* rounds up to the nearest multiple of ALIGNMENT */
#define ALIGN(size) (((size) + (ALIGNMENT-1)) & ~0x7)
/* SIZE_T_SIZE == 8 */
#define SIZE_T_SIZE (ALIGN(sizeof(size_t)))
#define BK(p) *((void ** )((size_t *)p + 1))
#define FD(p) *((void ** )((size_t *)p + 2))
#define HEAD(p) *((size_t *)p)
#define FOOT(p,size) *((size_t *)p + (size / 4) - 1)
// is ptr in heap?
#define IN_HEAP(ptr) (mem_heap_lo() + 4 <= ptr && ptr <= mem_heap_hi())
// head and tail of free chunk Double linked list
void * head;
// max of size of free chunk
size_t bmax;
// return one of the argument that is largest
size_t max(size_t p1, size_t p2){
if(p1 > p2) return p1;
return p2;
}
/*
* malloc_chunk - make a malloc chunk putting header and footer
*/
void malloc_chunk(void * p, size_t size){
HEAD(p ) = size | 1;
FOOT(p,size) = size | 1;
}
/*
* free_chunk - make a free chunk putting header, footer, bk, fd
*/
void free_chunk(void * p, size_t size,void * bk, void * fd){
HEAD(p ) = size;
BK(p) = bk;
FD(p) = fd;
FOOT(p,size) = size;
}
/*
* free_nol_chunk - make a free chunk but not on list because size is not big enough(< 16 bytes)
* only put header and footer
*/
void free_nol_chunk(void *p, size_t size){
HEAD(p ) = size;
FOOT(p,size) = size;
}
/*
* fd_bk_conn_p - connect the middle chunk with back chunk and front chunk(only for pointing p)
*
*/
void fd_bk_conn_p(void * p, void * bk, void * fd){
if(IN_HEAP(bk)) FD(bk) = p;
if(IN_HEAP(fd)) BK(fd) = p;
}
/*
* fd_bk_conn - connect fd and bk(like delete node)
*/
void fd_bk_conn(void * bk, void * fd){
if(IN_HEAP(bk)) FD(bk) = fd;
if(IN_HEAP(fd)) BK(fd) = bk;
}
/*
* free_to_alloc - change free chunk to allocated chunk
* and remake a free chunk for the free rest of the chunk
*/
void free_to_alloc(void * p, size_t size){
size_t free_size = HEAD(p);
void * free_bk = BK(p);
void * free_fd = FD(p);
int sw = 0;
if(head == p){
head = free_fd;
sw = 1;
}
malloc_chunk(p,size);
void * new_free_addr = (void *)((char *)p + size);
if(free_size - size >= 16){ // big enough to make a free chunk and put in the list
free_chunk(new_free_addr,free_size - size,free_bk,free_fd);
fd_bk_conn_p(new_free_addr,free_bk,free_fd);
if(sw) head = new_free_addr;
}
else if(free_size - size == 0){ // use all to make allocated chunk
fd_bk_conn(free_bk,free_fd);
}
else{ // rest size is not 0, but not enought to make a normal free chunk
free_nol_chunk(new_free_addr, free_size - size);
fd_bk_conn(free_bk,free_fd);
}
}
/*
* find_free - search the free chunk that is big enough to make allocated chunk in free chunk
* return the address of the free chunk or not
* + if last free chunk is the lastest chunk in the heap,
* + extend the free chunk and return it (better than allocating all size)
*/
void * find_free(newsize){
if(bmax < newsize) return 0;
void * it = head;
void *pit = NULL;
while(it != 0 && IN_HEAP(it)){
if(HEAD(it) >= newsize){
return it;
}
pit = it;
it = FD(it);
}
if(pit != NULL){ // this is plus part
if(!IN_HEAP((void*)((char *)pit + HEAD(pit))) && HEAD(pit) > 64){
mem_sbrk(ALIGN(newsize - HEAD(pit)));
free_chunk(pit,newsize,BK(pit),FD(pit));
return pit;
}
}
return 0;
}
/*
* find_bk - find a nearest free chunk on the back that is on the list. (p is not a pointer that pointing free chunk)
*/
void * find_bk(void * p){
size_t size;
if(head == NULL || p < head) return 0;
do{
do{
size = *((size_t *)p - 1) & (~0x7);
if(size == 0) return 0;
p = (void *)((char *)p - size);
}while(p >= mem_heap_lo() + 4 && (HEAD(p) & 1) == 1);
}while((HEAD(p) & (~0x7)) < 16);
if(p < mem_heap_lo() + 4) return 0;
return p;
}
/*
* find_fd - find a nearest free chunk on the front that is on the list. (p is not a pointer that pointing free chunk)
*/
void * find_fd(void * p){
size_t size = HEAD(p) & (~0x7);
do{
do{
p = (void *)((char *)p + size);
size = HEAD(p) & (~0x7);
if(size == 0) return 0;
}while(p <= mem_heap_hi() && (HEAD(p) & 1) == 1); // free chunk?
}while((HEAD(p) & (~0x7)) < 16); // on the list free chunk?
if(p > mem_heap_hi()) return 0;
return p;
}
/*
* merge - coalescing free chunks next to the free chunk that p is pointing
* also considered the chunks that is smaller than 16 bytes
*
*/
void merge(void *p){
int sw = 1;
while(sw){ // repeat until merging ended (have to repeat because of small chunks)
size_t size = HEAD(p) & (~0x7);
void *bk = BK(p);
void *fd = (void *)((char *)p + size);
sw = 0;
if(IN_HEAP(bk) && (HEAD(bk) & 1) == 0){ // back chunk is free chunk?
size_t bk_size = HEAD(bk) & (~0x7);
if(p == (void *)((char *)bk + bk_size)){ // is that chunk stick to p?
if(bk_size >= 16){ // free chunk on list
free_chunk(bk, size + bk_size,BK(bk),FD(p));
fd_bk_conn(bk,FD(p));
p = bk;
size = HEAD(p) & (~0x7);
}
else{ // not on list
free_chunk(bk, size + bk_size,BK(p),FD(p));
p = bk;
size = HEAD(p) & (~0x7);
}
bmax = max(bmax, size + bk_size);
sw = 1;
}
}
if(IN_HEAP(fd) && (HEAD(fd) & 1) == 0){ // front chunk is free chunk
size_t fd_size = HEAD(fd) & (~0x7);
if(fd == (void *)((char *)p + size)){ // is that chunk stick to p?
if(fd_size >= 16){ // free chunk on list
free_chunk(p,size + fd_size,BK(p),FD(fd));
fd_bk_conn(p,FD(fd));
}
else{ // not on list
free_chunk(p,size + fd_size,BK(p),FD(p));
}
bmax = max(bmax, size + fd_size);
sw = 1;
}
}
}
}
/*
* rest_to_free - make some trash space to free chunk if it is big
*/
void rest_to_free(void *ptr,size_t size){
void * bk = find_bk(ptr);
void * fd = find_fd(ptr);
if(head == NULL){
head = ptr;
}
if(bk == NULL) head = ptr;
free_chunk(ptr,size,bk,fd);
fd_bk_conn_p(ptr,bk,fd);
}
int mm_init(void)
{
mem_sbrk(4); // for the double word align
//this is for the small free chunk
//by Testing some cases, this is more good
head = mem_sbrk(64);
free_chunk(head,64,NULL,NULL);
bmax = 64;
return 0;
}
/*
* mm_malloc - make a allocated chunk!
* 1. if there is a free chunk that is big enough, allocate into it
* 2. else, get more heap and make an allocated chunk in it
*/
void *mm_malloc(size_t size)
{
int newsize = ALIGN(max(16,size + 8)); // least all chunk have to have more than 16 to make a free chunk
if(16 <= size && size <= 512){
newsize = 1;
while(newsize < size) newsize *= 2;
if((newsize * 85) / 100 > size) newsize = ALIGN(max(16,size + 8));
else newsize += 8;
}
void * good_free_chunk = find_free(newsize);
if(!IN_HEAP(good_free_chunk)){
void *p = mem_sbrk(newsize);
if(p == (void *) -1){
return NULL;
}
else{
malloc_chunk(p, newsize);
return (void *)((char *)p + 4);
}
}
else{
free_to_alloc(good_free_chunk,newsize);
return (void *)((char *)good_free_chunk + 4);
}
}
/*
* mm_free - free the allocated chunk
* make free, add on list, merge
*/
void mm_free(void *ptr)
{
ptr = (void *)((char *)ptr - 4);
size_t size = HEAD(ptr) & (~0x7);
bmax = max(bmax,size);
void * bk = find_bk(ptr);
void * fd;
if(bk == NULL) fd = head;
else fd = FD(bk);
if(head == NULL){
head = ptr;
}
if(bk == NULL) head = ptr;
free_chunk(ptr,size,bk,fd);
fd_bk_conn_p(ptr,bk,fd);
merge(ptr);
}
/*
* mm_realloc - try to keep the chunk to not move to other address
* 1. if new size is smaller than before size -> just change to smaller chunk and make a free chunk to rest
* 2. if not, if this chunk is the lastest chunk, increase the size of the chunk
* 3. if not, if the next chunk is free chunk and can cover the size that chunk need, overwrap the free chunk
* 4. if not, do the worst case, mm_malloc(new) -> move data(old -> new) -> mm_free(old)
*/
void *mm_realloc(void *ptr, size_t size)
{
ptr = (void *)((char *)ptr - 4);
size_t save_size = size;
size = ALIGN(size) + 8;
size_t bef_size = HEAD(ptr) & (~0x7);
void * rest_ptr;
size_t rest_size;
if(size <= bef_size){ // user want smaller
malloc_chunk(ptr,size);
rest_ptr = (void *)((char *)ptr + size);
rest_size = bef_size - size;
if(rest_size >= 16){
rest_to_free(rest_ptr,rest_size);
merge(rest_ptr);
}
else if(rest_size != 0){
free_nol_chunk(rest_ptr,rest_size);
}
return (void *)((char *)ptr + 4);
}
else{
void * next_ptr = (void *)((char *)ptr + bef_size);
if(!IN_HEAP(next_ptr)){ // is this lastest chunk?
rest_size = size - bef_size;
mem_sbrk(rest_size);
malloc_chunk(ptr,size);
return (void *)((char *)ptr + 4);
}
else if(size <= bef_size + (HEAD(next_ptr) & (~0x7)) && (HEAD(next_ptr) & 1) == 0){
// is there a free chunk next to it and it is big size to carry on?
size_t next_size= HEAD(next_ptr) & (~0x7);
malloc_chunk(ptr,size);
rest_ptr = (void *)((char *)ptr + size);
rest_size = bef_size + next_size - size;
if(rest_size >= 16){
rest_to_free(rest_ptr,rest_size);
merge(rest_ptr);
}
else if(rest_size != 0){
free_nol_chunk(rest_ptr,rest_size);
}
return (void *)((char *)ptr + 4);
}
else{ // just make new chunk...
void * new_ptr = mm_malloc(save_size);
if(new_ptr == NULL) return NULL;
memcpy((char *)new_ptr,(char *)ptr + 4,bef_size-8);
mm_free((void *)((char *)ptr + 4));
return new_ptr;
}
}
}
int mm_check(){
void *pit = NULL;
void * it = head;
//Check Doubled Linked List connection, free chunk header and free chunk merge
while(IN_HEAP(it)){
//connection
if(IN_HEAP(BK(it)) && BK(it) != pit) return 0;
if(pit != NULL && it != FD(pit)) return 0;
//free chunk header
if((HEAD(it) & 1) == 1) return 0;
//coalescing
if(pit != NULL && (void *)((char *)pit + HEAD(pit)) == it) return 0;
pit = it;
it = FD(it);
}
return 1;
}
|
C | // Room: /d/wuguan/npc/orange.c
// Date: 99/05/30 by Byt
inherit NPC;
void create()
{
set_name("", ({ "ju zi","orange"}) );
set("gender", "" );
set("age", 22);
set("long",
"\n");
set("combat_exp", 100);
set("attitude", "friendly");
setup();
carry_object("/clone/misc/cloth")->wear();
}
void init()
{
object ob;
ob = this_player();
::init();
if( interactive(ob) && !is_fighting() ) {
remove_call_out("greeting");
call_out("greeting", 1, ob);
}
}
void greeting(object ob)
{
if( !ob || environment(ob) != environment() ) return;
if (ob->query("mud_age")<1000)
{
command("hi " + ob->query("id"));
command("say ãǸһЩðָģָ̡\n");
call_out("teach1",5,ob);
}
}
void teach1(object ob)
{
if( !ob || environment(ob) != environment() ) return;
command("say ȣһaskָaskNPCһ\n");
command("say ϷУкܶNPCaskһЩҪϢ\n");
command("say ǣask <NPCӢ> about []\n");
call_out("teach2",7,ob);
}
void teach2(object ob)
{
if( !ob || environment(ob) != environment() ) return;
command("say ڸ˵һ˵lookiָ\n");
command("say lookǿ˼ǣlook [(˻Ʒ)]ɼдΪl\n");
command("say lһԼڳҲl ju zi ҡ\n");
command("say iܿԼϵĶ˸ֻͨһ·\n");
call_out("teach3",7,ob);
}
void teach3(object ob)
{
if( !ob || environment(ob) != environment() ) return;
command("say Ȼ˵һ˵getdropgiveָ\n");
command("say get ǼijƷdropӵijƷgiveǸ˶\n");
call_out("teach4",5,ob);
}
void teach4(object ob)
{
if( !ob || environment(ob) != environment() ) return;
command("say Ҫbuysellopencloseȳõָ\n");
command("say buyܹڵ뵱sellܹڵԼĶ\n");
command("say opencloseֱǴرŻ\n");
call_out("teach5",7,ob);
}
void teach5(object ob)
{
if( !ob || environment(ob) != environment() ) return;
command("say ˵һ˵wearremovesleep\n");
command("say wearremoveֱǴѵ·õģsleep˯\n");
command("say ؤӿ˯ɵҪϢ֮ij˯\n");
command("say ֪ϸһĻhelpѯԼԼʵ\n");
}
|
C | #define F_CPU 8000000L
#include <avr/io.h>
#include <util/delay.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LCD_Dir DDRD /* Define LCD data port direction */
#define LCD_Port PORTD /* Define LCD data port */
#define RS PD0 /* Define Register Select pin */
#define EN PD1 /* Define Enable signal pin */
#define LM75_ADDRESS 0x92 /*SHT21 Address*/
void LCD_Command( unsigned char cmnd )
{
LCD_Port = (LCD_Port & 0x0F) | (cmnd & 0xF0); /* sending upper nibble */
LCD_Port &= ~ (1<<RS); /* RS=0, command reg. */
LCD_Port |= (1<<EN); /* Enable pulse */
_delay_us(1);
LCD_Port &= ~ (1<<EN);
_delay_us(200);
LCD_Port = (LCD_Port & 0x0F) | (cmnd << 4); /* sending lower nibble */
LCD_Port |= (1<<EN);
_delay_us(1);
LCD_Port &= ~ (1<<EN);
_delay_ms(2);
}
void LCD_Char( unsigned char data )
{
LCD_Port = (LCD_Port & 0x0F) | (data & 0xF0); /* sending upper */
LCD_Port |= (1<<RS); /* RS=1, data reg. */
LCD_Port|= (1<<EN);
_delay_us(1);
LCD_Port &= ~ (1<<EN);
_delay_us(200);
LCD_Port = (LCD_Port & 0x0F) | (data << 4); /* sending lower */
LCD_Port |= (1<<EN);
_delay_us(1);
LCD_Port &= ~ (1<<EN);
_delay_ms(2);
}
void LCD_Init (void) /* LCD Initialize function */
{
LCD_Dir = 0xFF; /* Make LCD port direction as o/p */
_delay_ms(20); /* LCD Power ON delay always >15ms */
LCD_Command(0x02); /* send for 4 bit initialization of LCD */
LCD_Command(0x28); /* 2 line, 5*7 matrix in 4-bit mode */
LCD_Command(0x0c); /* Display on cursor off*/
LCD_Command(0x06); /* Increment cursor (shift cursor to right)*/
LCD_Command(0x01); /* Clear display screen*/
_delay_ms(2);
}
void LCD_String (char *str) /* Send string to LCD function */
{
int i;
for(i=0; str[i]!=0 && str[i]!=0x000a; i++) /* Send each char of string till the NULL And String should not be newline*/
{
LCD_Char(str[i]);
}
}
void LCD_Clear()
{
LCD_Command (0x01); /* Clear display */
_delay_ms(2);
LCD_Command (0x80); /* Cursor at home position */
}
/* Terms
* S = Start
* SR = Repeated Start
* P = Stop
* SLA+W = Slave Address Write mode
* SLA+R = Slave Address Read mode
* ACK = Acknowledge
* NACK = Not ACK
*/
void I2C_Init()
{
//SCL, SDA as output
DDRC |= (1 << DDC4) | (1 << DDC5);
//init I2C
//100kHz @ prescaler /4
TWBR = 8;
TWCR |= (1 << TWPS0);
//enable I2C
TWCR |= (1 << TWEN);
}
void I2C_Start(){
//send S
TWCR = (1 << TWEN) | (1 << TWINT) | (1 << TWSTA);
//wait complete then check status
while(!(TWCR & (1 << TWINT)));
}
void I2C_Stop(){
TWCR = (1 << TWEN) | (1 << TWINT) | (1 << TWSTO);
}
void I2C_Write(uint8_t data){
TWDR = data;
TWCR = (1 << TWEN) | (1 << TWINT);
//wait complete then check status
while(!(TWCR & (1 << TWINT)));
}
uint8_t I2C_ReadAck() {
TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
while (!(TWCR & (1<<TWINT)));
return TWDR;
}
uint8_t I2C_ReadNAck() {
TWCR = (1<<TWINT)|(1<<TWEN);
while (!(TWCR & (1<<TWINT)));
return TWDR;
}
uint8_t I2C_GetStatusCode() {
uint8_t status;
status = TWSR & 0xF8;
return status;
}
float readTempLM75AD() {
uint8_t high_byte;
uint8_t low_byte;
// Send S
I2C_Start();
if(I2C_GetStatusCode() != 0x08) I2C_Stop();
// SLA+W
I2C_Write((uint8_t)(LM75_ADDRESS));
if (I2C_GetStatusCode() != 0x18) I2C_Stop();
// Select for temperature
I2C_Write((uint8_t) 0x00);
if (I2C_GetStatusCode() != 0x28) I2C_Stop();
// SR
I2C_Start();
if(I2C_GetStatusCode() != 0x10) I2C_Stop();
// SLA+R
I2C_Write((uint8_t)(LM75_ADDRESS + 1));
if (I2C_GetStatusCode() != 0x40) I2C_Stop();
// Read MSB
high_byte = I2C_ReadAck();
if (I2C_GetStatusCode() != 0x50) I2C_Stop();
// Read LSB
low_byte = I2C_ReadNAck();
if (I2C_GetStatusCode() != 0x58) I2C_Stop();
// Send P
I2C_Stop();
// Convert
uint16_t result = (high_byte << 8) | low_byte;
float temperatureC = (float)result / 256.0 ;
return temperatureC;
}
int main(void) {
LCD_Init();
I2C_Init();
LCD_Clear();
while (1) {
unsigned char buffer[10];
float temp = readTempLM75AD();
dtostrf(temp, 3, 2, buffer);
strcat(buffer, " C\n");
LCD_Clear();
LCD_String(buffer);
_delay_ms(1000);
}
}
|
C | #include "../includes/philo.h"
int ft_atoi(const char *str)
{
int i;
long long res;
int minus;
i = 0;
minus = 1;
res = 0;
while (str[i] == '\n' || str[i] == '\t' || str[i] == ' ' ||
str[i] == '\v' || str[i] == '\f' || str[i] == '\r')
i++;
if (str[i] == '-' || str[i] == '+')
{
if (str[i] == '-')
minus = -1;
i++;
}
while (str[i] <= '9' && str[i] >= '0')
{
res = res * 10 + (str[i] - '0');
i++;
}
return (res * minus);
} |
C | #include <stdbool.h>
#define SIZE 4
struct game {
// game board
char board[SIZE][SIZE];
// current score
int score;
};
/**
* Adds random A or B tile to the game. This is very dumb function.
* The board must have at least one empty tile.
* If there is no empty tile, function will end in infinite loop.
* @param game reference to the game object
*/
void add_random_tile(struct game *game);
/**
* Renders the game
* @param game the game object with board and score to render
*/
void render(const struct game game);
/**
* Shifts the tiles either left or right direction so that there is no spaces
* between the tiles. Returns true if at least one tile is moved from its
* original position, otherwise false.
* @param game the game object with board to check
* @param start_x where to start in x-axe
* @param end_x where to end in x-axe
* @return true, if the board was shifted, or false otherwise.
*/
bool shift_tiles_on_x(struct game *game, int start_x, int end_x, int row);
/**
* Shifts the tiles either up or down direction so that there is no spaces
* between the tiles. Returns true if at least one tile is moved from its
* original position, otherwise false.
* @param game the game object with board to check
* @param start_y where to start in y-axe
* @param end_y where to end in y-axe
* @return true, if the board was shifted, or false otherwise.
*/
bool shift_tiles_on_y(struct game *game, int start_y, int end_y, int col);
/**
* Makes move in given direction
* If it is possible, function makes move in given direction,
* updates the current game state (board and score) and returns
* true. If it is not
* possible to move, returns false.
* @param game reference to the game object
* @param dy movement in y-axe
* @param dx movement in x-axe
* @return true, if game state was updated, false otherwise
*/
bool update(struct game *game, int dy, int dx);
/**
* Checks whether it is possible to make move
* Function checks game board if it is possible to make another
* move. The move is possible, if there are two tiles with the
* same letter nearby or there is at least one empty tile.
* @param game the game object with board to check
* @return true, if another movement is possible, or false otherwise.
*/
bool is_move_possible(const struct game game);
/**
* Checks whether game is already won.
* Returns true, if tile with letter 'K' is located on the board. Returns
* false, if it is not.
* @param game the game object with board to check
* @return true, if game is won, or false otherwise.
*/
bool is_game_won(const struct game game);
/* Extra functions */
/**
* Checks if the board has an empty space or not.
* Returns true if at least one tile is empty, otherwise false.
* @param game the game object with board to check
* @return true, if the board has an empty space, or false otherwise.
*/
bool has_empty_tile(const struct game game);
/**
* Draws the border line on the board based on the number of columns.
* @param size the width of the board.
*/
void drawBorder(const int size);
/**
* Updates the current board based on the slide direction either left or right.
* If it is possible, function makes move in given direction, updates
* the current game state (board and score) and returns true.
* If it is not possible to move, returns false.
* @param game reference to the game object
* @param start_x the first position in x-axe
* @param start_x the last position in x-axe
* @return true, if game state was updated, false otherwise
*/
bool update_on_x(struct game *game, int start_x, int end_x);
/**
* Updates the current board based on the slide direction either up or down.
* If it is possible, function makes move in given direction, updates
* the current game state (board and score) and returns true.
* If it is not possible to move, returns false.
* @param game reference to the game object
* @param start_y the first position in y-axe
* @param start_y the last position in y-axe
* @return true, if game state was updated, false otherwise
*/
bool update_on_y(struct game *game, int start_y, int end_y);
/**
* Write the current game state into a file. Returns true if
* the game is successfully saved, or otherwise false.
* @param game reference to the game object
* @param file the file to use for saving
* @return true, if the game was written to the file, false otherwise
*/
bool save_game(const struct game game, FILE *file);
/**
* Read a game from a file. Returns true if the game is not updated
* or all tiles are empty. Returns false if the game is successfully
* updated and at least one tile is alphabet.
* @param game reference to the game object
* @param file the file to read
* @return true, if game was not updated or all tiles are SPACEs, false otherwise.
*/
bool read_saved_game(struct game *game, FILE *file);
int start_k_game();
void reset_game_board(struct game *game);
bool start_new_game(struct game *game);
int direction_to_slide();
void save_game_before_quit(const struct game game);
|
C | #include <stdio.h>
int main() {
/* double quotes for strings */
/* An implicit null character \0 is placed at the end of the array */
/* If you put a null character inside a string, only the substring up to that point is printed */
char str_var1[] = "The cat is on the table";
char str_var2[] = "The cat is on the table\0"; /* I think this is equivalent to the previous, then I believe the compiler will NOT add a null character */
char str_var3[] = "The ca\0t is on the table"; /* null character \0 explicitly written in the middle, the string is terminated there */
/* As an array of chars, a string can be represented by representing each char in multiple ways */
/* Instead of the symbolic representation, let us represent some characters using their numeric representation (with \ in octal or with \x in hexadecimal) */
char str_var4[] = "The c\141t is on the table"; /* a = 97 */
/* The first 'a' is written with its octal representation */
/* What if I want to put a number right afterwards??? */
char str_var5[] = "The cat is on the t\141ble"; /* The second 'a' is written with its octal representation */
char str_var6[] = "The c\x61t is on the table"; /* The first 'a' is written with its hexadecimal representation */
char str_var7[] = "The cat is on the t\x61ble"; /* The second 'a' is written with its hexadecimal representation,
but there is a 'b' right after that makes the compiler think that it is a hexadecimal digit!
Then, it says "hex escape sequence out of range"
because \xff is the largest hexadecimal accepted for chars, and \x61b is larger... */
printf("%s\n", str_var1);
printf("%s\n", str_var2);
printf("%s\n", str_var3);
printf("%s\n", str_var4);
printf("%s\n", str_var5);
printf("%s\n", str_var6);
printf("%s\n", str_var7);
return 0;
}
|
C | #include <stdio.h>
// 迭 Ҹ ϴ ԼԴϴ.
void print_array(int* array, int size)
{
for (int i = 0; i < size; i++)
{
printf("%d ", array[i]);
}
printf("\n");
}
// 迭 Ҹ ȯϴ ԼԴϴ.
void swap_array(int* first, int* second, int size)
{
int temp;
for (int i = 0; i < size; i++)
{
temp = first[i];
first[i] = second[i];
second[i] = temp;
}
}
int main(void)
{
int first[] = { 1, 2, 3, 4, 5 };
int second[] = { 50, 40, 30, 20, 10 };
printf("ȯ \n");
printf("ù° 迭: ");
print_array(first, 5);
printf("ι° 迭: ");
print_array(second, 5);
swap_array(first, second, 5); // 迭 Ҹ ȯմϴ.
printf("ȯ \n");
printf("ù° 迭: ");
print_array(first, 5);
printf("ι° 迭: ");
print_array(second, 5);
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,fac=1,num=0;
printf("Ingrese un numero ");
scanf("%d",&num);
for (i=1;i<=num;i++){
fac=fac*i;
}
printf("El factorial es %d ",fac);
return 0;
}
|
C | #include <stdio.h>
#include <stdbool.h>
#define N 3
int magico(int a[20][20], int n){
int ref = 0;
for(int i = 0; i < n; i++){ // referencia da primeira linha
ref += a[i][0];
}
for(int i = 1; i < n; i++){ // resto das linhas
int linha = 0;
for(int j = 0; j < n; j++){
linha += a[i][j];
}
if(linha != ref) return false;
}
for(int i = 0; i < n; i++){ // colunas
int coluna = 0;
for(int j = 0; j < n; j++){
coluna += a[j][i];
}
if(coluna != ref) return false;
}
int diag1 = 0, diag2 = 0;
for(int i = 0; i < n; i++){ // diagonal principal
diag1 += a[i][i];
}
if(diag1 != ref) return false;
for(int i = 0; i < n; i++){ // diagonal secundaria
for(int j = 0; j < n; j++){
if(i+j == N-1){
diag2 += a[i][j];
}
}
}
if(diag2 != ref) return false;
return true;
}
int main(int argc, char const *argv[]) {
int cubo[20][20] = {{2,7,6},{9,5,1},{4,3,8}};
printf("%d\n", magico(cubo,3));
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* instructions2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: agottlie <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/03/04 15:32:04 by agottlie #+# #+# */
/* Updated: 2019/03/21 11:34:51 by agottlie ### ########.fr */
/* */
/* ************************************************************************** */
#include "../inc/push_swap.h"
void ra(t_st *st, char status)
{
if (st->a_size >= 2)
{
st->a[ind_a(st, st->a_size)] = st->a[st->a_top];
st->a_top = ind_a(st, 1);
(status == 1) ? put_inst(st, '6') : 0;
(st->v_flag == 1) ? ft_printf("ra\n") : 0;
(st->v_flag == 1) ? print_tab(st) : 0;
}
}
void rb(t_st *st, char status)
{
if (st->b_size >= 2)
{
st->b[ind_b(st, st->b_size)] = st->b[st->b_top];
st->b_top = ind_b(st, 1);
(status == 1) ? put_inst(st, '7') : 0;
(st->v_flag == 1) ? ft_printf("rb\n") : 0;
(st->v_flag == 1) ? print_tab(st) : 0;
}
}
void rr(t_st *st, char status)
{
ra(st, 0);
rb(st, 0);
(status == 1) ? put_inst(st, '8') : 0;
(st->v_flag == 1) ? ft_printf("rr\n") : 0;
(st->v_flag == 1) ? print_tab(st) : 0;
}
void rra(t_st *st, char status)
{
if (st->a_size >= 2)
{
st->a[ind_a(st, -1)] = st->a[ind_a(st, st->a_size - 1)];
st->a_top = ind_a(st, -1);
(status == 1) ? put_inst(st, '9') : 0;
(st->v_flag == 1) ? ft_printf("rra\n") : 0;
(st->v_flag == 1) ? print_tab(st) : 0;
}
}
void rrb(t_st *st, char status)
{
if (st->b_size >= 2)
{
st->b[ind_b(st, -1)] = st->b[ind_b(st, st->b_size - 1)];
st->b_top = ind_b(st, -1);
(status == 1) ? put_inst(st, 'a') : 0;
(st->v_flag == 1) ? ft_printf("rrb\n") : 0;
(st->v_flag == 1) ? print_tab(st) : 0;
}
}
|
C | #include<stdio.h>
#define filas 3
#define columnas 2
int main(){
int m,n;
char array[filas][columnas]={{'X','O'},{'O','X'},{'X','X'}};
printf("Introduce una fila: ");
scanf("%d",&m);
printf("Introduce una columna: ");
scanf("%d",&n);
printf("En la fila %d, columna %d encontramos: %c\n",m,n,array[m-1][n-1]);
printf("Introduce una fila: ");
scanf("%d",&m);
printf("Introduce una columna: ");
scanf("%d",&n);
printf("En la fila %d, columna %d encontramos: %c",m,n,array[m-1][n-1]);
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "src/sobel.h"
#define FORMAT_STRING_SIZE 4
/*
* Function to read arguments into variables.
* Input and Output files are necessary and threads number is optional.
* Returns -1 in case of missed parameters.
*/
int read_args(int argc, char **argv, char **input_file, char **output_file, int *threads_num)
{
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-i") == 0)
*input_file = argv[i + 1];
if (strcmp(argv[i], "-o") == 0)
*output_file = argv[i + 1];
if (strcmp(argv[i], "-t") == 0)
*threads_num = atoi(argv[i + 1]);
}
if (*input_file == NULL) {
printf("[ERROR] Input file is not specified!\n");
return -1;
}
if (*output_file == NULL) {
printf("[ERROR] Output file is not specified!\n");
return -1;
}
if (*threads_num == -1) {
printf("[WARNING] Num of threads was not specified. Setting to 1 as default.\n");
*threads_num = 1;
}
return 0;
}
/*
* Parses data from specified file path to the image structure.
*/
void read_image(struct image *in)
{
FILE *f;
if ((f = fopen(in->path, "r")) == NULL) {
printf("[ERROR] Could not open input file for reading!\n");
}
in->format = malloc(FORMAT_STRING_SIZE);
fscanf(f, "%s %d %d %d", in->format, &(in->width), &(in->height), &(in->max_val));
in->matrix = (struct pixel ***)malloc(sizeof(struct pixel **) * in->height);
for (int i = 0; i < in->height; i++) {
in->matrix[i] = (struct pixel **)malloc(sizeof(struct pixel *) * in->width);
for (int j = 0; j < in->width; j++) {
in->matrix[i][j] = (struct pixel *)malloc(sizeof(struct pixel));
fscanf(f, "%d %d %d", &(in->matrix[i][j]->r),
&(in->matrix[i][j]->g), &(in->matrix[i][j]->b));
}
}
fclose(f);
}
/*
* Writes data from resulting structure to the specified file.
*/
void write_image(struct image *out)
{
FILE *f;
if ((f = fopen(out->path, "w")) == NULL) {
printf("[ERROR] Could not open output file for writing!\n");
}
fprintf(f, "%s\n%d %d\n%d\n", out->format, out->width, out->height, out->max_val);
for (int i = 0; i < out->height; i++) {
for (int j = 0; j < out->width; j++) {
fprintf(f, "%d %d %d ", out->matrix[i][j]->r,
out->matrix[i][j]->g, out->matrix[i][j]->b);
}
fprintf(f, "\n");
}
fclose(f);
}
/*
* MAIN
*/
int main(int argc, char **argv)
{
struct image *img = (struct image*)malloc(sizeof(struct image));
char *input_file = NULL;
char *output_file = NULL;
int threads_num = -1;
int err = 0;
err = read_args(argc, argv, &input_file, &output_file, &threads_num);
if (err != 0) { return err; }
img->path = input_file;
read_image(img);
sobel(img, threads_num);
img->path = output_file;
write_image(img);
return 0;
} |
C | /* Ex06_01.c */
// 함수를 사용해보자.
#include <stdio.h>
void print_hello(void)
{
printf("Hello world!\n");
}
void printf_line(void)
{
int i;
for( i = 1; i <= 20; i++ )
{
printf("-");
}
printf("\n");
}
int main(void)
{
print_hello();
printf_line();
print_hello();
return 0;
}
|
C | #include <gmp.h>
#include <stdbool.h>
#include <stdarg.h>
#include <stdlib.h>
#include "primes.h"
bool isPrime(mpz_t n) {
mpz_t i, c, r;
mpz_init(i);
mpz_init(c);
mpz_init(r);
if (mpz_cmp_si(n, 2) < 0) return false;
if (mpz_cmp_si(n, 2) == 0) return true;
mpz_mod_ui(r, n, 2);
if (mpz_cmp_ui(r, 0) == 0) return false;
for (mpz_set_ui(i, 2); mpz_cmp(i, n) < 0; mpz_add_ui(i, i, 1)) {
mpz_mod(r, n, i);
if (mpz_cmp_ui(r, 0) == 0) return false;
}
return true;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
typedef struct treeNode {
char value[33];
struct treeNode *left, *right;
}TreeNode;
TreeNode* stack[300];
char name_variable[50][33];
int n = 0, value_variable[50];
TreeNode* newTreeNode(char *input){
TreeNode *current;
current = (TreeNode*) malloc(sizeof(TreeNode));
assert(current != NULL);
current->left = NULL;
current->right = NULL;
strcpy(current->value, input);
return current;
}
int getValue(TreeNode *root) {
if (root->left == NULL){
if(isdigit(root->value[0]))
return atoi(root->value);
else{
for(int i = 0; i < n; ++i){
if(!strcmp(name_variable[i], root->value))
return value_variable[i];
}
}
return 0;
}else {
switch (root->value[0]) {
case '+':
return getValue(root->left) + getValue(root->right);
case '-':
return getValue(root->left) - getValue(root->right);
case '*':
return getValue(root->left) * getValue(root->right);
default:
return getValue(root->left) / getValue(root->right);
}
}
}
int main(){
int top = 0, brackets = 0;
char tmp, input[33];
scanf("%s ", input);
if(input[0] == '(')
brackets++;
else{
stack[top] = newTreeNode(input);
}
while(brackets > 0) {
scanf("%s ", input);
if(input[0] == '(')
brackets++;
else if(input[0] == ')'){
stack[top-3]->right = stack[top-1];
stack[top-3]->left = stack[top-2];
top -= 2;
brackets--;
}else{
stack[top] = newTreeNode(input);
top++;
}
}
while(scanf("%s ", name_variable[n]) != EOF) {
scanf("%c ", &tmp);
scanf("%d", &value_variable[n]);
n++;
}
printf("%d", getValue(stack[0]));
return 0;
} |
C | // Remove blank lines from the given file
#include <stdio.h>
#define TEMPFILE "tempfile.txt"
int isnonblank(char * s)
{
int i;
for(i=0; s[i] != 0; i ++)
{
if (!isspace(s[i]))
return 1; // non-blank line
}
return 0;
}
main(int argc, char * argv[])
{
char line[100], *p;
FILE * sfp, *tfp;
if(argc < 2)
{
printf("Usage : removeblanklines filename");
exit(1);
}
sfp = fopen(argv[1],"rt");
if (sfp == NULL)
{
printf("\nFile [%s] not found!\n",argv[1]);
exit(2);
}
tfp = fopen(TEMPFILE,"wt");
if (tfp == NULL)
{
printf("\nSorry! Could not create temporary file!\n");
exit(2);
}
while(1)
{
p = fgets(line,100,sfp);
if (p == NULL) // EOF
break;
if (isnonblank(line)) // Non-blank line
fputs(line,tfp);
}
fclose(sfp);
fclose(tfp);
remove(argv[1]);
rename(TEMPFILE,argv[1]);
}
|
C | #ifndef __VIDEO_GR_H
#define __VIDEO_GR_H
/** @defgroup video_gr video_gr
* @{
*
* Functions for outputing data to screen in graphics mode
*/
/**
* @brief gets pointer to variable mouse_buffer
* @return pointer to variable mouse_buffer
*/
unsigned getMouse_buffer();
/**
* @brief gets pointer to variable double_buffer
* @return pointer to variable double_buffer
*/
unsigned getDouble_buffer();
/**
* @brief gets pointer to variable video_mem
* @return pointer to variable video_mem
*/
unsigned getVideo__mem();
/**
* @brief gets horizontal resolution of the screen
* @return horizontal resolution
*/
unsigned getH_res();
/**
* @brief gets vertical resolution of the screen
* @return vertical resolution
*/
unsigned getV_res();
/**
* @brief Initializes the video module in graphics mode
*
* Uses the VBE INT 0x10 interface to set the desired
* graphics mode, maps VRAM to the process' address space and
* initializes static global variables with the resolution of the screen,
* and the number of colors
*
* @param mode 16-bit VBE mode to set
* @return Virtual address VRAM was mapped to. NULL, upon failure.
*/
void *vg_init(unsigned short mode);
/**
* @brief Returns to default Minix 3 text mode (0x03: 25 x 80, 16 colors)
* @return 0 upon success, non-zero upon failure
*/
int vg_exit(void);
/**
* @brief sets the color of a pixel in the double buffer and in the mouse buffer
* @param x,y coordinates of the pixel we want to set
* @param color color which we want to set the pixel
* @return 0 in case of success, 1 otherwise
*/
int vg_set_pixel(int x, int y, unsigned int color);
/**
* @brief sets the color of a pixel in the mouse buffer
* @param x,y coordinates of the pixel we want to set
* @param color color which we want to set the pixel
* @return 0 in case of success, 1 otherwise
*/
int vg_set_mouse_pixel(int x, int y, unsigned int color);
/**
* @brief draws a square in the double buffer and in the mouse buffer
* @param xi,yi coordinates of the superior left vertice of the square
* @param size size of the square
* @param color color of the square
* @return 0 in case of success, 1 otherwise
*/
int vg_draw_square(int xi, int yi, int size,int color);
/**
* @brief draws a circle in the double buffer and in the mouse buffer
* @param xi,yi coordinates of the center of the circle
* @param radius radius of the circle
* @param color color of the circle
* @return 0 in case of success, 1 otherwise
*/
int vg_draw_circle(int xi, int yi,int radius, int color);
/**
* @brief copies the double_buffer into the video_buffer
* @return 0 in case of success, 1 otherwise
*/
int swap_double_video();
/**
* @brief copies the mouse_buffer into the video_buffer
* @return 0 in case of success, 1 otherwise
*/
int swap_mouse_video();
/**
* @brief copies the mouse_buffer into the double_buffer
* @return 0 in case of success, 1 otherwise
*/
int swap_mouse_double();
/**
* @brief copies the double_buffer into the mouse_buffer
* @return 0 in case of success, 1 otherwise
*/
int swap_double_mouse();
/**
* @brief sets a pixel in the mouse buffer to the color of the corresponding pixel in the double buffer
* @param x,y coordinates of the pixel
* @return 0 in case of success, 1 otherwise
*/
int mouse_to_double(int x, int y);
/** @} end of video_gr */
#endif /* __VIDEO_GR_H */
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int t = 0,
i = 0,
k = 0,
totalFrutas = 0,
contFrutas = 1;
double vlrDia = 0,
mediaKg = 0,
mediaVlr = 0,
vlrTotal = 0;
char frutas[10000];
//Leitura da qtd de casos de testes
scanf("%d", &t);
//Testes
for(i = 0; i < t; i++){
//Leitura do vlr gasto no dia
scanf("%lf\n", &vlrDia);
//Acumulador do vlr gasto
vlrTotal += vlrDia;
//Leitura das frutas compradas no dia
gets(frutas);
//Validacao de qtas frutas foram compradas no dia
while(frutas[k] != '\0'){
if(frutas[k] == ' '){
contFrutas++;
}
k++;
}
//Retorno do vlr inicial de k
k = 0;
//Acumulador da quantidade de frutas
totalFrutas += contFrutas;
//Impressao da qtd de kg de frutas por dia
printf("day %d: %d kg\n", i + 1, contFrutas);
//Retorno da qtde inicial de frutas
contFrutas = 1;
}
//Calculo da qtde media em kg de frutas por dia
mediaKg = totalFrutas / (double)i;
//Calculo do vlr medio gasto de frutas por dia
mediaVlr = vlrTotal / i;
//Impressao da media de kg de frutas por dia
printf("%.2f kg by day\n", mediaKg);
//Impressao do vlr medio gasto de frutas por dia
printf("R$ %.2f by day\n", mediaVlr);
}
|
C | /*************************************************************************
> File Name: 求荒岛面积.c
> Author:
> Mail:
> Created Time: 2017年07月19日 星期三 15时29分22秒
************************************************************************/
#include<stdio.h>
int book[21][21];
int sum;
int n,m;
int a[21][21];
void dfs(int x,int y,int color)
{
int arr[4][2]={{0,1},//向下
{0,-1},// 向上
{-1,0},//向左
{1,0}//向右
};
int tx,ty;
int i;
a[x][y]=color;
for(i=0;i<4;i++)
{
tx=x+arr[i][0];
ty=y+arr[i][1];
if(tx<1||tx>n||ty<1||ty>m)//防止越界
continue;
if(a[tx][ty]>0&&book[tx][ty]==0)//只有a大于1才是平地,book是标记走没走过
{
book[tx][ty]=1;
sum++;
dfs(tx,ty,color);//注意这个dfs在if里面,因为只有这个点可行,才会在这个点
//四个方向继续去找
}
}
return ;
}
int main()
{
int startx,starty;
int i,j;
printf("输入几行几列的荒岛:");
scanf("%d %d",&n,&m);
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
scanf("%d",&a[i][j]);
printf("请输入起点");
scanf("%d %d",&startx,&starty);
book[startx][starty]=1;
sum=1;
dfs(startx,starty,-1);
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
printf("%d ",a[i][j]);
putchar('\n');
}
printf("面积是:%d\n",sum);
}
|
C | #include "stdint.h"
typedef enum game_play_level {
STARTUP,
LEVEL_1_TRANSITION,
LEVEL_1,
LEVEL_2_TRANSITION,
LEVEL_2,
LEVEL_3_TRANSITION,
LEVEL_3,
LEVEL_4_TRANSITION,
LEVEL_4,
GAME_WINNER,
GAME_OVER_LEVEL,
MAX_GAME_LEVELS,
} game_play_level;
/**
* This function manages game play current level and assigns the duration of the current game play level
* @return The game play duration for the current level
*/
uint32_t game_play__level_manager(void);
/**
* This function manages the graphics activities for the current game play level. e.g., it assigns the
* number of enemies, the speed of the gameplay.
*/
uint32_t game_play__graphics_manager(void);
/**
* It is responsible for namaging life object by calculating the chance of reviving life object based
* on the given priority for each game play level.
*/
void game_play__life_object_manager(void);
void game_play__update_game_over_level(void); |
C | #include<stdio.h>
void main()
{
int year;
printf("Type Year:\n");
scanf("%d",&year);
if(year%100!=0 && year%4==0)
{
printf("Leap year");
}
else if(year%100==0 && year%400==0)
{
printf("Leap Year");
}
else
{
printf("Not Leap Year");
}
}
|
C | /*
This code was written to support the book, "ARM Assembly for Embedded Applications",
by Daniel W. Lewis. Permission is granted to freely share this software provided
that this notice is not removed. This software is intended to be used with a run-time
library adapted by the author from the STM Cube Library for the 32F429IDISCOVERY
board and available for download from http://www.engr.scu.edu/~dlewis/book3.
*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "library.h"
#include "graphics.h"
extern void UseLDRB(void *dst, void *src) ;
extern void UseLDRH(void *dst, void *src) ;
extern void UseLDR(void *dst, void *src) ;
extern void UseLDRD(void *dst, void *src) ;
extern void UseLDM(void *dst, void *src) ;
typedef int BOOL ;
#define FALSE 0
#define TRUE 1
typedef struct
{
uint16_t hue ; // 0 to 359 degrees
uint8_t sat ; // 0 to 100 percent
uint8_t val ; // 0 to 100 percent
} HSV ;
typedef struct
{
uint8_t blu ; // 0 to 255
uint8_t grn ; // 0 to 255
uint8_t red ; // 0 to 255
} RGB ;
typedef struct
{
char * label ;
void (*func)() ;
int index ;
unsigned cycles ;
} RESULT ;
static int Check(uint8_t *src, uint8_t *dst) ;
static int Compare(const void *p1, const void *p2) ;
static void Delay(uint32_t msec) ;
static void FillSpectrum(int x, int y, int height) ;
static uint32_t GetTimeout(uint32_t msec) ;
static void LEDs(int grn_on, int red_on) ;
static void Setup(uint8_t *src, uint8_t *dst) ;
static void ShowBest(RESULT results[]) ;
static void ShowResult(int which, RESULT results[], unsigned maxCycles) ;
static unsigned UseDMA(void) ;
static RGB HSV2RGB(HSV *hsv) ;
#define BAR_OFFSET 70
#define BAR_WIDTH 30
#define MAX_HEIGHT 210
#define FUNCTIONS 7
#define CPU_CLOCK_SPEED_MHZ 168
#define MIN(a,b) ((a < b) ? a : b)
#define MAX(a,b) ((a > b) ? a : b)
#define FONT_WIDTH 7
#define FONT_HEIGHT 12
static uint8_t src[512] __attribute__ ((aligned (1024))) ; // DMA burst mode cannot cross 1KB boiundary
static uint8_t dst[512] __attribute__ ((aligned (1024))) ; // DMA burst mode cannot cross 1KB boiundary
int main(void)
{
static RESULT results[FUNCTIONS] =
{
{"LDRB", UseLDRB},
{"LDRH", UseLDRH},
{"LDR", UseLDR},
{"LDRD", UseLDRD},
{"LDM", UseLDM},
{"mcpy", (void (*)()) memcpy},
{"DMA", NULL}
} ;
static uint32_t iparams[] = {(uint32_t) dst, (uint32_t) src, 512} ;
unsigned maxCycles, ovhd, dummy[2] ;
int which, srcErr, dstErr ;
InitializeHardware(HEADER, "Lab 3: Copying Data Quickly") ;
LEDs(0, 1) ;
srcErr = (((unsigned) src) & 0x3FF) != 0 ;
dstErr = (((unsigned) src) & 0x3FF) != 0 ;
if (srcErr) printf("src crosses 1KB boundary (%08X)\n", (unsigned) src) ;
if (dstErr) printf("dst crosses 1KB boundary (%08X)\n", (unsigned) dst) ;
if (srcErr || dstErr) while (1) ;
LEDs(1, 0) ;
ovhd = CountCycles(CallReturnOverhead, dummy, dummy, dummy) ;
for (which = 0; which < FUNCTIONS - 1; which++)
{
Setup(src, dst) ;
results[which].cycles = CountCycles(results[which].func, iparams, dummy, dummy) - ovhd ;
results[which].index = Check(src, dst) ;
}
Setup(src, dst) ;
results[which].cycles = UseDMA() ;
results[which].index = Check(src, dst) ;
qsort(results, FUNCTIONS, sizeof(RESULT), Compare) ;
maxCycles = results[0].cycles ;
SetColor(COLOR_BLACK) ;
DrawHLine(0, BAR_OFFSET + MAX_HEIGHT, XPIXELS) ;
for (which = 0; which < FUNCTIONS; which++)
{
ShowResult(which, results, maxCycles) ;
}
ShowBest(results) ;
return 0 ;
}
static void Setup(uint8_t *src, uint8_t *dst)
{
int k ;
for (k = 0; k < 512; k++)
{
*src++ = rand() ;
*dst++ = rand() ;
}
}
static int Check(uint8_t *src, uint8_t *dst)
{
int k ;
for (k = 0; k < 512; k++)
{
if (*src++ != *dst++) return k ;
}
return -1 ;
}
static void ShowResult(int which, RESULT results[], unsigned maxCycles)
{
float percent = ((float) results[which].cycles) / maxCycles ;
char text[100] ;
int x, y, offset ;
x = (XPIXELS / FUNCTIONS)*which + XPIXELS / (2*FUNCTIONS) - BAR_WIDTH / 2 ;
y = MAX_HEIGHT*(1 - percent) + BAR_OFFSET ;
offset = (BAR_WIDTH - FONT_WIDTH*strlen(results[which].label)) / 2 ;
DisplayStringAt(x + offset, BAR_OFFSET + MAX_HEIGHT + 5, results[which].label) ;
if (results[which].index >= 0)
{
SetColor(COLOR_RED) ;
FillRect(x, y, BAR_WIDTH, (unsigned) (percent*MAX_HEIGHT)) ;
SetColor(COLOR_BLACK) ;
DrawRect(x, y, BAR_WIDTH - 1, (unsigned) (percent*MAX_HEIGHT)) ;
}
else FillSpectrum(x, y, (unsigned) (percent*MAX_HEIGHT)) ;
sprintf(text, "%u", results[which].cycles) ;
offset = (BAR_WIDTH - FONT_WIDTH*strlen(text)) / 2 ;
DisplayStringAt(x + offset, y - 13, text) ;
if (results[which].index < 0) return ;
LEDs(0, 1) ;
SetForeground(COLOR_WHITE) ;
SetBackground(COLOR_RED) ;
sprintf(text, "Use%s failed at Index %d!", results[which].label, results[which].index) ;
DisplayStringAt(15, YPIXELS/3 + 15*which, text) ;
SetForeground(COLOR_BLACK) ;
SetBackground(COLOR_WHITE) ;
}
static void FillSpectrum(int x, int ymin, int height)
{
# define HUE_BEST 120
# define HUE_RNGE 190
uint32_t color ;
float percent ;
int y, ybtm, hue ;
HSV hsv ;
RGB rgb ;
hsv.sat = hsv.val = 100 ;
ybtm = ymin + height ;
if (ybtm >= BAR_OFFSET + MAX_HEIGHT)
ybtm = BAR_OFFSET + MAX_HEIGHT - 1 ;
for (y = 0; y < height; y++)
{
percent = (float) y / MAX_HEIGHT ;
hue = HUE_BEST - percent * HUE_RNGE ;
hsv.hue = (hue < 0) ? hue + 360 : hue ;
rgb = HSV2RGB(&hsv) ;
color = 0xFF000000 | *((uint32_t *) &rgb) ;
SetColor(color) ;
DrawHLine(x, ybtm - y, BAR_WIDTH) ;
SetColor(COLOR_BLACK) ;
DrawRect(x, ybtm - y - 1, BAR_WIDTH, y + 2) ;
Delay(5) ;
}
}
static unsigned UseDMA(void)
{
static uint32_t const MBURST = (1 << 23) ; // Write burst of 4 beats
static uint32_t const PBURST = (1 << 21) ; // Read burst of 4 beats
static uint32_t const MSIZE = (2 << 13) ; // Write 32-bit words
static uint32_t const PSIZE = (2 << 11) ; // Read 32-bit words
static uint32_t const MINC = (1 << 10) ; // Autoincr dst adrs
static uint32_t const PINC = (1 << 9) ; // Autoincr src adrs
static uint32_t const DIR = (2 << 6) ; // Memory-To-Memory
static uint32_t const EN = (1 << 0) ; // "Go"
static uint32_t const FTH = (3 << 0) ; // FIFO threshold = full
static uint32_t const DMDIS = (1 << 2) ; // Direct mode disabled
static uint32_t const TCIF0 = (1 << 5) ; // Transfer complete flag
volatile uint32_t * const pDMA2_LISR = (uint32_t *) 0x40026400 ;
static uint32_t * const pDMA2_LIFCR = (uint32_t *) 0x40026408 ;
static uint32_t * const pDMA2_S0CR = (uint32_t *) 0x40026410 ;
static uint32_t * const pDMA2_S0NDTR = (uint32_t *) 0x40026414 ;
static void ** const pDMA2_S0PAR = (void **) 0x40026418 ;
static void ** const pDMA2_S0M0AR = (void **) 0x4002641C ;
static uint32_t * const pDMA2_S0FCR = (uint32_t *) 0x40026424 ;
static uint32_t * const pRCC_AHB1ENR = (uint32_t *) 0x40023830 ;
uint32_t strt, stop, zero ;
*pRCC_AHB1ENR |= (1 << 22) ; // Enable DMA Clock
*pDMA2_S0CR = 0 ; // Disable DMA
*pDMA2_S0PAR = src ; // Setup src address
*pDMA2_S0M0AR = dst ; // Setup dst address
*pDMA2_S0NDTR = 512/4 ; // Setup word count
*pDMA2_S0FCR = DMDIS|FTH ; // Setup FIFO
zero = GetClockCycleCount() ;
*pDMA2_LIFCR = TCIF0 ; // Clear TCIF0
while ((*pDMA2_LISR & TCIF0) != 0) ; // wait for TCIF0 = 0
strt = GetClockCycleCount() ;
*pDMA2_S0CR = MBURST|PBURST|MSIZE|PSIZE|MINC|PINC|DIR|EN ;
while ((*pDMA2_LISR & TCIF0) == 0) ; // wait for TCIF0 = 1
stop = GetClockCycleCount() ;
return (stop - strt) - (strt - zero) ;
}
static void LEDs(int grn_on, int red_on)
{
static uint32_t * const pGPIOG_MODER = (uint32_t *) 0x40021800 ;
static uint32_t * const pGPIOG_ODR = (uint32_t *) 0x40021814 ;
*pGPIOG_MODER |= (1 << 28) | (1 << 26) ; // output mode
*pGPIOG_ODR &= ~(3 << 13) ; // both off
*pGPIOG_ODR |= (grn_on ? 1 : 0) << 13 ;
*pGPIOG_ODR |= (red_on ? 1 : 0) << 14 ;
}
static RGB HSV2RGB(HSV *hsv)
{
double f, p, q, t, h, s, v ;
double *pRed[] = {&v, &q, &p, &p, &t, &v} ;
double *pGrn[] = {&t, &v, &v, &q, &p, &p} ;
double *pBlu[] = {&p, &p, &t, &v, &v, &q} ;
unsigned val = hsv->val ;
unsigned sat = hsv->sat ;
unsigned hue = hsv->hue ;
RGB rgb ;
int i ;
val = MIN(val, 100) ;
if (sat == 0)
{
// achromatic (grey)
rgb.red = rgb.grn = rgb.blu = (val * 255 + 50) / 100 ;
return rgb ;
}
sat = MIN(sat, 100) ;
s = sat / 100.0 ;
h = (hue % 360) / 60.0 ; // 0.0 <= h < 6.0
i = (unsigned) h ; // 0 <= i < 6
f = h - (double) i ; // 0 <= f < 1.0
v = val / 100.0 ;
p = v * (1.0 - s) ;
q = v * (1.0 - s*f) ;
t = v * (1.0 - s*(1.0 - f)) ;
rgb.red = *pRed[i] * 255 + 0.5 ;
rgb.grn = *pGrn[i] * 255 + 0.5 ;
rgb.blu = *pBlu[i] * 255 + 0.5 ;
return rgb ;
}
static uint32_t GetTimeout(uint32_t msec)
{
uint32_t cycles = 1000 * msec * CPU_CLOCK_SPEED_MHZ ;
return GetClockCycleCount() + cycles ;
}
static void Delay(uint32_t msec)
{
uint32_t timeout = GetTimeout(msec) ;
while ((int) (timeout - GetClockCycleCount()) > 0) ;
}
static int Compare(const void *p1, const void *p2)
{
RESULT *r1 = (RESULT *) p1 ;
RESULT *r2 = (RESULT *) p2 ;
return r2->cycles - r1->cycles ;
}
static void ShowBest(RESULT results[])
{
# define RESULT_Y 100
char best[100], rate[100] ;
int chars1, chars2, chars, x ;
float bps ;
bps = (512 * CPU_CLOCK_SPEED_MHZ) / results[FUNCTIONS-1].cycles ;
sprintf(best, " Fastest: Use%-4s", results[FUNCTIONS-1].label) ;
sprintf(rate, " Rate: %.0f MB/sec", bps) ;
chars1 = strlen(best) ; chars2 = strlen(rate) ;
chars = MAX(chars1, chars2) ;
x = XPIXELS - FONT_WIDTH * (chars + 5) ;
SetForeground(COLOR_YELLOW) ;
FillRect(x, RESULT_Y, FONT_WIDTH*(chars + 1), 3*FONT_HEIGHT) ;
SetForeground(COLOR_BLACK) ;
DrawRect(x, RESULT_Y, FONT_WIDTH*(chars + 1), 3*FONT_HEIGHT) ;
SetBackground(COLOR_YELLOW) ;
DisplayStringAt(x + FONT_WIDTH/2, RESULT_Y + (1*FONT_HEIGHT/2), best) ;
DisplayStringAt(x + FONT_WIDTH/2, RESULT_Y + (3*FONT_HEIGHT/2), rate) ;
}
|
C | /*
** EPITECH PROJECT, 2020
** PSU_navy_2019
** File description:
** print_map
*/
#include "navy.h"
void print_map(char **map)
{
for (int i = 0; map[i] != NULL; i = i + 1) {
for (int j = 0; map[i][j] != '\0'; j = j + 1)
write(1 , &map[i][j], 1);
my_putchar('\n');
}
} |
C | #include <stdio.h>
#include <string.h>
int main() {
char stringArray[25];
printf("Please input a String!\n");
fgets(stringArray,25,stdin);
printf("Input is %s and length is %d\n", stringArray, strlen(stringArray));
int length = strlen(stringArray);
int i,j;
char temp;
for (i = length-1; i>=1; i--){
for(j=i-1; j>=0; j--){
if (stringArray[j]>stringArray[i]){
temp = stringArray[j];
stringArray[j] = stringArray[i];
stringArray[i] = temp;
}
}
}
printf("After Sorting is %s", stringArray);
return 0;
} |
C | #include<stdio.h>
#define TRUE 1
#define FALSE 0
typedef int BOOL;
BOOL chkPalindrome(char *str)
{
char *start=NULL;
char *end=NULL;
if(str==NULL)
{
return -1;
}
start=str;
end=str;
while(*end!='\0')
{
end++;
}
end--;
while(start<=end)
{
if(*start!=*end)
{
break;
}
start++;
end--;
}
if(start>end)
{
return TRUE;
}
else
{
return FALSE;
}
}
int main()
{
BOOL bRet=FALSE;
char arr[50]={'\0'};
printf("Enter String: ");
scanf("%[^'\n']s",arr);
bRet=chkPalindrome(arr);
if(bRet==TRUE)
{
printf("TRUE\n");
}
else
{
printf("FALSE\n");
}
return 0;
}
|
C | void infoUsrMenuInicial() {
printf("#######################################################################\n");
printf("############################ MENU INICIAL #############################\n");
printf("#######################################################################\n\n");
printf("Por favor, seleccione una de las siguientes opciones:\n\n");
printf("1) Edicion archivo Hosts.\n");
printf("0) Salir\n\n");
printf("Opcion seleccionada: ");
}
void infoUsrFinalPrograma() {
printf("\n\n#######################################################################\n");
printf("######### PULSE CUALQUIER TECLA PARA VOLVER AL MENU PRINCIPAL #########\n");
printf("#######################################################################");
}
void infoUsrSolicitarRutaManual() {
printf("\nPor favor, introduzca la ruta hacia el archivo:\n");
printf("(Ej. ruta relativa \"..\\Carpeta\\archivo.txt\" )\n");
printf("(Ej. ruta absoluta \"c:\\Carpeta\\archivo.txt\" )\n");
printf("\nRuta: ");
}
void infoUsrUsarRutaDefault() {
printf("Por favor, seleccione una de las siguientes opciones:\n\n");
printf("1) Utilizar ruta por defecto.\n");
printf("2) Indicar ruta manualmente.\n");
printf("\nOpcion seleccionada: ");
}
void infoUsrInicioMostrarContenidos() {
printf("\n#######################################################################\n");
printf("######################### MOSTRANDO CONTENIDOS ########################\n");
printf("#######################################################################\n\n");
}
void infoUsrFinMostrarContenidos() {
printf("\n#######################################################################\n");
printf("############################## FIN ARCHIVO ############################\n");
printf("#######################################################################\n\n");
}
void infoUsrErrorObtenerStrings(int numLinea) {
printf("ERROR DETECTADO OBTENIENDO PARES IP URL EN LA LINEA %d\n", numLinea);
printf("Revise que el archivo contenga pares IP URL en el siguiente formato:\n");
printf("\"XXX.XXX.XXX.XXX url.dominio\"\n");
printf("OPERACION CANCELADA\n");
}
|
C | #include <assert.h>
#include <iostream>
using namespace std;
int main()
{
const int n = 100;
double bchoosek[n+1];
for (int k=0;k<n+1;k++) { bchoosek[k] = 0.0; }
// compute binomial coefficients
bchoosek[0] = 1.0;
for (int k=0;k<n;k++) {
cout << "n = " << k+1 << endl;
for (int i=k+1;i>0;i--) {
bchoosek[i] += bchoosek[i-1];
}
for (int i=0;i<=k+1;i++) {
cout << bchoosek[i] << " ";
}
cout << endl;
}
}
|
C | /*
* hash.h
*
* Created on: Apr 23, 2017
* Author: cossete
*/
#ifndef HASH_H_
#define HASH_H_
#include <openssl/sha.h>
#include <openssl/ripemd.h>
void sha256(uint8_t *digest, const uint8_t *message, size_t len) {
SHA256_CTX ctx;
SHA256_Init(&ctx);
SHA256_Update(&ctx, message, len);
SHA256_Final(digest, &ctx);
}
void rmd160(uint8_t *digest, const uint8_t *message, size_t len) {
RIPEMD160_CTX ctx;
RIPEMD160_Init(&ctx);
RIPEMD160_Update(&ctx, message, len);
RIPEMD160_Final(digest, &ctx);
}
void hash256(uint8_t *digest, const uint8_t *message, size_t len) {
uint8_t tmp[SHA256_DIGEST_LENGTH];
sha256(tmp, message, len);
sha256(digest, tmp, SHA256_DIGEST_LENGTH);
}
void hash160(uint8_t *digest, const uint8_t *message, size_t len) {
uint8_t tmp[SHA256_DIGEST_LENGTH];
sha256(tmp, message, len);
rmd160(digest, tmp, SHA256_DIGEST_LENGTH);
}
#endif /* HASH_H_ */
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jko <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/01/25 14:23:10 by jko #+# #+# */
/* Updated: 2020/01/26 15:52:46 by jko ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
unsigned int ft_strlcpy(char *dest, char *src, unsigned int size);
int main(void)
{
char *dest = (char *) malloc(sizeof(char) * 20);
char t[] = {'a', 'b', 'c', 'd', '\0', '1', '2'};
printf("%s, %d vs %lu \n", t, ft_strlcpy(dest, t, 7), strlcpy(dest, t, 7));
char t1[] = {'1', 'A', 'b', '!', '\0', 'a', '\n'};
printf("%s, %d vs %lu \n", t1, ft_strlcpy(dest, t1, 7), strlcpy(dest, t1, 7));
char t2[] = {'a', 'B', 'c', 'D', '\0'};
printf("%s, %d vs %lu \n", t2, ft_strlcpy(dest, t2, 7), strlcpy(dest, t2, 7));
char t3[] = {'\0', 'a', 'b', 'c', '\0'};
printf("%s, %d vs %lu \n", t3, ft_strlcpy(dest, t3, 7), strlcpy(dest, t3, 7));
char t4[] = {'1', '2', '3', '4', '5', '6', '7'};
printf("%s, %d vs %lu \n", t4, ft_strlcpy(dest, t4, 8), strlcpy(dest, t4, 8));
char t5[] = "abc\0def\0";
printf("%s, %d vs %lu \n", t5, ft_strlcpy(dest, t5, 2), strlcpy(dest, t5, 2));
return (0);
}
|
C | /*
* headas_parstamp(fitsfile *fptr, FITS file pointer
* int hdunum HDU in which to write HISTORY block (0 -> current HDU)
* )
*
* This routine writes a block of HISTORY keywords detailing the runtime values of all
* parameters into the specified FITS file HDU. Any parameter beginning with a '@' is
* taken to indicate an ascii file containing a list of items. In these cases the
* "parameter = value" string is enclosed in parentheses and the file contents are expanded
* within the HISTORY block.
*/
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#include "headas_utils.h"
#include "headas_error.h"
#include "f77_wrap.h"
#include "ape/ape_trad.h"
#include "ape/ape_util.h"
#define PAREN_YES 1
#define PAREN_NO 0
#define FLAG_NOTE 2
typedef struct ParameterNote ParameterNote;
struct ParameterNote
{
char * name;
char * note;
ParameterNote * next;
};
static int hdpstmp(fitsfile *fptr, int linenum, char *pname, char *pval, int paren);
static int hdfstmp(fitsfile *fptr, int linenum, char *line);
static ParameterNote * headNote;
static ParameterNote *
query_parameter_note (ParameterNote * from, const char * name)
{
ParameterNote * p = from;
while (p) {
if (!strcasecmp(name, p->name))
return p;
p = p->next;
}
return 0;
}
/* 23May2003: Replaces headas_parstamp. Now takes input status pointer arg */
int HDpar_stamp(fitsfile *fptr, int hdunum, int *status){
int parcount;
int histpar, tref;
char ** par_name = 0;
char ** name = 0;
char * value = 0;
char taskn[73];
char datestr[32];
char msg[144];
char **results=NULL;
int nitems=0, listcount;
if (*status>0) return *status;
get_history(&histpar);
switch (histpar){
case -1:
*status = HD_ERROR_THROW("Error: HDpar_stamp(): no history parameter present", 1);
return *status;
break;
case 0:
break;
case 1:
if (hdunum > 0) { /* ie, if 0 then operate on the current HDU */
fits_movabs_hdu(fptr, hdunum, NULL, status);
if (*status) {
sprintf(msg, "Error moving to HDU %d", hdunum);
HD_ERROR_THROW(msg,*status);
return *status;
}
}
fits_get_system_time(datestr, &tref, status);
if (*status){
HD_ERROR_THROW("error finding system time",*status);
return *status;
}
get_toolnamev(taskn);
sprintf(msg,"START PARAMETER list for %s at %s",taskn, datestr);
/* Surround START (which may wrap) with blank HISTORY lines */
fits_write_history(fptr, " ", status);
fits_write_history(fptr, msg, status);
fits_write_history(fptr, " ", status);
/* Get names of parameters. */
*status = ape_trad_get_par_names(&par_name);
parcount = 0;
for (name = par_name; 0 == *status && 0 != *name; ++name, ++parcount) {
/* Get value of parameter as a string. */
*status = ape_trad_get_string(*name, &value);
if (0 != *status) {
sprintf(msg,"Error getting parameter \"%s\"",*name);
HD_ERROR_THROW(msg, *status);
free(value);
return *status;
}
if (*value != '@') {
if ((*status = hdpstmp(fptr, parcount+1, *name, value, PAREN_NO)) != 0){
HD_ERROR_THROW("parstamp error",*status);
free(value);
return *status;
}
{
ParameterNote * rp = headNote;
while (NULL != (rp = query_parameter_note(rp, *name))) {
if ((*status = hdpstmp(fptr, parcount+1, *name, rp->note, FLAG_NOTE)) != 0){
HD_ERROR_THROW("parstamp error", *status);
free(value);
return *status;
}
rp = rp->next;
}
}
} else {
results = expand_item_list(value, &nitems, ' ', 1, 1, 1, status);
if (*status){
/* warn on error importing file contents and proceed without expanding */
*status=0;
hdpstmp(fptr, parcount+1, *name, value, PAREN_NO);
break;
}
hdpstmp(fptr, parcount+1, *name, value, PAREN_YES);
for (listcount=0;listcount<nitems;listcount++){
if (listcount==0){
sprintf(msg,"START FILE listing: %s",hdbasename(value+1));
/* Surround START (which may wrap) with blank HISTORY lines */
fits_write_history(fptr, " ", status);
fits_write_history(fptr, msg, status);
fits_write_history(fptr, " ", status);
}
hdfstmp(fptr, listcount+1, results[listcount]);
}
sprintf(msg,"END FILE listing: %s",hdbasename(value+1));
fits_write_history(fptr, msg, status);
/* follow END (which may wrap) with a blank line */
fits_write_history(fptr, " ", status);
if (results) free(results);
}
free(value);
}
sprintf(msg,"END PARAMETER list for %s",taskn);
fits_write_history(fptr, msg, status);
/* follow END (which may wrap) with a blank line */
fits_write_history(fptr, " ", status);
ape_util_free_string_array(par_name);
break;
}
return *status;
}
FCALLSCFUN3(INT, HDpar_stamp,HDPAR_STAMP,hdpar_stamp, FITSUNIT, INT, PINT)
static int hdpstmp(fitsfile *fptr, int linenum, char *pname, char *pval, int flag){
char *histstr, msg[73];
int status=0, numlen, i;
numlen = sprintf(msg,"%d",linenum);
if (!(histstr = (char *) malloc(sizeof(char)*(strlen(pname)+strlen(pval)+numlen+8)))){
sprintf(msg,"malloc error for %s\n",pname);
status = MEMORY_ALLOCATION;
HD_ERROR_THROW(msg, status);
return status;
}
if (flag == PAREN_YES){
sprintf(histstr,"P%d (%s = %s)",linenum,pname,pval);
}
else if (flag == FLAG_NOTE) {
sprintf(histstr, " %s", pval);
}else{
sprintf(histstr,"P%d %s = %s",linenum,pname,pval);
}
if (strlen(histstr) <= 72){
fits_write_history(fptr, histstr, &status);
free(histstr);
} else {
strncpy(msg,histstr,72);
msg[72]='\0';
fits_write_history(fptr, msg, &status);
for (i=0; i < (int) strlen(histstr)/72; i++){
if (flag == FLAG_NOTE)
sprintf(msg, " ");
else
sprintf(msg,"P%d ",linenum);
strncat(msg,histstr+(i+1)*72,72-numlen-2);
msg[72]='\0';
fits_write_history(fptr, msg, &status);
}
free(histstr);
}
if (!status)
HD_ERROR_THROW("hdpstmp error", status);
return status;
}
static int hdfstmp(fitsfile *fptr, int linenum, char *line){
char *histstr, msg[73];
int status=0, numlen, i;
numlen = sprintf(msg,"%d",linenum);
if (!(histstr = (char *) malloc(sizeof(char)*(strlen(line)+numlen+3)))){
sprintf(msg,"malloc error for %s\n",line);
status = MEMORY_ALLOCATION;
HD_ERROR_THROW(msg, status);
return status;
}
sprintf(histstr,"F%d %s",linenum,line);
if (strlen(histstr) <= 72){
fits_write_history(fptr, histstr, &status);
free(histstr);
} else {
strncpy(msg,histstr,72);
msg[72]='\0';
fits_write_history(fptr, msg, &status);
for (i=0; i < (int) strlen(histstr)/72; i++){
sprintf(msg,"F%d ",linenum);
strncat(msg,histstr+(i+1)*72,72-numlen-2);
msg[72]='\0';
fits_write_history(fptr, msg, &status);
}
free(histstr);
}
if (!status)
HD_ERROR_THROW("hdfstmp error", status);
return status;
}
static char * string_copy (const char * s)
{
char * copy = malloc(strlen(s) + 1);
if (copy)
strcpy(copy, s);
return copy;
}
static void store_par_note (const char * name, const char * note)
{
static ParameterNote * tailNote;
/* this allows the same parameter to have multiple resolutions,
* could call query_resolved_parameter and update if it exists */
ParameterNote * p = calloc(1, sizeof(ParameterNote));
if (p) {
p->name = string_copy(name);
p->note = string_copy(note);
if (p->name && p->note) {
if (!headNote)
headNote = p;
if (tailNote)
tailNote->next = p;
tailNote = p;
}
}
}
void HDpar_note (const char * parameter, const char * format, ...)
{
char buffer[1024];
va_list args;
va_start(args, format);
#ifdef WIN32
_vsnprintf(buffer, sizeof(buffer), format, args);
#else
vsnprintf(buffer, sizeof(buffer), format, args);
#endif
va_end(args);
store_par_note(parameter, buffer);
}
void HDrelease_par_notes ()
{
ParameterNote * p = headNote;
headNote = 0;
while (p) {
ParameterNote * q = p->next;
free(p->name);
free(p->note);
free(p);
p = q;
}
}
|
C | #include "cdg.h"
int max(int a, int b) {
return a > b ? a : b;
}
void pushNodeListToStack(Stack * s, CDGNode * node) {
assert(NULL != node);
do {
stackPush(s, &node);
node = getNextNode(node);
} while (node);
}
void postOrder(CDGNode * root, Stack * s) {
if (NULL == root)
return;
Stack *temp = stackNew(sizeof(CDGNode *));;
CDGNode *node;
CDGNode *listNode;
pushNodeListToStack(temp, root);
while (!stackIsEmpty(temp)) {
stackPop(temp, &node);
if (getTrueNodeSet(node)) {
pushNodeListToStack(temp, getTrueNodeSet(node));
}
if (getFalseNodeSet(node)) {
pushNodeListToStack(temp, getFalseNodeSet(node));
}
stackPush(s, &node);
}
stackFree(temp);
}
CDGNode *getTrueNodeSet(CDGNode * node) {
return node->trueNodeSet;
}
CDGNode *setTrueNodeSet(CDGNode * node, CDGNode * trueNodeSet) {
node->trueNodeSet = trueNodeSet;
return node;
}
CDGNode *getFalseNodeSet(CDGNode * node) {
return node->falseNodeSet;
}
CDGNode *setFalseNodeSet(CDGNode * node, CDGNode * falseNodeSet) {
node->falseNodeSet = falseNodeSet;
return node;
}
CDGNode *setNextNode(CDGNode * node, CDGNode * nextNode) {
node->next = nextNode;
if (nextNode)
setParent(nextNode, getParent(node));
return node;
}
CDGNode *setTrueNodeSetScore(CDGNode * node, int score) {
CDGNode *curr;
curr = getTrueNodeSet(node);
while (curr != NULL) {
setScore(curr, score);
curr = curr->next;
}
return node;
}
CDGNode *setFalseNodeSetScore(CDGNode * node, int score) {
CDGNode *curr;
curr = getFalseNodeSet(node);
while (curr != NULL) {
setScore(curr, score);
curr = curr->next;
}
return node;
}
CDGNode *getLastNode(CDGNode * node) {
assert(NULL != node);
CDGNode *curr = node;
while (getNextNode(curr)) {
curr = getNextNode(curr);
}
return curr;
}
int isLeaf(CDGNode * node) {
if (getTrueNodeSet(node) || getFalseNodeSet(node))
return 0;
return 1;
}
int getConditionalNodeSum(CDGNode * node) {
int sum = 0;
while (node != NULL) {
if (!isLeaf(node)) {
sum += getScore(node);
}
node = getNextNode(node);
}
return sum;
}
int hasUncoveredChild(CDGNode * node, int branch) {
CDGNode *temp;
if (branch)
temp = getTrueNodeSet(node);
else
temp = getFalseNodeSet(node);
while (temp) {
if (isLeaf(temp) && 0 < getScore(temp))
return 1;
temp = getNextNode(temp);
}
return 0;
}
int hasUncoveredBranch(CDGNode * node, int branch) {
if (branch && NULL == getTrueNodeSet(node))
return 0;
if (0 == branch && NULL == getFalseNodeSet(node))
return 0;
if (0 == getBranchInfo(getID(node), branch))
return 1;
return 0;
}
int hasConditionalChild(CDGNode * node) {
CDGNode *temp;
temp = getTrueNodeSet(node);
while (temp) {
if (!isLeaf(temp))
return 1;
temp = getNextNode(temp);
}
temp = getFalseNodeSet(node);
while (temp) {
if (!isLeaf(temp))
return 1;
temp = getNextNode(temp);
}
return 0;
}
int isConditionalLeaf(CDGNode * node) {
if (isLeaf(node))
return 0;
if (!hasConditionalChild(node))
return 1;
if (0 < getConditionalNodeSum(getTrueNodeSet(node)))
return 0;
if (0 < getConditionalNodeSum(getFalseNodeSet(node)))
return 0;
return 1;
}
CDGNode *resetExpr(CDGNode * node) {
if (NULL != node->expr)
free(node->expr);
return node;
}
CDGNode *resetTrueNodeSet(CDGNode * node) {
node->trueNodeSet = NULL;
return node;
}
CDGNode *resetFalseNodeSet(CDGNode * node) {
node->falseNodeSet = NULL;
return node;
}
CDGNode *resetParent(CDGNode * node) {
node->parent = NULL;
return node;
}
CDGNode *resetNextNode(CDGNode * node) {
node->next = NULL;
return node;
}
CDGNode *getMaxScoreConditionNode(CDGNode * node) {
CDGNode *out = NULL;
do {
if (!isLeaf(node) && 0 < getScore(node)) {
if ((NULL == out) || (getScore(out) < getScore(node))) {
out = node;
}
}
node = getNextNode(node);
} while (NULL != node);
return out;
}
CDGNode *getMaxScoreConditionChildNode(CDGNode * node, int *outcome) {
CDGNode *maxTrue = NULL;
CDGNode *maxFalse = NULL;
if (getTrueNodeSet(node)) {
maxTrue = getMaxScoreConditionNode(getTrueNodeSet(node));
}
if (getFalseNodeSet(node)) {
maxFalse = getMaxScoreConditionNode(getFalseNodeSet(node));
}
if (NULL == maxFalse) {
*outcome = 1;
return maxTrue;
}
if (NULL == maxTrue) {
*outcome = 0;
return maxFalse;
}
if (getScore(maxTrue) < getScore(maxFalse)) {
*outcome = 0;
return maxFalse;
}
*outcome = 1;
return maxTrue;
}
CDGNode *newNode(int id, int score, int outcome, const char *expr, CDGNode * trueNodeSet, CDGNode * falseNodeSet, CDGNode * parent, CDGNode * next) {
CDGNode *node;
node = (CDGNode *) malloc(sizeof(CDGNode));
assert(NULL != node);
setID(node, id);
setScore(node, score);
setOutcome(node, outcome);
setExpr(node, expr);
setTrueNodeSet(node, trueNodeSet);
setFalseNodeSet(node, falseNodeSet);
setParent(node, parent);
setNextNode(node, next);
return node;
}
CDGNode *newBlankNode() {
return newNode(-1, 1, 1, NULL, NULL, NULL, NULL, NULL);
}
void deleteNode(CDGNode * node) {
assert(NULL != node);
/* resetExpr(node);
resetTrueNodeSet(node);
resetFalseNodeSet(node);
resetParent(node);
resetNextNode(node); */
free(node);
}
void deleteNodeList(CDGNode * node) {
assert(NULL != node);
CDGNode *next;
do {
next = getNextNode(node);
deleteNode(node);
node = next;
} while (node);
}
void deleteCDG(CDGNode * root) {
if (NULL == root)
return;
CDGNode *node;
Stack *nodeStack = stackNew(sizeof(CDGNode *));
postOrder(root, nodeStack);
while (!stackIsEmpty(nodeStack)) {
stackPop(nodeStack, &node);
deleteNode(node);
}
stackFree(nodeStack);
}
int getID(CDGNode * node) {
return node->id;
}
CDGNode *setID(CDGNode * node, int id) {
node->id = id;
return node;
}
int getScore(CDGNode * node) {
return node->score;
}
CDGNode *setScore(CDGNode * node, int score) {
node->score = score;
return node;
}
int getOutcome(CDGNode * node) {
return node->outcome;
}
CDGNode *setOutcome(CDGNode * node, int outcome) {
node->outcome = outcome;
return node;
}
char *getExpr(CDGNode * node) {
if (node->expr != NULL)
return node->expr;
return NULL;
}
CDGNode *setExpr(CDGNode * node, const char *expr) {
if (NULL == expr) {
node->expr = NULL;
return node;
}
node->expr = (char *)malloc(sizeof(char) * (strlen(expr) + 1));
strcpy(node->expr, expr);
return node;
}
CDGNode *addTrueNode(CDGNode * node, CDGNode * trueNode) {
if (NULL == trueNode)
return node;
trueNode->next = node->trueNodeSet;
node->trueNodeSet = trueNode;
setParent(trueNode, node);
return node;
}
CDGNode *addFalseNode(CDGNode * node, CDGNode * falseNode) {
if (NULL == falseNode)
return node;
falseNode->next = node->falseNodeSet;
node->falseNodeSet = falseNode;
setParent(falseNode, node);
return node;
}
CDGNode *getParent(CDGNode * node) {
return node->parent;
}
CDGNode *setParent(CDGNode * node, CDGNode * parentNode) {
node->parent = parentNode;
return node;
}
CDGNode *getNextNode(CDGNode * node) {
return node->next;
}
CDGNode *updateScore(CDGNode * node, int initialize) {
assert(NULL != node);
if (isLeaf(node))
return node;
if (isConditionalLeaf(node)) {
if (initialize) {
if (getBranchInfo(node->id, 1) && !getBranchInfo(node->id, 0)) {
setScore(node, 1);
setTrueNodeSetScore(node, 0);
setFalseNodeSetScore(node, 1);
return setOutcome(node, 0);
} else if (getBranchInfo(node->id, 0) && !getBranchInfo(node->id, 1)) {
setScore(node, 1);
setFalseNodeSetScore(node, 0);
setTrueNodeSetScore(node, 1);
return setOutcome(node, 1);
} else if (getBranchInfo(node->id, 0) && getBranchInfo(node->id, 1)) {
setScore(node, 0);
setTrueNodeSetScore(node, 0);
setFalseNodeSetScore(node, 0);
return setOutcome(node, 1);
}
}
else {
if (hasUncoveredChild(node, 1)) {
setScore(node, 1);
return setOutcome(node, 1);
}
if (hasUncoveredChild(node, 0)) {
setScore(node, 1);
return setOutcome(node, 0);
}
}
setScore(node, 0);
return setOutcome(node, 1);
}
int trueScore = getConditionalNodeSum(getTrueNodeSet(node));
int falseScore = getConditionalNodeSum(getFalseNodeSet(node));
if (trueScore >= falseScore) {
if (node->id == 0) {
setScore(node, trueScore);
setOutcome(node, 1);
}
else {
if (getBranchInfo(node->id, 1) && getBranchInfo(node->id, 0))
setScore(node, trueScore);
else
setScore(node, trueScore + 1);
setOutcome(node, 1);
}
}
else {
if (node->id == 0) {
setScore(node, falseScore);
setOutcome(node, 0);
} else {
if (getBranchInfo(node->id, 1) && getBranchInfo(node->id, 0))
setScore(node, falseScore);
else
setScore(node, falseScore+1);
setOutcome(node, 0);
}
}
return node;
}
CDGNode *propagateScoreChange(CDGNode * node) {
CDGNode *currNode;
currNode = node;
while (currNode) {
updateScore(currNode, 0);
currNode = getParent(currNode);
}
return node;
}
CDGNode *visitAnyOneNode(CDGNode * node) {
assert(NULL != node);
do {
if (isLeaf(node) && 1 == getScore(node)) {
setScore(node, 0);
return node;
}
node = getNextNode(node);
} while (node);
return NULL;
}
CDGNode *visitAnyOneChild(CDGNode * node) {
CDGNode *child = NULL;
if (getFalseNodeSet(node)) {
child = visitAnyOneNode(getFalseNodeSet(node));
}
if (NULL == child && getTrueNodeSet(node)) {
child = visitAnyOneNode(getTrueNodeSet(node));
}
assert(NULL != child);
return child;
}
CDGNode *unVisitNode(CDGNode * node) {
return setScore(node, 1);
}
CDGNode *updateCDG(CDGNode * root, int initialize) {
int size = sizeof(CDGNode *);
assert(NULL != root);
Stack *nodeStack = stackNew(size);
CDGNode *node;
postOrder(root, nodeStack);
while (!stackIsEmpty(nodeStack)) {
stackPop(nodeStack, &node);
updateScore(node, initialize);
}
stackFree(nodeStack);
return root;
}
void visitChildren(CDGNode * node, int outcome) {
CDGNode *children;
if (outcome) {
children = getTrueNodeSet(node);
} else {
children = getFalseNodeSet(node);
}
while (children) {
if (isLeaf(children)) {
setScore(children, 0);
}
children = getNextNode(children);
}
return;
}
void visitIfExists(CDGNode * node, CDGNode * nodes[], int size) {
int i;
for (i = 0; i < size; i++) {
if (getID(node) == getID(nodes[i])) {
visitChildren(node, getOutcome(nodes[i]));
return;
}
}
return;
}
void coverNodes(CDGNode * root, CDGNode * nodes[], int size) {
assert(NULL != root);
if (0 == size)
return;
Stack *nodeStack = stackNew(sizeof(CDGNode *));
CDGNode *node;
postOrder(root, nodeStack);
while (!stackIsEmpty(nodeStack)) {
stackPop(nodeStack, &node);
visitIfExists(node, nodes, size);
}
updateCDG(root, 0);
return;
}
CDGPath *setPathNode(CDGPath * path, CDGNode * node) {
assert(NULL != path);
path->node = node;
return path;
}
CDGPath *setNextPath(CDGPath * path, CDGPath * nextPath) {
assert(NULL != path);
path->next = nextPath;
return path;
}
CDGPath *newPath() {
CDGPath *path;
path = (CDGPath *) malloc(sizeof(CDGPath));
assert(NULL != path);
setPathNode(path, NULL);
setNextPath(path, NULL);
return path;
}
CDGNode *getPathNode(CDGPath * path) {
assert(NULL != path);
return path->node;
}
CDGPath *getNextPath(CDGPath * path) {
assert(NULL != path);
return path->next;
}
CDGNode *copyToPathNode(CDGNode * pathNode, CDGNode * node) {
assert(NULL != pathNode);
setID(pathNode, getID(node));
setExpr(pathNode, getExpr(node));
setOutcome(pathNode, getOutcome(node));
return pathNode;
}
CDGNode *pathToList(CDGNode * head) {
assert(NULL != head);
Stack *nodeStack = stackNew(sizeof(CDGNode *));
CDGNode *node;
CDGNode *list = NULL;
postOrder(head, nodeStack);
while (!stackIsEmpty(nodeStack)) {
stackPop(nodeStack, &node);
list = setNextNode(copyToPathNode(newBlankNode(), node), list);
}
return list;
}
CDGNode *getTopPath(CDGNode * node, Stack * changedNodes, Stack * changedBranches) {
CDGNode *pathNode = newBlankNode();
CDGNode *temp = pathNode;
int branch;
while (node) {
if (0 != getScore(node)) {
stackPush(changedNodes, &node);
branch = getOutcome(node);
stackPush(changedBranches, &branch);
if (isLeaf(node)) {
setScore(node, 0);
} else {
setNextNode(temp, copyToPathNode(newBlankNode(), node));
temp = getNextNode(temp);
if (getOutcome(node)) {
setBranchInfo(getID(node), 1, getBranchInfo(getID(node), 0));
setTrueNodeSet(temp, getTopPath(getTrueNodeSet(node), changedNodes, changedBranches));
} else {
setBranchInfo(getID(node), getBranchInfo(getID(node), 1), 1);
setFalseNodeSet(temp, getTopPath(getFalseNodeSet(node), changedNodes, changedBranches));
}
}
}
node = getNextNode(node);
}
if (temp == pathNode) {
deleteNode(pathNode);
pathNode = NULL;
} else {
temp = pathNode;
pathNode = getNextNode(pathNode);
deleteNode(temp);
}
return pathNode;
}
CDGPath *getTopPaths(CDGContext * ctx, CDGNode * root, int numberOfPaths) {
CDGPath *pathHead = NULL;
CDGNode *path;
CDGPath *currPath;
CDGNode *node;
int branch;
Stack *changedNodes = stackNew(sizeof(CDGNode *));
Stack *changedBranches = stackNew(sizeof(int));
while (numberOfPaths--) {
path = getTopPath(root, changedNodes, changedBranches);
if (NULL == path)
break;
if (NULL == pathHead) {
pathHead = setPathNode(newPath(), path);
currPath = pathHead;
} else {
setNextPath(currPath, setPathNode(newPath(), path));
currPath = getNextPath(currPath);
}
updateCDG(root, 0);
}
while (!stackIsEmpty(changedNodes) && !stackIsEmpty(changedBranches)) {
stackPop(changedNodes, &node);
stackPop(changedBranches, &branch);
if (isLeaf(node)) {
setScore(node, 1);
} else {
if (branch)
setBranchInfo(getID(node), 0, getBranchInfo(getID(node), 0));
else
setBranchInfo(getID(node), getBranchInfo(getID(node), 1), 0);
}
}
updateCDG(root, 0);
stackFree(changedNodes);
stackFree(changedBranches);
/* Updating context */
(*ctx).topPaths = pathHead;
/* Ensuring atleast one path was found */
if (NULL == pathHead)
return NULL;
/* Creating list of nodes from complicated path form */
CDGPath *outPathHead = NULL;
currPath = NULL;
path = NULL;
while (NULL != pathHead) {
path = getPathNode(pathHead);
if (NULL == outPathHead) {
outPathHead = setPathNode(newPath(), pathToList(path));
currPath = outPathHead;
} else {
setNextPath(currPath, setPathNode(newPath(), pathToList(path)));
currPath = getNextPath(currPath);
}
pathHead = getNextPath(pathHead);
}
return outPathHead;
}
void deletePaths(CDGPath * path) {
assert(NULL != path);
CDGPath *next;
do {
next = getNextPath(path);
deleteNodeList(getPathNode(path));
setNextPath(path, NULL);
free(path);
path = next;
} while (path);
}
CDGNode *addDummyNodes(CDGNode * node) {
while (node) {
if (!isLeaf(node)) {
if (NULL == getTrueNodeSet(node)) {
addTrueNode(node, newBlankNode());
} else if (NULL == getFalseNodeSet(node)) {
addFalseNode(node, newBlankNode());
}
}
addDummyNodes(getTrueNodeSet(node));
addDummyNodes(getFalseNodeSet(node));
node = getNextNode(node);
}
return node;
}
CDGNode *findNode(CDGNode * node, int id) {
if (NULL == node)
return NULL;
if (id == getID(node))
return node;
CDGNode *temp = NULL;
/* temp = findNode(getTrueNodeSet(node),id);
*
* if ( temp ) return temp;
*
* temp = findNode(getFalseNodeSet(node), id);
* if ( temp ) return temp; */
return findNode(getNextNode(node), id);
}
int nodeExists(CDGNode * node, int id) {
return NULL != findNode(node, id);
}
CDGNode *buildFeasiblePath(CDGNode * node, CDGNode * list) {
while (node && 0 == nodeExists(list, getID(node))) {
node = getNextNode(node);
}
if (NULL == node)
return NULL;
CDGNode *out = NULL;
out = copyToPathNode(newBlankNode(), node);
setTrueNodeSet(out, buildFeasiblePath(getTrueNodeSet(node), list));
setFalseNodeSet(out, buildFeasiblePath(getFalseNodeSet(node), list));
setNextNode(out, buildFeasiblePath(getNextNode(node), list));
return out;
}
CDGNode *getFeasiblePath(CDGNode * path, CDGNode * list) {
return buildFeasiblePath(path, list);
}
CDGNode *getFeasibleSatNodes(CDGContext * ctx, int pathRank, CDGNode * list) {
assert(NULL != ctx);
assert(NULL != (*ctx).topPaths);
CDGPath *topPath = (*ctx).topPaths;
while (0 < pathRank--) {
topPath = getNextPath(topPath);
}
return pathToList(getFeasiblePath(getPathNode(topPath), list));
}
int getPathLength(CDGNode * node) {
if (NULL == node)
return 0;
return 1 + getPathLength(getNextNode(node));
}
/*int getPathLength(CDGNode* node) {
if ( NULL == node ) return 0;
return 1 + getPathLength(getTrueNodeSet(node)) + getPathLength(getFalseNodeSet(node)) + getPathLength(getNextNode(node));
}*/
|
C | /**
* @file hashtable.c
* @author Adam Sinclair
* @created Sun April 8 2018
* @purpose Implementation of HashTable
**/
#include "HashTableAPI.h"
#include "debug.h"
static unsigned int hash(const char* string, unsigned int size);
HashTable initializeHashTable(int size, char* (*printFunction)(void* toBePrinted), void (*deleteFunction)(void* toBeDeleted), int (*compareFunction)(const void* first, const void* second)){
if(size < 1)
log_error_exit("Size parameter is invalid: [%d]", size);
if(deleteFunction == NULL || printFunction == NULL || compareFunction == NULL)
log_error_exit("HashTable with size [%d] has NULL function pointer.", size);
HashTable ht;
ht.maxSize = size;
ht.currentSize = 0;
// Allocate space for the array of entries
if((ht.entries = calloc((size_t)ht.maxSize, sizeof(Entry))) == NULL)
log_error_exit("Allocating hash table of size [%d] failed.", size);
// For each entry, initialize the chain
for(int i=0; i<ht.maxSize; i++)
ht.entries[i].chain = initializeList(printFunction, deleteFunction, compareFunction);
return ht;
}
void deleteHashTable(HashTable* ht)
{
if(ht == NULL)
return;
for(int i=0; i<ht->maxSize; i++)
{
Entry* entry = NULL;
entry = &ht->entries[i];
if(entry != NULL)
{
clearList(entry->chain);
entry = NULL;
}
}
free(ht->entries);
}
void clearHashTable(HashTable* ht)
{
if(ht == NULL)
return;
for(int i=0; i<ht->maxSize; i++)
{
Entry* entry = NULL;
entry = &ht->entries[i];
if(entry != NULL)
{
clearList(entry->chain);
entry = NULL;
}
}
}
bool insertEntry(HashTable* ht, const char* key, void* data)
{
if(ht == NULL || ht->maxSize <= 0) {
log_error("%s", "HashTable is NULL or has no space.\n");
return false;
} else if(key == NULL) {
log_error("%s", "Key is NULL or empty.\n");
return false;
} else if(data == NULL) {
log_error("%s", "Data is NULL.\n");
return false;
}
// Get hashcode from key and insert into entry chain
int hashValue = hash(key, ht->maxSize);
// Check if node with key already exists
if(getEntry(ht, key) != NULL)
{
log_debug("Entry with key [%s] already exists. Nothing added.\n", key);
return false;
}
insertBack(ht->entries[hashValue].chain, data, key);
ht->currentSize++;
return true;
}
void* getEntry(HashTable* ht, const char* key)
{
if(ht == NULL || ht->maxSize <= 0) {
log_error("%s", "HashTable is NULL or has no space.\n");
return NULL;
} else if(key == NULL) {
log_error("%s", "Key is NULL or empty.\n");
return NULL;
}
int hashValue = hash(key, ht->maxSize);
return findElement(*ht->entries[hashValue].chain, key);
}
void deleteEntry(HashTable* ht, const char* key)
{
if(ht == NULL || ht->maxSize <= 0) {
log_error("%s", "HashTable is NULL or has no space.\n");
return;
} else if(key == NULL) {
log_error("%s", "Key is NULL or empty.\n");
return;
}
// Get hashcode from key
int hashValue = hash(key, ht->maxSize);
// Find data element from LinkedList
void* data = findElement(*ht->entries[hashValue].chain, key);
if(data == NULL)
return;
// Delete node from entry chain
data = deleteDataFromList(ht->entries[hashValue].chain, key);
// Delete data from Data struct
ht->entries[hashValue].chain->deleteData(data);
ht->currentSize--;
}
int getKeyIndex(HashTable* ht, const char* key)
{
if(ht == NULL || key == NULL || strlen(key) < 1)
return -1;
int hashCode = hash(key, ht->maxSize);
return getIndex(ht->entries[hashCode].chain, key);
}
/**
* Implement FNV-1a hash algorithm
* https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
*
* @param string Represents a label for some information.
* @param size Size of hash table used for modulo operation.
* @return A non-zero number representing the index in a table.
**/
static unsigned int hash(const char* string, unsigned int size)
{
if(string == NULL || strlen(string) < 1)
return 0;
int len = strlen(string);
unsigned long hash = 2166136261u;
for(int i=0; i<len; i++)
{
hash ^= string[i];
hash *= 16777617u;
}
return hash % size;
}
|
C | #include<stdio.h>
#include<stdlib.h>
# define max 4
int a[max],top;
top=-1;
void push(int val)
{
if(top==max-1)
printf("\n Stack Overflow !! No values can be added now.\n");
else
{
top++;
a[top]=val;
}
}
void pop()
{
if(top==-1)
printf("\n Stack underflow !! No elements can be deleted.\n");
else
{
printf("The element to be deleted is %d.",a[top]);
top--;
}
}
void display()
{
int pos;
pos=0;
printf("\n ELEMENTS OF STACK : ");
while(pos<=top)
{
printf("\t%d",a[top-pos]);
pos++;
}
}
void pal()
{
int flag,i;
for(i=0;i<=(top+1)/2;++i)
{
if(a[top-i]==a[i])
{
flag=0;
}
else
{
flag=1;
break;
}
}
if(flag==0)
printf("\n\t STACK IS PALINDROME.");
else
printf("\n\t STACK IS NOT PALINDROME.");
}
void status()
{
printf("\n The status of top is %d\n",top);
}
int main()
{
int ch,val;
while(ch!=5)
{
printf("\n\n\t MENU \n 1. PUSH VALUES IN STACK\n 2.POP VALUE FROM STACK\n 3.STACK IS PALINDROME OR NOT\n 4.STATUS OF STACK\n 5.EXIT \n\n Enter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1 : printf("\n Enter value to be pushed in stack : ");
scanf("%d",&val);
push(val);
break;
case 2 : pop();
break;
case 3 : pal();
break;
case 4 : display();
status();
break;
case 5 : exit(0);
break;
default : printf("Invalid Choice !!!!!\n");
}
}
return 0;
}
|
C | /*
* string output to stderr only
*/
#include<stdio.h>
int main(int argc,char** argv){
perror("Hello world\n");
return 0;
}
|
C | /* Implementation of dequeue */
#include<stdio.h>
#include<stdlib.h>
#define MAX 1007
int dequeue[MAX];
int front = -1;
int rear = -1;
void insert_front(int item);
void insert_rear(int item);
int del_front();
int del_rear();
void display();
int isEmpty();
int isFull();
int main(){
int choice,item;
while(1){
printf("1.Insert at front\n");
printf("2.Insert at rear\n");
printf("3.Delete at front\n");
printf("4.Delete at rear\n");
printf("5.Display\n");
scanf("%d",&choice);
switch(choice){
case 1:
scanf("%d",&item);
insert_front(item);
break;
case 2:
scanf("%d",&item);
insert_rear(item);
break;
case 3:
printf("%d delted from front\n",del_front());
break;
case 4:
printf("%d delted from rear\n",del_rear());
break;
case 5:
display();
break;
default:
exit(1);
}
}
return 0;
}
void insert_rear(int item){
if(isFull()){
printf("Queue Overflow!\n");
return;
}
if(front == -1)
front = rear = 0;
else if(rear == MAX-1)
rear = 0;
else
rear++;
dequeue[rear] = item;
}
void insert_front(int item){
if(isFull()){
printf("Queue Overflow!\n");
return;
}
if(front == -1){
front = rear=0;
}
else if(front == 0)
front = MAX -1;
else
front--;
dequeue[front] = item;
}
int del_front(){
if(isEmpty()){
printf("Queue Underflow!\n");
exit(1);
}
int item = dequeue[front];
if(front == rear){
front = rear = -1;
}
else if(front == MAX-1)
front =0;
else
front++;
return item;
}
int del_rear(){
if(isEmpty()){
printf("Queue Underflow!\n");
exit(1);
}
int item = dequeue[rear];
if(front == rear){
front = rear = -1;
}
else if(rear == 0)
rear = MAX-1;
else
rear--;
return item;
}
int isEmpty(){
if(front == -1)
return 1;
else
return 0;
}
int isFull(){
if(front ==0 && rear==MAX-1 || front == rear+1)
return 1;
else
return 0;
}
void display(){
int i;
if(isEmpty()){
printf("Queue Underflow!\n");
return;
}
if(rear< front){
for(i=front ;i<MAX;i++)
printf("%d\n",dequeue[i]);
for(i= 0 ;i<=rear;i++)
printf("%d\n",dequeue[i]);
}
else{
for(i=front ;i<=rear;i++)
printf("%d\n",dequeue[i]);
}
printf("\n\n");
} |
C | /*
** EPITECH PROJECT, 2021
** mylib
** File description:
** mylib
*/
#include "../../includes/utils.h"
char *my_revstr(char *str)
{
char tmp;
int index = 0;
int len = my_strlen(str) - 1;
while (index < len) {
tmp = str[index];
str[index] = str[len];
str[len] = tmp;
++index;
--len;
}
return str;
}
|
C | #include <stdio.h>
#include <string.h>
int main(void)
{
// char inputOne[5] = "B";
// char inputTwo[5] = "A";
// printf("문자열 비교 : %d\n", strcmp(inputOne, inputTwo));
char input[10] = "I Love You";
char result[5] = "Love";
strcpy(result, input);
printf("문자열 복사 : %s\n", result);
return 0;
} |
C | /*******************************************************************************
* Stefan Bylund 2017
*
* String utility functions.
******************************************************************************/
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stropts.h>
#include <ctype.h>
#include <rect.h>
#include <font/fzx.h>
#include "str_util.h"
char *str_lower_case(char *s)
{
if (s != NULL)
{
uint16_t i;
for (i = 0; s[i]; i++)
{
s[i] = tolower(s[i]);
}
}
return s;
}
char *str_remove_cr(char *s)
{
if ((s != NULL) && (strchr(s, '\r') != NULL))
{
char *src;
char *dst;
for (src = s, dst = s; *src != '\0'; src++)
{
*dst = *src;
if (*dst != '\r')
{
dst++;
}
}
*dst = '\0';
}
return s;
}
char *str_remove_trailing_lf(char *s)
{
if ((s != NULL) && (strlen(s) > 0))
{
if (s[strlen(s) - 1] == '\n')
{
s[strlen(s) - 1] = '\0';
}
}
return s;
}
char *str_word_wrap(FILE *out, char *s)
{
int fd;
struct fzx_font *font;
struct r_Rect16 paper;
uint16_t width;
char *line;
char *line_end;
if ((out == NULL) || (s == NULL))
{
return s;
}
fd = fileno(out);
if (fd < 0)
{
return s;
}
font = (struct fzx_font *) ioctl(fd, IOCTL_OTERM_FONT, -1);
ioctl(fd, IOCTL_OTERM_FZX_GET_PAPER_RECT, &paper);
width = paper.width - ioctl(fd, IOCTL_OTERM_FZX_LEFT_MARGIN, -1) - 1;
line = strtok(s, "\n");
while (line != NULL)
{
line_end = fzx_string_partition_ww(font, line, width);
*line_end = '\n';
line = strtok(line_end + 1, "\n");
}
return s;
}
|
C | #include <stdint.h>
#include "kassert.h"
#include "rpi.h"
#include "thread.h"
#include "interrupt.h"
#include "mmu.h"
static core_tasks_ctlr core_tasks[CORE_NUM] = {0};
static const struct cpu_context empty_context = {0};
extern void ret_from_fork(void);
extern void context_switch(struct task_struct* prev, struct task_struct* next);
extern void enable_irq(void);
extern void disable_irq(void);
void preempt_disable(void){
unsigned core = CORE_ID();
core_tasks[core].current->preempt_count = 1;
}
void preempt_enable(void){
unsigned core = CORE_ID();
core_tasks[core].current->preempt_count = 0;
}
void scheduler_tick(void){
unsigned core = CORE_ID();
if (core_tasks[core].current->preempt_count != 0) {
return;
}
// when entering exception, interrupts are disabled, but we enable them bcs we can have interrupts happen while scheduling
enable_irq();
schedule();
disable_irq();
}
void core_timer_clearer(void){
SET_CORE_TIMER(TIMER_INT_PERIOD);
}
void switch_to(struct task_struct * next){
unsigned core = CORE_ID();
if (core_tasks[core].current == next)
return;
struct task_struct *prev = core_tasks[core].current;
core_tasks[core].current = next;
context_switch(prev, next);
}
void schedule(void){
unsigned core = CORE_ID();
preempt_disable();
struct task_struct *temp = core_tasks[core].current;
int found = 0;
while(temp != NULL){
if(temp->state == TASK_READY){
found = 1;
break;
}
temp = temp->next;
}
if(!found){
preempt_enable();
return;
}
if(core_tasks[core].current->state != TASK_ZOMBIE)
core_tasks[core].current->state = TASK_READY;
temp->state = TASK_RUNNING;
switch_to(temp);
preempt_enable();
}
void join_task(struct task_struct *p){
while(p->state != TASK_ZOMBIE)
schedule();
}
void join_all_core_tasks(void){
unsigned core = CORE_ID();
while(core_tasks[core].tasks_num > 1){
schedule();
}
}
void join_all(void){
while(core_tasks[0].tasks_num > 1
|| core_tasks[1].tasks_num != 1
|| core_tasks[2].tasks_num != 1
|| core_tasks[3].tasks_num != 1){
schedule();
}
disable_core_timer_int();
}
void exit_task(void){
unsigned core = CORE_ID();
preempt_disable();
core_tasks[core].current->state = TASK_ZOMBIE;
core_tasks[core].tasks_num--;
core_tasks[core].current->next->previous = core_tasks[core].current->previous;
core_tasks[core].current->previous->next = core_tasks[core].current->next;
schedule();
}
// core0 forks the tasks for the other cores when starting
struct task_struct* fork_task(core_number_t core, void (*fn)(void *, void *), void *arg, void *ret){
if(core_tasks[core].tasks_num >= NR_TASKS)
panic("max threads reached");
struct task_struct *p = NULL;
for(int i = 1; i < NR_TASKS; i++){ // there can be zombies in the slots, so need to go through all the array
if(core_tasks[core].tasks[i].state == TASK_ZOMBIE){
p = &core_tasks[core].tasks[i];
break;
}
}
if(p == NULL){
panic("could not find a slot for the task to fork core: %d function address: 0x%x\n", core, fn);
}
p->cpu_context = empty_context;
p->next = NULL;
p->previous = NULL;
p->state = TASK_READY;
p->preempt_count = 1; //disable preemtion until starting to execute thread
p->cpu_context.x19 = (uint64_t)fn;
p->cpu_context.x20 = (uint64_t)arg;
p->cpu_context.x21 = (uint64_t)ret;
p->cpu_context.pc = (uint64_t)&ret_from_fork;
uintptr_t stack_pointer = ((uintptr_t) &p->stack[8191]) - 16;
p->cpu_context.sp = (uint64_t)pi_roundup(stack_pointer, 16); // this makes sure sp is aligned 16 and not cloberring the other stuff
demand(is_aligned(p->cpu_context.sp, 16), "sp not aligned 16 when forking task");
if(core_tasks[core].tasks_num == 0){ // if there are no tasks, current is task 0 (main)
core_tasks[core].tasks[0].next = p;
core_tasks[core].tasks[0].previous = p;
p->next = &(core_tasks[core].tasks[0]);
p->previous = &(core_tasks[core].tasks[0]);
core_tasks[core].current = &core_tasks[core].tasks[0];
core_tasks[core].tasks_num++; // we effectively add 2 tasks at the start, p + main
} else {
struct task_struct *q = core_tasks[core].current->next;
core_tasks[core].current->next = p;
p->next = q;
q->previous = p;
p->previous = core_tasks[core].current;
}
core_tasks[core].tasks_num++;
return p;
}
void secondary_cores_threading_init(void){
unsigned core = CORE_ID();
if(core_tasks[core].tasks_num == 0) return; // if there was no task for us
enable_core_timer_int();
//reset_mains_stack();
core_tasks[core].current->state = TASK_RUNNING;
SET_CORE_TIMER(TIMER_INT_PERIOD);
join_all_core_tasks();
disable_core_timer_int();
demand(core_tasks[core].tasks_num == 1, "not idle core %d went to sleep, num of tasks %d\n", core, core_tasks[core].tasks_num);
}
void threading_init(void){
enable_core_timer_int();
PUT32(CORE_MAILBOX_WRITETOSET + 16, (uintptr_t)&secondary_cores_threading_init);
PUT32(CORE_MAILBOX_WRITETOSET + 32, (uintptr_t)&secondary_cores_threading_init);
PUT32(CORE_MAILBOX_WRITETOSET + 48, (uintptr_t)&secondary_cores_threading_init);
WAKE_CORES();
core_tasks[0].current->state = TASK_RUNNING;
SET_CORE_TIMER(TIMER_INT_PERIOD);
}
/**
*
*
* #pragma omp parallel for schedule(dynamic, 1)
*for (int y = 0; y < s->height; y++) {
* ...
*}
*This is an Open Multi-Processing (OpenMP) pragma. It’s a higher-level threading API than POSIX or Win32 threads.
*
*
*/ |
C | //gcc BERKIN_MYMORE.c -o myMore
// Created by berkin on 05.11.2016.
// Finished by berkin on 14.11.2016 at 01:45
// Edited project name on 15.11.2016 at 18:42
#include "stdlib.h"
#include "stdio.h"
#include "unistd.h"
#define BUFFER_SIZE 500
#define MAXIMUM_LINE_NUMBER 100
#define LINES_PER_TURN 24
int main(int argc, char *argv[]){
int read_exit = atoi(argv[1]);
char read_msg[MAXIMUM_LINE_NUMBER][BUFFER_SIZE];
read(read_exit, &read_msg, LINES_PER_TURN*BUFFER_SIZE);
for (int i = 0; i < LINES_PER_TURN; ++i) {
printf("%s",read_msg[i]);
}
close(read_exit);
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* set_color.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: omykolai <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/04/27 13:34:36 by omykolai #+# #+# */
/* Updated: 2018/04/27 15:57:06 by omykolai ### ########.fr */
/* */
/* ************************************************************************** */
#include "corewar.h"
unsigned int vm_color(unsigned int c, int type)
{
if (c >= C_PROCESS_DEFAULT)
c -= C_DIF;
if (type == C_PROCESS)
return (c + C_DIF);
if (type == C_PLAYER)
return (c);
return (0);
}
void set_color(t_vm *vm, void *pos, unsigned int color, int age)
{
unsigned char *cpos;
long i;
cpos = pos;
i = cpos - vm->mem;
vm->vis[i].color = color;
vm->vis[i].age = (unsigned)age;
}
void set_color4(t_vm *vm, void *pos, unsigned int color, int age)
{
unsigned char *cpos;
long i;
long j;
cpos = pos;
i = cpos - vm->mem;
j = -1;
while (++j < 4)
{
vm->vis[(i + j) % MEM_SIZE].color = color;
vm->vis[(i + j) % MEM_SIZE].age = (unsigned)age;
}
}
|
C |
#include "shm_sem.h"
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <unistd.h>
void ReadData(const char* path_input, char* shared_memory, int id_sem);
void ReadToSharedMemory(const char* path_input)
{
errno = 0;
key_t key = ftok(FTOK_PATHNAME, FTOK_PROJ_ID);
if (key < 0) {
perror("Error ftok()");
exit(EXIT_FAILURE);
}
int id_sem = semget(key, N_SEMAPHORES, 0666 | IPC_CREAT);
if (id_sem < 0) {
perror("Error semget");
exit(EXIT_FAILURE);
}
int ret = 0;
// Block other readers
struct sembuf sops_MutexReaders[2] = {
{SEM_READER_EXIST, 0, 0},
{SEM_READER_EXIST, 1, SEM_UNDO}
};
ret = semop(id_sem, sops_MutexReaders, 2);
if (ret < 0) {
perror("Error semop");
exit(EXIT_FAILURE);
}
// Wait end of previous transfer
struct sembuf sops_WaitingPrevious[1] =
{SEM_N_ACTIVE_PROC, 0, 0};
ret = semop(id_sem, sops_WaitingPrevious, 1);
if (ret < 0) {
perror("Error semop");
exit(EXIT_FAILURE);
}
AssignSem(id_sem, SEM_WRITE_FROM_SHM, 1);
// Reader already init SEM_WRITE_FROM_SHM
// Not block writer if reader die
struct sembuf sops_DefenceDeadlock[2] = {
{SEM_READER_READY, 1, SEM_UNDO},
{SEM_WRITE_FROM_SHM, -1, SEM_UNDO},
};
ret = semop(id_sem, sops_DefenceDeadlock, 2);
if (ret < 0) {
perror("Error semop");
exit(EXIT_FAILURE);
}
// Check that writer exists
// Mark that reader is alive
struct sembuf sops_WaitingPair[3] = {
{SEM_WRITER_READY, -1, 0},
{SEM_WRITER_READY, 1, 0},
{SEM_N_ACTIVE_PROC, 1, SEM_UNDO},
};
ret = semop(id_sem, sops_WaitingPair, 3);
if (ret < 0) {
perror("Error semop");
exit(EXIT_FAILURE);
}
int id_shm = 0;
char* shared_memory = ConstructSharedMemory(key, SIZE_SHARED_MEMORY,
&id_shm);
ReadData(path_input, shared_memory, id_sem);
// Clear semaphores
struct sembuf sops_FinishReading[3] = {
{SEM_READER_READY, -1, SEM_UNDO},
{SEM_N_ACTIVE_PROC, -1, SEM_UNDO},
{SEM_READER_EXIST, -1, SEM_UNDO},
};
ret = semop(id_sem, sops_FinishReading, 3);
if (ret < 0) {
perror("Error semop");
exit(EXIT_FAILURE);
}
}
void ReadData(const char* path_input, char* shared_memory, int id_sem)
{
assert(path_input);
assert(shared_memory);
int fd_input = open(path_input, O_RDONLY);
if (fd_input < 0) {
perror("Error open");
exit(EXIT_FAILURE);
}
ssize_t n_bytes = -1;
while(n_bytes != 0) {
int ret = 0;
struct sembuf sops_BeforeRead[1] =
{SEM_READ_TO_SHM, -1, 0};
ret = semop(id_sem, sops_BeforeRead, 1);
if (ret < 0) {
perror("Error semop");
exit(EXIT_FAILURE);
}
n_bytes = read(fd_input, shared_memory + sizeof(n_bytes),
SIZE_SHARED_MEMORY - sizeof(n_bytes));
if (n_bytes < 0) {
perror("Error read");
exit(EXIT_FAILURE);
}
*(ssize_t*)shared_memory = n_bytes;
struct sembuf sops_AfterRead[1] =
{SEM_WRITE_FROM_SHM, 1, 0};
ret = semop(id_sem, sops_AfterRead, 1);
if (ret < 0) {
perror("Error semop");
exit(EXIT_FAILURE);
}
}
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* pipex.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mbenmesb <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/13 13:58:33 by mbenmesb #+# #+# */
/* Updated: 2021/11/13 13:58:36 by mbenmesb ### ########.fr */
/* */
/* ************************************************************************** */
#include "pipex.h"
int ft_get_parent_ret(t_struct *ptr, char **argv, char **envp)
{
int ret;
ret = ft_create_parent(ptr, argv, envp);
if (ret)
{
ft_free_t_struct(&ptr);
return (ret);
}
return (0);
}
int ft_get_child_ret(t_struct *ptr, char **argv, char **envp)
{
int ret;
ret = ft_create_child(ptr, argv, envp);
if (ret)
{
ft_free_t_struct(&ptr);
return (ret);
}
return (0);
}
int ft_check_fork(t_struct *ptr, char **argv, char **envp)
{
int ret;
if ((*ptr).retour == -1)
{
ft_free_t_struct(&ptr);
perror (" pb fork ");
exit(1);
}
if ((*ptr).retour == 0)
{
ret = ft_get_child_ret(ptr, argv, envp);
return (ret);
}
else
{
ret = ft_get_parent_ret(ptr, argv, envp);
return (ret);
}
}
void ft_check_fork_fd1(t_struct *ptr, char **argv, char **envp, int ret)
{
pid_t retour_fd1;
if (ret == 2)
exit(1);
if (ret == 1)
{
ft_error_msg(argv);
ft_create_pipe(ptr);
retour_fd1 = fork();
if (retour_fd1 == -1)
{
ft_free_t_struct(&ptr);
perror (" pb fork ");
exit(1);
}
if (retour_fd1 == 0)
{
ret = ft_get_parent_ret(ptr, argv, envp);
(*ptr).errnum = ret;
exit(ret);
}
ret = (*ptr).errnum ;
ft_free_t_struct(&ptr);
exit(ret);
}
}
int main(int argc, char *argv[], char *envp[])
{
t_struct *ptr;
int ret;
if (argc != 5)
{
ft_putstr_fd("usage: ./pipex infile cmd1 cmd2 outfile \n", 1);
return (1);
}
ptr = ft_struct_init(&ptr, argv);
(*ptr).path_tab = ft_get_path(envp);
ret = ft_check_open_error(ptr);
if (ret == 2 || ret == 1)
ft_check_fork_fd1(ptr, argv, envp, ret);
ft_create_pipe(ptr);
(*ptr).retour = fork();
ret = ft_check_fork(ptr, argv, envp);
if (ret)
return (ret);
ft_free_t_struct(&ptr);
return (0);
}
|
C | SARA HASNAOUI MATRICOLA:322294
#include "mylib.h"
#include <stdio.h>
#include <stdlib.h>
int main(){
int choose=0;
system("clear");
do while{
printf("Scegli un opzione \n");
printf(" 1. Crea cunicoli,\n 2. Gioca, \n 3. Termina Gioco.\n");
printf(">$");
scanf("%d",&choose);
system("clear");
switch(choose){
case 1:
crea_cunicoli();
break;
case 2:
gioca();
break;
case 3:
printf("Termine del gioco.\\\\\\..\n");
termina_gioco();
break;
default:
printf("Opzione non valida.....\n");
break;
}
}while(choose!=3);
return 0;
}
|
C | #include <stdio.h>
int main(void) {
// your code goes here
int year;
scanf("%d",&year);
if(year%4==0)
printf("yes");
else
printf("no");
return 0;
}
|
C | #include <stdio.h>
/**********************************************
Program Nilai
Deskripsi : Mengetahui grade dari sebuah nilai yang diinput
IS : User siap menginput nilai
FS : Di layar tertulis grade nilai
Dibuat oleh :
Nama : Diaz Adha Asri Prakoso
Tanggal : 24 Oktober 2018
**********************************************/
void main (void)
//KAMUS
{ float Nilai;
//ALGORITMA
printf ("Masukkan Nilai = ");
scanf ("%f", &Nilai);
if (Nilai<80)
{
if (Nilai>=70)
{
printf ("Grade B\n");
}
else //Nilai < 70
{
if (Nilai>=60&&Nilai<70)
{
printf ("Grade C\n");
}
else //Nilai < 60 OR Nilai >= 70
{
if (Nilai>=50&&Nilai<60)
{
printf ("Grade D\n");
}
else //Nilai < 50 OR Nilai >= 60
{
printf ("Grade E\n");
}
}
}
}
else //Nilai >= 80
{
printf ("Grade A\n");
}
system ("PAUSE");
}
|
C | #include <stdio.h>
#include <string.h>
int main() {
char str_a[20]; //Tableau de 20 caracteres
char *pointer; //Pointeur pour un tablau de caractere
char *pointer2; //Un seconde pointeur
strcpy(str_a, "Hello world !\n");
pointer = str_a; //fixer le premier pointeur au debut du tableau
printf(pointer);
pointer2 = pointer + 2; //fixer le second pointeur deux octets plus loint
printf(pointer2); //affichage de pointeur2
strcpy(pointer2, "\t pointer2 est ici !\n"); //copier la chaine désigné par le pointeur
printf(pointer); //affiche pointeur a nouveau
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sbednar <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/12/03 19:21:12 by edraugr- #+# #+# */
/* Updated: 2019/01/18 00:04:59 by sbednar ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static t_list *newlst(size_t fd)
{
t_list *new;
if (!(new = (t_list *)malloc(sizeof(t_list))))
return (NULL);
new->next = NULL;
new->content = (void *)ft_strdup("");
new->content_size = fd;
if (!(new->content))
return (NULL);
return (new);
}
static t_list *getcurlst(int fd, t_list **l)
{
t_list *temp;
temp = *l;
while (temp)
{
if (temp->content_size == (unsigned int)fd)
return (temp);
temp = temp->next;
}
if (!(temp = newlst((size_t)fd)))
return (NULL);
ft_lstadd(l, temp);
temp = *l;
return (temp);
}
static int node_solver(t_list *src, char **line)
{
char *temp;
if (src->content && (temp = ft_strchr((char *)src->content, '\n')))
{
if (!(*line = ft_strsub(src->content, 0, temp - (char *)src->content)))
return (-1);
temp++;
temp = ft_strdup(temp);
free(src->content);
src->content = temp;
return (1);
}
return (0);
}
static int end_it(char **line, t_list *src)
{
if (src->content)
if (ft_strlen((char *)src->content))
{
if (!(*line = ft_strdup((char *)src->content)))
return (-1);
else
{
if (line[0][ft_strlen(*line) - 1] == '\n')
line[0][ft_strlen(*line) - 1] = '\0';
free(src->content);
src->content = NULL;
return (1);
}
}
return (0);
}
int get_next_line(const int fd, char **line)
{
static t_list *l;
t_list *src;
char buff[BUFF_SIZE + 1];
int place;
char *temp;
temp = NULL;
if (fd < 0 || !line || (read(fd, buff, 0) < 0)
|| !(src = getcurlst(fd, &l)))
return (-1);
if ((place = node_solver(src, line)))
return (place);
while ((place = read(fd, buff, BUFF_SIZE)))
{
buff[place] = '\0';
if (!(temp = ft_strjoin((char *)src->content, buff)))
return (-1);
ft_memdel(&(src->content));
src->content = (void *)temp;
if ((place = node_solver(src, line)))
return (place);
}
return (end_it(line, src));
}
|
C | #include <stdio.h>
void printd(int n){
if(n<0){
putchar('-');
n = -n;
}
if(n/10)
printd(n/10);
putchar(n%10 + '0');
}
void qsort(int v[], int left, int right){
int i, last;
void swap(int v[], int i, int j);
if(left>=right)
return;
swap(v, left, (left+right)/2);
last = left;
for(i=left+1; i<=right;i++)
if(v[i]<v[left])
swap(v, ++last, i);
swap(v, left, last);
qsort(v, left, last-1);
qsort(v, last+1, right);
}
void swap(int v[], int i, int j){
int temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* strmapi.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: amwangal <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/20 18:42:28 by amwangal #+# #+# */
/* Updated: 2018/03/21 17:09:44 by amwangal ### ########.fr */
/* */
/* ************************************************************************** */
/*
** The function ft_strmap() applies the function f to each character of the
** string given as an argument by giving its index as the first argument to
** create a "fresh" new string (with malloc(3)) resulting from the successive
** applications of f.
*/
#include "libft.h"
char *ft_strmapi(char *s, char (*f)(unsigned int, char))
{
int i;
int len;
char *map;
i = 0;
if (s == 0)
return (NULL);
len = ft_strlen(s);
map = malloc(sizeof(char) * (len + 1));
if (map == 0)
return (NULL);
while (s[i] != '\0')
{
map[i] = f(i, s[i]);
i++;
}
map[i] = '\0';
return (map);
}
|
C | /*
* Uart.h
*
* Created on: Jan 23, 2018
* Author: Karl Kobel
*/
#ifndef UART_H_
#define UART_H_
#include "stm32f4xx_ll_usart.h"
typedef enum
{
// U_MATCH, // setup a callback to fire when a received character matches
U_IDLE, // setup a callback to fire after line idle
U_CHAR, // setup a callback for each received character
//U_MATCH_9B, // setup a callback to fire when a received character matches - 9 bit mode receive
U_IDLE_9B, // setup a callback to fire after N time of line idle - 9 bit mode receive
//U_CHAR_9B, // setup a callback for each received character - 9 bit mode receive
} U_MODE;
#define U_DATAWIDTH_7B LL_USART_DATAWIDTH_7B
#define U_DATAWIDTH_8B LL_USART_DATAWIDTH_8B
#define U_DATAWIDTH_9B LL_USART_DATAWIDTH_9B
#define U_PARITY_NONE LL_USART_PARITY_NONE
#define U_PARITY_EVEN LL_USART_PARITY_EVEN
#define U_PARITY_ODD LL_USART_PARITY_ODD
#define U_STOPBITS_0_5 LL_USART_STOPBITS_0_5
#define U_STOPBITS_1 LL_USART_STOPBITS_1
#define U_STOPBITS_1_5 LL_USART_STOPBITS_1_5
#define U_STOPBITS_2 LL_USART_STOPBITS_2
typedef struct
{
U_MODE mode; // U_MATCH / U_IDLE / U_CHAR
char match; // the match character for U_MATCH
uint32_t bits; // number of bits. Ex 8 or 9
uint32_t parity; // parity emun from hal_uart.h
uint32_t stop_bits; // number of stopbits emun from hal_uart.h
uint32_t baud; // the real BAUD value, ie: 19200
void (*UartRxCallback)(uint8_t* buf, uint8_t* len); // called when the receive is complete (mode dependant)
void (*UartTxCallback)(void); // called when the transmit is complete
} UART_DEF;
// Example Usage
//
// UART_DEF uart_def;
//
// uart_def.mode = U_CHAR;
// uart_def.bits = U_DATAWIDTH_8B;
// uart_def.parity = U_PARITY_NONE;
// uart_def.stop_bits = U_STOPBITS_2;
// uart_def.baud = 9600;
// uart_def.UartRxCallback = ReceivedChar;
// uart_def.UartTxCallback = TransmitComplete;
// if(Uart2_Init(&uart_def) != HAL_OK)
// {
// _Error_Handler(__FILE__, __LINE__);
// }
//
// The Rx callback will get called for each character
// The Tx callback will get called when all of the characters have been transmitted
//
// NOTE: both callbacks are called in an interrupt domain.
// Don't block within the callback
//
// Special note for U_IDLE_9B mode
// This behaves like U_IDLE mode, but the character receiver returns two bytes.
// The 8 bit character will be in the first (odd) location of the character array,
// and the 9th bit will be in the second location (either a 0 or a 1).
// The number of characters returned does not include the extra byte for the 9th bit (a true count of the characters)
// Cast the uint8_t array into a uint16_t array so the indexing works correctly
//
#endif /* UART_H_ */
|
C | #include <time.h>
#include <stdbool.h>
clock_t startTime = 0;
bool timedOut = true;
bool harTimetUt()
{
clock_t tid = clock();
if(tid - startTime > 3000000 && !timedOut)
{
timedOut = true;
return true;
}
return false;
}
void startTimer()
{
startTime = clock();
timedOut = false;
}
|
C | /* gcc -Wall math.c -lm */
#include <stdio.h>
#include <math.h> /* IMPORTANT! */
int main (void)
{
double x = pow (2.0, 3.0); /* need math.h */
printf ("Two cubed is %f\n", x);
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
main( int ac, char *av[] )
{
int do_random, i, j, size, loop ;
long fout, li ;
if ( ac <= 3 )
{
printf("Usage: %s size loop|max_random 0/1[1=random]\n", av[0] ) ;
printf(" loop: number of size output in the case of the "
"sequencial number\n") ;
printf(" max_random: the max value of the output\n") ;
exit( 1 ) ;
}
size = atoi( av[ 1 ] ) ;
if ( size <= 0 )
{
printf("Usage: %s size loop \n", av[0] ) ;
exit( 1 ) ;
}
loop = atoi( av[ 2 ] ) ;
if ( loop <= 0 )
{
printf("Usage: %s size loop \n", av[0] ) ;
exit( 1 ) ;
}
if ( ac >= 4 )
do_random = atoi( av[ 3 ] ) ;
else
do_random = 1 ;
if ( do_random )
{
while ( size-- )
{
printf("%d\n", (int)(random() % loop )) ;
}
} else
{
while ( loop-- )
{
for ( j = 0 ; j < size ; j++ )
{
printf("%d\n", j ) ;
}
}
}
}
|
C | /*
Tail implementation for XV6
created by Siddharth Singh ([email protected])
The reason why tail implementation is lot more difficult than head is because
1. We can't keep the whole file in memory as the file may be very large. We need to keep a array of pointers, each pointing to a
//char array containing a line.
2. We don't know what the size of each line is so we can't allocate memory before we see the line.
//the line can be 1000s of character long so wee need to keep dynmically allocating more memory to store the line.
*/
#include "types.h"
#include "user.h"
char buf[10];
//default number of lines to print
int numl = 10;
int debug = 0;
#define NULL 0
/* Copy data from souce to destination memory */
void memcpy(void *dest, void *src, uint n)
{
// Typecast src and dest addresses to (char *)
char *csource = (char *)src;
char *cdestination = (char *)dest;
// Copy contents of src[] to dest[]
for (int i=0; i<n; i++)
cdestination[i] = csource[i];
}
/* Reallocate the memory */
void *realloc(void *ptr, uint originalLength, uint newLength)
{
if(debug == 1){
printf(1,"original length = %d , new length = %d " , originalLength , newLength);
}
if (newLength == 0)
{
free(ptr);
if(debug == 1){
printf(1,"lenght of new memmory allocation is 0");
}
return NULL;
}
else if (!ptr)
{
if(debug == 1){
printf(1, "original pointer passed was null");
}
return malloc(newLength);
}
else if (newLength <= originalLength)
{
if(debug == 1){
printf(1, "Realloc: New memory cannot be less than original memory");
}
return ptr;
}
else
{
// assert((ptr) && (newLength > originalLength));
void *ptrNew = malloc(newLength);
if (ptrNew)
{
memcpy(ptrNew, ptr, originalLength);
if(debug == 1){
printf(1,"allocated");
}
/* Free old memory */
free(ptr);
}
return ptrNew;
}
}
void tail(int fd)
{
int n,i,l=0;
/* initial length of the memory */
int lenght = 100;
/*index at which to store current line */
int index_to_store = 0;
/* index into the array from where we should start printing */
int start_to_print = 0;
//this is to check if there is any line in the input when we press control + d to quit tail.
int temp_data = 0;
//used to generate pointers to the last numl lines
int pointer_generator_counter = 0;
//array of pointers to the last numl lines
char *pointer_to_last_n_lines[numl];
//length of each line. This will grow as we add more data to the line
int length_each_line[numl];
//tells us till what index have we filled the line
int count_each_line[numl];
char *pointer_to_last_n_lines2[numl];
//generating an array of pointers which will point to the last numl lines.
for(;pointer_generator_counter<numl; pointer_generator_counter++){
if(debug == 1){
printf(1, "%d creating pointers" , pointer_generator_counter);
}
//allocate memory
pointer_to_last_n_lines[pointer_generator_counter] = malloc( sizeof(char) * ( lenght ) );
//just copying the pointer
pointer_to_last_n_lines2[pointer_generator_counter] = pointer_to_last_n_lines[pointer_generator_counter];
//initial length of line
length_each_line[pointer_generator_counter] = 100;
//where to insert data into line
count_each_line[pointer_generator_counter] = 0;
}
//reading from file discriptor
while((n = read(fd, buf, sizeof(buf))) > 0)
{
// printf(1,"%d \n" , fd);
temp_data = 1;
for(i=0;i<n;i++)
{
//check if we are near the end of the memory allocated to the line. If we are we reallocate more memory and
//copy the old memory to new memeory and free old memory
if(count_each_line[index_to_store] == length_each_line[index_to_store] -3){
if(debug == 1){
printf(1," realloc called\n" );
}
//expand the array size by relloc and update the length
//reallocating twice the memory as it was before
char *temp = realloc(pointer_to_last_n_lines2[index_to_store] , length_each_line[index_to_store] , sizeof(char)*( length_each_line[index_to_store]*2));
pointer_to_last_n_lines2[index_to_store] = temp;
//increasing the size of line
length_each_line[index_to_store] *= 2;
if(debug == 1){
printf(1," realloc called 2\n" );
}
pointer_to_last_n_lines2[index_to_store][count_each_line[index_to_store]] = buf[i];
if(debug == 1){
printf(1,"realloc called 3\n" );
}
}else{
//we are not near the end of the allocated memory so we keep on adding characters to the memory
pointer_to_last_n_lines2[index_to_store][count_each_line[index_to_store]] = buf[i];
}
// printf(1,"this works");
count_each_line[index_to_store]++;
if(debug == 1){
printf(1,"this works count is %d %c \n" , count_each_line[index_to_store] , buf[i]);
}
//new line character
if(buf[i] == '\n'){
temp_data = 0;
//put a null at the end of the current line so that we can print it.
pointer_to_last_n_lines2[index_to_store][count_each_line[index_to_store]] = '\0';
//increment the index to where we store the line. Note that this moves in a circular way
//so if we have to print last 10 lines after writing to the 9th array index it will write at the 0th position
index_to_store = (index_to_store + 1)%numl;
//as it is storing in a circular way we need to know from were we should start printing.
//this keeps track of it
start_to_print = (index_to_store)%numl;
count_each_line[index_to_store] = 0;
l++;
}
}
}
// printf(1, "%d" , n);
if(temp_data == 1){
//if there was data in the last line and it didn't end with a new line character we increment the start_to_print
//as you can see from the code above start_to_print only increments when we encounter a new line character
start_to_print = (++index_to_store)%numl;
}
//using this variable to loop over all the lines
pointer_generator_counter = 0;
//printing the last numl lines
for(;pointer_generator_counter<numl; pointer_generator_counter++){
printf(1, "%s", pointer_to_last_n_lines2[(pointer_generator_counter+start_to_print)%numl]);
}
//if we are not able to read anything from the file discrptor
if(n < 0)
{
printf(1, "tail: read error\n");
exit();
}
}
int main(int argc, char *argv[])
{
char abc[10];
int fd, i;
//getting the arguments, argc==1 when we call tail without any parameters.
if(argc>1 && argv[1][0]=='-')
{
for(i=1;i<sizeof(abc);i++)
//reading the number from the argument, one character at a time
abc[i-1]=argv[1][i];
//convert the number to integer
numl=atoi(abc);
}else{
// the first parameter may be a file name. Lets check if the second parameter is a number
if(argc==3 && argv[2][0]=='-')
{
for(i=1;i<sizeof(abc);i++)
abc[i-1]=argv[2][i];
numl=atoi(abc);
if((fd = open(argv[1], 0)) < 0 ){
printf(1, "tail: cannot open %s\n", argv[1]);
//this can be the number of lines to print and input from pipe
tail(0);
exit();
}
tail(fd);
close(fd);
exit();
}
}
//if argc == 1, tail was called without any arguments
if(argc <= 1){
tail(0);
exit();
}
i=2;
if(argc==2)
i=1;
for(; i < argc; i++){
if((fd = open(argv[i], 0)) < 0 ){
printf(1, "tail: cannot open %s, it may input parameter\n", argv[i]);
//this can be the number of lines to print and input from pipe
tail(0);
exit();
}
tail(fd);
close(fd);
}
exit();
}
|
C | /* Binary Search Tree interface for use in CS136 Fall 2015
Author: Gordon V. Cormack
Description:
"struct inttree" is an abstract data type that maintains
a binary search tree with distinct int elements.
*/
struct inttree; // definition is secret
struct inttree * create(); /* return a new, empty BST;
O(1) time */
void insert(struct inttree *t, int e); /* add element e to t;
do nothing if e already in t;
O(height(t)) time */
void delete(struct inttree *t, int e); /* delete e from t;
do nothing if e not in t;
O(height(t)) time */
void destroy(struct inttree *t); /*destroy t; O(n) time */
void print(struct inttree *t); /* print t sideways; O(n) time */
int height(struct inttree *t); /* height of t; O(1) time */
/* The following functions must be implemented for assignment
10.
*/
/* A10p0 -- return the number of elements in t, O(1) time */
int size(struct inttree *t);
|
C | #include <criterion/criterion.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "quests/prereq.h"
#include "quests/samples.h"
/* tests init function for prereq struct */
Test(prereq, init)
{
int hp = 40;
int level = 5;
prereq_t prereq;
int rc = prereq_init(&prereq, hp, level);
cr_assert_eq(rc, SUCCESS, "prereq_init failed!");
cr_assert_eq(prereq.hp, 40, "prereq_init did not set hp");
cr_assert_eq(prereq.level, 5, "prereq_init did not set level");
}
/* Tests new function for prereq struct */
Test(prereq, new)
{
int hp = 20;
int level = 17;
prereq_t *prereq = prereq_new(hp, level);
cr_assert_not_null(prereq, "prereq_new failed to create a prereq");
cr_assert_eq(prereq->hp, 20, "prereq did not set hp");
cr_assert_eq(prereq->level, 17, "prereq did not set level");
}
|
C | #define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
void selfadd(int* pa)
{
(*pa)++;
}
int main()
{
int x = 1;
selfadd(&x);
printf("%d\n", x);
return 0;
}
//int is_leap_year(int y)
//{
// if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
// return 1;
// else
// return 0;
//
//}
//
//
//int main()
//{
// int year = 0;
// for (year = 1000; year <= 2000; year++)
// {
// if (1 == is_leap_year(year))
// {
// printf("%d\n", year);
// }
// }
//
//
// return 0;
//}
|
C | #include <stdio.h>
void bubbleSort(int vetor[], int n);
int main() {
int vetor[] = {5, 2, 3, 1, 4, 7, 6};
bubbleSort(vetor[], 7);
return 0;
}
void bubbleSort(int vetor[], int n) {
int tmp, i, j;
for(i = 0; i < n - 1; i++) {
for(j = 0; j < n - i - 1; j++) {
if(vetor[j] > vetor[j + 1]) {
tmp = vetor[j];
vetor[j] = vetor[j + 1];
vetor[j + 1] = tmp;
}
}
}
} |
C | /* wordwrap.c - given a proportional font and a window of a certain size,
figure out how many words we can fit in a line. with some utilities for justification of text */
#define WORDWRAP_INTERNALS
#include "wordwrap.h"
typedef struct wwdata {
int wid; /* wrap window width */
int wid_sp; /* precalc window width + font spacing for word split
* test */
int ww; /* width of imbedded word */
int endw; /* width to last pixel of word (word on end of line) */
int line_left; /* pixel width to end of window */
int tab_width; /* size of a tab */
char sub_cr; /* what to output carraige returns with in output lines */
char *wstart; /* start of word to parse */
} Wwdata;
enum whywrap {
WW_EOTEXT = 0, /* end of text */
WW_EOWORD = 1, /* end of word */
WW_HARDCR = 2, /* hard return */
WW_EOLINE = 3, /* ran out of line, in white space */
WW_WSTART = 4, /* end of white space */
WW_SPLIT = 5, /* long word is split */
}
static char *wwnext_word( Wwdata *wd,
Vfont *f,
char *outw ) /* output word */
/* Copy 1st word in 's' to outw including leading spaces.
What's a word? It's something separated by a space, new line,
carraige return or tab. If the word won't fit inside of width
w, this routine will only copy the parts that fit into outw. */
{
char *s;
char c;
int ww,cw,ew; /* word width, char width, tab width */
int endsp_wid;
int word_end;
s = wd->wstart; /* get start of word */
c = *s;
ww = 0;
for(;;)
{
switch(c)
{
case 0: /* end of text */
{
ww->why = WW_EOTEXT;
goto check_endw;
}
case '\n':
case '\r':
{
wd->why = WW_HARDCR;
*out++ = wd->sub_cr;
goto check_endw;
}
case ' ':
case '\t':
{
endsp_wid = f->end_space;
word_end = ww;
/* copy leading blanks until end or eol */
for(;;)
{
if(c == ' ')
{
if((ww + endsp_wid) > wd->line_left)
goto end_of_line;
if((ww += fspace_width(f,s)) > wd->line_left)
{
ww -= fspace_width(f,s);
goto end_of_line;
}
}
else if (c == '\t')
{
if ((ww += wd->tab_width) > wd->line_left)
{
ww -= wd->tab_width;
goto end_of_line;
}
}
else
{
wd->why = WW_WSTART;
goto check_endw;
}
*outw++ = c;
c = *(++s);
}
end_of_line:
if(word_end && word_end == ww) /* space after word wrapped */
++s; /* ignore space at end of line after word */
wd->why = WW_EOLINE;
goto check_endw;
}
default:
{
if( (ww += (cw = fchar_spacing(f,s))) > wd->wid_sp)
{
ww -= cw;
if(!(f->flags & VFF_XINTERLEAVE))
{
wd->ww = ww;
ww->why = WW_SPLIT;
goto done;
}
ew = fendchar_width(f,s);
if((ww + ew) > wd->wid)
{
wd->ww = ww;
ww->why = WW_SPLIT;
goto done;
}
ww += cw; /* keep going */
}
*outw++ = c;
}
} /* end of switch */
c = *(++s);
} /* end of loop */
check_endw:
wd->ww = ww;
if(f->flags & VFF_XINTERLEAVE)
ww += vfont_interleave_extra(f,s,s - wstart);
done:
*outw++ = 0;
wd->endw = ww;
return(s);
}
int wwnext_line(Vfont *f,
char **ps, /* input text stream (Modified) */
const int w, /* pixel width to fit into */
char *buf, /* destination one line */
int sub_cr) /* character to substitute for <lf> or <cr> */
/* Copies as many words from s into buf as will fit in width. Terminates
buf with zero. sets stream pointer to next line or NULL if this is the
last line. returns width of line from font */
{
int lw, ed; /* line width, end diff */
char *ns, *s;
Wwdata wd;
s = *ps;
lw = 0;
ed = 0;
/* load structure and pre-calc'd items */
wd.sub_cr = sub_cr;
wd.wid = w;
wd.wid_sp = w + f->spacing;
if(f->flags & VFF_XINTERLEAVE)
wd.wid_sp -= f->widest_end;
wd.tab_width = Min(f->tab_width,w);
wd.line_left = wd.wid;
if(s == NULL)
return(0);
for (;;)
{
/* note that ew will include spacing */
ns = wwnext_word(&wd,f,s,buf);
if((wd.line_left - wd.endw) <= 0) /* outta line */
{
*buf = 0;
goto line_done
}
switch(wd.why)
{
case WW_WSTART: /* end of white space */
wd.line_left -= wd.endw;
case WW_EOTEXT: /* end of text */
s = NULL;
case WW_SPLIT: /* long word is split */
case WW_HARDCR: /* hard return */
case WW_EOLINE: /* ran out of line, in white space */
wd.line_left -= wd.endw;
goto line_done;
}
/* use end width for width test */
if((wd.endw + lw) > wd.wid + f->spacing)
{
buf[0] = 0;
break;
}
if(buf[0] == sub_cr)
{
s++;
break;
}
ed = wd.endw - wd.ww;
lw += wd.ww; /* add mid line width */
buf += ns - s;
s = ns;
}
line_done:
*ps = s;
return(w - line_left);
}
|
C | /*
Copyright (c) Centre National de la Recherche Scientifique (CNRS,
France). 2010.
Copyright (c) Members of the EGEE Collaboration. 2008-2010. See
http://www.eu-egee.org/partners/ for details on the copyright
holders.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
---------------------------------------------------------------------
Developed by Etienne DUBLE - CNRS LIG (http://www.liglab.fr)
etienne __dot__ duble __at__ imag __dot__ fr
---------------------------------------------------------------------
*/
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>
#include <time.h>
#include <libgen.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <sys/syscall.h>
extern int errno;
#include "append_to_string.h"
#include "common_fd_tools.h"
#include "common_other_tools.h"
#include "common_colors.h"
#include "log.h"
#include "system_commands.h"
#define __BASE_DIAGNOSIS_DIRECTORY "/tmp/ipv6_diagnosis"
#define __FULL_COMMAND_LINE_FILE "full_command_line"
#define __MKDIR_PERMISSIONS (S_IRWXU | S_IRWXG | S_IRWXO)
#define __FOPEN_PERMISSIONS "w"
extern char *program_basename;
extern char *program_command_line;
int mkdir_777(char *dir)
{
mode_t old_umask;
int result;
old_umask = umask(0);
result = mkdir(dir, __MKDIR_PERMISSIONS);
umask(old_umask);
return result;
}
FILE *fopen_666(char *file)
{
mode_t old_umask;
FILE *result;
old_umask = umask(0);
result = fopen(file, __FOPEN_PERMISSIONS);
umask(old_umask);
return result;
}
// This function creates a directory path
int recursive_mkdir(char *dir)
{
int result = -1;
char *basedir_alloc, *basedir;
basedir_alloc = (char*) malloc((strlen(dir) + 1)*sizeof(char));
// if recursion arrived at "/" it is time to stop!
if (strcmp(dir, "/") != 0)
{
// first try
result = mkdir_777(dir);
// if dir already exist we do not consider it is an error
if ((result != 0)&&(errno == EEXIST))
{
result = 0;
}
if ((result != 0)&&(errno != ENOENT))
{
colored_print_if_tty(RED, "** IPv6 CARE failed to create %s (%s).", dir, strerror(errno));
PRINTF("\n");
fflush(tty_fd);
}
// if first try failed with error "no such file or directory"
if ((result != 0)&&(errno == ENOENT))
{
// we calculate the base dir
// (we first make a copy because dirname modifies the string)
strcpy(basedir_alloc, dir);
basedir = dirname((char *)basedir_alloc);
// and call the function on this base dir
result = recursive_mkdir(basedir);
if (result == 0)
{ // if result was ok on the base dir,
// we should now be able to create the initial directory
result = mkdir_777(dir);
}
}
}
free(basedir_alloc);
return result;
}
// This function creates the directory path related to the running program
// and returns a string representing this path.
char *get_or_create_the_directory_related_to_the_program()
{
static int directory_created = 0;
static char *directory_path_alloc = NULL;
char *symlink_dir_path_alloc, *symlink_path_alloc,
*full_command_line_path_alloc;
time_t now;
struct tm time_details;
static char* month_name[12] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
FILE *file;
if (directory_created == 0)
{
// build the path of the directory
asprintf(&directory_path_alloc, "%s/%s/by_pid/pid_%d", __BASE_DIAGNOSIS_DIRECTORY,
program_basename, getpid());
// create the directory if the directory do not already exists
if (recursive_mkdir(directory_path_alloc) != 0)
{ // error already reported in recursive_mkdir()
free(directory_path_alloc);
return NULL;
}
else
{
// we create a symbolic link with the date in order to find easily
// which pid is the one we want to look at
time(&now);
localtime_r(&now, &time_details);
asprintf(&symlink_dir_path_alloc, "%s/%s/by_time/%s_%d_%d_%02dh%02d",
__BASE_DIAGNOSIS_DIRECTORY, program_basename,
month_name[time_details.tm_mon], time_details.tm_mday,
1900 + time_details.tm_year, time_details.tm_hour,
time_details.tm_min);
// create the directory
recursive_mkdir(symlink_dir_path_alloc);
asprintf(&symlink_path_alloc, "%s/pid_%d",
symlink_dir_path_alloc, getpid());
symlink(directory_path_alloc, symlink_path_alloc);
free(symlink_path_alloc);
free(symlink_dir_path_alloc);
// we also create the full_command_line file
asprintf(&full_command_line_path_alloc, "%s/%s",
directory_path_alloc, __FULL_COMMAND_LINE_FILE);
file = fopen(full_command_line_path_alloc, "w");
fprintf(file, "%s\n", program_command_line);
fclose(file);
free(full_command_line_path_alloc);
directory_created = 1;
}
}
return directory_path_alloc;
}
// This function creates the directory path related to the running thread
// and returns a string representing this path.
char *get_or_create_the_directory_related_to_the_thread()
{
static __thread int directory_created = 0;
static __thread char *directory_path_alloc_thread = NULL;
char *directory_path;
int thread_id;
if (directory_created == 0)
{
directory_path = get_or_create_the_directory_related_to_the_program();
if (directory_path != NULL)
{
thread_id = get_thread_id();
// if this is the main thread started at execution of the program, put diagnosis in the main directory
if (thread_id == 0)
{
//directory_path_alloc_thread = directory_path;
asprintf(&directory_path_alloc_thread, "%s", directory_path);
}
else
{ // this thread was created later on, put diagnosis in a dedicate directory
asprintf(&directory_path_alloc_thread, "%s/thread_%d", directory_path, thread_id);
recursive_mkdir(directory_path_alloc_thread);
}
directory_created = 1;
}
}
return directory_path_alloc_thread;
}
// this function opens the log file and returns its file descriptor
FILE *open_log_file()
{
FILE *file = NULL;
char *full_filename_alloc;
char *directory_path;
directory_path = get_or_create_the_directory_related_to_the_thread();
if (directory_path != NULL)
{
asprintf(&full_filename_alloc, "%s/log", directory_path);
// open the file
file = fopen_666(full_filename_alloc);
free(full_filename_alloc);
if (file == NULL)
{
colored_print_if_tty(RED, "** IPv6 CARE failed to create or open %s (%s).", full_filename_alloc, strerror(errno));
PRINTF("\n");
fflush(tty_fd);
}
}
return file;
}
|
C | /*
** EPITECH PROJECT, 2019
** libmy
** File description:
** returns the factorial of a number
*/
int factorial(int nb)
{
int nbcpy = nb;
if (nb == 0) {
return (1);
} else if (nb < 0) {
return (0);
}
for (int i = 1; i < nbcpy; i++) {
nb *= i;
}
return (nb);
}
|
C | #include "main.h"
// Démarrer le mode graphique de Ncurses
void initialiser_ncurses(void) {
initscr(); // Initialisation de l'écran standard de Ncurses (stdscr)
noecho(); // Ne pas écrire ce que l'utilisateur tape dans la saisie
curs_set(false); // Cacher le curseur
// Si le terminal ne supporte pâs les couleurs, on termine l'initialisation
if (!has_colors()) {
return;
} else { // Sinon, on déclare les couleurs du mode graphique
// Activation du mode couleur de ncurses
start_color();
// Déclaration des palettes de couleur
initialiser_couleur(COLOR_RED); // Création de la couleur "rouge"
initialiser_couleur(COLOR_GREEN); // Création de la couleur "vert"
initialiser_couleur(COLOR_YELLOW); // Création de la couleur "jaune"
initialiser_couleur(COLOR_BLUE); // Création de la couleur "bleu"
initialiser_couleur(COLOR_MAGENTA); // Création de la couleur "magenta"
initialiser_couleur(COLOR_CYAN); // Création de la couleur "cyan"
initialiser_couleur(COLOR_WHITE); // Création de la couleur "blanc"
}
}
// Désinitialisation de Ncurses
void fermer_ncurses(void) {
endwin(); // Fermer toutes les fenêtres de ncurses actuellement ouvertes et quitter le mode "graphique"
}
// Initialisations des couleurs (pour Ncurses)
void initialiser_couleur(int couleur) {
// La librairie ncurses gère les couleurs d'une façon particulière:
// On doit déclarer une paire de couleurs de fond de texte avec un numéro de paire qui constituent une "palette"
// Exemple: paire 1 = rouge en fond et blanc en couleur de texte.
// Ici, on utilise un petit raccourci: Vu que les valeurs des couleurs de base du terminal vont de 0 à 7, on peut initialiser une paire avec ce même numéro
// Exemple:
// Paire #1:
// Couleur de texte: 1 (ROUGE)
// Couleur de fond: Noir
init_pair(couleur, couleur, COLOR_BLACK);
}
// Calcule le centre d'une zone rectangulaire
// Cette zone rectangulaire est définie comme suit :
/*
gauche (axe X)
v
haut > +-----------------+ ^
(axe Y) | | |
| | |
| X | | hauteur (axe Y)
| x;y (centre) | |
| | |
+-----------------+ V
<---------------->
largeur (axe X)
Les pointeurs x et y sont les valeurs de "retour" de la fonction
*/
void calculer_centre(int hauteur, int largeur, int haut, int gauche, int* y, int* x) {
*y = haut + (hauteur / 2); // Attribution de la hauteur dans y
*x = gauche + (largeur / 2); // Attribution de la largeur dans x
}
// Centre une fenêtre dans une zone rectangulaire définie par les valeurs haut, gauche, hauteur et largeur
// La fenêtre aura la taille spécifiée par hauteur_cible et largeur_cible
// (voir explications de calculer_centre pour plus d'informations)
void centrer_fenetre(WINDOW* fenetre, int hauteur_cible, int largeur_cible, int hauteur, int largeur, int haut, int gauche) {
//Initialisation des variabes "coordonnées"
int y, x;
calculer_centre(hauteur, largeur, haut, gauche, &y, &x); // calcule le centre de la fenêtre
wresize(fenetre, hauteur_cible, largeur_cible); //Change la taille de la fenêtre
mvwin(fenetre, y - (hauteur_cible / 2), x - (largeur_cible / 2)); //Change la position de la fenêtre
}
// Créer une nouvelle fenêtre de taille 0
WINDOW* nouvelle_fenetre(void) {
WINDOW* fenetre = newwin(0, 0, 0, 0); // Nouvelle fenêtre de taille et position 0
keypad(fenetre, true); // Ne pas attendre l'appui sur entrer pour recevoir la saisie
return fenetre; //renvoi fenetre
}
// Efface l'écran et l'actualise
void effacer_ecran(void) {
erase(); //Efface l'écran
refresh(); //Actualise l'écran
} |
C | /*
* Copyright (c) 1993 Colin Plumb. All rights reserved.
* For licensing and other legal details, see the file legal.c.
*
* MS-DOS non-echoing keyboard routines.
*/
#include <conio.h> /* For getch() and kbhit() */
#include <signal.h> /* For raise() */
#ifdef _MSC_VER
#include <time.h> /* For clock() */
#else
#include <dos.h> /* For sleep() */
#endif
#include "kb.h"
#include "random.h" /* For randEvent() */
/* These are pretty boring */
void kbCbreak(void) { }
void kbNorm(void) { }
int kbGet(void)
{
int c;
c = getch();
if (c == 0)
c = 0x100 + getch();
/*
* Borland C's getch() uses int 0x21 function 0x7,
* which does not detect break. So we do it explicitly.
*/
if (c == 3)
raise(SIGINT);
randEvent(c);
return c;
}
#ifdef _MSC_VER
/*
* Microsoft Visual C 1.5 (at least) does not have sleep() in the
* library. So we use this crude approximation. ("crude" because,
* assuming CLOCKS_PER_SEC is 18.2, it rounds to 18 to avoid floating
* point math.)
*/
#ifndef CLOCKS_PER_SEC
#define CLOCKS_PER_SEC CLK_TCK
#endif
static unsigned
sleep(unsigned t)
{
clock_t target;
target = clock() + t * (unsigned)CLOCKS_PER_SEC;
while (clock() < target)
;
return 0;
}
#endif
void kbFlush(int thorough)
{
do {
while(kbhit())
(void)getch();
if (!thorough)
break;
/* Extra thorough: wait for one second of quiet */
sleep(1);
} while (kbhit());
}
|
C | #ifndef CORTHREAD_LOCK_INCLUDE_H
#define CORTHREAD_LOCK_INCLUDE_H
#include "corthread_define.h"
#ifdef __cplusplus
extern "C" {
#endif
/* corthread locking */
/**
* corthread mutex, thread unsafety, one corthread mutex can only be used in the
* same thread, otherwise the result is unpredictable
*/
typedef struct CT_CORTHREAD_MUTEX CT_CORTHREAD_MUTEX;
/**
* corthread read/write mutex, thread unsafety, can only be used in the sampe thread
*/
typedef struct CT_CORTHREAD_RWLOCK CT_CORTHREAD_RWLOCK;
/**
* create one corthread mutex, can only be used in the same thread
* @return {CT_CORTHREAD_MUTEX*} corthread mutex returned
*/
CORTHREAD_API CT_CORTHREAD_MUTEX* ct_corthread_mutex_create(void);
/**
* free corthread mutex created by ct_corthread_mutex_create
* @param l {CT_CORTHREAD_MUTEX*} created by ct_corthread_mutex_create
*/
CORTHREAD_API void ct_corthread_mutex_free(CT_CORTHREAD_MUTEX* l);
/**
* lock the specified corthread mutex, return immediately when locked, or will
* wait until the mutex can be used
* @param l {CT_CORTHREAD_MUTEX*} created by ct_corthread_mutex_create
*/
CORTHREAD_API void ct_corthread_mutex_lock(CT_CORTHREAD_MUTEX* l);
/**
* try lock the specified corthread mutex, return immediately no matter the mutex
* can be locked.
* @param l {CT_CORTHREAD_MUTEX*} created by ct_corthread_mutex_create
* @return {int} 0 returned when locking successfully, -1 when locking failed
*/
CORTHREAD_API int ct_corthread_mutex_trylock(CT_CORTHREAD_MUTEX* l);
/**
* the corthread mutex be unlock by its owner corthread, fatal will happen when others
* release the corthread mutex
* @param l {CT_CORTHREAD_MUTEX*} created by ct_corthread_mutex_create
*/
CORTHREAD_API void ct_corthread_mutex_unlock(CT_CORTHREAD_MUTEX* l);
/****************************************************************************/
/**
* create one corthread rwlock, can only be operated in the sampe thread
* @return {CT_CORTHREAD_RWLOCK*}
*/
CORTHREAD_API CT_CORTHREAD_RWLOCK* ct_corthread_rwlock_create(void);
/**
* free rw mutex created by ct_corthread_rwlock_create
* @param l {CT_CORTHREAD_RWLOCK*} created by ct_corthread_rwlock_create
*/
CORTHREAD_API void ct_corthread_rwlock_free(CT_CORTHREAD_RWLOCK* l);
/**
* lock the rwlock, if there is no any write locking on it, the
* function will return immediately; otherwise, the caller will wait for all
* write locking be released. Read lock on it will successful when returning
* @param l {CT_CORTHREAD_RWLOCK*} created by ct_corthread_rwlock_create
*/
CORTHREAD_API void ct_corthread_rwlock_rlock(CT_CORTHREAD_RWLOCK* l);
/**
* try to locking the Readonly lock, return immediately no matter locking
* is successful.
* @param l {CT_CORTHREAD_RWLOCK*} crated by ct_corthread_rwlock_create
* @retur {int} 1 returned when successfully locked, or 0 returned if locking
* operation is failed.
*/
CORTHREAD_API int ct_corthread_rwlock_tryrlock(CT_CORTHREAD_RWLOCK* l);
/**
* lock the rwlock in Write Lock mode, return until no any one locking it
* @param l {CT_CORTHREAD_RWLOCK*} created by ct_corthread_rwlock_create
*/
CORTHREAD_API void ct_corthread_rwlock_wlock(CT_CORTHREAD_RWLOCK* l);
/**
* try to lock the rwlock in Write Lock mode. return immediately no matter
* locking is successful.
* @param l {CT_CORTHREAD_RWLOCK*} created by ct_corthread_rwlock_create
* @return {int} 1 returned when locking successfully, or 0 returned when
* locking failed
*/
CORTHREAD_API int ct_corthread_rwlock_trywlock(CT_CORTHREAD_RWLOCK* l);
/**
* the rwlock's Read-Lock owner unlock the rwlock
* @param l {CT_CORTHREAD_RWLOCK*} crated by ct_corthread_rwlock_create
*/
CORTHREAD_API void ct_corthread_rwlock_runlock(CT_CORTHREAD_RWLOCK* l);
/**
* the rwlock's Write-Lock owner unlock the rwlock
* @param l {CT_CORTHREAD_RWLOCK*} created by ct_corthread_rwlock_create
*/
CORTHREAD_API void ct_corthread_rwlock_wunlock(CT_CORTHREAD_RWLOCK* l);
#ifdef __cplusplus
}
#endif
#endif |
C | /*
* Copyright (c) 2009 The Trustees of Indiana University and Indiana
* University Research and Technology
* Corporation. All rights reserved.
*
* Author(s): Torsten Hoefler <[email protected]>
*
*/
#include <inttypes.h>
#include <stdio.h>
#include "calibrate.h"
#define UINT32_T uint32_t
#define UINT64_T uint64_t
#define HRT_INIT(print, freq) do {\
if(print) printf("# initializing x86-64 timer (takes some seconds)\n"); \
HRT_CALIBRATE(freq); \
} while(0)
typedef struct {
UINT32_T l;
UINT32_T h;
} x86_64_timeval_t;
#define HRT_TIMESTAMP_T x86_64_timeval_t
/* TODO: Do we need a while loop here? aka Is rdtsc atomic? - check in the documentation */
#define HRT_GET_TIMESTAMP(t1) \
__asm__ __volatile__ ( \
"xorl %%eax, %%eax \n\t" \
"cpuid \n\t" \
"rdtsc \n\t" \
: "=a" (t1.l), "=d" (t1.h) \
: \
: "%ebx", "%ecx" \
);
#define HRT_GET_ELAPSED_TICKS(t1, t2, numptr) \
*numptr = (((( UINT64_T ) t2.h) << 32) | t2.l) - (((( UINT64_T ) t1.h) << 32) | t1.l);
#define HRT_GET_TIME(t1, time) time = (((( UINT64_T ) t1.h) << 32) | t1.l)
/* Timing API: */
static const char* CPU_FREQ_FILENAME = ".cpu_freq";
static unsigned long long g_timerfreq;
/*
static double HRT_GET_USEC(unsigned long long ticks) {
return 1e6*(double)ticks/(double)g_timerfreq;
}
*/
static double HRT_GET_MSEC(unsigned long long ticks) {
return 1e3*(double)ticks/(double)g_timerfreq;
}
/* Must be called before get_clock_time */
static void init_clock_time () {
char buff[128];
FILE* cpufreq_file = fopen (CPU_FREQ_FILENAME, "r");
if (cpufreq_file) {
if (fgets (buff, 128, cpufreq_file)) {
g_timerfreq = (uint64_t)strtod (buff, NULL);
}
else {
exit (-1);
}
fclose (cpufreq_file);
}
else {
HRT_INIT(0, g_timerfreq);
FILE* cpufreq_file = fopen (CPU_FREQ_FILENAME, "w");
fprintf(cpufreq_file, "%llu\n", g_timerfreq);
fclose( cpufreq_file );
}
/*printf ("cycles per sec = %llu\n", g_timerfreq);*/
}
/* Returns accurate time in ms */
double get_clock_time () {
HRT_TIMESTAMP_T t;
uint64_t ticks;
HRT_GET_TIMESTAMP(t);
HRT_GET_TIME(t, ticks);
return HRT_GET_MSEC(ticks);
}
|
C | #define PY_SSIZE_T_CLEAN
#include <Python.h>
/* Prototype for main function */
static PyObject* checksum(PyObject*, PyObject*);
/* List methods and module definition */
static PyMethodDef MyMethods[] = {
{"checksum", checksum, METH_VARARGS, "Compute an IPv4 checksum of arbitrary data."},
{NULL, NULL, 0, NULL} /* Sentinel */
};
static struct PyModuleDef mymodule = {
.m_base = PyModuleDef_HEAD_INIT,
.m_name = "ipv4checksum",
.m_doc = NULL,
.m_size = -1,
.m_methods = MyMethods,
.m_slots = NULL
};
PyMODINIT_FUNC PyInit_ipv4checksum() {
return PyModule_Create(&mymodule);
}
/* Compute an IPv4 checksum */
static uint16_t _checksum(const void* data, int len) {
uint32_t checksum = 0;
unsigned int left = len;
const uint16_t* ptr_16 = data;
while (left > 1) {
checksum += *ptr_16++;
left -= 2;
}
if (left) {
checksum += *(uint8_t*) ptr_16;
}
/* Fold result into 16 bits */
while (checksum > 0xffff) {
checksum = (checksum >> 16) + (checksum & 0xFFFF);
}
return (uint16_t) ~checksum;
}
/* Main function that wraps over `_checksum` */
static PyObject* checksum(PyObject* self, PyObject* arg) {
const unsigned char* data;
Py_ssize_t count;
uint32_t result;
(void)self;
if (PyArg_ParseTuple(arg, "s#", &data, &count) == 0) {
return NULL;
}
result = _checksum(data, count);
return PyLong_FromLong((long) result);
} |
C | /* copycat_cli.c
* Caleb Zulawski
*
* Handles command line argument parsing, logging,
* and displaying errors.
*/
#include "copycat.h"
/* Library functions */
#include <stdio.h> // sscanf, printf
#include <getopt.h> // getopt
#include <stdlib.h> // exit
#include <string.h> // strerror
/* Parses command line arguments and stores them in a struct */
cc_error_t cc_parse_args(int argc, char* argv[], Options* options) {
options->buffersize = DEFAULT_BUFFER_SIZE;
options->outfile_index = -1;
options->argc = argc;
options->argv = argv;
options->mode = DEFAULT_FILE_PERM;
int c;
while ((c = getopt(argc, argv, "+b:m:o:vh")) != -1) {
switch (c) {
case 'b':
if ( !sscanf(optarg, "%u", &options->buffersize) )
cc_error(CC_USAGE);
break;
case 'm':
if ( !sscanf(optarg, "%o", &options->mode) )
cc_error(CC_USAGE);
break;
case 'o':
options->outfile_index = optind-1;
break;
case 'v':
options->verbose = 1;
break;
case 'h':
cc_error(CC_USAGE);
break;
case '?':
cc_error(CC_USAGE);
break;
}
}
options->infiles_index = optind;
return CC_NONE;
}
/* Logs some information if the -v verbose flag is set */
void cc_log(Options* options) {
if (options->verbose) {
// OUTPUT FILE
if (options->outfile_index != -1)
printf("Output file:\t%s\n", options->argv[options->outfile_index]);
else
printf("Printing to standard output stream\n");
// INPUT FILES
for (int i = options->infiles_index; i < options->argc; i++) {
printf("Input file:\t%s\n", options->argv[i]);
}
if (options->infiles_index == options->argc)
printf("Reading from standard input stream\n");
// BUFFER SIZE
printf("Buffer size:\t%u\n", options->buffersize);
// OUTPUT FILE PERMISSIONS
printf("Output mode:\t%o\n", options->mode);
}
}
/* Handles errors other than read/write associated */
void cc_error(cc_error_t e) {
switch (e) {
case CC_NONE:
return;
case CC_USAGE:
printf("Usage: copycat [OPTION]... [FILE]...\n");
printf("Concatenate FILE(s), or standard input, to standard output.\n");
printf("Similar to GNU cat.\n\n");
printf(" -v print diagnostic messages to standard error\n");
printf(" -b SIZE size of internal copy buffer, in bytes\n");
printf(" -m MODE file mode, in octal\n");
printf(" -o FILE output to FILE instead of standard output\n");
printf(" -h display this help and exit\n");
exit(-1);
case CC_MALLOC_FAIL:
printf("Could not allocate buffer!\n");
exit(-1);
}
}
/* Handles read/write errors */
void cc_error_f(cc_file_error_t e, int err, char filename[]) {
switch (e) {
case CC_F_NONE:
return;
case CC_F_OPEN_RD:
case CC_F_OPEN_WR:
fprintf(stderr, "Error opening file %s: %s\n", filename, strerror(err));
exit(-1);
case CC_F_READ:
fprintf(stderr, "Error reading from file %s: %s\n", filename, strerror(err));
exit(-1);
case CC_F_WRITE:
fprintf(stderr, "Error writing to file %s: %s\n", filename, strerror(err));
}
} |
C | #include<stdio.h>
void disp(int *, int );
int main()
{
int a[5]={1,2,3,4,5};
disp(&a[0],5);
}
void disp(int *a, int n)
{
int i;
for(i=0;i<n;i++)
++*a;
printf("The values of the array..\n");
for(i=0;i<n;i++)
printf(" %d",a[i]);
printf("\n");
}
|
C | /* tst-strptime2 - Test strptime %z timezone offset specifier. */
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <time.h>
#include <libc-diag.h>
/* Dummy string is used to match strptime's %s specifier. */
static const char dummy_string[] = "1113472456";
/* buffer_size contains the maximum test string length, including
trailing NUL. */
enum
{
buffer_size = 20,
};
/* Verbose execution, set with --verbose command line option. */
static bool verbose;
/* mkbuf - Write a test string for strptime with the specified time
value and number of digits into the supplied buffer, and return
the expected strptime test result.
The test string, buf, is written with the following content:
a dummy string matching strptime "%s" format specifier,
whitespace matching strptime " " format specifier, and
timezone string matching strptime "%z" format specifier.
Note that a valid timezone string is either "Z" or contains the
following fields:
Sign field consisting of a '+' or '-' sign,
Hours field in two decimal digits, and
optional Minutes field in two decimal digits. Optionally,
a ':' is used to seperate hours and minutes.
This function may write test strings with minutes values outside
the valid range 00-59. These are invalid strings and useful for
testing strptime's rejection of invalid strings.
The ndigits parameter is used to limit the number of timezone
string digits to be written and may range from 0 to 4. Note that
only 2 and 4 digit strings are valid input to strptime; strings
with 0, 1 or 3 digits are invalid and useful for testing strptime's
rejection of invalid strings.
This function returns the behavior expected of strptime resulting
from parsing the the test string. For valid strings, the function
returns the expected tm_gmtoff value. For invalid strings,
LONG_MAX is returned. LONG_MAX indicates the expectation that
strptime will return NULL; for example, if the number of digits
are not correct, or minutes part of the time is outside the valid
range of 00 to 59. */
static long int
mkbuf (char *buf, bool neg, bool colon, unsigned int hhmm, size_t ndigits)
{
const int mm_max = 59;
char sign = neg ? '-' : '+';
int i;
unsigned int hh = hhmm / 100;
unsigned int mm = hhmm % 100;
long int expect = LONG_MAX;
i = sprintf (buf, "%s %c", dummy_string, sign);
#if __GNUC_PREREQ (7, 0)
/* GCC issues a warning when it thinks the snprintf buffer may be too short.
This test is explicitly using short buffers to force snprintf to truncate
the output so we ignore the warnings. */
DIAG_PUSH_NEEDS_COMMENT;
DIAG_IGNORE_NEEDS_COMMENT (7.0, "-Wformat-truncation");
#endif
if (colon)
snprintf (buf + i, ndigits + 2, "%02u:%02u", hh, mm);
else
snprintf (buf + i, ndigits + 1, "%04u", hhmm);
#if __GNUC_PREREQ (7, 0)
DIAG_POP_NEEDS_COMMENT;
#endif
if (mm <= mm_max && (ndigits == 2 || ndigits == 4))
{
long int tm_gmtoff = hh * 3600 + mm * 60;
expect = neg ? -tm_gmtoff : tm_gmtoff;
}
return expect;
}
/* Write a description of expected or actual test result to stdout. */
static void
describe (bool string_valid, long int tm_gmtoff)
{
if (string_valid)
printf ("valid, tm.tm_gmtoff %ld", tm_gmtoff);
else
printf ("invalid, return value NULL");
}
/* Using buffer buf, run strptime. Compare results against expect,
the expected result. Report failures and verbose results to stdout.
Update the result counts. Return 1 if test failed, 0 if passed. */
static int
compare (const char *buf, long int expect, unsigned int *nresult)
{
struct tm tm;
char *p;
bool test_string_valid;
long int test_result;
bool fail;
int result;
p = strptime (buf, "%s %z", &tm);
test_string_valid = p != NULL;
test_result = test_string_valid ? tm.tm_gmtoff : LONG_MAX;
fail = test_result != expect;
if (fail || verbose)
{
bool expect_string_valid = expect != LONG_MAX;
printf ("%s: input \"%s\", expected: ", fail ? "FAIL" : "PASS", buf);
describe (expect_string_valid, expect);
if (fail)
{
printf (", got: ");
describe (test_string_valid, test_result);
}
printf ("\n");
}
result = fail ? 1 : 0;
nresult[result]++;
return result;
}
static int
do_test (void)
{
char buf[buffer_size];
long int expect;
int result = 0;
/* Number of tests run with passing (index==0) and failing (index==1)
results. */
unsigned int nresult[2];
unsigned int ndigits;
unsigned int step;
unsigned int hhmm;
nresult[0] = 0;
nresult[1] = 0;
/* Create and test input string with no sign and four digits input
(invalid format). */
sprintf (buf, "%s 1030", dummy_string);
expect = LONG_MAX;
result |= compare (buf, expect, nresult);
/* Create and test input string with "Z" input (valid format).
Expect tm_gmtoff of 0. */
sprintf (buf, "%s Z", dummy_string);
expect = 0;
result |= compare (buf, expect, nresult);
/* Create and test input strings with sign and digits:
0 digits (invalid format),
1 digit (invalid format),
2 digits (valid format),
3 digits (invalid format),
4 digits (valid format if and only if minutes is in range 00-59,
otherwise invalid).
If format is valid, the returned tm_gmtoff is checked. */
for (ndigits = 0, step = 10000; ndigits <= 4; ndigits++, step /= 10)
for (hhmm = 0; hhmm <= 9999; hhmm += step)
{
/* Test both positive and negative signs. */
expect = mkbuf (buf, false, false, hhmm, ndigits);
result |= compare (buf, expect, nresult);
expect = mkbuf (buf, true, false, hhmm, ndigits);
result |= compare (buf, expect, nresult);
/* Test with colon as well. */
if (ndigits >= 3)
{
expect = mkbuf (buf, false, true, hhmm, ndigits);
result |= compare (buf, expect, nresult);
expect = mkbuf (buf, true, true, hhmm, ndigits);
result |= compare (buf, expect, nresult);
}
}
if (result > 0 || verbose)
printf ("%s: %u input strings: %u fail, %u pass\n",
result > 0 ? "FAIL" : "PASS",
nresult[1] + nresult[0], nresult[1], nresult[0]);
return result;
}
/* Add a "--verbose" command line option to test-skeleton.c. */
#define OPT_VERBOSE 10000
#define CMDLINE_OPTIONS \
{ "verbose", no_argument, NULL, OPT_VERBOSE, },
#define CMDLINE_PROCESS \
case OPT_VERBOSE: \
verbose = true; \
break;
#define TEST_FUNCTION do_test ()
#include "../test-skeleton.c"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.