language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include "hardening.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int error_occured = 0;
static int current_iteration = -1;
inline int hardened_compare_and_return_int(int var_a, int var_b, char* file, long line, char* var_name)
{
int result;
int a = var_a;
int b = var_b;
result = int_xor(a, b);
if(result != 0)
{
dump_error_info(&a, &b, sizeof(int), file, line, var_name);
}
return a;
}
inline long hardened_compare_and_return_long(long var_a, long var_b, char* file, long line, char* var_name)
{
long result;
long a = var_a;
long b = var_b;
result = long_xor(a, b);
if(result != 0)
{
dump_error_info(&a, &b, sizeof(long), file, line, var_name);
}
return a;
}
inline float hardened_compare_and_return_float(float var_a, float var_b, char* file, long line, char* var_name)
{
int result;
float a = var_a;
float b = var_b;
result = float_xor(a, b);
if(result != 0)
{
dump_error_info(&a, &b, sizeof(float), file, line, var_name);
}
return a;
}
inline double hardened_compare_and_return_double(double var_a, double var_b, char* file, long line, char* var_name)
{
long result;
double a = var_a;
double b = var_b;
result = double_xor(a, b);
if(result != 0)
{
dump_error_info(&a, &b, sizeof(double), file, line, var_name);
}
return a;
}
inline void* hardened_compare_and_return_ptr(void* var_a, void* var_b, char* file, long line, char* var_name)
{
void* result;
void* a = var_a;
void* b = var_b;
result = ptr_xor(a, b);
if(result != 0)
{
dump_error_info(&a, &b, sizeof(void*), file, line, var_name);
}
return a;
}
/*
inline void* hardened_compare_and_return_double_array(void* var_a, void* var_b, int size, char* file, long line, char* var_name)
{
long result;
double* a = (double*)var_a;
double* b = (double*)var_b;
int num_elem = size / sizeof(double);
int i;
for(i = 0; i < num_elem; i++)
{
result = double_xor(a[i], b[i]);
if(result != 0)
{
dump_error_info(&a[i], &b[i], sizeof(double), file, line, var_name);
}
}
return var_a;
}
void* hardened_compare_and_return_double_struct(void* var_a, void* var_b, int size, char* file, long line, char* var_name)
{
long result;
double* a = (double*)var_a;
double* b = (double*)var_b;
int num_elem = size / sizeof(double);
int i;
for(i = 0; i < num_elem; i++)
{
result = double_xor(a[i], b[i]);
if(result != 0)
{
dump_error_info(&a[i], &b[i], sizeof(double), file, line, var_name);
}
}
return var_a;
}
*/
void dump_error_info(void* var_a, void* var_b, long long size, char* file, long line, char* var_name)
{
//#pragma omp critical(c1)
{
if(current_iteration != get_iteration_number())
{
current_iteration = get_iteration_number();
error_occured = 0;
}
if(error_occured == 0)
{
error_occured = 1;
printf("\nHardening error:\n");
printf("\tfile: \"%s\"\n", file);
printf("\tvariable: \"%s\"\n", var_name);
printf("\tline %d\n", line);
printf("\tsize %d bytes\n", size);
char var_1_bits[1024];
char var_2_bits[1024];
get_bits_str(var_1_bits, var_a, size);
get_bits_str(var_2_bits, var_b, size);
printf("\tvar_1 bits: %s\n", var_1_bits);
printf("\tvar_2 bits: %s\n", var_2_bits);
#ifdef LOGS
//end_iteration();
char error_details[500];
sprintf(error_details, " file: [%s], var_name: [%s], line: [%d], size_bytes: [%d], var_1_bits: [%s], var_2_bits: [%s]", file, var_name, line, size, var_1_bits, var_2_bits);
log_error_detail(error_details);
//log_error_count(1);
//end_log_file();
#endif
//exit(1);
}
}
}
/*
inline void* hardened_compare_and_return(void* var_a, void* var_b, long long size, char* file, long line, char* var_name)
{
if(memcmp(var_a, var_b, size) != 0)
{
#pragma omp critical(c1)
{
if(current_iteration != get_iteration_number())
{
current_iteration = get_iteration_number();
error_occured = 0;
}
if(error_occured == 0)
{
error_occured = 1;
printf("\nHardening error:\n");
printf("\tfile: \"%s\"\n", file);
printf("\tvariable: \"%s\"\n", var_name);
printf("\tline %d\n", line);
printf("\tsize %d bytes\n", size);
char var_1_bits[1024];
char var_2_bits[1024];
get_bits_str(var_1_bits, var_a, size);
get_bits_str(var_2_bits, var_b, size);
printf("\tvar_1 bits: %s\n", var_1_bits);
printf("\tvar_2 bits: %s\n", var_2_bits);
printf("\tvar_1 address: %p\n", var_a);
printf("\tvar_2 address: %p\n", var_b);
#ifdef LOGS
//end_iteration();
char error_details[500];
sprintf(error_details, " file: [%s], var_name: [%s], line: [%d], size_bytes: [%d], var_1_bits: [%s], var_2_bits: [%s], var_1_addr: [%p], var_2_addr: [%p]", file, var_name, line, size, var_1_bits, var_2_bits, var_a, var_b);
log_error_detail(error_details);
//log_error_count(1);
//end_log_file();
#endif
//exit(1);
}
}
}
return var_a;
}
inline void* hardened_compare_and_return_array(void* array_ptr_a, void* array_ptr_b, long long size)
{
char* bytes_array_a = (char*)((char**)array_ptr_a);
char* bytes_array_b = (char*)((char**)array_ptr_b);
#ifdef HARDENING_DEBUG
printf("hardening_array: array_ptr_1 = %p, array_ptr_2 = %p, array_size = %d\n", bytes_array_a, bytes_array_b, size);
#endif
if(memcmp(bytes_array_a, bytes_array_b, size) != 0)
{
printf("\nHardening error: at file \"%s\"\n\n", __FILE__);
exit(1);
}
return array_ptr_a;
}
*/
void get_bits_str(char* dest_buffer, void* value, long long size)
{
char* char_array = (char*)value;
int temp_buffer[1024];
int i, j;
for(i = 0; i < size; i++)
{
int power = 1;
for(j = 0; j < 8; j++)
{
temp_buffer[(size*8 - 1) - (i*8 + j)] = ((int)char_array[i] & power) >> j;
power *= 2;
}
}
for(i = 0; i < size * 8; i++)
{
sprintf(dest_buffer + i, "%d", temp_buffer[i]);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "list_test.h"
#include "list.h"
List _g_list_header = LIST_NULL;
#define MAX_BUF_SIZE (20)
static void cleanLine(void)
{
while ( '\n' != getchar()) {
;
}
}
void T_createList(void)
{
List p_header = LIST_NULL;
if (!p_header) {
fprintf(stdout, "[*] %s: p_list is NULL\n", __FILE__);
}
p_header = createList();
if ( !p_header) {
fprintf(stdout, "<X> Create list fail.\n");
return ;
} else {
fprintf(stdout, "[*] Create list successfully.\n");
p_header->item = 0xFFFFFFF;
p_header->p_next = NULL;
_g_list_header = p_header;
}
}
void T_destroyList(void)
{
if (!_g_list_header) {
fprintf(stdout, "<T_destroyList> %s-%d: global list is NULL.\n", __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
if ( TRUE != destroyList(_g_list_header)) {
fprintf(stdout, "<T_destroyList> Destroy list fail %s-%d.\n", __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
if ( !_g_list_header) {
fprintf(stdout, "<T_destroyList> %s-%d: destroy fail.\n", __FILE__, __LINE__);
exit(EXIT_FAILURE);
} else {
fprintf(stdout, "<T_destroyList> %s-%d: destroy list successfully.\n", __FILE__, __LINE__);
}
}
void T_getLengthList(void)
{
if ( !_g_list_header) {
fprintf(stdout, "[X] Global list header is NULL\n");
exit(EXIT_FAILURE);
}
fprintf(stdout, "[*] Length of list is %d\n", getLengthList(_g_list_header));
}
void T_isEmptyList(void)
{
if ( !_g_list_header) {
fprintf(stdout, "[X] Global list header is NULL : <%s>-%d\n", __FILE__, __LINE__);
return ;
}
if ( TRUE == isEmptyList(_g_list_header)) {
fprintf(stdout, "[*] List is empty\n");
} else {
fprintf(stdout, "[*] List is not empty\n");
}
}
void T_insertItemHeaderList(void)
{
UINT32 buffer[MAX_BUF_SIZE];
UINT32 index;
fputs("[*] Insert item to header of list.\n", stdout);
for (index = 0; index != MAX_BUF_SIZE; ++index) {
buffer[index] = (index + 1) * 11;
}
for (index = 0; index != MAX_BUF_SIZE; ++index) {
if ( TRUE != insertItemHeaderList(_g_list_header,
buffer[index])) {
fprintf(stdout, "[X] Insert item fail. <%s>-%d\n",
__FILE__,
__LINE__);
exit(EXIT_FAILURE);
}
}
}
void T_insertItemTailList(void)
{
UINT32 buffer[MAX_BUF_SIZE];
UINT32 index;
fputs("[*] Insert item to tail of list.\n", stdout);
for (index = 0; index != MAX_BUF_SIZE; ++index) {
buffer[index] = (index + 1) * 100;
}
for (index = 0; index != MAX_BUF_SIZE; ++index) {
if ( TRUE != insertItemTailList(_g_list_header,
buffer[index])) {
fprintf(stdout, "[X] Insert item fail. <%s>-%d\n",
__FILE__,
__LINE__);
exit(EXIT_FAILURE);
}
}
}
void T_insertItemList(void)
{
UINT32 buffer[MAX_BUF_SIZE];
UINT32 index;
if ( !_g_list_header) {
fprintf(stdout, "[X] Global list is NULL. <%s>-%d\n",
__FILE__, __LINE__);
return ;
}
for (index = 0; index != MAX_BUF_SIZE; ++index) {
buffer[index] = index * 10;
if ( TRUE != insertItemList(_g_list_header, _g_list_header, buffer[index])) {
fprintf(stdout, "[X] Insert item to list fail. <%s>-%d\n", __FILE__, __LINE__);
return ;
} else {
fprintf(stdout, "[*] Insert item to list successfully. <%s>-%d\n", __FILE__, __LINE__);
}
}
}
void T_retrieveList(void)
{
fprintf(stdout, "[*] Retrieve list:\n");
if ( !_g_list_header) {
fprintf(stdout, "[X] Global list is NULL. <%s>-%d.\n",
__FILE__,
__LINE__);
return ;
}
retrieveList(_g_list_header);
}
void T_clearList(void)
{
if ( !_g_list_header) {
fprintf(stdout, "[X] List header is NULL. <%s>-%d\n",
__FILE__,
__LINE__);
exit(EXIT_FAILURE);
}
if ( FALSE == clearList(_g_list_header)) {
fprintf(stdout, "[X] Clear list fail.<%s>-%d\n",
__FILE__,
__LINE__);
exit(EXIT_FAILURE);
} else {
if ( !getLengthList(_g_list_header)) {
fprintf(stdout, "[*] Clear list successfully.\n");
}
}
}
void T_deleteItemHeaderList(void)
{
int user_get;
ElemType value_to_be_deleted;
if ( !_g_list_header) {
fprintf(stdout, "Gloabl list header is NULL: <%s>-%d\n",
__FILE__,
__LINE__);
return ;
}
do {
if ( TRUE != deleteItemHeaderList(_g_list_header, &value_to_be_deleted)) {
fprintf(stdout, "<T_deleteItemHeaderList> delete fail: <%s>-%d\n",
__FILE__,
__LINE__);
return ;
}
T_getLengthList();
T_retrieveList();
puts("Do you want to continue to delete? <4 to quit>");
scanf("%d", &user_get);
cleanLine();
} while ( 4 != user_get);
T_getLengthList();
T_retrieveList();
}
void T_findLastList(void)
{
Position p_temp = LIST_NULL;
if ( !_g_list_header) {
fprintf(stdout, "<T_findLastList> global list is NULL. %s - %d\n", __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
p_temp = findLastList(_g_list_header);
if ( LIST_NULL == p_temp) {
fprintf(stdout, "<T_findLastList> find last list is NULL. %s - %d\n", __FILE__, __LINE__);
exit(EXIT_FAILURE);
} else {
fprintf(stdout, "Find last node: value is %d\n", p_temp->item);
}
}
void T_deleteItemTailList(void)
{
ElemType value_to_be_deleted;
int user_get;
if ( !_g_list_header) {
fprintf(stdout, "<T_deleteItemTailList> global list is NULL %s-%d\n",
__FILE__,
__LINE__);
exit(EXIT_FAILURE);
}
do {
if ( TRUE == deleteItemTailList(_g_list_header, &value_to_be_deleted)) {
fprintf(stdout, "Delete item ok. value is [*%d]\n", value_to_be_deleted);
} else {
fprintf(stdout, "<T_deleteItemTailList> delete item fail. %s-%d\n",
__FILE__,
__LINE__);
}
T_retrieveList();
puts("Do you want to continue? <4 to quit>");
scanf("%d", &user_get);
cleanLine();
} while ( 4 != user_get);
}
void T_getItemByIndexList(void)
{
UINT32 index;
ElemType value = 0;
if ( !_g_list_header) {
fprintf(stdout, "<T_getItemByIndex> global is NULL. %s-%d\n",
__FILE__,
__LINE__);
exit(EXIT_FAILURE);
}
if ( getLengthList(_g_list_header) > 0) {
index = 3;
if ( FALSE == getItemByIndexList(_g_list_header,
index,
&value)) {
fprintf(stdout, "<T_getItemByIndex> get item fail. %s-%d\n",
__FILE__,
__LINE__);
exit(EXIT_FAILURE);
} else {
fprintf(stdout, "Index<%d> value is %d\n", index, value);
}
index = 6;
if ( FALSE == getItemByIndexList(_g_list_header,
index,
&value)) {
fprintf(stdout, "<T_getItemByIndex> get item fail. %s-%d\n",
__FILE__,
__LINE__);
exit(EXIT_FAILURE);
} else {
fprintf(stdout, "Index<%d> value is %d\n", index, value);
}
}
}
void T_getIndexByItemList(void)
{
UINT32 index;
UINT32 value = 0;
if ( !_g_list_header) {
fprintf(stdout, "<T_getIndexByItemList> global is NULL. %s-%d\n",
__FILE__,
__LINE__);
exit(EXIT_FAILURE);
}
if ( getLengthList(_g_list_header) > 0) {
value = 1000;
if ( TRUE == getIndexByItemList(_g_list_header,
value,
&index)) {
fprintf(stdout, "Value %d's index is %d.\n",
value, index);
} else {
fprintf(stderr, "<T_getIndexByItemList> get index fail. %s-%d\n",
__FILE__,
__LINE__);
exit(EXIT_FAILURE);
}
value = 1020;
if ( TRUE == getIndexByItemList(_g_list_header,
value,
&index)) {
fprintf(stdout, "Value %d's index is %d.\n",
value, index);
} else {
fprintf(stderr, "<T_getIndexByItemList> get index fail. %s-%d\n",
__FILE__,
__LINE__);
// exit(EXIT_FAILURE);
return ;
}
}
}
void T_insertItemByIndexList(void)
{
if ( !_g_list_header) {
fprintf(stdout, "<T_insertItemByIndexList> global is NULL. %s-%d\n",
__FILE__,
__LINE__);
exit(EXIT_FAILURE);
}
fprintf(stdout, "We will insert item 1111 into location of 5.\n");
if ( TRUE == insertItemByIndexList(_g_list_header,
5,
1111)) {
fprintf(stdout, "Insert successfully.\n");
} else {
fprintf(stdout, "Insert 1111 into location of 5 fail.\n");
}
T_retrieveList();
fprintf(stdout, "We will insert item 2222 into location of 10.\n");
if ( TRUE == insertItemByIndexList(_g_list_header,
10,
2222)) {
fprintf(stdout, "Insert successfully.\n");
} else {
fprintf(stdout, "Insert 2222 into location of 10 fail.\n");
}
T_retrieveList();
fprintf(stdout, "We will insert item 3333 into location of %d.\n", getLengthList(_g_list_header));
if ( TRUE == insertItemByIndexList(_g_list_header,
getLengthList(_g_list_header),
3333)) {
fprintf(stdout, "Insert successfully.\n");
} else {
fprintf(stdout, "Insert 3333 into location of %d fail.\n", getLengthList(_g_list_header));
}
T_retrieveList();
}
void T_sortList(void)
{
if ( !_g_list_header) {
fprintf(stderr, "<T_sortList> global is NULL. %s-%d\n",
__FILE__,
__LINE__);
exit(EXIT_FAILURE);
}
fprintf(stdout, "\n------------------------------ Sort List With Ascending Order --------------------------\n");
sortList(_g_list_header, ASCENDING);
T_retrieveList();
fprintf(stdout, "\n------------------------------ Sort List With Descending Order --------------------------\n");
sortList(_g_list_header, DESCENDING);
T_retrieveList();
}
#define MAX_RANDOM_NUM (10)
void T_mergeList(void)
{
List p_list_a = LIST_NULL;
List p_list_b = LIST_NULL;
List p_list_c = LIST_NULL;
size_t index;
ElemType value;
srand(time(0));
/* Create 3 different list first */
p_list_a = createList();
if ( LIST_NULL == p_list_a) {
fprintf(stdout, "Create list A fail.\n");
exit(EXIT_FAILURE);
}
p_list_b = createList();
if ( LIST_NULL == p_list_b) {
fprintf(stdout, "Create List B fail.\n");
exit(EXIT_FAILURE);
}
p_list_c = createList();
if ( LIST_NULL == p_list_c) {
fprintf(stdout, "Create List C fail.\n");
exit(EXIT_FAILURE);
}
/* Insert 10 data into list-A and list-B */
for (index = 0; index != MAX_RANDOM_NUM; ++index) {
value = rand()%100 + 1;
if ( TRUE != insertItemTailList(p_list_a, value)) {
fprintf(stdout, "Insert item %d into list-a fail.\n", value);
}
value = rand()%100 + 1;
if ( TRUE != insertItemTailList(p_list_b, value)) {
fprintf(stdout, "Insert item %d into list-b fail.\n", value);
}
}
#ifdef __DEBUG_SORT_LIST_
if ( TRUE != sortList(p_list_a, ASCENDING)) {
fprintf(stdout, "Sorted List-A fail.\n");
}
if ( TRUE != sortList(p_list_b, ASCENDING)) {
fprintf(stdout, "Sorted List-B fail.\n");
}
#endif /* __DEBUG_SORT_LIST_ */
fprintf(stdout, "\nAll items of List-A is: \n");
retrieveList(p_list_a);
fprintf(stdout, "\nAll items of List-B is: \n");
retrieveList(p_list_b);
fprintf(stdout, "\nBefore merge, All items of List-C is: \n");
retrieveList(p_list_c);
if ( TRUE != mergeList(p_list_a, p_list_b, p_list_c)) {
fprintf(stdout, "Merge List-A and List-B into List-C fail.\n");
}
fprintf(stdout, "\nAfter merge, all items of List-C is: \n");
retrieveList(p_list_c);
destroyList(p_list_a);
destroyList(p_list_b);
destroyList(p_list_c);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "lexer.h"
#include "history.h"
/*
** Transformation of the command into a list of token in 2 parts:
** Elementary token (tokeniser) and group of token (token_secondary).
** Rebinding of the list for the history.
*/
t_token *lexer(char *line, t_shell *sh, int opt)
{
t_token *list;
if ((line == NULL) || ((list = tokeniser(line)) == NULL))
return (NULL);
if (opt && token_rebinding(list, sh) == EXIT_FAILURE)
fprintf(stderr, "Error in commande rebinding: Malloc failled");
if (token_replace(&list, sh) == EXIT_FAILURE)
return (NULL);
if (token_secondary(&list) == EXIT_FAILURE)
return (NULL);
return (list);
}
|
C
|
/*
* $Id$
*
* utils.c
*
* SmartPalm Mobile APRS Display
* Copyright (c) 2001, Joelle Maslak
* Portions Copyright (c) 2005, Curtis E. Mills, WE7U
* All Rights Reserved (see license)
*
*/
#include <PalmOS.h>
#include <PalmCompatibility.h>
//#include <math.h>
extern double sin(double);
extern double cos(double);
extern double sqrt(double);
extern float acos(float);
extern float atan(float);
#include "SmartPalm.h"
#include "utils.h"
static float computeCloseDistance (float lat1, float lon1, float lat2, float lon2);
static float computeCloseBearing (float lat1, float lon1, float lat2, float lon2);
void timeformat (char * d, UInt32 i, int length)
{
int tmp;
UInt32 divisor;
divisor = 1;
for (tmp=1; tmp<length; tmp++) {
divisor = divisor * 10;
}
while (length > 0) {
tmp = i / divisor;
i = i % divisor;
*(d++) = '0' + tmp;
length--;
divisor = divisor / 10;
}
*d = '\0';
}
// returns n'th (0-based) comma-delimeted field within buffer
// true if field found, false otherwise
Boolean GetField(const char *buffer, UInt n, char *result, UInt max)
{
int i;
UInt count = 0;
// skip n commas
for (i = 0; i < (int)n; i++) {
while (*buffer && *buffer != ',')
buffer++;
if (*buffer == '\0')
return false;
buffer++;
}
while (*buffer && *buffer != ',') {
if (++count > max) {
return false;
}
*result++ = *buffer++;
}
if (*buffer != ',')
return false;
if (++count < max) {
*result = '\0';
}
return true;
}
float nm2sm(float f) {
return f * 1.15077944802;
}
float sm2nm(float f) {
return f / 1.15077944802;
}
float gps2internal(char * gpsdegree, char direction) {
int integerpart;
float decimalpart, ret;
decimalpart = asctofloat(gpsdegree) / 100;
integerpart = (int) decimalpart;
decimalpart = decimalpart - integerpart;
decimalpart = decimalpart / .60;
ret = decimalpart + integerpart;
if ((direction == 'W') || (direction == 'S')) {
ret = 0 - ret;
}
return ret;
}
Boolean validDegrees(char * s)
{
if (!validNumber(s)) { return false; }
if (StrAToI(s) > 360) { return false; }
if (StrAToI(s) < 0) { return false; }
return true;
}
Boolean validNumber(char * s)
{
while (*s != '\0') {
if ((*s < '0') || (*s > '9')) {
return false;
}
s++;
}
return true;
}
Boolean validPathField(char * s)
{
char tmp[10];
int i;
i = 0;
while (GetField(s, i, tmp, 9)) {
if (!validCallsign(tmp)) {
return false;
}
i++;
}
if (i > 8) { return false; }
return true;
}
char uc(char s)
{
if ((s >= 'a') && (s <= 'z')) { return (s + 'A' - 'a'); }
return s;
}
Boolean validCallsign(char * s)
{
int i;
char callpart[10];
char ssidpart[10];
i = StrLen(s);
if ((i < 1) || (i > 9)) { return false; }
callpart[0] = '\0';
ssidpart[0] = '\0';
i = 0;
while ((*s != '-') && (*s != '\0')) {
if (((uc(*s) < 'A') || (uc(*s) > 'Z')) && ((*s < '0') || (*s > '9'))) { return false; }
callpart[i++] = *s;
callpart[i] = '\0';
s++;
}
i = StrLen(callpart);
if ((i < 1) || (i > 6)) { return false; }
if (*s == '-') { s++; }
i = 0;
while (*s != '\0') {
if ((*s < '0') || (*s > '9')) { return false; }
ssidpart[i++] = *s;
ssidpart[i] = '\0';
s++;
}
i = StrAToI(s);
if ((i < 0) || (i > 15)) { return false; }
return true;
}
FieldPtr SetFieldTextFromHandle (Word fieldID, Handle txtH)
{
Handle oldTxtH;
FormPtr frm = FrmGetActiveForm();
FieldPtr fldP;
fldP = FrmGetObjectPtr(frm, FrmGetObjectIndex(frm, fieldID));
ErrNonFatalDisplayIf(!fldP, "missing field");
oldTxtH = FldGetTextHandle(fldP);
FldSetTextHandle(fldP, txtH);
FldDrawField(fldP);
if (oldTxtH != NULL) {
MemHandleFree(oldTxtH);
}
return fldP;
}
FieldPtr SetFieldTextFromStr(Word fieldID, CharPtr strP)
{
Handle txtH;
txtH = MemHandleNew(StrLen(strP) + 1);
if (!txtH) {
ErrNonFatalDisplayIf(1, "Can't allocate memory");
return NULL;
}
StrCopy(MemHandleLock(txtH), strP);
MemHandleUnlock(txtH);
return SetFieldTextFromHandle(fieldID, txtH);
}
char * GetFieldText(Word fieldID)
{
char * p;
FormPtr frm = FrmGetActiveForm();
FieldPtr fldP;
fldP = FrmGetObjectPtr(frm, FrmGetObjectIndex(frm, fieldID));
ErrNonFatalDisplayIf(!fldP, "missing field");
p = FldGetTextPtr(fldP);
if (p == NULL) {
p = "";
}
return p;
}
char * addSpaces (char * in)
{
char * out;
char * p, * q;
unsigned int commacount = 0;
if (in == NULL) { in = ""; }
p = in;
while (*p != '\0') {
if (*p == ',') {
commacount++;
}
p++;
}
out = MemPtrNew(StrLen(in) + 1 + commacount);
ErrFatalDisplayIf(out == NULL, "Can't allocate memory");
p = in;
q = out;
while (*p != '\0') {
*(q++) = *p;
if (*p == ',') {
*(q++) = ' ';
}
p++;
}
*q = '\0';
return out;
}
float asctofloat (char * s) {
int divisor;
float result = 0.0;
int intpart = 0;
while (*s != '.') {
if (s == '\0') { return (float) intpart; }
intpart = intpart * 10.0;
if ((*s >= '0') && (*s <= '9')) {
intpart = intpart + (*s - '0');
}
s++;
}
result = (float) intpart;
s++; // Skip the dot
intpart = 0;
divisor = 1;
while (*s != '\0') {
if ((*s >= '0') && (*s <= '9')) {
intpart = (intpart * 10) + (*s - '0');
divisor = divisor * 10;
}
s++;
}
result = result + (((float) intpart) / ((float) divisor));
return result;
}
float computeDistance (float lat1, float lon1, float lat2, float lon2) {
float A = (lat1 / 180.0) * PI; // lat1 in radians
float B = (lat2 / 180.0) * PI; // lat2 in radians
float L = ((lon2 - lon1) / 180.0) * PI; // lon1 - lon2 in radians (note that lon1/lon2 signs are flipped)
float D; // distance in degrees of an arc
float distance;
if ((lat1 > 90.0) || (lat2 > 90.0)) { return -100.0; }
if (L > PI) { L = L - 2*PI; }
if (L < -PI) { L = L + 2*PI; }
D = acos((sin(A) * sin(B)) + (cos(A) * cos(B) * cos(L)));
// if (D > PI) { D = D - PI; }
distance = (D * 180 / PI) * 60 * 1.1508;
if (distance < 20) {
distance = computeCloseDistance(lat1, lon1, lat2, lon2);
}
return distance;;
}
static float computeCloseDistance (float lat1, float lon1, float lat2, float lon2) {
double avglat = (lat2 + lat1) / 2.0;
double deltalat = (lat1 - lat2);
double deltalon = (lon1 - lon2);
double longituderadius = 3956.0 * cos((float) avglat);
double longitudefactor = (2.0 * PI * longituderadius) / 360;
double latitudefactor = 69.048;
double x = longitudefactor * deltalon;
double y = latitudefactor * deltalat;
float distance;
if (x < 0.0) { x = -x; }
if (y < 0.0) { y = -y; }
distance = sqrt( (float)( (x*x) + (y*y) ) );
return distance;
}
static float computeCloseBearing (float lat1, float lon1, float lat2, float lon2) {
double avglat = (lat2 + lat1) / 2.0;
double deltalat = (lat1 - lat2);
double deltalon = (lon1 - lon2);
double longituderadius = 3956.0 * cos((float) avglat);
double longitudefactor = (2.0 * PI * longituderadius) / 360;
double latitudefactor = 69.048;
double x = longitudefactor * deltalon;
double y = latitudefactor * deltalat;
float bearing;
if (x < 0.0) { x = -x; }
if (y < 0.0) { y = -y; }
bearing = ((atan((float) (y / x)) * 180) / PI) + 0;
if ((deltalon > 0.0) && (deltalat >= 0.0)) {
bearing = 270.0 - bearing; /* OK */
} else if ((deltalon <= 0.0) && (deltalat > 0.0)) {
bearing = 90.0 + bearing; /* OK */
} else if ((deltalon > 0.0) && (deltalat <= 0.0)) {
bearing = 270.0 + bearing; /* OK */
} else if ((deltalon <= 0.0) && (deltalat < 0.0)) {
bearing = 90.0 - bearing; /* OK */
}
return bearing;
}
float computeBearing (float lat1, float lon1, float lat2, float lon2) {
float A = (lat1 / 180.0) * PI; // lat1 in radians
float B = (lat2 / 180.0) * PI; // lat2 in radians
float L = ((lon2 - lon1) / 180.0) * PI; // lon1 - lon2 in radians (note that lon1/lon2 signs are flipped)
float C; // True bearing to lat2/lon2 from lat1/lon2 (beware of negatives!) -- In RADIANS
float D; // Distance in radians of arc length
float bearing;
float distance;
if ((lat1 > 90.0) || (lat2 > 90.0)) { return -100.0; }
if (L > PI) { L = L - 2*PI; }
if (L < -PI) { L = L + 2*PI; }
D = acos((sin(A) * sin(B)) + (cos(A) * cos(B) * cos(L)));
C = acos((sin(B) - (sin(A) * cos(D))) / (cos(A) * sin(D)));
bearing = (C * 180.0) / PI;
if (sin(L) < 0) {
bearing = 360 - bearing;
}
distance = (D * 180 / PI) * 60 * 1.1508;
if (distance < 20) {
bearing = computeCloseBearing(lat1, lon1, lat2, lon2);
}
return bearing;
}
char * nameDirection (float direction) {
int i = 0;
direction = direction + 11.25;
if (direction > 360.0) { direction = direction - 360.0; }
i = (int) (direction / 22.5);
switch (i) {
case 0: return "N";
case 1: return "NNE";
case 2: return "NE";
case 3: return "ENE";
case 4: return "E";
case 5: return "ESE";
case 6: return "SE";
case 7: return "SSE";
case 8: return "S";
case 9: return "SSW";
case 10: return "SW";
case 11: return "WSW";
case 12: return "W";
case 13: return "WNW";
case 14: return "NW";
case 15: return "NNW";
}
return "ERR";
}
void positionformat(char * d, float s, int length, int precision)
{
float mult;
int i;
if (s < 0) { s = 0 - s; }
timeformat(d, (int) s, length - precision - 3);
s = s - ((float) ((int) s));
s = s * 60.0;
timeformat(d+length-precision-3, (int) s, 2);
s = s - ((float) ((int) s));
if (precision == 0) { return; }
*(d+length-precision-1) = '.';
mult = 1.0;
for (i=0; i<precision; i++) {
mult = mult * 10.0;
}
s = (s * mult) + .5;
timeformat(d+length-precision, (int) s, precision);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int numero;
int opcion=-9;
while(opcion!=0){
printf("\n1-Creciente:\n");
printf("2-Decreciente:\n");
printf("3-Factorial:\n");
printf("4-Binario:\n");
printf("5-Sumar hasta N:\n");
printf("0-Salir\n");
scanf("%d",&opcion);
switch(opcion){
case 1:printf("\nIngrese numero:\n");
scanf("%d",&numero);
mostrarcreciente(numero);
break;
case 2:printf("\nIngrese numero:\n");
scanf("%d",&numero);
mostrardecreciente(numero);
break;
case 3:printf("\nIngrese numero:\n");
scanf("%d",&numero);
printf("=%d",factorial(numero));
break;
case 4 :printf("\nIngrese numero\n");
scanf("%d",&numero);
decABin(numero);
break;
case 5:printf("\nIngrese numero: \n");
scanf("%d",&numero);
printf("%d",sumarHastaN(numero));
case 0:break;
}
}
return 0;
}
void mostrarcreciente(int numero){
if(numero>0){
mostrarcreciente(numero-1);
printf("%d",numero);
}
}
void mostrardecreciente(int numero){
if (numero>0){
printf("%d",numero);
mostrardecreciente(numero-1);
}
}
int factorial(int numero){
if( numero > 1 ){
printf("*%d",numero);
numero = numero*(factorial(numero-1));
}
else{
return numero;
}
}
void decABin(int n)
{
if (n!=0)
{
decABin(n/2);
printf("%i",n%2);
}
}
int sumarHastaN(int n)
{
if(n==1)
return 1;
else
return (sumarHastaN(n-1)+n);
}
|
C
|
/**
******************************************************************************
* @file : main_boot.c
* @brief : Bootloader app body
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include <stdbool.h>
#include <stdint.h>
#include "sys_mcu.h"
#include "sys_ll_serial.h"
#include "sys_ll_gpio.h"
#include "printf.h"
#include "memory_shared.h"
#include "shell.h"
#include "boot.h"
/* Private includes ----------------------------------------------------------*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define WAITING_CHR '.' /*!< Defined char to indicate waiting on CLI */
#define BREAK_CHR 'x' /*!< Defined break character to enter into CLI mode */
#define INIT_DELAY_COUNT ( 5U ) /*!< Number of seconds for break detection */
#define INIT_DELAY_1SEC ( 1000U ) /*!< Number of ms of a second */
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static void app_init_peripheral(void);
static bool app_scan_break_chr(void);
static int app_cli_send_chr_wrapper(char c);
static void app_cli_loop(void);
static bool app_init_share(void);
/* Private function definition -----------------------------------------------*/
/**
* @brief Link for putchar used in printf implementation.
*
* @param character character to send.
*/
void _putchar(char character)
{
(void)SYS_LL_SerialSend(SYS_LL_SERIAL_0, (uint8_t *)&character, 1U);
}
/**
* @brief Init system peripheral.
*
*/
static void app_init_peripheral(void)
{
(void)SYS_LL_SerialInit(SYS_LL_SERIAL_0);
SYS_LL_GpiolInit();
printf("\r\n\r\n--- Init Bootloader ---\r\n");
}
/**
* @brief Clear input buffer searching for break character.
*
* @return true Found breck character.
* @return false cleared buffer without finding breack character.
*/
static bool app_scan_break_chr(void)
{
uint8_t u8RxChr;
uint32_t u32InitDelayCount = INIT_DELAY_COUNT;
bool bRetval = false;
printf("\r\nPress '%c' to init CLI", BREAK_CHR);
/* Give some time to capture break chr*/
while ( u32InitDelayCount-- )
{
Sys_Mcu_Delay(INIT_DELAY_1SEC);
while ( SYS_LL_SerialRead(SYS_LL_SERIAL_0, &u8RxChr, 1U) != 0U )
{
if ( u8RxChr == BREAK_CHR )
{
bRetval = true;
}
}
if ( bRetval )
{
printf("\r\nBreak chr found, init CLI");
break;
}
printf("%c", WAITING_CHR);
}
return bRetval;
}
/**
* @brief Wrapper send function used in shell implementation
*
* @param c character to send.
* @return int number of bytes to sent.
*/
static int app_cli_send_chr_wrapper(char c)
{
uint8_t u8TxData = (uint8_t)c;
return SYS_LL_SerialSend(SYS_LL_SERIAL_0, &u8TxData, 1U);
}
/**
* @brief Main loop for CLI app.
*
*/
void app_cli_loop(void)
{
/* Init shell */
sShellImpl shell_impl = {
.send_char = app_cli_send_chr_wrapper,
};
shell_boot(&shell_impl);
/* Data consumer loop */
uint8_t u8DataRx = 0;
while (1U)
{
if ( SYS_LL_SerialRead(SYS_LL_SERIAL_0, &u8DataRx, 1U) != 0U )
{
char cDataRx = (char)u8DataRx;
shell_receive_char(cDataRx);
}
}
}
/**
* @brief Init and check RAM share data.
*
* @return true App image not validated.
* @return false App image not validated.
*/
static bool app_init_share(void)
{
bool bRetval = true;
shared_init_struct();
shared_increment_boot_count();
uint8_t u8BootCount = shared_get_boot_count();
uint32_t u32BootFlags = shared_get_boot_flags();
printf("\r\nRAM Share Data:", u8BootCount);
printf("\r\n - Boot count: %d", u8BootCount);
printf("\r\n - Boot Status flags: 0x%08X", u32BootFlags);
if ( (u8BootCount > SHARE_MAX_BOOT_COUNT) && !shared_get_boot_flag(SHARE_BOOT_FLAG_VALID_APP) )
{
printf("\r\nApplication Image not stable, wait in CLI mode");
bRetval = false;
}
return bRetval;
}
/* Private user code ---------------------------------------------------------*/
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* Init flash, system clocks and user error interface */
Sys_Mcu_Init();
/* Initialize all configured peripherals */
app_init_peripheral();
/* Update boot counter */
if ( app_init_share() )
{
/* Scan input buffer for break character */
if ( !app_scan_break_chr() )
{
Boot_start_app();
}
}
/* Handle for CLI app */
app_cli_loop();
/* Not executed */
while (1)
{
}
}
/* EOF */
|
C
|
#define _BSD_SOURCE /* Get on_exit() declaration from <stdlib.h */
#include <stdlib.h>
#include "../lib/tlpi_hdr.h"
static void atexitFunc1(void)
{
printf("atexit function 1 called\n");
}
static void atexitFunc2(void)
{
printf("atexit function 2 called\n");
}
static void onexitFunc(int exitStatus,void *arg)
{
printf("on_exit function called:status=%d,arg=%ld\n",exitStatus,(long)arg);
}
int main(int argc,char *argv[])
{
if(on_exit(onexitFunc,(void*)10)!=0)
fatal("on_exit 1");
if(atexit(atexitFunc1)!=0)
fatal("atexit 1");
if(atexit(atexitFunc2)!=0)
fatal("atexit 2");
if(on_exit(onexitFunc,(void*)20)!=0)
fatal("on_exit 2");
exit(2);
}
|
C
|
//******************************************************************************
// MSP430FR69xx Demo - eUSCI_A1 UART echo at 9600 baud using BRCLK = 8MHz
//
// Description: This demo echoes back characters received via a PC serial port.
// SMCLK/ DCO is used as a clock source and the device is put in LPM3
// The auto-clock enable feature is used by the eUSCI and SMCLK is turned off
// when the UART is idle and turned on when a receive edge is detected.
// Note that level shifter hardware is needed to shift between RS232 and MSP
// voltage levels.
//
// The example code shows proper initialization of registers
// and interrupts to receive and transmit data.
// To test code in LPM3, disconnect the debugger.
//
// ACLK = VLO, MCLK = DCO = SMCLK = 8MHz
//
// MSP430FR6989
// -----------------
// RST -| P3.4/UCA1TXD|----> PC (echo)
// | |
// | |
// | P3.5/UCA1RXD|<---- PC
// | |
//
//******************************************************************************
#include <msp430.h>
#include <stdio.h>
#include "myprintf.h"
/*-------------------------------------------------------------------
DESCRIPTION: Send one char in TX buffer, if it is not busy. Wait until not busy.
INPUTS: One char.
OUTPUTS: Send all the char in TX buffer.
RETURNS: None.
---------------------------------------------------------------------*/
// Modify this routine so that it points to YOUR UART
void putChar(unsigned char byte)
{
while(!(UCA1IFG & UCTXIFG)); // USCI_A0 TX buffer ready?
UCA1TXBUF = byte; // Load Tx register that clear UCA0TXIFG
}
/*-------------------------------------------------------------------
DESCRIPTION: Send string buffer.
INPUTS: Send String
OUTPUTS: Send all the char in TX buffer.
RETURNS: None.
---------------------------------------------------------------------*/
void print_uart(char *pcString) {
while (*pcString != '\0') {
while (!(UCA1IFG & UCTXIFG));
UCA1TXBUF = *pcString++;
_delay_cycles(1000);
}
}
/*
void printString(char * pcString) {
int i=0;
while(pcString[i] != '\0')
{
putChar(pcString[i++]);
}
} */
/*-------------------------------------------------------------------
DESCRIPTION: Move numbers of lines up in the HyperTerminal.
INPUTS: None.
OUTPUTS: Line up to TX buffer.
RETURNS: None.
---------------------------------------------------------------------*/
void linesUp(unsigned char lines)
{
unsigned char i;
for (i = 0; i < lines; ++i)
{
putChar(0x1b);
putChar(0x5b);
putChar(0x41);
}
}
/*-------------------------------------------------------------------
DESCRIPTION: Send out charater strings with defined width, justification
and padding. Width = 0 or width < string length means
unlimited width. Normal padding is space and left justification,
but it can pad '0' or pad to the right side, depending on pad value.
pad justification padding char
bxxxxxx00 left ' '
bxxxxxx1x right ' ' or '0'
bxxxxxxx1 left or right '0'
INPUTS: Valid string and special charater in form of "\n" for example
refered by pointer *string. Output field width. Justification and padding flag pad.
OUTPUTS: Sent formated string to com port output.
RETURNS: Total of chars sent.
---------------------------------------------------------------------*/
#define PAD_RIGHT 0x01
#define PAD_ZERO 0x02
int prints(char *string, unsigned char width, unsigned char pad)
{
int pc = 0;
unsigned char padchar = ' '; // The pading char is space normally
if (width > 0) // If output width is defined
{
unsigned char len = 0;
char *ptr;
for (ptr = string; *ptr; ++ptr) ++len; // Calculate string length and put it in len
if (len >= width) width = 0; // If string is longer than width, then width is not applicable define as zero
else width -= len; // Else redefine width as padding spaces
if (pad & PAD_ZERO) padchar = '0'; // If padding char is zero, then get padchar as zero ready instead of original space
}
if (!(pad & PAD_RIGHT)) // If not right padding - left justification
{
for (; width > 0; --width) // If ther is padding width. Output padding char as '0' or ' '.
{
putChar (padchar);
++pc;
}
}
for (; *string ; ++string) // Output the full string
{
putChar (*string);
++pc;
}
for (; width > 0; --width) { // Write padding char to the right if normal left justification
putChar (padchar);
++pc;
}
return pc; // Return the output char number
}
/*-------------------------------------------------------------------
* DESCRIPTION: Print 32 bit signed interger in dec or hex. In specific
* width, padding and justification using prints(). Use 12 byte buffer
* which is enough for 32 bit int.
* INPUTS: Up to 32 byte signed interger i. Counting base: 10 or 16.
* Sign flag sg. Output string width. padding and justification flag.
* Leter base for number conversion.
* OUTPUTS: Sent formated interger as string to com port output.
* RETURNS: Total of chars sent.
---------------------------------------------------------------------*/
#define PRINT_BUF_LEN 12
int printi(long int i, unsigned char b, unsigned char sg, unsigned char width, unsigned char pad, unsigned char letbase)
{
char print_buf[PRINT_BUF_LEN]; // Interger as string array
char *s;
char neg = 0;
unsigned long int t;
unsigned long int u = i;
int pc = 0;
if (i == 0) // If output char is 0, then just output it with padding and width.
{
print_buf[0] = '0';
print_buf[1] = '\0'; // Always remenber to put string end
return prints(print_buf, width, pad); // Print out zero and done.
}
if (sg && (b == 10) && (i < 0)) // If it is a negative int, then record the '-' and number as positive
{
neg = 1;
u = -i;
}
s = print_buf + PRINT_BUF_LEN-1; // Point s to the end of the output buffer and put a null there.
*s = '\0';
while (u) // Convert the positive int to string with whatever counting base, dec, or hex.
{
t = u % b;
if( t >= 10 )
t += letbase - '0' - 10;
*--s = t + '0';
u /= b;
}
if (neg)
{ // If it is a negative number
if( width && (pad & PAD_ZERO) )
{
// If there is width, right justified and pad with zero, output negative sign.
putChar ('-');
++pc;
--width;
}
else *--s = '-'; // Otherwise put the '-' to string buffer.
}
return pc + prints (s, width, pad); // Output the string buffer and return the output counter.
}
/*-------------------------------------------------------------------
* DESCRIPTION: short form of printf. Print argument strings with mixed
* varables (string or interger)inside formated.
* INPUTS: Argument string pointer.
* OUTPUTS: print out the argument with style using prints() and printi().
* RETURNS: Total of chars sent.
* Warning!!! varables and constant numbers even 0, must casted with
* (long int)in printf(), if it is going to print out using
* format "u", "d", "X" and "x"! Or the complier will assigned
* 16-bit for data smaller than 16 bit and the argument pointer
* will fetch a wrong 32-bit data and the argument point
* increament will be in wrong size.
* Limitations: 1) It treats all interger as 32 bit data only.
* 2) No floating point data presentation.
* 3) Has left/right alignment with 0 padding.
* 4) Has format code "s", "d", "X", "x", "u" and "c" only.
---------------------------------------------------------------------*/
int myprintf(char *format, ...)
{
int width, pad;
int pc = 0;
char scr[2];
va_list args;
va_start(args, format);
for (; *format != 0; ++format) {
if (*format == '%') {
++format;
width = pad = 0;
if (*format == '\0') break;
if (*format == '%') goto out;
if (*format == '-') {
++format;
pad = PAD_RIGHT;
}
while (*format == '0') {
++format;
pad |= PAD_ZERO;
}
for ( ; *format >= '0' && *format <= '9'; ++format) {
width *= 10;
width += *format - '0';
}
if( *format == 's' ) {
char *s = (char *)va_arg( args, int );
pc += prints (s?s:"(null)", width, pad);
continue;
}
if( *format == 'd' ) {
pc += printi (va_arg( args, long int ), 10, 1, width, pad, 'a');
continue;
}
if( *format == 'x' ) {
pc += printi (va_arg( args, long int ), 16, 0, width, pad, 'a');
continue;
}
if( *format == 'X' ) {
pc += printi (va_arg( args, long int ), 16, 0, width, pad, 'A');
continue;
}
if( *format == 'u' ) {
pc += printi (va_arg( args, long int ), 10, 0, width, pad, 'a');
continue;
}
if( *format == 'c' ) { // char are converted to int then pushed on the stack
scr[0] = (char)va_arg( args, int );
scr[1] = '\0';
pc += prints (scr, width, pad);
continue;
}
}
else {
out:
putChar(*format);
++pc;
}
}
va_end( args );
return pc;
}
//===============================================================================================
void printTest(void)
{
char *ptr = "Hello world!";
char *np = 0;
long int i = 5;
int bs = sizeof(long int)*8; // Bit to shift
long int mi = ((long int)1 << (bs-1)) + 1; // Maximum negative number
myprintf("%s\r\n", ptr);
myprintf("printf test\r\n");
myprintf("%s is null pointer\r\n", np);
myprintf("%d = 5\r\n", (long int)i);
myprintf("%d = - max int\r\n", mi);
myprintf("Long int 123456789 print out is %u", (long int)123456789);
myprintf("\r\nmi in hex is %x\r\n", (long int)mi);
myprintf("bs in dec is %u\r\n", (long int)bs);
myprintf("char %c = 'a'\r\n", 'a');
myprintf("hex %x = ff\r\n", (long int)0xff);
myprintf("hex %02x = 00\r\n", (long int)0);
myprintf("signed %d = unsigned %u = hex %x\r\n", (long int)-32767, (long int)-32767, (long int)-32767);
myprintf("signed %d = unsigned %u = hex %x\r\n", (long int)-3, (long int)-3, (long int)-3);
myprintf("%d %s(s)%", (long int)0, "message");
myprintf("\r\n");
myprintf("%d %s(s) with %%\r\n", (long int)0, "message");
myprintf("justif: \"%-10s\"\r\n", "left");
myprintf("justif: \"%10s\"\r\n", "right");
myprintf(" 3: %04d zero padded\r\n", (long int)3);
myprintf(" 3: %-4d left justif.\r\n", (long int)3);
myprintf(" 3: %4d right justif.\r\n", (long int)3);
myprintf("-3: %04d zero padded\r\n", (long int)-3);
myprintf("-3: %-4d left justif.\r\n", (long int)-3);
myprintf("-3: %4d right justif.\r\n\r\n\r\n", (long int)-3);
}
//==================================================================================================
/*
void uart_gpio_init(unsigned char ch)
{
// Configure GPIO
switch(ch)
{
case USCI_A0:
P2SEL0 |= BIT0 | BIT1; // USCI_A0 UART operation
P2SEL1 &= ~(BIT0 | BIT1);
break;
case USCI_A1:
// launchpad backchannel
P3SEL0 |= BIT4 | BIT5; // USCI_A1 UART operation
P3SEL1 &= ~(BIT4 | BIT5);
break;
default:
// error
break;
}
}*/
//*****************************************************************************
// UART init routine
//*****************************************************************************
void initialize_uart(void)
{
//Configure GPIO
P3SEL0 |= BIT4 | BIT5; // USCI_A0 UART operation using Backchannel
P3SEL1 &= ~(BIT4 | BIT5);
// Configure USCI_A0 for UART mode
UCA1CTLW0 |= UCSWRST; // Put eUSCI into software reset
// Baud Rate Setting
// Use Table 30-5 in Family User Guide
UCA1CTLW0 |= UCSSEL__SMCLK; // CLK = SMCLK / specifies clock source for UART
UCA1BR0 = 52; //9600 // specifies bit rate (baud) of 9600
UCA1BR1 = 0x00;
UCA1MCTLW |= UCOS16 | UCBRF_1 | 0x4900;
UCA1CTLW0 &= ~UCSWRST; // Initialize eUSCI
UCA1IE |= UCRXIE; // Enable USCI_A1 RX interrupt
}
//*****************************************************************************
// @End of file
//*****************************************************************************
|
C
|
/*
Name: Ejercicio 35
Copyright: BlueCode
Author: Guillermo Canto
Date: 06/02/20 21:52
Description: E.P. que lea 25 números (N) y que imprima los que sean iguales a cero.
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
float n;
int i = 0;
while(i<25){
//Entrada
printf("#%d. Ingrese un numero: ", ++i);
scanf("%f", &n);
//Proceso,Salida
if(n == 0){
printf("Ingresaste un cero\n");
}
i++;
}
return 0;
}
|
C
|
enum
{
M_TEAM = 1<<0,
M_CTF = 1<<1,
M_OVERTIME = 1<<2,
M_EDIT = 1<<3,
M_DEMO = 1<<4,
M_LOCAL = 1<<5,
M_LOBBY = 1<<6,
M_ELIMINATION = 1<<7,
M_LASTMAN = 1<<8,
M_JUGGERNAUT = 1<<9,
M_INFECTION = 1<<10,
M_HOLD = 1<<11
};
static struct gamemodeinfo
{
const char *name, *prettyname;
int flags;
const char *info;
} gamemodes[] =
{
{ "demo", "Demo", M_DEMO | M_LOCAL, NULL},
{ "edit", "Edit", M_EDIT, "\f0Cooperative Editing\ff: edit maps with multiple players simultaneously" },
{ "dm", "Deathmatch", M_LOBBY, "\f0Deathmatch\ff: kill everyone to score points" },
{ "tdm", "Team Deathmatch", M_TEAM, "\f0Team Deathmatch\ff: kill the enemy team to score points for your team" },
{ "ctf", "Capture The Flag", M_CTF | M_TEAM, "\f0Capture The Flag\ff: capture the enemy flag and bring it back to your flag to score points for your team" },
{ "elim", "Elimination", M_ELIMINATION | M_TEAM, "\f0Elimination\ff: eliminate the enemy team to win the round and score points for your team" },
{ "lms", "Last Man Standing", M_LASTMAN, "\f0Last Man Standing\ff: eliminate everyone to win the round and score points" },
{ "jugg", "Juggernaut", M_JUGGERNAUT, "\f0Juggernaut\ff: kill players or kill the juggernaut to become the new juggernaut and score points easier" },
{ "infect", "Infection", M_INFECTION, "\f0Infection\ff: survive the infection or infect as many survivors as you can as a zombie to score points" },
{ "hold", "Hold", M_HOLD | M_TEAM, "\f0Team Deathmatch\ff: take and hold flag for 20 seconds to score points for your team." }
};
#define STARTGAMEMODE (-1)
#define NUMGAMEMODES ((int)(sizeof(gamemodes)/sizeof(gamemodes[0])))
#define m_valid(mode) ((mode) >= STARTGAMEMODE && (mode) < STARTGAMEMODE + NUMGAMEMODES)
#define m_check(mode, flag) (m_valid(mode) && gamemodes[(mode) - STARTGAMEMODE].flags&(flag))
#define m_checknot(mode, flag) (m_valid(mode) && !(gamemodes[(mode) - STARTGAMEMODE].flags&(flag)))
#define m_checkall(mode, flag) (m_valid(mode) && (gamemodes[(mode) - STARTGAMEMODE].flags&(flag)) == (flag))
#define m_ctf (m_check(gamemode, M_CTF))
#define m_teammode (m_check(gamemode, M_TEAM))
#define m_overtime (m_check(gamemode, M_OVERTIME))
#define isteam(a,b) (m_teammode && a==b)
#define m_elimination (m_check(gamemode, M_ELIMINATION))
#define m_round (m_check(gamemode, M_ELIMINATION|M_LASTMAN|M_INFECTION))
#define m_dm (m_checknot(gamemode, M_EDIT|M_CTF|M_ELIMINATION|M_LASTMAN|M_INFECTION))
#define m_lms (m_check(gamemode, M_LASTMAN))
#define m_juggernaut (m_check(gamemode, M_JUGGERNAUT))
#define m_infection (m_check(gamemode, M_INFECTION))
#define m_hold (m_check(gamemode, M_HOLD))
#define m_demo (m_check(gamemode, M_DEMO))
#define m_edit (m_check(gamemode, M_EDIT))
#define m_lobby (m_check(gamemode, M_LOBBY))
#define m_timed (m_checknot(gamemode, M_DEMO|M_EDIT|M_LOCAL))
#define m_botmode (m_checknot(gamemode, M_DEMO|M_LOCAL))
#define m_mp(mode) (m_checknot(mode, M_LOCAL))
enum
{
MUT_DEFAULT = 1<<0,
MUT_CLASSIC = 1<<1, MUT_INSTA = 1<<2, MUT_EFFIC = 1<<3, MUT_RANDOMWEAPON = 1<<4, MUT_ONEWEAPON = 1<<5,
MUT_VAMPIRE = 1<<6, MUT_HEADHUNTER = 1<<7, MUT_LOCATIONALDAMAGE = 1<<8, MUT_MAYHEM = 1<<9, MUT_NOPOWERUP = 1<<10, MUT_NOITEMS = 1<<11,
MUT_GHOST = 1<<12, MUT_SLUGGARD = 1<<13, MUT_WALLJUMP = 1<<14, MUT_FALLDAMAGE = 1<<15,
MUT_ALL = MUT_DEFAULT|MUT_CLASSIC|MUT_INSTA|MUT_EFFIC|MUT_RANDOMWEAPON|MUT_ONEWEAPON|MUT_VAMPIRE|MUT_HEADHUNTER|MUT_LOCATIONALDAMAGE|MUT_MAYHEM|MUT_NOPOWERUP|MUT_NOITEMS|MUT_GHOST|MUT_SLUGGARD|MUT_WALLJUMP|MUT_FALLDAMAGE
};
static struct mutatorinfo
{
const char *name, *prettyname;
int flags, exclude;
const char *info;
} mutator[] __attribute__((unused)) =
{
{ "default", "", MUT_DEFAULT, MUT_ALL, ""},
{ "classic", "Classic", MUT_CLASSIC, MUT_DEFAULT | MUT_INSTA | MUT_EFFIC | MUT_NOITEMS, "\f6Classic\ff: collect items for ammo, shield and health" },
{ "insta", "Instagib", MUT_INSTA, MUT_DEFAULT | MUT_CLASSIC | MUT_EFFIC | MUT_VAMPIRE | MUT_RANDOMWEAPON | MUT_ONEWEAPON, "\n\f6Instagib\ff: you spawn with unlimited railgun ammo and die instantly from one shot" },
{ "effic", "Efficiency", MUT_EFFIC, MUT_DEFAULT | MUT_CLASSIC | MUT_INSTA | MUT_RANDOMWEAPON | MUT_ONEWEAPON, "\f6Efficiency\ff: you spawn with shield and all weapons" },
{ "voosh", "Voosh", MUT_RANDOMWEAPON, MUT_DEFAULT|MUT_INSTA|MUT_EFFIC|MUT_ONEWEAPON, "\f6Voosh\ff: all players switch to one random weapon every 15 seconds" },
{ "one-weapon", "One Weapon", MUT_ONEWEAPON, MUT_DEFAULT|MUT_INSTA|MUT_EFFIC|MUT_RANDOMWEAPON, "\f6One Weapon\ff: only one weapon is available" },
{ "vamp", "Vampire", MUT_VAMPIRE, MUT_INSTA, "\f6Vampire\ff: deal damage to regenerate health" },
{ "head-hunter", "Head Hunter", MUT_HEADHUNTER, MUT_LOCATIONALDAMAGE, "\f6Head Hunter\ff: only headshos deal damage" },
{ "loc-damage", "Locational Damage", MUT_LOCATIONALDAMAGE, MUT_HEADHUNTER|MUT_INSTA, "\f6Locational Damage\ff: damage depends on which body area you hit" },
{ "mayhem", "Mayhem", MUT_MAYHEM, NULL, "\f6Mayhem\ff: land a headshot with any hitscan weapon to instantly kill enemies" },
{ "no-power", "No Power-ups", MUT_NOPOWERUP, 0, "\f6No Power-ups\ff: power-ups never spawn in the map" },
{ "no-items", "No Items", MUT_NOITEMS, MUT_CLASSIC, "\f6No items\ff: items never spawn" },
{ "ghost", "Ghost", MUT_GHOST, NULL, "\f6Ghost\ff: players are much harder to see" },
{ "sluggard", "Sluggard", MUT_SLUGGARD, 0, "\f6Sluggard\ff: player speed is decreased" },
{ "wall-jump", "Wall jump", MUT_WALLJUMP, NULL, "\f6Wall jump\ff: players can wall jump" },
{ "fall-damage", "Fall damage", MUT_FALLDAMAGE, 0, "\f6Fall damage\ff: damage is applied when a player exceeds the maximum jumping height threshold" }
};
#define NUMMUTATORS ((int)(sizeof(mutator)/sizeof(mutator[0])))
#define m_default(b) (b&MUT_DEFAULT)
#define m_classic(b) (b&MUT_CLASSIC)
#define m_insta(b) (b&MUT_INSTA)
#define m_effic(b) (b&MUT_EFFIC)
#define m_randomweapon(b) (b&MUT_RANDOMWEAPON)
#define m_oneweapon(b) (b&MUT_ONEWEAPON)
#define m_vampire(b) (b&MUT_VAMPIRE)
#define m_headhunter(b) (b&MUT_HEADHUNTER)
#define m_locationaldam(b) (b&MUT_LOCATIONALDAMAGE)
#define m_mayhem(b) (b&MUT_MAYHEM)
#define m_nopowerups(b) (b&MUT_NOPOWERUP)
#define m_noitems(b) (b&MUT_INSTA || b&MUT_NOITEMS)
#define m_ghost(b) (b&MUT_GHOST)
#define m_sluggard(b) (b&MUT_SLUGGARD)
#define m_walljump(b) (b&MUT_WALLJUMP)
#define m_falldamage(b) (b&MUT_FALLDAMAGE)
#define m_headshot(b) (b&MUT_HEADHUNTER || b&MUT_LOCATIONALDAMAGE || b&MUT_MAYHEM)
#define m_regen(b) (!(b&MUT_CLASSIC) && !(b&MUT_INSTA) && !(b&MUT_EFFIC) && !(b&MUT_VAMPIRE))
#define m_unlimitedammo(b) ((b&MUT_INSTA) || (b&MUT_ONEWEAPON))
|
C
|
//
// main.c
// 141-LinkedListCycle
//
// Created by HuangLibo on 2017/8/20.
// Copyright © 2017年 Huang Libo. All rights reserved.
//
/*
141. Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct ListNode {
int val;
struct ListNode * next;
};
bool hasCycle(struct ListNode * head) {
if (head == NULL) return false;
struct ListNode * slow, * fast;
slow = head;
fast = head;
while (slow && fast && fast->next ) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow) {
return true;
}
}
return false;
}
int main(int argc, const char * argv[]) {
struct ListNode * head, * current, * newNode;
current = (struct ListNode *)malloc(sizeof(struct ListNode));
current->next = NULL;
head = current;
for (int i = 0; i < 3; ++i) {
newNode = (struct ListNode *)malloc(sizeof(struct ListNode));
newNode->next = NULL;
current->next = newNode;
current = current->next;
}
// current->next = head;
bool result = hasCycle(head);
printf("%d\n", result);
// struct ListNode * tmp;
// while (head != NULL) {
// tmp = head;
// head = head->next;
// free(tmp);
// }
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
int min(int x,int y)
{
return x<y?x:y;
}
int main()
{
int t,i,count,la,lb;
int a1[130],b1[130];
char a[10004],b[10004];
scanf("%d",&t);
while(t--)
{
for(i=0;i<130;i++)
{
a1[i]=0;
b1[i]=0;
}
scanf("%s",a);
scanf("%s",b);
la=strlen(a);
lb=strlen(b);
for(i=0;i<la;i++)
a1[a[i]]++;
for(i=0;i<lb;i++)
b1[b[i]]++;
count=0;
for(i=0;i<130;i++)
{
count=count+min(a1[i],b1[i]);
}
printf("%d\n",count);
}
return 0;
}
|
C
|
// formas básicas do goto, for, while e do while
#include <stdio.h>
int main()
{
int i = 0, j = 0, k = 0, l = 0, count = 3;
imprimir:
printf("o valor de i é: %d\n", i);
i++;
if (i < 3)
goto imprimir;
printf("#################\n");
for (size_t j = 0; j < count; j++)
{
printf("o valor de j é: %d\n", i);
}
printf("#################\n");
while (k < 3)
{
printf("o valor de k é: %d\n", k);
k++;
}
printf("#################\n");
do
{
printf("o valor de l é: %d\n", l++);
} while (l < 3);
return 0;
}
|
C
|
// Clockwise dir-high
#include "Arduino.h"
const int STEP_DELAY = 1000;
int speeddelay = 1000;
// M1 Constants - Motor Z Ramps Pinouts
const int M1DPin = 41;
const int M1EPin = 37;
const int M1SPin = 39;
// M2 Constants - Motor X Ramps Pinouts
const int M2DPin = 40;
const int M2EPin = 36;
const int M2SPin = 38;
// M3 Constants - Motor Y Ramps Pinouts
const int M3DPin = 35;
const int M3EPin = 31;
const int M3SPin = 33;
// M4 Constants - Motor E Ramps Pinouts
const int M4DPin = 34;
const int M4EPin = 30;
const int M4SPin = 32;
void motorsetup(){
// Set up all pin modes
// Motor 1
pinMode(M1DPin, OUTPUT);
pinMode(M1EPin, OUTPUT);
pinMode(M1SPin, OUTPUT);
// Motor 2
pinMode(M2DPin, OUTPUT);
pinMode(M2EPin, OUTPUT);
pinMode(M2SPin, OUTPUT);
// Motor 3
pinMode(M3DPin, OUTPUT);
pinMode(M3EPin, OUTPUT);
pinMode(M3SPin, OUTPUT);
// Motor 4
pinMode(M4DPin, OUTPUT);
pinMode(M4EPin, OUTPUT);
pinMode(M4SPin, OUTPUT);
}
void forward()
{
// Motor 2 - C-Clockwise Step // Motor 1 - Clockwise Step
// Motor 3 - C-Clockwise Step // Motor 4 - Clockwise Step
// Set Directions
digitalWrite(M1DPin, HIGH); // Clockwise
digitalWrite(M2DPin, LOW); // C-Clockwise
digitalWrite(M3DPin, LOW); // C-Clockwise
digitalWrite(M4DPin, HIGH); // Clockwise
// Low
digitalWrite(M1SPin, LOW);
digitalWrite(M2SPin, LOW);
digitalWrite(M3SPin, LOW);
digitalWrite(M4SPin, LOW);
delayMicroseconds(STEP_DELAY);
// High
digitalWrite(M1SPin, HIGH);
digitalWrite(M2SPin, HIGH);
digitalWrite(M3SPin, HIGH);
digitalWrite(M4SPin, HIGH);
delayMicroseconds(STEP_DELAY);
// Low
digitalWrite(M1SPin, LOW);
digitalWrite(M2SPin, LOW);
digitalWrite(M3SPin, LOW);
digitalWrite(M4SPin, LOW);
delayMicroseconds(speeddelay);
}
void backward()
{
// Motor 2 - Clockwise Step // Motor 1 - C-Clockwise Step
// Motor 3 - Clockwise Step // Motor 4 - C-Clockwise Step
// Set Directions
digitalWrite(M1DPin, LOW); // C-Clockwise
digitalWrite(M2DPin, HIGH); // Clockwise
digitalWrite(M3DPin, HIGH); // Clockwise
digitalWrite(M4DPin, LOW); // C-Clockwise
// Low
digitalWrite(M1SPin, LOW);
digitalWrite(M2SPin, LOW);
digitalWrite(M3SPin, LOW);
digitalWrite(M4SPin, LOW);
delayMicroseconds(STEP_DELAY);
// High
digitalWrite(M1SPin, HIGH);
digitalWrite(M2SPin, HIGH);
digitalWrite(M3SPin, HIGH);
digitalWrite(M4SPin, HIGH);
delayMicroseconds(STEP_DELAY);
// Low
digitalWrite(M1SPin, LOW);
digitalWrite(M2SPin, LOW);
digitalWrite(M3SPin, LOW);
digitalWrite(M4SPin, LOW);
delayMicroseconds(speeddelay);
}
void left()
{
// Motor 2 - Clockwise Step // Motor 1 - Clockwise Step
// Motor 3 - C-Clockwise Step // Motor 4 - C-Clockwise Step
// Set Directions
digitalWrite(M1DPin, HIGH); // Clockwise
digitalWrite(M2DPin, HIGH); // Clockwise
digitalWrite(M3DPin, LOW); // C-Clockwise
digitalWrite(M4DPin, LOW); // C-Clockwise
// Low
digitalWrite(M1SPin, LOW);
digitalWrite(M2SPin, LOW);
digitalWrite(M3SPin, LOW);
digitalWrite(M4SPin, LOW);
delayMicroseconds(STEP_DELAY);
// High
digitalWrite(M1SPin, HIGH);
digitalWrite(M2SPin, HIGH);
digitalWrite(M3SPin, HIGH);
digitalWrite(M4SPin, HIGH);
delayMicroseconds(STEP_DELAY);
// Low
digitalWrite(M1SPin, LOW);
digitalWrite(M2SPin, LOW);
digitalWrite(M3SPin, LOW);
digitalWrite(M4SPin, LOW);
delayMicroseconds(speeddelay);
}
void right()
{
// Motor 2 - C-Clockwise Step // Motor 1 - C-Clockwise Step
// Motor 3 - Clockwise Step // Motor 4 - Clockwise Step
// Set Directions
digitalWrite(M1DPin, LOW); // C-Clockwise
digitalWrite(M2DPin, LOW); // C-Clockwise
digitalWrite(M3DPin, HIGH); // Clockwise
digitalWrite(M4DPin, HIGH); // Clockwise
// Low
digitalWrite(M1SPin, LOW);
digitalWrite(M2SPin, LOW);
digitalWrite(M3SPin, LOW);
digitalWrite(M4SPin, LOW);
delayMicroseconds(STEP_DELAY);
// High
digitalWrite(M1SPin, HIGH);
digitalWrite(M2SPin, HIGH);
digitalWrite(M3SPin, HIGH);
digitalWrite(M4SPin, HIGH);
delayMicroseconds(STEP_DELAY);
// Low
digitalWrite(M1SPin, LOW);
digitalWrite(M2SPin, LOW);
digitalWrite(M3SPin, LOW);
digitalWrite(M4SPin, LOW);
delayMicroseconds(speeddelay);
}
void forwardLeft()
{
// Motor 2 - Disabled // Motor 1 - Clockwise Step
// Motor 3 - C-Clockwise Step // Motor 4 - Disabled
// Set Directions
digitalWrite(M1DPin, HIGH); // Clockwise
digitalWrite(M3DPin, LOW); // C- Clockwise
// Low
digitalWrite(M1SPin, LOW);
digitalWrite(M3SPin, LOW);
delayMicroseconds(STEP_DELAY);
// High
digitalWrite(M1SPin, HIGH);
digitalWrite(M3SPin, HIGH);
delayMicroseconds(STEP_DELAY);
// Low
digitalWrite(M1SPin, LOW);
digitalWrite(M3SPin, LOW);
delayMicroseconds(speeddelay);
}
void forwardRight()
{
// Motor 2 - C-Clockwise step // Motor 1 - Disabled
// Motor 3 - Disabled // Motor 4 - Clockwise step
// Set Directions
digitalWrite(M2DPin, LOW); // C-Clockwise
digitalWrite(M4DPin, HIGH); // Clockwise
// Low
digitalWrite(M2SPin, LOW);
digitalWrite(M4SPin, LOW);
delayMicroseconds(STEP_DELAY);
// High
digitalWrite(M2SPin, HIGH);
digitalWrite(M4SPin, HIGH);
delayMicroseconds(STEP_DELAY);
// Low
digitalWrite(M2SPin, LOW);
digitalWrite(M4SPin, LOW);
delayMicroseconds(speeddelay);
}
void backwardLeft()
{
// Motor 2 - Clockwise step // Motor 1 - Disabled
// Motor 3 - Disabled // Motor 4 - C-Clockwise step
// Set Directions
digitalWrite(M2DPin, HIGH); // Clockwise
digitalWrite(M4DPin, LOW); // C-Clockwise
// Low
digitalWrite(M2SPin, LOW);
digitalWrite(M4SPin, LOW);
delayMicroseconds(STEP_DELAY);
// High
digitalWrite(M2SPin, HIGH);
digitalWrite(M4SPin, HIGH);
delayMicroseconds(STEP_DELAY);
// Low
digitalWrite(M2SPin, LOW);
digitalWrite(M4SPin, LOW);
delayMicroseconds(speeddelay);
}
void backwardRight()
{
// Motor 2 - Disabled // Motor 1 - C-Clockwise
// Motor 3 - Clockwise // Motor 4 - Disabled
// Set Directions
digitalWrite(M1DPin, LOW); // C-Clockwise
digitalWrite(M3DPin, HIGH); // Clockwise
// Low
digitalWrite(M1SPin, LOW);
digitalWrite(M3SPin, LOW);
delayMicroseconds(STEP_DELAY);
// High
digitalWrite(M1SPin, HIGH);
digitalWrite(M3SPin, HIGH);
delayMicroseconds(STEP_DELAY);
// Low
digitalWrite(M2SPin, LOW);
digitalWrite(M4SPin, LOW);
delayMicroseconds(speeddelay);
}
void disableMotors()
{
digitalWrite(M1EPin, 1);
digitalWrite(M2EPin, 1);
digitalWrite(M3EPin, 1);
digitalWrite(M4EPin, 1);
}
void enableMotors()
{
digitalWrite(M1EPin, 0);
digitalWrite(M2EPin, 0);
digitalWrite(M3EPin, 0);
digitalWrite(M4EPin, 0);
}
|
C
|
#include<stdio.h>
#include<string.h>
#define max(x,y)(x > y? x:y)
int dp[102][102];
char a[103],b[103];
int main(){
int cas = 1;
while(gets(a)){
if(strcmp(a, "#") == 0)break;
gets(b);
int as = strlen(a),bs = strlen(b);
for(int i = 0; i <= as;++i) dp[0][i] = 0;
for(int i = 0; i <= bs;++i) dp[i][0] = 0;
for(int i = 1; i <= as;++i){
for(int j = 1; j <= bs;++j){
dp[i][j] = max(dp[i][j-1],dp[i-1][j]);
if(a[i-1] == b[j-1])
dp[i][j] = max(dp[i][j], dp[i-1][j-1]+1);
}
}
printf("Case #%d: you can visit at most %d cities.\n",cas++,dp[as][bs]);
}
return 0;
}
|
C
|
#include <stdio.h>
void minMax(int arr[], int size, int *min, int *max);
int main() {
int n;
printf("How many numbers?\n");
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int min, max;
minMax(arr, n, &min, &max);
printf("min=%d, max=%d\n", min, max);
return 0;
}
void minMax(int arr[], int size, int *refMin, int *refMax) {
int min = arr[0];
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] < min) {
min = arr[i];
}
if (arr[i] > max) {
max = arr[i];
}
}
*refMin = min;
*refMax = max;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
//#include "time_functions.h"
#include "setpath_defs.h"
void read_chars(FILE *fp,FILE *outfp);
void read_lines(FILE *fp,FILE *outfp);
int main(int argc, char *argv[]){
FILE *fp;
FILE *outfp;
char buff[80];
if (argc != 3){
printf("Usage: %s filename mode\n", argv[0]);
}
setpath(); // must invoke before doing any IO (what are file names for getting fp?)
// open input and output files
if ((fp = fopen(argv[1],"r")) == NULL){
printf("Can't open %s\n", argv[1]);
return 1;
}
setvbuf(fp,buff,_IONBF,80);
outfp = fopen("outfile.txt","w"); // CHANGE
setvbuf(outfp,buff,_IONBF,80);
//request mode for program to use
int mode = atoi(argv[2]);
if(mode==0){
//start_timing();
read_chars(fp,outfp);
//stop_timing();
}
else if(mode==1){
//start_timing();
read_lines(fp,outfp);
//stop_timing();
}
else {
printf("Incorrect mode input, mode must be either '1' for line-by-line modeor '0' for character-by-character mode");
return 1;
}
//close files
fclose(fp);
fclose(outfp);
//compute and display times
//double x = get_wall_clock_dif(); //wall clock difference
//int y = get_nanodiff(); //CPU clock difference
double x = 0.00;
int y = 0;
printf("Wall clock time: %f\nCPU time: %d\n",x,y);
//pause311();
return 0;
}
//Function 1 - character-by-character mode
void read_chars(FILE *fp, FILE *outfp){
int ch;
while ((ch = getc(fp)) != EOF) {
putc(ch, outfp);
}
printf("finished reading characters\n");
}
//Function 2 - line-by-line mode
void read_lines(FILE *fp, FILE *outfp){
char line[80];
while (fgets(line,sizeof(line),fp) != NULL) {
fputs(line,outfp);
}
printf("finished reading lines\n");
}
#include "setpath_fn.h"
|
C
|
//
// main.c
// Proj1
//
// Created by Tony on 6/28/16.
// Copyright © 2016 Anthony Cavallo. All rights reserved.
// This program uses the Blowfish encryption algorithm to encrypt a message from stdin with a key as one of the command-line inputs.
#include "blow.h"
//This comment is added solely to test if GitHub is actually counting my commits.
int main(int argc, const char * argv[]) {
unsigned long key = strtol(argv[1], NULL, 16);
// printf("The key is %lu\n", key);
splitKey(key);
unsigned long count = 0;
char *msg;// = "This is a test.\nIt is not a very good test.\nBut a test nontheless.\n";
int i = 0;
msg = malloc(sizeof(char *));
char words[1024];
while((fgets(words,1024,stdin)) != NULL) {
// printf("%lu\n", strlen(words));
//Since we don't know how big the message actually is, we just keep reallocating memory to msg for the current size plus whatever is coming in next.
msg = realloc(msg, strlen(msg) + strlen(words));
//After which we concatenate the previous message with what just came in from stdin.
strcat(msg, words);
i++;
}
unsigned int L = 0, R = 0;
// printf("L = %u\tR = %u\tstrlen(msg) = %lu\n", L, R, strlen(msg));
// printf("%lu\n", (strlen(msg) % 8));
//We have to get an accurate count of how big the message is. That way, we can extend the count to pad the message with 0's to the next byte.
if(strlen(msg) % 8 == 0) {
count = strlen(msg);
} else {
count = strlen(msg) / 8 + 1;
count *= 8;
}
// printf("count = %lu\n", count);
//With this for loop, we iterate through the entire message, along with any additional bytes up to the next mod 8 if necessary to ensure that we are packing with zeroes.
int index = 0;
for(i = 0; i < count; i++) {
//I think this is where I messed up originally. This was after the index increment, which means that it would only get 7 bytes or so before resetting. Maybe not, I'll have to ask Schulte later.
if(index >= 8) {
// printf("L = %x\n", L);
// printf("R = %x\n", R);
index = 0;
magicHappens(L, R, 1);
L = 0; R = 0;
}
if(i < strlen(msg)) {
// printf("index = %i\n", index);
if(index < 4) {
// printf("Byte: %x\tShifted: %x\n", msg[i], msg[i] << 8);
L = L | msg[i];
if(index != 3)
L <<= 8;
} else {
// printf("Byte: %x\tShifted: %x\n", msg[i], msg[i] << 8);
R = R | msg[i];
if(index != 7)
R <<= 8;
}
index++;
} else {
//We need to account for any of the leftover bytes. Therefore, we need to shift left, to pack with 0s, anything that isn't there. First we check to see if the index is less than 4, otherwise we can skip L and move straight to R.
if(index < 4) {
L <<= 8 * (4 - index);
R = 0;
} else {
//Now, we need to shift over R by the number of missing bytes. Since we're doing bit shifting, we need to multiply the missing bits by 8 after subtracting from the total it could be, i.e. 8.
R <<= 8 * (8 - index);
}
magicHappens(L, R, 1);
break;
}
}
//print(msg);
free(msg); //Don't forget to free memory with char stars
return 0;
}
//Useless leftover method I didn't feel like deleting. It's just too pretty.
void print(char * msg) {
int i;
for(i = 0; i < strlen(msg); i++) {
printf("%c", msg[i]);
}
}
|
C
|
/*
** EPITECH PROJECT, 2020
** NWP_myteams_2019
** File description:
** load_message
*/
#include <stdlib.h>
#include "my_message.h"
#include "definitions.h"
int load_message(server_t *server, char **words)
{
uuid_t sender_uuid;
uuid_t receiver_uuid;
message_t *message;
uuid_parse(words[1], sender_uuid);
uuid_parse(words[2], receiver_uuid);
message = create_message(sender_uuid, receiver_uuid, words[4]);
if (message == NULL) {
return (-1);
}
message->sent_time = atol(words[3]);
add_message_to_list(message, &server->messages);
return (0);
}
|
C
|
#include "main.h"
/**
* *_memcpy - The _memcpy() function copies n bytes
* * from memory area src to memory area dest
* *@dest:area where bytes are copied to
* *@src:area where bytes are copied from
* *@n:number of bytes to copy
* *Return: returns a pointer to n
* */
char *_memcpy(char *dest, char *src, unsigned int n)
{
unsigned int i = 0;
for (; i < n; i++)
dest[i] = src[i];
return (dest);
}
|
C
|
/******************************************************************************
* FILE : domain.c
* AUTHOR : Joshua Miller
* DESCRIPTION : Structures and functions for the domain
******************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <math.h>
#include "domain.h"
#include "libjosh/libjosh.h"
#include "params.h"
#define FCONV 1.0e1
domain *domain_new(double x, double y, double z)
{
srand(12345);
domain *new = (domain*)malloc(sizeof(domain));
new->dim[0] = x;
new->dim[1] = y;
new->dim[2] = z;
for (int i = 0; i < 3; i ++){
new->v0[i] = 0;
new->boundary[i] = REFLECTING;
}
LOG("Created domain %.2f x %.2f x %.2f", x, y, z);
new->npart = 0;
return new;
}
int domain_set_boundary(domain *dm, int id, boundary_t b){
return dm->boundary[id] = b;
}
double randomd(double min, double max)
{
return (rand()/(double)RAND_MAX)*max + min;
}
double norm(double *a)
{
double norm = 0;
for (int d = 0; d < 3; d++){
norm += a[d]*a[d];
}
return sqrt(norm);
}
void normalize(double *a, double m)
{
double n = norm(a);
for (int d = 0; d < 3; d++)
a[d] *= m/n;
}
void allocate_dm(domain *dm, int n)
{
dm->npart = n;
LOG("Populating domain [%p] with [%d] particles", dm, n);
ERROR_IF(!(dm->r = malloc(n*VECSIZE)),
"Unable to allocate positions");
ERROR_IF(!(dm->oldr = malloc(n*VECSIZE)),
"Unable to allocate old positions");
ERROR_IF(!(dm->oldmu = malloc(n*VECSIZE)),
"Unable to allocate old positions");
ERROR_IF(!(dm->v = malloc(n*VECSIZE)),
"Unable to allocate old positions");
ERROR_IF(!(dm->F = malloc(n*VECSIZE)),
"Unable to allocate old positions");
ERROR_IF(!(dm->T = malloc(n*VECSIZE)),
"Unable to allocate old positions");
ERROR_IF(!(dm->temp = malloc(n*VECSIZE)),
"Unable to allocate buffer space");
ERROR_IF(!(dm->tempmu = malloc(n*VECSIZE)),
"Unable to allocate buffer space");
ERROR_IF(!(dm->mu = malloc(n*VECSIZE)),
"Unable to allocate buffer space");
ERROR_IF(!(dm->E = malloc(n*sizeof(double))),
"Unable to allocate buffer space: E");
ERROR_IF(!(dm->magnetic = malloc(n*sizeof(unsigned char))),
"Unable to allocate buffer space: mag");
ERROR_IF(!(dm->pr = malloc(3*sizeof(double))),
"Unable to allocate buffer space: mag");
ERROR_IF(!(dm->oldpr = malloc(3*sizeof(double))),
"Unable to allocate buffer space: mag");
ERROR_IF(!(dm->pF = malloc(3*sizeof(double))),
"Unable to allocate buffer space: mag");
}
int domain_populate(domain *dm, int n)
{
allocate_dm(dm, n);
double r = pow(dm->npart, 1/3.);
vec cell = {dm->dim[0]/r, dm->dim[1]/r, dm->dim[2]/r};
LOG("Cube discretization count: %f", r);
for (int j = 0; j < 3; j ++)
LOG("Particle discretization distance: %f", cell[j]);
dm->pr[0] = dm->dim[0] + 10;
dm->pr[1] = dm->dim[1] / 2.;
dm->pr[2] = dm->dim[2] / 2;
dm->pFave = 0;
dm->pR = 5;
for (int d = 0; d < 3; d ++){
dm->oldpr[d] = dm->pr[d];
dm->F[d] = 0;
}
int m = 0;
for (double i = 0; i < ceil(r); i++){
for (int j = 0; j < ceil(r); j++){
for (int k = 0; k < ceil(r); k++){
if (randomd(0., 1.) < ratio){
dm->magnetic[m] = 1;
for (int d = 0; d < 3; d++){
dm->mu[3*m+d] = randomd(-1., 2.);
}
normalize(dm->mu+3*m, MU);
for (int d = 0; d < 3; d++){
dm->oldmu[3*m+d] = dm->mu[3*m+d];
}
} else {
for (int d = 0; d < 3; d++)
dm->mu[3*m+d] = 0.;
}
dm->oldr[3*m+0] = (i+.5)*cell[0];
dm->oldr[3*m+1] = (j+.5)*cell[1];
dm->oldr[3*m+2] = (k+.5)*cell[2];
for (int d = 0; d < 3; d ++){
double scale = 10;
dm->v[3*m+d] = randomd(-scale, 2*scale) + dm->v0[d];
dm->r[3*m+d] = dm->oldr[3*m+d] + dm->v[3*m+d]*dt;
}
m++;
if (m >= dm->npart) break;
}
if (m >= dm->npart) break;
}
if (m >= dm->npart) break;
}
LOG("Populated domain with %d particles", m);
return m;
}
int domain_set_v0(domain *dm, double x, double y, double z)
{
LOG("Setting initial velocity to [%.3f, %.3f, %.3f]", x, y, z);
dm->v0[0] = x;
dm->v0[1] = y;
dm->v0[2] = z;
return 0;
}
double dist(domain *dm, int m, int n, vec r)
{
double temp = 0;
for (int d = 0; d < 3; d ++){
r[d] = dm->r[3*m+d] - dm->r[3*n+d];
r[d] = r[d] - (dm->boundary[d] == PERIODIC)*
dm->dim[d]*rint(r[d]/dm->dim[d]);
temp += r[d]*r[d];
}
return sqrt(temp);
}
double dot(double *a, double *b)
{
double res = 0;
for (int d = 0; d < 3; d++)
res += a[d]*b[d];
return res;
}
void cross(double *a, double *b, vec c)
{
c[0] = a[2]*b[3] - a[3]*b[2];
c[1] = a[3]*b[1] - a[1]*b[3];
c[2] = a[1]*b[2] - a[2]*b[1];
}
void force_DipoleDipole(domain *dm, int m)
{
if (!dm->magnetic[m])
return;
vec r = {0,0,0};
double f;
for (int j = 0; j < dm->npart; j++){
double rmj = dist(dm, m, j, r);
for (int d = 0; d < 3; d ++){
if (j!=m){
double mj = dot(dm->mu+3*m, dm->mu+3*j);
double mr = dot(dm->mu+3*m, r);
double jr = dot(dm->mu+3*j, r);
f = mj*r[d]/rmj;
f -= 5*mr*jr*r[d]/pow(rmj,3);
f += (mr*dm->mu[3*j+d] + jr*dm->mu[3*m+d])/rmj;
f *= 3/(4*PI*MU_0*pow(rmj,4))*1e2;
dm->F[3*m+d] += f;
}
}
}
}
void force_DLVO(domain *dm, int m)
{
for (int i = 0; i < dm->npart; i++){
if (i!=m){
vec res;
double r = dist(dm, m, i, res);
double C = 3*MU_S*MU_S/(4*PI*MU_0*pow(2*R, 4));
double f = C*exp(-40*(r - 2*R));
dm->E[m] += C*exp(-40*r)*exp(40*2*R)*(40*r+1)/(r*r);
for (int d = 0; d < 3; d++)
dm->F[3*m+d] += res[d]/r*f;
}
}
}
void force_DLVO_Projectile(domain *dm)
{
for (int m = 0; m < dm->npart; m++){
vec res;
double r = 0;
for (int d = 0; d < 3; d ++){
res[d] = dm->pr[d] - dm->r[3*m+d];
r += res[d]*res[d];
}
double C = 3*MU_S*MU_S/(4*PI*MU_0*pow(2*R, 4));
double f = C*exp(-40*(r - R - dm->pR));
for (int d = 0; d < 3; d++)
dm->pF[d] += res[d]/r*f;
}
dm->pFave += dm->pF[0];
}
void force_DLVO_Proj_Part(domain *dm, int m)
{
for (int i = 0; i < dm->npart; i++){
if (i!=m){
vec res;
res[0] = dm->r[3*m+0] - dm->pr[0];
res[1] = dm->r[3*m+1] - dm->pr[1];
res[2] = dm->r[3*m+2] - dm->pr[2];
double r = norm(res);
double C = 3*MU_S*MU_S/(4*PI*MU_0*pow(2*R, 4));
double f = C*exp(-40*(r - R - dm->pR));
dm->E[m] += C*exp(-40*r)*exp(40*2*R)*(40*r+1)/(r*r);
for (int d = 0; d < 3; d++)
dm->F[3*m+d] += res[d]/r*f;
}
}
}
void force_drag(domain *dm, int m)
{
for (int d = 0; d < 3; d++)
dm->F[3*m+d] -= dm->v[3*m+d]*1.5e-2*R;
}
void check_boundary(domain *dm, int m)
{
for (int d = 0; d < 3; d ++){
if (dm->boundary[d] == PERIODIC){
if (dm->r[3*m+d] > dm->dim[d]){
dm->r[3*m+d] -= dm->dim[d];
dm->oldr[3*m+d] = dm->oldr[3*m+d] - dm->dim[d];
} else if (dm->r[3*m+d] < 0) {
dm->r[3*m+d] += dm->dim[d];
dm->oldr[3*m+d] = dm->oldr[3*m+d] + dm->dim[d];
}
} else if (dm->boundary[d] == REFLECTING) {
if (dm->r[3*m+d] > dm->dim[d]){
dm->r[3*m+d] = 2*dm->dim[d] - dm->r[3*m+d];
dm->oldr[3*m+d] = 2*dm->dim[d] - dm->oldr[3*m+d];
}
if (dm->r[3*m+d] < 0) {
dm->r[3*m+d] *= -1;
dm->oldr[3*m+d] *= -1;
}
}
}
}
void torque_DipoleDipole(domain *dm, int m)
{
if (!(dm->mu[3*m] || dm->mu[3*m+1] || dm->mu[3*m+2]))
return;
vec r, mxj, mxr;
double t;
for (int j = 0; j < dm->npart; j++){
if (j!=m){
double rmj = dist(dm, m, j, r);
cross(dm->mu+3*m, dm->mu+3*j, mxj);
cross(dm->mu+3*m, r, mxr);
double jr = dot(dm->mu+3*j, r);
for (int d = 0; d < 3; d ++){
t = mxj[d];
t -= 3/(rmj*rmj)*jr*mxr[d];
dm->T[3*m+d] += t;
}
}
}
}
void torque_H(domain *dm, int m)
{
vec M = {0,-H, 0};
vec t = {0, 0, 0};
cross(dm->mu+3*m, M, t);
for (int d = 0; d < 3; d++)
dm->T[3*m+d] += t[d]*1e3;
}
void calculate_torque(domain *dm, int m)
{
for (int d = 0; d < 3; d++)
dm->T[3*m+d] = 0;
torque_DipoleDipole(dm, m);
torque_H(dm, m);
return;
}
int calculate_force(domain *dm, int m)
{
dm->E[m] = 0;
for (int d = 0; d < 3; d++)
dm->F[3*m+d] = 0;
force_DLVO(dm, m);
force_DipoleDipole(dm, m);
force_DLVO_Proj_Part(dm, m);
force_drag(dm, m);
return 0;
}
int update_angles(domain *dm, int a, int b)
{
for (int m = a; m < b; m++){
if (dm->magnetic[m]){
calculate_torque(dm, m);
for (int d = 0; d < 3; d++){
dm->tempmu[3*m+d] = 2*dm->mu[3*m+d] - dm->oldmu[3*m+d]
+ dm->T[3*m+d]*10*dt*dt;
}
normalize(dm->tempmu+3*m, MU);
}
}
return 0;
}
int update_positions(domain *dm, int a, int b)
{
/* update the particles */
for (int m = a; m < b; m++){
calculate_force(dm, m);
for (int d = 0; d < 3; d++){
dm->temp[3*m+d] = 2*dm->r[3*m+d] - dm->oldr[3*m+d]
+ dm->F[3*m+d]*FCONV*dt*dt;
dm->v[3*m+d] = (dm->temp[3*m+d] - dm->oldr[3*m+d])/(2*dt);
dm->E[m] += dot(dm->v+3*m, dm->v+3*m)*.5;
}
}
return 0;
}
int checkpoint_count = 0;
int print_checkpoint(char *basepath, domain *dm){
char path[1028];
checkpoint_count++;
sprintf(path, "%s/chk_%05d.dat", basepath, checkpoint_count);
FILE *chkpnt = fopen(path, "w");
sprintf(path, "%s/mag_%05d.dat", basepath, checkpoint_count);
FILE *magchkpnt = fopen(path, "w");
WARN_IF(!chkpnt, "Unable to open checkpoint file [%s]", path);
sprintf(path, "%s/proj_%05d.dat", basepath, checkpoint_count);
for (int m = 0; m < dm->npart; m++){
for (int d = 0; d < 3; d++)
fprintf(chkpnt, "%f\t", dm->r[3*m+d]);
for (int d = 0; d < 3; d++)
fprintf(chkpnt, "%f\t", dm->mu[3*m+d]);
fprintf(chkpnt, "%d\t", dm->magnetic[m]);
fprintf(chkpnt, "\n");
if (dm->magnetic[m]){
for (int d = 0; d < 3; d++)
fprintf(magchkpnt, "%f\t", dm->r[3*m+d]);
for (int d = 0; d < 3; d++)
fprintf(magchkpnt, "%f\t", fabs(dm->mu[3*m+d]));
fprintf(magchkpnt, "\n");
}
}
FILE *proj = fopen(path, "w");
WARN_IF(!chkpnt, "Unable to open checkpoint file [%s]", path);
/* for (int m = 0; m < 5; m ++){ */
for (int d = 0; d < 3; d++)
fprintf(proj, "%f\t", dm->pr[d]);
fprintf(proj, "%f\n", norm(dm->pF));
/* } */
fclose(chkpnt);
fclose(magchkpnt);
fclose(proj);
return 0;
}
|
C
|
#include "be_mem.h"
#include "berry.h"
#include <stdlib.h>
#define os_malloc( size ) malloc( size )
#define os_free( ptr ) free( ptr )
#define os_realloc( ptr, size ) realloc( ptr, size )
#define addr_pos( a, p, o ) ( (void *) ( (size_t) (a) o( p ) ) )
#define addr_region( a, s ) addr_pos( ( a ), sizeof( s ), + )
#define addr_base( a, s ) addr_pos( ( a ), sizeof( s ), - )
typedef struct
{
size_t use;
} memlist;
typedef struct
{
size_t size;
} mdesc;
static memlist mlist = { .use = 0 };
void *
be_malloc( size_t size )
{
mdesc * obj = os_malloc( size + sizeof( mdesc ) );
if ( obj != NULL )
{
obj->size = size;
mlist.use += size;
return( addr_region( obj, mdesc ) );
}
return( NULL );
}
void
be_free( void * ptr )
{
if ( ptr != NULL )
{
mdesc * obj = addr_base( ptr, mdesc );
mlist.use -= obj->size;
os_free( obj );
}
}
void *
be_realloc( void * ptr, size_t size )
{
if ( ptr != NULL )
{
mdesc * obj, * old = addr_base( ptr, mdesc );
mlist.use = mlist.use + size - old->size;
obj = (mdesc *) os_realloc( old, size + sizeof( mdesc ) );
if ( obj != NULL )
{
obj->size = size;
return( addr_region( obj, mdesc ) );
}
os_free( old );
return( NULL );
}
return( be_malloc( size ) );
}
size_t
be_mcount( void )
{
return( mlist.use );
}
|
C
|
/*
24. int eval(char *s);
A simple stack-based expression evaluator. The input string contains expression in Reverse Polish
Notation with four possible arithmetic operators (+, -, *, /) and integer decimal numbers. The routine
should return integer result of expression. Assume that all input numbers fit in 32 bits, handle
arithmetic overflow and underflow by saturating the result to MAXINT or MININT as appropriate.
*/
#include <stdio.h>
extern int eval(char *s);
int main(int argc, char *argv[])
{
printf("Expression to be evaluated: %s\n", argv[1]);
printf("Result: %d\n\n", eval(argv[1]));
}
|
C
|
#ifdef RaspberryPi
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdint.h> //uint8_t definitions
#include <errno.h> //error output
#include <stdlib.h> //for exit(int);
#include <wiringPi.h>
#include <wiringSerial.h>
void loop(void);
void setup(void);
void append(char *dst, char c);
char device[] = "/dev/ttyACM0";
// filedescriptor
int fd;
unsigned long baud = 9600;
unsigned long time = 0;
#define TCP_PORT 8088
#define BUFSIZE 1024
int main(int argc, char **argv) {
setup();
int sockfd;
struct sockaddr_in server_addr;
char buf[BUFSIZE];
if(argc < 2) {
printf("usage : %s IP_ADDRESS\n", argv[0]);
return -1;
}
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket()");
return -1;
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
inet_pton(AF_INET, argv[1], &(server_addr.sin_addr.s_addr));
server_addr.sin_port = htons(TCP_PORT);
if(connect(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
perror("connect()");
return -1;
}
while(1) {
memset(buf, 0, BUFSIZE);
char emptySTR[BUFSIZE];
strcpy(buf, emptySTR);
if (millis() - time >= 1000){
serialPuts(fd, "Pong!\n");
serialPutchar(fd, 65);
time = millis();
}
// read signal
if (serialDataAvail(fd)){
while(1) {
char newChar = serialGetchar(fd);
append(buf, newChar);
if(newChar == '\n') {
break;
}
}
if(send(sockfd, buf, BUFSIZE, MSG_DONTWAIT) <= 0) {
perror("send()");
break;
}
memset(buf, 0, BUFSIZE);
if(recv(sockfd, buf, BUFSIZE, 0) <= 0) {
perror("recv()");
return -1;
}
printf("Sending message... %s", buf);
if(strncmp(buf, "q", 1) == 0) {
break;
}else if(strncmp(buf,"on",2)==0){
system("sudo python3 test.py on");
}else if(strncmp(buf,"off",3)==0){
system("sudo python3 test.py off");
}
fflush(stdout);
}
}
close(sockfd);
return 0;
}
void setup(){
printf("%s \n", "Raspberry Startup!");
fflush(stdout);
//get filedescriptor
if ((fd = serialOpen(device, baud)) < 0){
fprintf(stderr, "Unable to open serial device: %s\n", strerror(errno));
exit(1); //error
}
//setup GPIO in wiringPi mode
if (wiringPiSetup() == -1){
fprintf(stdout, "Unable to start wiringPi: %s\n", strerror(errno));
exit(1); //error
}
}
void append(char *dst, char c) {
char *p = dst;
while (*p != '\0') p++; // 문자열 끝 탐색
*p = c;
*(p+1) = '\0';
}
#endif //#ifdef RaspberryPi
|
C
|
#include <stdio.h>
int main()
{
int c;
int space_num, table_num, return_num;
space_num = table_num = return_num = 0;
printf("the value of EOF is %d\n", EOF);
while ((c = getchar()) != EOF) {
putchar(c);
if (c == ' ')
space_num ++;
else if (c == '\t')
table_num ++;
else if (c == '\n')
return_num ++;
}
printf("space: %d, table: %d, return: %d\n", space_num, table_num, return_num);
}
|
C
|
#include "http_accept.h"
#include <pthread.h>
void *wait_task(void *arg)
{
int epfd = *(int *)arg;
struct epoll_event *job = NULL;
job = (struct epoll_event *)malloc(sizeof(struct epoll_event) * 1024);
if(job == NULL)
{
perror("malloc job list fail!\n");
pthread_exit(NULL);
}
while(1)
{
int n;
if((n = epoll_wait(epfd, job, 1024, -1)) < 0)
{
perror("epoll wait failed!\n");
continue;
}
for(int i = 0; i < n; ++i)
{
struct http_request *ptr = (struct http_request *)job[i].data.ptr;
if(job[i].events == EPOLLIN)
{
http_recv(ptr, epfd);
}
else if(job[i].events == EPOLLOUT)
{
http_send(ptr, epfd);
}
}
}
free(job);
pthread_exit(NULL);
}
void http_recv(struct http_request *ptr, int epfd)
{
char buf[10240];
int fd = ptr -> fd;
size_t n = recv(fd, buf, 10240, 0);
//printf("%s", buf);
if(n < 0)
{
perror("recv fail\n");
free(ptr);
close(fd);
}
else if(n == 0)
{
perror("connect close!\n");
free(ptr);
close(fd);
}
else
{
int i = 0, j = 0;
while(buf[i] == ' ' && buf[i] != '\0')
i++;
while(buf[i] != ' ' && buf[i] != '\0')
{
ptr -> method[j] = buf[i];
i++;
j++;
}
ptr -> method[j] = '\0';
strcpy(ptr -> path, "../page");
while(buf[i] == ' ' && buf[i] != '\0')
i++;
j = 7;
while(buf[i] != ' ' && buf[i] != '\0')
{
ptr -> path[j] = buf[i];
i++;
j++;
}
ptr -> path[j] = '\0';
if(strstr(buf, "keep-alive") != NULL || strstr(buf, "Keep-Alive") != NULL)
ptr -> alive = 1;
//http_send(ptr, epfd);
epoll_mod(epfd, ptr, EPOLLOUT);
//printf("method:%s\n", ptr -> method);
//printf("path:%s\n", ptr -> path);
//printf("alive:%d\n", ptr -> alive);
}
return ;
}
void http_send(struct http_request *ptr, int epfd)
{
//printf("%d\n", ptr->alive);
if(strcmp(ptr -> method, "GET") != 0)
{
request_stat(ptr -> fd, 405);
if(ptr -> alive == 1)
{
epoll_mod(epfd, ptr, EPOLLIN);
}
else
{
close(ptr -> fd);
free(ptr);
}
}
else
{
char *path = ptr -> path;
int l = strlen(path);
if(path[l - 1] == '/')
{
strcat(path , "index.html");
}
Sendfile(ptr -> fd, path);
if(ptr -> alive == 1)
{
epoll_mod(epfd, ptr, EPOLLIN);
}
else
{
close(ptr -> fd);
free(ptr);
}
}
return ;
}
void Sendfile(int fd, char *path)
{
//printf("sendfile:%s\n", path);
struct stat st;
int l = strlen(path);
char line[1024];
char header[1024];
if(stat(path, &st) == 0)
{
if(S_ISREG(st.st_mode))
{
int filefd = open(path, O_RDONLY);
strcpy(line, line200);
if(strcasecmp(&path[l - 4], ".jpg") == 0)
{
sprintf(header, imgheader , st.st_size);
}
else
{
sprintf(header, htmlheader, st.st_size);
}
strcat(line, header);
write(fd, line, strlen(line));
sendfile(fd, filefd, NULL, st.st_size);
close(filefd);
}
else
{
request_stat(fd, 404);
}
}
else
{
request_stat(fd, 404);
}
return ;
}
void request_stat(int fd, int stat)
{
char line[1024];
char header[1024];
if(stat == 404)
{
strcpy(line, line404);
}
else if(stat == 405)
{
strcpy(line, line405);
}
else if(stat == 500)
{
strcpy(line, line500);
}
sprintf(header, htmlheader, 0);
strcat(line, header);
write(fd, line, strlen(line));
return ;
}
|
C
|
/*
** my_file_tomatrix.c for wireframe in /home/antonin.rapini/ModulesTek1/GraphicalProgramming/wireframe/utils
**
** Made by Antonin Rapini
** Login <antonin.rapini@epitech.net>
**
** Started on Sat Dec 3 20:14:52 2016 Antonin Rapini
** Last update Tue Jan 3 18:44:15 2017 Antonin Rapini
*/
#include <stdlib.h>
#include <unistd.h>
#include "my_game.h"
#include "utils.h"
int my_create_line(t_game *game, int j, int i)
{
if ((game->map.map[j] = malloc(sizeof(int) * (i + 1))) == NULL)
return (1);
game->map.map[j][i] = -1;
return (0);
}
int my_fillmap(char *file, t_game *game)
{
char *old_i;
int i;
int j;
j = 0;
old_i = file;
while (file[i])
{
if (file[i] == '\n')
{
file[i] = '\0';
file += i + 1;
if ((my_create_line(game, j, i)))
return (1);
i = 0;
while (old_i[i++])
game->map.map[j][i - 1] = old_i[i - 1] - 48;
j++;
i = 0;
old_i = file;
}
else
i++;
}
return (0);
}
|
C
|
/*
DTMF decoder.
see also connect.txt
Just show the detected DTMF signal in a 16x2 lcd.
set timebase=10us or 50us of oszifox (test the GS port of LC7385) will show the wave clearly.
*/
#include <inttypes.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include "lcd.h"
volatile uint8_t q;
const char q_table_Hex[] PROGMEM = {
'D','1','2','3','4','5','6','7','8','9','0','*','#','A','B','C'
};
void decoder_init(void)
{
DDRD &= ~((1<<PD2)|(1<<PD4)|(1<<PD5)|(1<<PD6)|(1<<PD7));
PORTD |= ((1<<PD2)|(1<<PD4)|(1<<PD5)|(1<<PD6)|(1<<PD7));
/*
EIMSK = (1<<INT0);
EICRA = ((1<<ISC00)|(1<<ISC01));
EIFR = (1<<INTF0);
*/
//!! ATTENTION!
// here should add :
// sei();
// to enable global interrupt.
}
/*
ISR(INT0_vect)
{
cli();
nop();
q=(PIND>>4);
sei();
}
*/
int main(void)
{
unsigned char buffer[33]={'\0'};
uint8_t i=0,new=1;
decoder_init();
lcd_init(LCD_DISP_ON);
for(;;){
// use PD2 as a simple IO port.
// VERY STUPID, ONLY FOR DEBUG.
if(PIND & (1<<PD2)){
q=(PIND>>4);
if(new){
buffer[i]=pgm_read_byte(q_table_Hex+q);
i++;
buffer[i]='\0';
if(i>=32)
i=0;
lcd_clrscr();
lcd_gotoxy(0,0);
lcd_puts(buffer);
new=0;
}
}else{
new=1;
//lcd_puts("No signal\ndetected!");
}
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
int ret,p[2];
char rfd[4],wfd[4];
char msg[50] = {"HELLO THIS IS DISCRIPTOR PIPE EXAMPLE\n"};
if(pipe(p) == -1)
{
perror("pipe creation fails\n");
exit(EXIT_FAILURE);
}
ret = fork();
switch(ret){
case -1:
printf("%s: ERROR: fork failure\n"__FILE__);
break;
case 0:
printf("%s: CHILD pid: %d ppid: %d\n",__FILE__,getpid(),getppid());
sprintf(rfd,"%d",p[0]);
sprintf(wfd,"%d",p[1]);
execl("./01client","01client",rfd,wfd,NULL);
printf("%s: ERROR: EXCEL FAIL\n"__FILE__);
break;
default:
printf("%s: PARENT pid: %d ppid: %d\n",__FILE__,getpid(),getppid());
break;
}
ret = write(p[1],msg,sizeof(msg));
printf("%s: Bytes Written %d\n",__FILE__,ret);
return 0;
}
|
C
|
//P6136 5.5s
#include <stdio.h>
#include <stdlib.h>
#define INF 2147483647
struct tree
{
struct tree* ls;
struct tree* rs;
int siz,con,data,height;
};
typedef struct tree stu;
typedef struct tree* ptr;
int tot;
stu pol[1600000];
int read()
{
int q=0,w=1;
char c=getchar();
while (c>'9' || c<'0')
{
if(c=='-') w=-1;
c=getchar();
}
while (c>='0' && c<='9')
{
q=q*10+c-'0';
c=getchar();
}
return w*q;
}
int size(ptr now)
{return now?now->siz:0;}
int h(ptr now)
{return now?now->height:0;}
void pushup(ptr now)
{
if (now==NULL) return;
now->height=1;
now->siz=now->con;
now->siz+=size(now->ls);
now->siz+=size(now->rs);
if (h(now->ls)>h(now->rs))
now->height+=h(now->ls);
else now->height+=h(now->rs);
return;
}
void left(ptr* now)
{
ptr tmp=(*now)->rs;
(*now)->rs=tmp->ls;
tmp->ls=*now;
tmp->siz=(*now)->siz;
pushup(*now),pushup(tmp);
*now=tmp; return;
}
void right(ptr* now)
{
ptr tmp=(*now)->ls;
(*now)->ls=tmp->rs;
tmp->rs=*now;
tmp->siz=(*now)->siz;
pushup(*now),pushup(tmp);
*now=tmp; return;
}
void balance(ptr *now)
{
if (*now==NULL) return;
if (h((*now)->ls)-h((*now)->rs)==2)
{
if (h((*now)->ls->ls)>h((*now)->ls->rs)) right(now);
else left(&(*now)->ls),right(now); return;
}
if (h((*now)->rs)-h((*now)->ls)==2)
{
if (h((*now)->rs->rs)>h((*now)->rs->ls)) left(now);
else right(&(*now)->rs),left(now); return;
}
return;
}
void ins(ptr* now,int num)
{
if (*now==NULL)
{
*now=&pol[tot++];
(*now)->siz=(*now)->con=1;
(*now)->data=num,(*now)->height=0;
(*now)->ls=(*now)->rs=NULL; return;
}
if ((*now)->data==num)
{
(*now)->con++;
pushup(*now); return;
}
if ((*now)->data>num) ins(&(*now)->ls,num);
else ins(&(*now)->rs,num);
pushup(*now); balance(now); return;
}
void del(ptr* now,int num)
{
if (*now==NULL) return;
if ((*now)->data==num)
{
if ((*now)->con>1) (*now)->con--;
else
{
ptr cng=*now;
if ((*now)->ls==NULL) *now=(*now)->rs;
else if ((*now)->rs==NULL) *now=(*now)->ls;
else
{
cng=(*now)->rs;
while (cng->ls) cng=cng->ls;
(*now)->data=cng->data;
(*now)->con=cng->con,cng->con=1;
del(&(*now)->rs,cng->data);
}
}
}
else
{
if ((*now)->data>num) del(&(*now)->ls,num);
else del(&(*now)->rs,num);
}
pushup(*now); balance(now); return;
}
int fnd(ptr now,int num)
{
if (now==NULL) return 0;
if (now->data==num) return size(now->ls);
if (now->data>num) return fnd(now->ls,num);
return size(now->ls)+now->con+fnd(now->rs,num);
}
int kth(ptr now,int num)
{
if (now==NULL) return INF;
if (size(now->ls)>=num) return kth(now->ls,num);
if (size(now->ls)+now->con>=num) return now->data;
return kth(now->rs,num-size(now->ls)-now->con);
}
int qan(ptr now,int num,int ans)
{
if (now->data>=num)
{
if (now->ls==NULL) return ans;
return qan(now->ls,num,ans);
}
if (now->rs==NULL) return now->data;
return qan(now->rs,num,now->data);
}
int hou(ptr now,int num,int ans)
{
if (now->data<=num)
{
if (now->rs==NULL) return ans;
return hou(now->rs,num,ans);
}
if (now->ls==NULL) return now->data;
return hou(now->ls,num,now->data);
}
int main()
{
ptr root=NULL;
int n,m,x,y,ans=0,last=0;
n=read(),m=read();
while (n--)
{
x=read();
ins(&root,x);
}
while (m--)
{
x=read(),y=read(),y^=last;
if (x==1) {ins(&root,y); continue;}
if (x==2) {del(&root,y); continue;}
if (x==3)
{
last=fnd(root,y)+1;
ans^=last; continue;
}
if (x==4)
{
last=kth(root,y);
ans^=last; continue;
}
if (x==5)
{
last=qan(root,y,-INF);
ans^=last; continue;
}
if (x==6)
{
last=hou(root,y,INF);
ans^=last; continue;
}
}
printf("%d\n",ans);
return 0;
}
|
C
|
#include <time.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
/**
* Problem 16 from Project Euler
*
* 2?15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
* What is the sum of the digits of the number 2^1000?
*
* PLEASE NOTE
* In order to compile you must have gcc, or similar, installed
*
*/
#define POW (1000)
#define MIN_POW ( POW - 1)
int main(int argc,char* argv[])
{
// Benchmark variables
double start, end;
// The array of every power
unsigned int powers[POW] = {1};
// Total
unsigned int total = 0;
// Start the benchmark
start = clock();
for(unsigned short int i = 1; i <= POW; i++)
{
for(unsigned short int j = 0; j < MIN_POW; j++)
{
powers[j] *= 2;
}
for(unsigned short int j = 0; j < MIN_POW; j++)
{
if(powers[j] > 9)
{
powers[j + 1] += 1;
powers[j] %= 10;
}
}
}
// Sum all the digits
for(unsigned int i = 0; i < MIN_POW; i++)
{
total += powers[i];
}
// Algorithm end
end = clock();
printf("%d\n", total);
printf("Algorithm end.\n");
printf("Total time: %f\n", (end - start)/CLOCKS_PER_SEC);
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
static const char grepInstruction[] = " | grep -a ERROR | grep -Eao \"https?://\\S+?\\/|http?://\\S+?\\/\" > ";
static const char getInstruction[] = " && wget -i ";
static const char catInstruction[] = "cat ";
static const char defaultOutput[] = "error_urls.log";
int main(int argc, char **argv, char **env)
{
if (argc != 2)
{
printf("error, expected 1 argument, got %d\n", argc - 1);
exit(EXIT_FAILURE);
}
char *inputFile = argv[1];
// Check if file exists
FILE *file = fopen(inputFile, "rt");
if (!file)
{
printf("can't open %s\n", inputFile);
exit(EXIT_FAILURE);
}
// Compute size of buffer
size_t instructionSize =
strlen(argv[1]) + sizeof(catInstruction) +
sizeof(grepInstruction) + sizeof(getInstruction) + 2 * sizeof(defaultOutput);
char *buffer = (char *) calloc(instructionSize + 1, sizeof(char));
/* ............................
* ............................
* ............................
* */
strcat(buffer, catInstruction);
strcat(buffer, inputFile);
strcat(buffer, grepInstruction);
strcat(buffer, defaultOutput);
strcat(buffer, getInstruction);
strcat(buffer, defaultOutput);
int result = 0;
result = system(buffer);
free(buffer);
return result;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define TAM 10
struct cadJogos {
int id;
char nome[50];
char cat[20];
float tamanho;
int ano;
};
int main(int argc, char const *argv[]) {
// ponteiros para arquivos
FILE *arq1;
FILE *arq2;
FILE *ind;
// matriz que servira como Indice Denso, '2' pois tem dois campos (ID e posicao)
int matrizIndice[TAM][2];
// posicao dentro da matriz
int pos = 0;
int i, count = 0, i2, j2, op;
// referencia da struct
struct cadJogos jogos[TAM];
//count = 50 pois já existem 49 cadastros (de 0 a 49)
do {
// volta do goto
v:
menu();
printf("\n Opção: ");
scanf("%d", &op);
switch (op) {
case 1:
printf("Consultar jogo:\n");
goto v;
case 2:
printf("Atualizar/Alterar registro\n");
goto v;
case 3:
printf("Excluir jogo\n");
goto v;
case 4:
printf("\n\tCadastro\n");
int cadOp;
printf("Quantos jogos deseja cadastrar? \nR:");
scanf("%d", &cadOp);
for (i = 0; i < cadOp; i++) {
// chamada da funcao rand com valores aleatorios de 0 a 99
jogos[i].id = rand() % 99;
printf("\n Nome (sem espaços): ");
scanf("%s", &jogos[i].nome);
printf("\n Categoria (sem espaços): ");
scanf("%s", &jogos[i].cat);
printf("\n Tamanho: ");
scanf("%f", &jogos[i].tamanho);
printf("\n Ano: ");
scanf("%d", &jogos[i].ano);
// contador para futuro for
count++;
}
arq1 = fopen("cadJogos.dat", "wb");
if (arq1 == NULL) {
printf("ERRO\n");
exit(1);
}
// escrita no arquivo com as classes da struct
fwrite(&jogos[0], sizeof(struct cadJogos), cadOp, arq1);
fclose(arq1);
goto v;
case 5:
arq2 = fopen("cadJogos.dat", "rb");
//no indice denso contem as chaves ordenadas e a posicao relativa na linear no arquivo
if (arq2 == NULL) {
printf("ERRO\n");
exit(1);
}
printf("\n\n");
// leitura do cadastro dos jogos, linha por linha
fread(&jogos[0], sizeof(jogos), 1, arq2);
for (i = 0; i < TAM; i++) {
printf("\n\n");
printf(" ID = %d\n NOME = %s\n CATEGORIA = %s\n TAMANHO = %.2f GB\n ANO = %d\n", jogos[i].id, jogos[i].nome, jogos[i].cat, jogos[i].tamanho, jogos[i].ano);
}
//pegar valores e jogar em uma matriz
fclose(arq2);
goto v;
case 6:
ind = fopen("cadJogos.dat", "rb");
if (ind!=NULL)
{
// leitura para print
fread(&jogos[0], sizeof(jogos), 1, ind);
for (i2 = 0; i2 < TAM; i2++) {
// contando posicao
pos++;
printf ("\n ID ou Chave = [%d] \n Posição relativa linear no arquivo = [%d]\n",jogos[i2].id, pos);
}
pos = 0;
fclose (ind);
}
goto v;
}
} while(op != 0);
return 0;
}
void menu(){
printf("\n\n");
printf("\t\t Bem vindo.\n");
printf("\n Selecione uma das opções abaixo:\n");
printf("\n [1] Consultar um jogo;\n [2] Alterar/Atualizar um campo do jogo;\n [3] Excluir um jogo;\n [4] Inserir um jogo;\n [5] Imprimir jogos;\n [0] Sair.\n [6] Teste da matriz(Indice Denso)\n");
}
|
C
|
// scanf1.c
#include<stdio.h>
int main(int argc,char**argv)
{
int a;
printf("数を入れてください:");
scanf("%d",&a);
printf("入力された数は %d です。\n",a);
return 0;
}
|
C
|
// commit: 7e6be42a77989c01155bdc7333ea58206e1563d4 2011-03-08
// pthread_once should not deadlock
#include <pthread.h>
#include <semaphore.h>
#include <errno.h>
#include <string.h>
#include "test.h"
#define T(f) if ((r=(f))) t_error(#f " failed: %s\n", strerror(r))
#define E(f) if (f) t_error(#f " failed: %s\n", strerror(errno))
static int count;
static void init(void)
{
count++;
}
static void *start(void *arg)
{
void **a = arg;
int r;
E(sem_post(a[1]));
T(pthread_once(a[0], init));
E(sem_post(a[1]));
return 0;
}
static int deadlocked(sem_t *s)
{
struct timespec ts;
E(sem_wait(s));
E(clock_gettime(CLOCK_REALTIME, &ts));
ts.tv_nsec += 100*1000*1000;
if (ts.tv_nsec >= 1000*1000*1000) {
ts.tv_nsec -= 1000*1000*1000;
ts.tv_sec += 1;
}
errno = 0;
E(sem_timedwait(s,&ts));
if (errno != ETIMEDOUT)
return 0;
t_error("pthread_once deadlocked\n");
return 1;
}
int main(void)
{
pthread_t t1,t2,t3;
pthread_once_t once = PTHREAD_ONCE_INIT;
sem_t s1,s2,s3;
void *p;
int r;
E(sem_init(&s1,0,0));
E(sem_init(&s2,0,0));
E(sem_init(&s3,0,0));
T(pthread_create(&t1, 0, start, (void*[]){&once,&s1}));
T(pthread_create(&t2, 0, start, (void*[]){&once,&s2}));
T(pthread_create(&t3, 0, start, (void*[]){&once,&s3}));
if (!deadlocked(&s1)) T(pthread_join(t1,&p));
if (!deadlocked(&s2)) T(pthread_join(t2,&p));
if (!deadlocked(&s3)) T(pthread_join(t3,&p));
if (count != 1)
t_error("pthread_once ran init %d times instead of once\n", count);
E(sem_destroy(&s1));
E(sem_destroy(&s2));
E(sem_destroy(&s3));
return t_status;
}
|
C
|
#include "my_tar.h"
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
#include <errno.h>
#include <dirent.h>
#include <utime.h>
int tar(char** av, int fFlag, char* tarName, int* i, char* path, int mode, int ac) {
char buffer[100] = {0};
if(fFlag) {
my_strncpy(&buffer[my_strlen(buffer)], av[*i], my_strlen(av[*i]) + 1);
*i = *i + 1;
tarName = buffer;
}
switch(mode) {
case cMode:
createTar(tarName, av, path, fFlag, i, ac);
break;
case tMode:
if (*i < ac - 1) {
printf("error: only one archive file can be specified for listing\n");
return 1;
}
if(!fFlag) {
printf("error: archive -f must be specified\n");
return 1;
}
if(tarList(tarName)) return 1;
break;
case xMode:
if(!fFlag) {
printf("error: archive -f must be specified\n");
return 1;
}
if(tarExtract(tarName, path)) return 1;
break;
case rMode:
if(!fFlag) {
printf("error: archive -f must be specified\n");
return 1;
}
if(tarAppend(tarName, av, i, ac)) return 1;
break;
case uMode:
if(!fFlag) {
printf("error: archive -f must be specified\n");
return 1;
}
if(updateEntry(tarName, av, *i, ac)) return 1;
*i = ac;
break;
default:
printf("error: no mode specified\n");
return 1;
break;
}
return 0;
}
int handleOptions(char** av, char* path, int* i, int* fFlag, int* mode) {
if((*av[*i] == '-') && *(av[*i] + 1) == 'C') {
if( !(av[*i+1]) ) {
printf("error: directory not specified\n");
return 1;
}
if(!isDirectory(av[*i + 1])) {
printf("error: directory %s does not exist", av[*i + 1]);
return 1;
}
my_strncpy(path, av[*i + 1], my_strlen(av[*i + 1]) + 1);
path[my_strlen(path)] = '/';
*i = *i + 1;
}
else if(setFlags(mode, fFlag, av[*i] + 1)) {
return 1;
}
return 0;
}
int setFlags(int* mode, int* fFlag, char* flags) {
while(*flags) {
if(*mode && *flags != 'f') {
printf("error: only one mode may be specified\n");
return 1;
}
switch(*flags++) {
case 'c':
*mode = cMode;
break;
case 'r':
*mode = rMode;
break;
case 't':
*mode = tMode;
break;
case 'u':
*mode = uMode;
break;
case 'x':
*mode = xMode;
break;
case 'f':
*fFlag = 1;
break;
case 'C':
printf("C must be specified seperately\n");
break;
default:
printf("%c is not a valid option\n", *flags);
return 1;
break;
}
}
return 0;
}
void setToZero(tar_header* head) {
for(unsigned int i = 0; i < sizeof(head->name); i++) head->name[i] = '\0';
for(unsigned int i = 0; i < sizeof(head->mode); i++) head->mode[i] = '\0';
for(unsigned int i = 0; i < sizeof(head->owner); i++) head->owner[i] = '\0';
for(unsigned int i = 0; i < sizeof(head->group); i++) head->group[i] = '\0';
for(unsigned i = 0; i < sizeof(head->size); i++) head->size[i] = '\0';
for(unsigned i = 0; i < sizeof(head->modified); i++) head->modified[i] = '\0';
head->type = '\0';
head->linkNum = '\0';
for(unsigned i = 0; i < sizeof(head->link); i++) head->link[i] = '\0';
for(unsigned i = 0; i < sizeof(head->padding); i++) head->padding[i] = '\0';
}
void createFile(char* fullPath, int flags, unsigned int mode, unsigned int size, unsigned int modTime, int type, int fd) {
if(type == DIRECTORY) {
mkdir(fullPath, mode);
}
else {
char buffer[4096];
int readFile = open(fullPath, flags, mode);
writeToOffset(fd, readFile, size, buffer);
int offset = size % BLOCK_SIZE == 0 ? 0 : BLOCK_SIZE - size % BLOCK_SIZE;
lseek(fd, offset, SEEK_CUR);
close(readFile);
}
struct utimbuf* times = (struct utimbuf*)malloc(sizeof(struct utimbuf));
times->actime = modTime;
times->modtime = modTime;
utime(fullPath, times);
free(times);
}
int tarExtract(char* tarName, char* path) {
int fd = open(tarName, O_RDONLY);
if(fd == -1) {
printf("error: could not open file %s", tarName);
return 1;
}
tar_header head;
char fullPath[my_strlen(path) + sizeof(head.name) + 1];
my_strncpy(fullPath, path, my_strlen(path));
while(read(fd, &head, sizeof(tar_header))) {
struct stat fileStat;
unsigned long size = oct2num(head.size, 8, sizeof(head.size));
unsigned long modTime = oct2num(head.modified, 8, sizeof(head.modified));
unsigned int mode = oct2num(head.mode, 8, sizeof(head.mode));
my_strncpy(fullPath + my_strlen(path), head.name, sizeof(head.name));
int flags = (O_CREAT | O_WRONLY);
if(!stat(fullPath, &fileStat)) {
unsigned long time = fileStat.st_mtime;
if(modTime > time) {
flags |= O_TRUNC;
createFile(fullPath, flags, mode, size, modTime, head.type, fd);
}
else if (head.type != DIRECTORY) {
lseek(fd, size + BLOCK_SIZE - (size % BLOCK_SIZE == 0 ? BLOCK_SIZE : size % BLOCK_SIZE), SEEK_CUR);
}
}
else {
createFile(fullPath, flags, mode, size, modTime, head.type, fd);
}
}
return 0;
}
int tarList(char* tarName) {
int fd = open(tarName, O_RDONLY);
if(fd < 0) {
printf("error: archive %s does not exist\n", tarName);
return 1;
}
tar_header head;
while(read(fd, &head, sizeof(head))) {
printf("%s\n", head.name);
if(head.type != DIRECTORY) {
unsigned long size = oct2num(head.size, 8, sizeof(head.size));
lseek(fd, size + (size % BLOCK_SIZE == 0 ? 0 : BLOCK_SIZE - size % BLOCK_SIZE), SEEK_CUR);
}
}
close(fd);
return 0;
}
int tarAppend(char* tarName, char** args, int* i, int numArgs) {
int fd = open(tarName, O_RDWR, 0644);
if(fd < 0) {
printf("error: %s does not exist", tarName);
return 1;
}
lseek(fd, 0, SEEK_END);
for(; *i < numArgs; *i = *i + 1) {
if(tarAdd(fd, args[*i])) return 1;
}
close(fd);
return 0;
}
void readContents(char** dirFiles, tar_header* head) {
struct dirent *de;
DIR *dp;
dp = opendir(head->name);
int index = 0;
while((de = readdir(dp))) {
if(de->d_name[0] != '.') {
dirFiles[index] = (char*)malloc(100);
my_strncpy(dirFiles[index], head->name, my_strlen(head->name) + 1);
dirFiles[index][my_strlen(head->name)] = '/';
my_strncpy(dirFiles[index++] + my_strlen(head->name) + 1, de->d_name, my_strlen(de->d_name) + 1);
}
}
closedir(dp);
}
int updateDir(int fd, tar_header* head, struct stat fileStat, char* arg, char* tarName) {
lseek(fd, -BLOCK_SIZE, SEEK_CUR);
tar_header newDir;
writeEntry(&newDir, fileStat, arg, fd);
int fileCount = getFileCount(head->name);
if(fileCount == -1) return 1;
char** dirFiles = (char**)malloc(fileCount*sizeof(char*));
readContents(dirFiles, head);
int returnToOffset = lseek(fd, 0, SEEK_CUR);
close(fd);
if(updateEntry(tarName, dirFiles, 0, fileCount)) return 1;
freeStrings(dirFiles, fileCount);
fd = open(tarName, O_RDWR);
lseek(fd, returnToOffset, SEEK_SET);
return 0;
}
void transferContents(int readFile, int tmp, char* buffer) {
int bytes;
for(unsigned int k = 0; k < sizeof(buffer); k++) buffer[k] = '\0';
while((bytes = read(readFile, buffer, sizeof(buffer)))) {
write(tmp, buffer, bytes);
}
}
void writeToOffset(int fd, int tmp, unsigned int writeToVal, char* buffer) {
int bytes;
unsigned int totalBytes = 0;
while(totalBytes != writeToVal) {
bytes = read(fd, buffer, totalBytes + 4096 < writeToVal ? sizeof(buffer) : writeToVal - totalBytes);
write(tmp, buffer, bytes);
totalBytes += bytes;
}
}
void insertEntry(int fd, unsigned long size, struct stat fileStat, char* arg) {
unsigned int writeToVal = lseek(fd, 0, SEEK_CUR) - 512;
unsigned int writeFromVal = lseek(fd, size, SEEK_CUR);
lseek(fd, 0, SEEK_SET);
int tmp = open(tempFile, O_CREAT|O_RDWR|O_TRUNC, 0777);
char buffer[4096];
writeToOffset(fd, tmp, writeToVal, buffer);
tar_header newEntry;
writeEntry(&newEntry, fileStat, arg, tmp);
unsigned long newSize = oct2num(newEntry.size, 8, sizeof(newEntry.size));
unsigned long newOffset = (newSize % 512 == 0 ? 0 : BLOCK_SIZE - newSize % BLOCK_SIZE);
int readFile = open(arg, O_RDONLY);
transferContents(readFile, tmp, buffer);
close(readFile);
int returnToOffset = lseek(tmp, newOffset, SEEK_CUR);
lseek(fd, writeFromVal, SEEK_SET);
transferContents(fd, tmp, buffer);
lseek(tmp, 0, SEEK_SET);
lseek(fd, 0, SEEK_SET);
transferContents(tmp, fd, buffer);
close(tmp);
lseek(fd, returnToOffset, SEEK_SET);
}
int updateEntry(char *tarName, char **args, int i, int numArgs) {
char contains[numArgs - i];
for(int i = 0; i < (int) sizeof(contains); i++) {
contains[i] = '0';
}
int fd = open(tarName, O_RDWR);
if(fd < 0) {
printf("error: %s does not exist", tarName);
return 1;
}
tar_header head;
while((read(fd, &head, sizeof(tar_header)))) {
long unsigned size = oct2num(head.size, 8, sizeof(head.size));
long unsigned offset = size + (size % BLOCK_SIZE == 0 ? 0 : BLOCK_SIZE - size % BLOCK_SIZE);
for(int j = i; j < numArgs; j++) {
if(!my_strncmp(args[j], head.name, my_strlen(args[j]) > my_strlen(head.name) ? my_strlen(args[j]) : my_strlen(head.name))) {
struct stat fileStat;
if(stat(args[j], &fileStat) < 0) {
printf("path name %s does not exist", args[j]);
return 1;
}
if((unsigned long) fileStat.st_mtime > oct2num(head.modified, 8, sizeof(head.modified))) {
if(head.type == DIRECTORY) {
if(updateDir(fd, &head, fileStat, args[j], tarName)) return 1;
}
else {
insertEntry(fd, offset, fileStat, args[j]);
offset = 0;
}
}
contains[j - i] = '1';
}
}
if(head.type != DIRECTORY) {
lseek(fd, offset, SEEK_CUR);
}
}
lseek(fd, 0, SEEK_END);
for(int j = i; j < numArgs; j++) {
if(contains[j - i] == '0') {
tarAdd(fd, args[j]);
}
}
close(fd);
return 0;
}
int writeEntry(tar_header * head, struct stat fileStat, char* arg, int fd) {
setToZero(head);
my_strncpy(head->name, arg, my_strlen(arg));
utoa(fileStat.st_mode & 0777, 8, head->mode);
utoa(fileStat.st_uid, 8, head->owner);
utoa(fileStat.st_gid, 8, head->group);
utoa(fileStat.st_size, 8, head->size);
utoa(fileStat.st_mtime, 8, head->modified);
switch(fileStat.st_mode & S_IFMT) {
case S_IFREG: head->type = REGULAR; break;
case S_IFDIR: head->type = DIRECTORY; break;
case S_IFCHR: head->type = CHAR; break;
case S_IFBLK: head->type = BLOCK; break;
case S_IFIFO: head->type = FIFO; break;
case S_IFSOCK: printf("error: cannot tar socket"); return 1; break;
default: printf("error: unknown file type"); return 1; break;
}
utoa(fileStat.st_nlink, 10, &head->linkNum);
write(fd, head, sizeof(tar_header));
return 0;
}
void freeStrings(char** strings, int count) {
for(int i = 0; i < count; i++) {
free(strings[i]);
}
free(strings);
}
int tarAdd(int fd, char* arg) {
struct stat fileStat;
if(stat(arg, &fileStat) < 0) {
printf("path name %s does not exist", arg);
return 1;
}
tar_header head;
if(writeEntry(&head, fileStat, arg, fd)) return 1;
if(head.type == DIRECTORY) {
int fileCount = getFileCount(head.name);
char** dirFiles = (char**)malloc(fileCount*sizeof(char*));
readContents(dirFiles, &head);
for(int i = 0; i < fileCount; i++) {
tarAdd(fd, dirFiles[i]);
}
freeStrings(dirFiles, fileCount);
}
else {
int readFile = open(arg, O_RDONLY);
unsigned long fileSize = fileStat.st_size;
char buffer[4096];
transferContents(readFile, fd, buffer);
close(readFile);
for(unsigned long i = 0; i < (fileSize % BLOCK_SIZE == 0 ? 0 : BLOCK_SIZE - fileSize % BLOCK_SIZE); i++) {
write(fd, "\0", 1);
}
}
return 0;
}
int createTar(char* tarName, char** args, char* path, int flag, int* i, int numArgs) {
char fullPath[200];
my_strncpy(fullPath, path, my_strlen(path));
if(tarName)
my_strncpy(fullPath + my_strlen(path), tarName, my_strlen(tarName) + 1);
int fd = flag ? open(fullPath, O_CREAT|O_RDWR|O_TRUNC, 0644) : 1;
for(; *i < numArgs; *i = *i + 1) {
if(tarAdd(fd, args[*i])) return 1;
}
close(fd);
return 0;
}
|
C
|
#include "main.h"
#include <stdio.h>
/**
* reset_to_98 - change pointer's value
* @n: takes pointer of typer int
*/
void reset_to_98(int *n)
{
*n = 98;
}
|
C
|
#include "holberton.h"
#include <stdio.h>
#include <stdlib.h>
/**
* str_concat - function that concatenates two strings
* @s1: String #1.
* @s2: String #2.
* Return: Pointer to the new concatenated string.
*/
char *str_concat(char *s1, char *s2)
{
int iter1, iter2;
char *concat;
if (s1 == NULL)
s1 = "";
if (s2 == NULL)
s2 = "";
concat = malloc(sizeof(char) * (_strlen(s1) + _strlen(s2) + 1));
if (!concat)
return ('\0');
for (iter1 = 0; s1[iter1]; iter1++)
concat[iter1] = s1[iter1];
for (iter2 = 0; s2[iter2]; iter2++, iter1++)
concat[iter1] = s2[iter2];
concat[iter1] = '\0';
return (concat);
}
/**
* _strlen - Return the lenght of a string.
* @str: String to count.
* Return: Number of characters in str..
*/
int _strlen(char *str)
{
int iter = 0;
while (str[iter])
iter++;
return (iter);
}
|
C
|
#include <stdio.h>
#include "funcs.h"
#include <math.h>
int main(void)
{
system("chcp 1251");
int i = 0, d;
while (i != -1)
{
system("cls");
printf("1\n");
printf("2\n");
printf("3\n");
printf("4\n");
printf("5\n");
printf("6()\n\n");
int n = 0, k = 0;
float e = 0.0;
printf(" : ");
scanf_s("%d", &d);
switch (d)
{
case 1:
system("cls");
printf("1\n");
printf(" n:");
scanf_s("%d", &n);
printf("=%f\n\n", zadanie1(n));
system("pause");
break;
case 2:
system("cls");
printf("2\n");
printf(" E =");
scanf_s("%f", &e);
printf(" =%f\n\n", zadanie2(e));
system("pause");
break;
case 3:
system("cls");
printf("3\n");
printf(" n= ");
scanf_s("%d", &n);
printf(" k= ");
scanf_s("%d", &k);
printf(" = ");
zadanie3(n, k);
system("pause");
break;
case 4:
system("cls");
printf("4\n");
printf(" E =");
scanf_s("%f", &e);
printf(" = %d\n\n", zadanie4(e));
system("pause");
break;
case 5:
system("cls");
printf("5\n");
printf("E = ");
scanf_s("%f", &e);
printf(" = %d\n\n", zadanie5(e));
system("pause");
break;
case 6:
i = -1;
break;
default:
printf(" ");
system("pause");
}
}
system("pause");
return (0);
}
|
C
|
#ifndef list_type
#define list_type
#include <stdbool.h>
typedef struct lelement LElement;
typedef struct llist LList;
//Generic list Element
struct lelement {
LElement *next;
LElement *prev;
void *data;
};
//Generic List Structure
struct llist {
int NumEl; //Number of elements in list
LElement *pFirst; //Ptr to first element in list
LElement *pLast; //Ptr to last element in list
};
void CreateList(LList *list);
LElement *AddToList(void *item, LList *list);
bool DelFromList(unsigned short num, LList * list);
void FreeList(LList * list);
#define FOR_EACH(item_ptr, list) \
for (item_ptr = list.pFirst; item_ptr != NULL; item_ptr=item_ptr->next)
#endif
|
C
|
/*
* SPI_Second_Driver.c
*
* Created: 10/7/2020 7:52:27 PM
* Author : Ahmed Atef
*/
#include "SPI.h"
#include "LED.h"
#define F_CPU 4000000
#include <util/delay.h>
int main(void)
{
uint8 Recivie_data = 0 ; // variable to recive data
uint8 Transfer_data = 0 ; // send a dummy byte to Master from slave
LED0_Init();
LED1_Init();
SPI_Init_Slave();
while (1)
{
Recivie_data = SPI_Transmit_and_Recive(Transfer_data); // send a dummy byte to Master and recived data from master and add the data to variable Recivie_data
if(Recivie_data == '1')
{
LED0_ON();
}
else if(Recivie_data == '2')
{
LED0_OFF();
}
else if (Recivie_data == '3')
{
LED1_ON();
}
else if (Recivie_data== '4')
{
LED1_OFF();
}
}
}
|
C
|
int is_symbol(char p) {
switch (p) {
case '+': case '-':
case '*': case '/':
case '%': case '=':
case ';': case ':':
case '(': case ')':
case '{': case '}':
case '[': case ']':
case '<': case '>':
case '!': case '?':
case '&': case '^':
case '|': case '#':
case ',': case '.':
case '\\': {
return 1;
}
default: {
return 0;
}
}
}
int is_line_comment(const char* p, int pos) {
return (strncmp(&p[pos], "//", 2) == 0);
}
int is_block_comment_begin(const char* p, int pos) {
return (strncmp(&p[pos], "/*", 2) == 0);
}
int is_block_comment_end(const char* p, int pos) {
return (strncmp(&p[pos], "*/", 2) == 0);
}
int main() {
char* str = malloc(sizeof(char) * 256);
strncpy(str, "### // aaaa \n bbbb\0", 256);
const char* p = str;
int cnt = 0;
int pos = 0;
while (p[pos]) {
if (isspace(p[pos])) {
cnt += 1;
}
else if (is_line_comment(p, pos)) {
while (p[pos] != '\n') {
++pos;
}
cnt += 2;
continue;
}
else if (is_block_comment_begin(p, pos)) {
while (!is_block_comment_end(p, pos)) {
++pos;
}
pos += 2;
cnt += 3;
continue;
}
else if (p[pos] == '#') {
cnt += 4;
}
else if (p[pos] == 39) {
cnt += 5;
}
else if (p[pos] == '"') {
cnt += 6;
}
else if (isalpha(p[pos])) {
cnt += 7;
}
else if (isdigit(p[pos])) {
cnt += 8;
}
else if (is_symbol(p[pos])) {
cnt += 9;
}
else {
printf("%c\n", p[pos]);
return 10;
}
++pos;
}
return cnt;
}
|
C
|
/* McDowell (2013), Crack the Coding Interview, 5e
* Question #1.1 (pp. 73)
* Implement a function void reverse(char *str) in C or C++ which rever-
* ses a null-terminated string. */
#include <stdio.h>
#include <string.h>
void reverse(char *);
void reverse(char *s) {
int i = 0, j = strlen(s) - 1;
while(i < j) {
*(s + i) ^= *(s + j);
*(s + j) ^= *(s + i);
*(s + i) ^= *(s + j);
++i;
--j;
}
}
|
C
|
// Server side C/C++ program to demonstrate Socket programming
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include<sys/wait.h>
#include <stdlib.h>
#include <netinet/in.h>
#include<pwd.h>
#include <string.h>
#include<assert.h>
#define PORT 8080
int main(int argc, char const *argv[])
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char *hello = "Hello from server";
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
if (bind(server_fd, (struct sockaddr *)&address,
sizeof(address)) < 0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
pid_t f_pid;
pid_t child_pid = fork();
int status = 0;
if( child_pid == 0 ){
// fork returns 0 inside child process
printf("Log: Child Process: forked child_pid = %d\n", child_pid);
printf("Log: Child Process: Current pid = %d\n",getpid());
printf("Log: Child Process: Current uid = %ld\n", (long) getuid());
//Changing user from root to "nobody"
struct passwd *passwd_ptr = getpwnam("nobody");
if(passwd_ptr == NULL){
perror("Failed to drop privilages since passwd_ptr is null");
exit(EXIT_FAILURE);
}
printf("Log: Child Process: UID of nobody=%ld\n",(long) passwd_ptr->pw_uid);
if (setuid(passwd_ptr->pw_uid) < 0)
perror("Log: Child Process: setuid() error");
else
printf("Log: Child Process: UID after setuid() = %ld\n",(long) getuid());
valread = read( new_socket , buffer, 1024);
printf("%s\n",buffer );
send(new_socket , hello , strlen(hello) , 0 );
printf("Hello message sent\n");
}
else if (child_pid > 0){
//fork return PID of child process inside parent
//Waiting for child process to complete
printf("Log: Parent Process: Waiting for child process to complete\n");
if((f_pid = wait(&status)) < 0){
perror("Log: Parent Process: Error in wait");
_exit(1);
}
printf("Log: Parent Process: Forked child pid: %d\n", child_pid);
printf("Log: Parent Process: Current pid = %d\n",getpid());
printf("Log: Parent Process: Current uid = %ld\n",(long) getuid());
printf("Log: Parent Process: Completed\n");
}
else{
perror("Error! fork() failed");
_exit(2);
}
return 0;
}
|
C
|
#ifndef _SCHEDULER_H
#define _SCHEDULER_H
#include "stm32f10x.h"
#define SCH_MAX_TASKS 30
#define SCHEDULERPERIOD 1000
extern void Scheduler_Dispatch_Tasks(void);
extern void Scheduler_Dispatch_Task_with_index(uint8_t index);
extern unsigned char Scheduler_Add_Task(void (*pFunction)(void), const unsigned int DELAY, const unsigned int PERIOD);
extern unsigned char Scheduler_Delete_Task(const unsigned char TASK_INDEX);
extern void Scheduler_init(void);
extern void Scheduler_start(void);
extern void Run_scheduler(void);
extern void Scheduler_Refresh_task(const unsigned char TASK_INDEX);
// Total memory per task is 7 bytes
typedef struct
{
void (*pTask)(void); // Pointer to the task (must be a 'void (void)' function)
uint16_t Delay; // Delay (ticks) until the function will (next) be run
uint16_t Period; // Interval (ticks) between subsequent runs.
uint8_t RunMe; // Incremented (by scheduler) when task is due to execute
} sTask;
#endif
|
C
|
#include <jayc/jlog_stdio.h>
#include <jayc/jproc.h>
#include <jayc/jutil_time.h>
#include <jayc/jcon_client_tcp.h>
#include <jayc/jcon_thread.h>
#include <string.h>
#define EXITVALUE_SUCCESS 0
#define EXITVALUE_FAILURE 1
static jcon_client_t *g_client = NULL;
static jcon_thread_t *g_thread = NULL;
static void exit_handler(int exit_value, void *ctx)
{
if(g_client != NULL)
{
jcon_client_session_free(g_client);
}
if(g_thread != NULL)
{
jcon_thread_free(g_thread);
}
}
static void data_handler(void *ctx, jcon_client_t *client);
static void create_handler(void *ctx, int create_type, const char *reference_string);
static void close_handler(void *ctx, int close_type, const char *reference_string);
int main()
{
jproc_exit_setHandler(&exit_handler, NULL);
jlog_t *logger = jlog_stdio_session_init(JLOG_LOGTYPE_DEBUG);
if(logger == NULL)
{
jproc_exit(EXITVALUE_FAILURE);
}
jlog_global_session_set(logger);
int ret_check;
// Create client.
g_client = jcon_client_tcp_session_init("127.0.0.1", 1234, logger);
if(g_client == NULL)
{
JLOG_ERROR("Could not create client.");
jproc_exit(EXITVALUE_FAILURE);
}
// Connect client.
ret_check = jcon_client_reset(g_client);
if(ret_check == 0)
{
JLOG_ERROR("Could not connect client.");
jproc_exit(EXITVALUE_FAILURE);
}
// Create thread.
g_thread = jcon_thread_init(g_client, data_handler, create_handler, close_handler, logger, NULL);
if(g_thread == NULL)
{
JLOG_ERROR("Could not create thread.");
jproc_exit(EXITVALUE_FAILURE);
}
// Wait while thread is running.
while(jcon_thread_isRunning(g_thread))
{
// Sleep 1 second before checking again.
jutil_time_sleep(1, 0);
}
// Free memory.
jcon_thread_free(g_thread);
g_thread = NULL;
jcon_client_session_free(g_client);
g_client = NULL;
jproc_exit(EXITVALUE_SUCCESS);
}
void data_handler(void *ctx, jcon_client_t *client)
{
int ret_check;
char buf[256] = { 0 };
size_t buf_size = sizeof(buf);
// Read data.
ret_check = jcon_client_recvData(client, buf, buf_size);
if(ret_check == 0)
{
JLOG_ERROR("Could not read.");
return;
}
// Print data read.
JLOG_INFO("Client [%s] recieved [%s].", jcon_client_getReferenceString(client), buf);
char *resp = "ACK";
// Send acknowledgement message.
ret_check = jcon_client_sendData(client, resp, strlen(resp));
if(ret_check == 0)
{
JLOG_ERROR("Could not send data.");
return;
}
}
void create_handler(void *ctx, int create_type, const char *reference_string)
{
JLOG_INFO("ClientThread [%s] started with create-type [%d].", reference_string, create_type);
}
void close_handler(void *ctx, int close_type, const char *reference_string)
{
JLOG_INFO("ClientThread [%s] closed with close-type [%d].", reference_string, close_type);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_fillelem.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tpacaud <tpacaud@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/04/27 16:00:51 by tpacaud #+# #+# */
/* Updated: 2019/06/20 18:18:47 by tpacaud ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/ft_printf.h"
/*
**Fill the structure
*/
t_elem *ft_filldi(t_printinfo *list, va_list va, t_elem *elem)
{
if (list->is_long_double || list->max)
elem->lli = va_arg(va, long long int);
else if (list->is_long)
elem->lli = va_arg(va, long int);
else
elem->lli = va_arg(va, int);
return (elem);
}
t_elem *ft_fillunsigned(t_printinfo *list, va_list va, t_elem *elem)
{
if (list->is_long_double || list->max)
elem->ulli = va_arg(va, unsigned long long int);
else if (list->is_long || ft_strchr("OU", list->t))
elem->ulli = va_arg(va, unsigned long int);
else
elem->ulli = va_arg(va, unsigned int);
if (ft_strchr("OU", list->t))
{
list->is_long = 1;
list->t = (list->t == 'U') ? 'u' : list->t;
list->t = (list->t == 'O') ? 'o' : list->t;
list->is_char = 0;
list->is_short = 0;
}
return (elem);
}
t_elem *ft_fillfloats(t_printinfo *list, va_list va, t_elem *elem)
{
if (list->is_long_double != 0)
elem->long_double = va_arg(va, long double);
else
elem->dble = va_arg(va, double);
return (elem);
}
|
C
|
/**
* @file ADC.h
*
* @brief The header file and function prototypes for the ADC.
* @details For single ended conversion, the ADC value an be found from the voltage using:
* @f[ \frac {V_{in} * 1024}{V_{ref}} @f]
* @author Kevin Harrington
* @date February 11, 2010
*
* @author Justin Barrett
* @date August 23, 2011
*
* @author Eric Willcox
* @date August 19, 2013
*/
#ifndef ADC_H_
#define ADC_H_
/**
* @brief Initializes one and only one channel of the ADC.
*
* @param channel The ADC channel to initialize.
* @return void
*
* @todo Create the corresponding function to initialize the ADC using the channel parameter. Pages: 233 - 252
*/
void InitADC(unsigned char channel);
/**
* @brief Disables ADC functionality from one and only one pin.
*
* @param channel The ADC channel to disable.
* @return void
*
* @todo Create the corresponding function to clear the last ADC calculation register. Pages: 233 - 252
*/
void ClearADC(unsigned char channel);
/**
* @brief Run a conversion on and get the analog value from one ADC channel.
*
* @param channel The ADC channel to run a conversion on.
* @return unsigned short value The 10-bit value returned by the ADC conversion.
*
* @todo Create the corresponding function to obtain the value of the last calculation. Pages: 233 - 252
*/
unsigned short GetADC(unsigned char channel);
#endif /* ADC_H_ */
|
C
|
#include <stdio.h>
int main(void)
{
const int a = 90;
*(int *)&a = 999;
printf("a = %d\n", a);
int *p = (int *)&a;
*p = 1000;
printf("a = %d\n", a);
printf("*p = %d\n", *p);
return 0;
}
|
C
|
//Julio Villazón | A01370190 -> Trabajo hecho con Jesus Gonzalez
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <math.h>
typedef struct
{
int min;
int max;
int count;
char * hist;
} Urn;
int traverseDirectoryTree(char *, int);
int is_regular_file(const char *);
int get_file_size(const char *);
int allocateUrn(Urn *,int, int, int);
void createUrns(Urn *, int, int);
int populateNewUrns(Urn *, char *, int, int, int);
void printAllStruc(Urn *, int);
void generateHist(Urn *, int, int);
int main(int arc, const char * argv[])
{
char path[256];
int nUrns = 1;
int urnSize;
int nFiles;
Urn *urns;
Urn *uAux;
Urn *final;
printf("Ingrese el tamaño de la urna: ");
scanf("%d", &urnSize);
printf("Ingrese la ruta del directorio: ");
scanf("%s", path);
urns = (Urn *)malloc(sizeof(Urn));
final = urns;
uAux = urns;
uAux->count = 0;
uAux->min = 0;
uAux->max = urnSize - 1;
int maxSize = traverseDirectoryTree(path, urnSize);
nUrns = allocateUrn(urns, maxSize, urnSize, nUrns);
urns = (Urn *)realloc(urns, sizeof(Urn) * nUrns);
createUrns(urns, urnSize, nUrns);
nFiles = populateNewUrns(urns, path, urnSize, nUrns, nFiles);
generateHist(urns, nFiles, nUrns);
printAllStruc(urns, nUrns);
for (; uAux < final; ++uAux)
{
free(uAux->hist);
}
free(urns);
return 0;
}
int traverseDirectoryTree(char * path, int urnSize)
{
DIR *d;
struct dirent *dir;
int maxSize = urnSize;
d = opendir(path);
if (d)
{
while ((dir = readdir(d)) != NULL)
{
char *currentPath = realpath(dir->d_name, NULL);
if (is_regular_file(currentPath))
{
int fSize = get_file_size(dir->d_name);
//printf("%s -> %d\n", dir->d_name, fSize);
if (maxSize < fSize)
maxSize = fSize;
//printf("MaX: %d \n", maxSize);
}
else
{
// Aqui es donde se revisarian los directorios que existen en el directorio dado por el usuario. El problema es que creemos que el readdir nos esta dando los nombres tanto del directorio actual (.) y el directorio anterior (..) por lo que se esta ciclano la funcion recursiva buscando en el mismo directorio muchos veces.
// maxSize = traverseDirectoryTree(currentPath, urnSize);
}
}
closedir(d);
return maxSize;
}
}
int is_regular_file(const char * path)
{
struct stat path_stat;
stat(path, &path_stat);
return S_ISREG(path_stat.st_mode);
}
int get_file_size(const char * file_name)
{
struct stat sb;
if (stat(file_name, &sb) != 0)
{
fprintf(stderr, "'stat' failed for '%s': %s.\n",
file_name, strerror(errno));
exit(EXIT_FAILURE);
}
return sb.st_size;
}
int allocateUrn(Urn * urn, int maxSize, int urnSize, int nUrns)
{
Urn * final = urn + nUrns - 1;
int diff = maxSize - final->max;
int newUrns = (diff + urnSize - 1) / urnSize;
nUrns += newUrns;
//printf("DIFF: %d, NEW URNS: %d, TOTAL URNS: %d\n", diff, newUrns, nUrns);
return nUrns;
}
void createUrns(Urn * urns, int urnSize, int nUrns)
{
Urn * uAux = urns;
Urn * final = uAux + nUrns;
int count = 0;
for (; uAux < final; ++uAux)
{
if (uAux->max == 0)
{
uAux->count = 0;
uAux->min = urnSize * count;
uAux->max = uAux->min + urnSize - 1;
}
count++;
}
}
int populateNewUrns(Urn *urns, char *path, int urnSize, int nUrns, int nFiles)
{
DIR *d;
struct dirent *dir;
Urn *uAux = urns;
Urn *final = urns + nUrns;
d = opendir(path);
if (d)
{
while ((dir = readdir(d)) != NULL)
{
char *currentPath = realpath(dir->d_name, NULL);
if (is_regular_file(currentPath))
{
int fSize = get_file_size(dir->d_name);
uAux = urns;
final = uAux + nUrns;
for (; uAux < final; ++uAux)
{
if (fSize >= uAux->min && fSize <= uAux->max)
{
uAux->count++;
}
}
}
else
{
// traverseDirectoryTree(urns, final, currentPath);
}
++nFiles;
}
closedir(d);
return nFiles;
}
}
void generateHist(Urn * urns, int nFiles, int nUrns){
int histSize;
int resize = nFiles * 0.1;
Urn * uAux = urns;
Urn * final = urns + nUrns;
for (; uAux < final; ++uAux)
{
if (uAux->count != 0)
{
histSize = resize * uAux->count;
uAux->hist = (char *)malloc(sizeof(char) * histSize);
while (histSize != 0)
{
strcat(uAux->hist, "*");
--histSize;
}
}
}
}
void printAllStruc(Urn * uAux, int nUrns)
{
Urn *aux = uAux;
Urn *final = aux + nUrns;
printf("Urna \t\t Número de archivos \t Histograma\n\n");
for (; aux < final; ++aux)
{
if(aux->count != 0)
printf("%d - %d \t %2d \t\t\t %s\n", aux->min, aux->max, aux->count, aux->hist);
}
printf("\n\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define RANGE 256
void counting_sort(char arr[]) {
int n = strlen(arr);
int i = 0;
char output[n];
int count[RANGE];
memset(count, 0, sizeof(count));
for (i = 0; i < n; i++) {
count[arr[i]]++;
}
for (i = 1; i < RANGE; i++) {
count[i] += count[i-1];
}
for (i = n-1; i >= 0; i--) {
output[count[arr[i]] - 1] = arr[i];
count[arr[i]]--;
}
for (i = 0; i < n; i++) {
arr[i] = output[i];
}
}
int main()
{
char arr[] = "mnbvcxzlkjhgfdsaapouytrewq";
counting_sort(arr);
printf("%s\n", arr);
}
|
C
|
#include<stdio.h>
int main()
{
int m,k;
printf("");
scanf("%d",&k);
if(k==1)
goto remove;
for(m=2;m<k;m++)
{
if(k%m==0)//km
{
remove:
printf("Ϊ\n");
goto to;
}
}
printf("Ϊ\n");
to:
system("pause");
return 0;
}
/*#include<stdio.h>
#include <stdlib.h>
int main()
{
int m, k;
int flag = 1;
printf ("һ");
while (scanf ("%d", &k) == 1)
{
for(m = 2; m <= k; m++)
if (k % m == 0)
break;
if (k == m)
printf ("%dΪ\n", k);
else
printf ("%dΪ\n", k);
printf ("һq˳");
}
system ("pause");
return 0;
}
*/
|
C
|
//undefined behavior number 9 - similar to number 8
#include <stdio.h>
#include <stdlib.h>
int *gl_ptr;
void func2(){
int a = 23;
gl_ptr = &a;
}
void func1(){
func2();
}
int main(){
func1();
printf("gl_ptr = %d\n", *gl_ptr); //will be removed
return 0;
}
|
C
|
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <time.h>
int* initTab(int* tab, int size){
int i=0;
tab=(int*)malloc((sizeof(int))*size);
for(i=0; i<size; i++){
tab[i] = 3;
}
return tab;
}
int main(){
int* tabNum;
int i=0;
int size = 100;
tabNum = initTab(tabNum, size);
for(i=0; i<size; i++){
printf("tab %d = %d\n", i, tabNum[i]);
}
return 0;
}
|
C
|
#ifndef __GX_LIBINI_H__
#define __GX_LIBINI_H__
#include "gxtype.h"
#include "gxcore.h"
__BEGIN_DECLS
#define EINVALID_HANDLE (0)
/*********************************************************
* @brief ڴУһINIļʽINI
* @param [in] memory ָһ洢INIļʽڴ
* @param [in] size memoryڴС
* @return handle_t ɹֵINIʧܷEINVALID_HANDLE
* @remarks
*/
handle_t ini_loadmemory(const char *memory, int size);
/** ******************************************************
* @brief һINIļ
* @param [in] fname INIļ
* @return handle_t ɹֵINIʧܷEINVALID_HANDLE
* @remarks
*/
handle_t ini_open(const char* fname);
/*********************************************************
* @brief һµINIļ
* @param [in] fname ҪINIļ
* @return handle_t ɹֵINIʧܷEINVALID_HANDLE
* @remarks fnameļΪNULLʱһڴе
INIļINIļini_saveκθı䣬
ini_closeͷINIļԴ
*/
handle_t ini_create(const char* fname);
/*********************************************************
* @brief еINIļݱ浽ļ
* @param [in] piniҪINIļָ
* @return int ֵΪ洢ļָ뱣ɹNULLʧ
* @remarks
*/
char* ini_save(handle_t ini);
/*********************************************************
* @brief еINIļݣINIıʽ浽ڴ
* @param [in] iniҪINIļ
* @param [in] memĿڴ
* @param [in] sizeĿڴmemС
* @return int ֵΪmemʵʴ洢ֽڴС0ʾ
* @remarks
*/
size_t ini_savememory(handle_t ini, char* mem, size_t size);
/*********************************************************
* @brief ͷINIļռõڴԴ
* @param [in] pini ҪͷŵINIļָ
* @return void ֵ
* @remarks
*/
void ini_close(handle_t ini);
/*********************************************************
* @brief ȡָļֵ
* @param [in] pini INIļָ
* @param [in] section ַָ
* @param [in] param ַָ
* @return char* valueֵַָ룬NULLȡʧ
* @remarks
*/
char *ini_get(handle_t ini,
const char* section,
const char* param);
/*********************************************************
* @brief ָļֵ
* @param [in] pini INIļָ
* @param [in] param ַָ
* @value [in] ڱҪõֵַָ
* @return int ֵΪ0óɹ-1ʧ
* @remarks
*/
int ini_set(handle_t ini, const char *section, const char *param, const char *value);
/*********************************************************
* @brief ¼
* @param [in] pini INIļָ
* @param [in] section ַָ
* @param [in] param ַָ
* @param [in] value ֵַָ
* @return int ֵΪ0óɹ-1ʧ
* @remarks
*/
int ini_append(handle_t ini, const char *section, const char *param, const char *value);
/*********************************************************
* @brief Ƴָ
* @param [in] pini INIļָ
* @param [in] section ַָ
* @param [in] param ַָ, ֵΪNULLʱʾɾsection
parameters
* @return int ֵΪ0ɾɹ-1ɾʧ
* @remarks
*/
int ini_remove(handle_t ini, const char *section, const char *param);
/*********************************************************
* @brief ϲINIļ
* @param [in,out] src_old INIļָ
* @param [in] src_new INIļָ
* @return ֵΪ0ϲɹ-1ϲʧ
* @remark ϲINIļsrc_newڵsectionkey,src_old
ڣӵsrc_oldУѾڣsrc_newеֵ
src_oldеֵ
*/
int ini_merge(handle_t old_ini, handle_t new_ini);
__END_DECLS
#endif
|
C
|
//Write an OpenMP parallel program for Points Classification. Prove the correctness of sequential program with that of parallel.
//Clustering
#include<stdio.h>
#include<omp.h>
#include<math.h>
#include<time.h>
#include<stdlib.h>
#define no_of_clusters 4
int cluster_centers[no_of_clusters][2] = {{20, 20},{60,60},{20,60},{60,20}};
int no_of_points = 9;
int datapoints[100][2];
int cluster[no_of_clusters];
void distribute_points() //distributes points in the x-y plane
{
int upper = 100, lower = 0;
#pragma omp parallel for num_threads(8)
{
for(int i = 0; i < no_of_points; i++)
{
datapoints[i][0] = (rand() % (upper - lower + 1)) + lower;
datapoints[i][1] = (rand() % (upper - lower + 1)) + lower;
}
}
}
double get_distance(int x1, int y1, int x2, int y2)
{
return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2)); //get Euclidean distance between datapoint and cluster center
}
void cluster_points()
{
int min_dist, i, j;
double dist;
int cluster_index;
#pragma omp parallel for num_threads(8) private(cluster_index, i, j, dist, min_dist)
{
for(i = 0; i < no_of_points; i++)
{
min_dist = 999;
dist = 0;
for(j = 0; j < no_of_clusters; j++)
{
dist = get_distance(datapoints[i][0], datapoints[i][1], cluster_centers[j][0], cluster_centers[j][1]);
if(dist < min_dist)
{
min_dist = dist;
cluster_index = j;
}
}
printf("\nPoint: (%d, %d) in cluster: (%d, %d)", datapoints[i][0], datapoints[i][1], cluster_centers[cluster_index][0], cluster_centers[cluster_index][1]);
cluster[cluster_index]++;
}
}
}
void main()
{
distribute_points();
//double start_time = omp_get_wtime();
cluster_points();
//double time_taken = omp_get_wtime() - start_time;
//printf("Time taken : %f", time_taken);
printf("\n");
for(int i = 0; i < no_of_clusters; i++)
printf("CLuster: (%d, %d) -> %d\n", cluster_centers[i][0], cluster_centers[i][1], cluster[i]);
}
|
C
|
#include "game.h"
void init_game(uint8_t* rom) {
// ROM Validation:
if( rom[0] != 'N' && rom[1] != 'E' && rom[2] != 'S' && rom[3] != '\32') {
debug_print("%s","Invalid ROM file, header does not match");
free(rom);
exit(0);
}
// Get header file information: https://wiki.nesdev.com/w/index.php/INES
gamepack.prg_rom_banks = rom[4];
gamepack.chr_rom_banks = rom[5];
gamepack.prg_rom_size = rom[4] * 0x4000;
gamepack.chr_rom_size = rom[5] * 0x2000;
gamepack.flags_six = rom[6];
gamepack.flags_seven = rom[7];
gamepack.mapper_mode = (gamepack.flags_seven & 0xF0) | ((gamepack.flags_six & 0xF0) >> 4);
gamepack.rom_data = 0x10 + rom;
int i;
debug_print("%s", "\033[32;1mGame init info\033[0m\n");
for(i = 0; i < 8; i++){
debug_print("0x%02X \n", gamepack.rom_data[i]);
}
if (!(gamepack.flags_six & 0x1)) {
gamepack.mirror_mode = Horizontal;
} else if (gamepack.flags_six & 0x1) {
gamepack.mirror_mode = Vertical;
} else if (gamepack.flags_six & 0x8) {
gamepack.mirror_mode = FourScreen;
} else {
gamepack.mirror_mode = SingleScreen;
}
debug_print("PRG ROM Size: 0x%02X\n", gamepack.prg_rom_size);
debug_print("PRG ROM Bank: 0x%02X\n", gamepack.prg_rom_banks);
debug_print("CHR ROM Size: 0x%02X\n", gamepack.chr_rom_size);
debug_print("CHR ROM Bank: 0x%02X\n", gamepack.chr_rom_banks);
debug_print("Flag 6: 0x%02X\n", gamepack.flags_six);
debug_print("Flag 7: 0x%02X\n", gamepack.flags_seven);
debug_print("Mapper Mode: 0x%02X\n", gamepack.mapper_mode);
}
uint8_t* get_rom_file() {
return gamepack.rom_data;
}
uint8_t get_prg_banks() {
return gamepack.prg_rom_banks;
}
uint8_t get_chr_banks() {
return gamepack.chr_rom_banks;
}
uint8_t get_mapper() {
return gamepack.mapper_mode;
}
void set_mirror_mode(uint8_t value) {
gamepack.mirror_mode = value;
}
uint8_t get_mirror_mode() {
return gamepack.mirror_mode;
}
|
C
|
// Broker peering simulation (part 3)
// Prototypes the full flow of status and tasks
#include "czmq.h"
#define NBR_CLIENTS 10
#define NBR_WORKERS 5
#define WORKER_READY "\001" // Signals worker is ready
// Our own name; in practice, this would be configured per node
static char *self;
// This is the client task. It issues a burst of requests and then
// sleeps for a few seconds. This simulates sporadic activity; when
// a number of clients are active at once, the local workers should
// be overloaded. The client uses a REQ socket for requests and also
// pushes statistics to the monitor socket:
static void
client_task (zsock_t *pipe, void *args)
{
zsock_signal (pipe, 0);
int rc;
void *ctx = zmq_ctx_new ();
zsock_t *client_sock = zsock_new (ZMQ_REQ);
rc = zsock_connect (client_sock, "ipc://%s-localfe.ipc", self);
assert( rc == 0 );
zsock_t *monitor_sock = zsock_new (ZMQ_PUSH);
rc = zsock_connect (monitor_sock, "ipc://%s-monitor.ipc", self);
assert( rc == 0 );
void *client = zsock_resolve(client_sock);
void *monitor = zsock_resolve(monitor_sock);
while (true) {
sleep ((uint) randof (5));
int burst = randof (15);
while (burst--) {
char task_id [5];
sprintf (task_id, "%04X", randof (0x10000));
// Send request with random hex ID
zstr_send (client, task_id);
// Wait max ten seconds for a reply, then complain
zmq_pollitem_t pollset [1] = { { client, 0, ZMQ_POLLIN, 0 } };
rc = zmq_poll (pollset, 1, 10 * 1000 * ZMQ_POLL_MSEC);
if (rc == -1)
break; // Interrupted
if (pollset [0].revents & ZMQ_POLLIN) {
char *reply = zstr_recv (client);
if (!reply)
break; // Interrupted
// Worker is supposed to answer us with our task id
assert (streq (reply, task_id));
zstr_sendf (monitor, "%s", reply);
free (reply);
}
else {
zstr_sendf (monitor, "E: CLIENT EXIT - lost task %s", task_id);
zmq_ctx_destroy (&ctx);
return;
}
}
}
zmq_ctx_destroy (&ctx);
}
// This is the worker task, which uses a REQ socket to plug into the
// load-balancer. It's the same stub worker task that you've seen in
// other examples:
static void
worker_task (zsock_t *pipe, void * args)
{
zsock_signal (pipe, 0);
int rc;
void *ctx = zmq_ctx_new ();
zsock_t *worker_sock = zsock_new (ZMQ_REQ);
rc = zsock_connect (worker_sock, "ipc://%s-localbe.ipc", self);
assert(rc == 0);
// Tell broker we're ready for work
zframe_t *frame = zframe_new (WORKER_READY, 1);
zframe_send (&frame, worker_sock, 0);
void *worker = zsock_resolve(worker_sock);
// Process messages as they arrive
while (true) {
zmsg_t *msg = zmsg_recv (worker);
if (!msg)
break; // Interrupted
// Workers are busy for 0/1 seconds
sleep ((uint) randof (2));
zmsg_send (&msg, worker);
}
zmq_ctx_destroy (&ctx);
}
// The main task begins by setting up all its sockets. The local frontend
// talks to clients, and our local backend talks to workers. The cloud
// frontend talks to peer brokers as if they were clients, and the cloud
// backend talks to peer brokers as if they were workers. The state
// backend publishes regular state messages, and the state frontend
// subscribes to all state backends to collect these messages. Finally,
// we use a PULL monitor socket to collect printable messages from tasks:
int main (int argc, char *argv [])
{
// First argument is this broker's name
// Other arguments are our peers' names
if (argc < 2) {
printf ("syntax: peering3 me {you}…\n");
return 0;
}
self = argv [1];
printf ("I: preparing broker at %s…\n", self);
srandom ((unsigned) time (NULL));
int rc;
// Prepare local frontend and backend
void *ctx = zmq_ctx_new ();
zsock_t *localfe_sock = zsock_new (ZMQ_ROUTER);
rc = zsock_bind (localfe_sock, "ipc://%s-localfe.ipc", self);
assert(rc == 0);
zsock_t *localbe_sock = zsock_new (ZMQ_ROUTER);
rc = zsock_bind (localbe_sock, "ipc://%s-localbe.ipc", self);
assert(rc == 0);
// Bind cloud frontend to endpoint
zsock_t *cloudfe_sock = zsock_new (ZMQ_ROUTER);
zsock_set_identity (cloudfe_sock, self);
rc = zsock_bind (cloudfe_sock, "ipc://%s-cloud.ipc", self);
assert(rc == 0);
// Connect cloud backend to all peers
zsock_t *cloudbe_sock = zsock_new (ZMQ_ROUTER);
zsock_set_identity (cloudbe_sock, self);
int argn;
for (argn = 2; argn < argc; argn++) {
char *peer = argv [argn];
printf ("I: connecting to cloud frontend at '%s'\n", peer);
rc = zsock_connect (cloudbe_sock, "ipc://%s-cloud.ipc", peer);
assert(rc == 0);
}
// Bind state backend to endpoint
zsock_t *statebe_sock = zsock_new (ZMQ_PUB);
rc = zsock_bind (statebe_sock, "ipc://%s-state.ipc", self);
assert(rc == 0);
// Connect state frontend to all peers
zsock_t *statefe_sock = zsock_new (ZMQ_SUB);
zsock_set_subscribe (statefe_sock, "");
for (argn = 2; argn < argc; argn++) {
char *peer = argv [argn];
printf ("I: connecting to state backend at '%s'\n", peer);
rc = zsock_connect (statefe_sock, "ipc://%s-state.ipc", peer);
assert(rc == 0);
}
// Prepare monitor socket
zsock_t *monitor_sock = zsock_new (ZMQ_PULL);
rc = zsock_bind (monitor_sock, "ipc://%s-monitor.ipc", self);
assert(rc == 0);
// After binding and connecting all our sockets, we start our child
// tasks - workers and clients:
int worker_nbr;
for (worker_nbr = 0; worker_nbr < NBR_WORKERS; worker_nbr++)
zactor_new (worker_task, NULL);
// Start local clients
int client_nbr;
for (client_nbr = 0; client_nbr < NBR_CLIENTS; client_nbr++)
zactor_new (client_task, NULL);
// Queue of available workers
int local_capacity = 0;
int cloud_capacity = 0;
zlist_t *workers = zlist_new ();
// The main loop has two parts. First, we poll workers and our two service
// sockets (statefe and monitor), in any case. If we have no ready workers,
// then there's no point in looking at incoming requests. These can remain //
// on their internal 0MQ queues://
void *localfe = zsock_resolve(localfe_sock);
void *localbe = zsock_resolve(localbe_sock);
void *cloudfe = zsock_resolve(cloudfe_sock);
void *cloudbe = zsock_resolve(cloudbe_sock);
void *statefe = zsock_resolve(statefe_sock);
void *statebe = zsock_resolve(statebe_sock);
void *monitor = zsock_resolve(monitor_sock);
while (true) {
zmq_pollitem_t primary [] = {
{ localbe, 0, ZMQ_POLLIN, 0 },
{ cloudbe, 0, ZMQ_POLLIN, 0 },
{ statefe, 0, ZMQ_POLLIN, 0 },
{ monitor, 0, ZMQ_POLLIN, 0 }
};
// If we have no workers ready, wait indefinitely
rc = zmq_poll (primary, 4,
local_capacity? 1000 * ZMQ_POLL_MSEC: -1);
if (rc == -1)
break; // Interrupted
// Track if capacity changes during this iteration
int previous = local_capacity;
zmsg_t *msg = NULL; // Reply from local worker
if (primary [0].revents & ZMQ_POLLIN) {
msg = zmsg_recv (localbe);
if (!msg)
break; // Interrupted
zframe_t *identity = zmsg_unwrap (msg);
zlist_append (workers, identity);
local_capacity++;
// If it's READY, don't route the message any further
zframe_t *frame = zmsg_first (msg);
if (memcmp (zframe_data (frame), WORKER_READY, 1) == 0)
zmsg_destroy (&msg);
}
// Or handle reply from peer broker
else
if (primary [1].revents & ZMQ_POLLIN) {
msg = zmsg_recv (cloudbe);
if (!msg)
break; // Interrupted
// We don't use peer broker identity for anything
zframe_t *identity = zmsg_unwrap (msg);
zframe_destroy (&identity);
}
// Route reply to cloud if it's addressed to a broker
for (argn = 2; msg && argn < argc; argn++) {
char *data = (char *) zframe_data (zmsg_first (msg));
size_t size = zframe_size (zmsg_first (msg));
if (size == strlen (argv [argn])
&& memcmp (data, argv [argn], size) == 0)
zmsg_send (&msg, cloudfe);
}
// Route reply to client if we still need to
if (msg)
zmsg_send (&msg, localfe);
// If we have input messages on our statefe or monitor sockets, we
// can process these immediately:
if (primary [2].revents & ZMQ_POLLIN) {
char *peer = zstr_recv (statefe);
char *status = zstr_recv (statefe);
cloud_capacity = atoi (status);
free (peer);
free (status);
}
if (primary [3].revents & ZMQ_POLLIN) {
char *status = zstr_recv (monitor);
printf ("%s\n", status);
free (status);
}
// Now route as many clients requests as we can handle. If we have
// local capacity, we poll both localfe and cloudfe. If we have cloud
// capacity only, we poll just localfe. We route any request locally
// if we can, else we route to the cloud.
while (local_capacity + cloud_capacity) {
zmq_pollitem_t secondary [] = {
{ localfe, 0, ZMQ_POLLIN, 0 },
{ cloudfe, 0, ZMQ_POLLIN, 0 }
};
if (local_capacity)
rc = zmq_poll (secondary, 2, 0);
else
rc = zmq_poll (secondary, 1, 0);
assert (rc >= 0);
if (secondary [0].revents & ZMQ_POLLIN)
msg = zmsg_recv (localfe);
else
if (secondary [1].revents & ZMQ_POLLIN)
msg = zmsg_recv (cloudfe);
else
break; // No work, go back to primary
if (local_capacity) {
zframe_t *frame = (zframe_t *) zlist_pop (workers);
zmsg_wrap (msg, frame);
zmsg_send (&msg, localbe);
local_capacity--;
}
else {
// Route to random broker peer
int peer = randof (argc - 2) + 2;
zmsg_pushmem (msg, argv [peer], strlen (argv [peer]));
zmsg_send (&msg, cloudbe);
}
}
// We broadcast capacity messages to other peers; to reduce chatter,
// we do this only if our capacity changed.
if (local_capacity != previous) {
// We stick our own identity onto the envelope
zstr_sendm (statebe, self);
// Broadcast new capacity
zstr_sendf (statebe, "%d", local_capacity);
}
}
// When we're done, clean up properly
while (zlist_size (workers)) {
zframe_t *frame = (zframe_t *) zlist_pop (workers);
zframe_destroy (&frame);
}
zlist_destroy (&workers);
zmq_ctx_destroy (&ctx);
return EXIT_SUCCESS;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_otool.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: eparisot <eparisot@42.student.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/12 12:41:26 by eparisot #+# #+# */
/* Updated: 2019/11/12 17:28:54 by eparisot ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_otool.h"
char *get_arch_name(int type)
{
if (type == CPU_TYPE_I386)
return ("i386");
else if (type == CPU_TYPE_X86_64)
return ("x86_64");
else if (type == CPU_TYPE_POWERPC)
return ("ppc");
else if (type == CPU_TYPE_POWERPC64)
return ("ppc64");
return ("???");
}
void ft_otool(void *obj, void *end, char *obj_name)
{
unsigned int magic_nb;
magic_nb = *(int *)obj;
if (magic_nb == MH_MAGIC_64 || magic_nb == MH_CIGAM_64)
{
(magic_nb == MH_MAGIC_64) ? set_cpu(0) : set_cpu(1);
handle_64(obj, end, obj_name);
}
else if (magic_nb == MH_MAGIC || magic_nb == MH_CIGAM)
{
(magic_nb == MH_MAGIC) ? set_cpu(0) : set_cpu(1);
handle_32(obj, end, obj_name);
}
else if (magic_nb == FAT_MAGIC_64 || magic_nb == FAT_CIGAM_64)
handle_fat(obj, end, 64, obj_name);
else if (magic_nb == FAT_MAGIC || magic_nb == FAT_CIGAM)
handle_fat(obj, end, 32, obj_name);
else if (magic_nb == AR_MAGIC || magic_nb == AR_CIGAM)
handle_arch(obj, end, obj_name);
else
ft_putstr("Error corrupted or not implemented\n");
}
static void read_obj(char *obj_name)
{
int fd;
void *obj;
struct stat buf;
if ((fd = open(obj_name, O_RDONLY)) < 0)
{
print_err("Error openning file", obj_name);
return ;
}
if (fstat(fd, &buf) < 0)
{
print_err("Error stating file", obj_name);
close(fd);
return ;
}
if ((obj = mmap(0, buf.st_size, PROT_READ, MAP_PRIVATE, fd, 0)) == \
MAP_FAILED)
print_err("Error mapping file", obj_name);
else
{
close(fd);
ft_otool(obj, obj + buf.st_size, obj_name);
if (munmap(obj, buf.st_size) < 0)
print_err("Error munmap", "");
}
}
int main(int argc, char *argv[])
{
int i;
i = 0;
if (argc >= 2)
while (++i < argc)
read_obj(argv[i]);
else
read_obj("a.out\0");
return (0);
}
|
C
|
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#include "lexer.h"
#include "ast.h"
#include "parser.h"
#include "symbol.h"
#include "compile.h"
#include "vm.h"
#include "alvc.h"
#define arg(s) (!strcmp(s, argv[i]))
extern char* yyfile;
extern FILE* yyin;
static char* progname;
int main (int argc, char* argv[]) {
int i = 1;
FILE *alvcin = NULL;
Node *ast = NULL;
SymTable *st = NULL;
Program *p = NULL;
int exit_status = EXIT_SUCCESS;
struct {
enum { COMPILE, EXEC, BYTECODE, TRACE } mode;
char *out, *in;
} options = { COMPILE, NULL, NULL };
progname = basename (argv[0]);
if (!(argc == 2 && arg("-h")) && argc < 3)
fatal ("not enough arguments (run with -h)");
if (arg("-h")) {
puts (
"alvc -- the Awesome L Virtual machine and Compiler\n"
" usage: alvc mode input [output]\n"
" mode: may be either -c (compile), -x (execute),\n"
" -b (execute bytecode), -t (trace) ou -h (help)\n"
" input: input file in L or in bytecode\n"
" output: output file, defaults to /dev/stdout (only for -c/-t)"
);
exit (EXIT_SUCCESS);
}
else if (arg("-c")) options.mode = COMPILE;
else if (arg("-x")) options.mode = EXEC;
else if (arg("-b")) options.mode = BYTECODE;
else if (arg("-t")) options.mode = TRACE;
else fatal ("unknwon mode");
yyfile = argv[++i];
options.in = yyfile;
if (argv[++i]) options.out = argv[i];
alvcin = fopen (options.in, "r");
if (NULL == alvcin) {
fprintf (stderr, "unable to open %s for reading (%s)\n",
options.in, strerror (errno));
exit (errno);
}
yyin = alvcin;
if (EXEC != options.mode && BYTECODE != options.mode && NULL != options.out) {
stdout = freopen (options.out, "w+", stdout);
if (NULL == stdout) {
fprintf (stderr, "unable to open %s for writing (%s)\n",
options.out, strerror (errno));
exit (errno);
}
}
if (options.mode != BYTECODE) {
next_token ();
ast = rule_program ();
st = SymTable_new (
Node_countType (ast, N_VAR_DEC) +
Node_countType (ast, N_FUN_DEC) +
Node_countType (ast, N_ARR_DEC)
);
SymTable_build (st, ast);
if (SymTable_hasFailed (false)) exit(EXIT_FAILURE);
p = AST_compile (ast, st);
}
switch (options.mode) {
case COMPILE:
Program_dump (p, st);
break;
case EXEC:
runvm (VM_new (p, SymTable_globalSize (st)), p, &exit_status);
break;
case BYTECODE: {
VM *vm = VM_fromBytecode (alvcin);
runvm (vm, (p = VM_extractProgram (vm)), &exit_status);
} break;
case TRACE:
SymTable_print (st);
Program_print (p);
break;
}
if (NULL != p) Program_destroy (p);
if (NULL != st) SymTable_destroy (st);
if (NULL != ast) Node_destroy (ast);
fclose (alvcin);
exit (exit_status);
}
void runvm (VM *vm, Program *p, int *es) {
if (VM_getDebugMode ()) {
puts ("Running the following program: ");
Program_print (p);
}
*es = VM_run (vm);
VM_destroy (vm);
}
void fatal (char *msg) {
fprintf (stderr, "fatal: %s [%s]\n", msg, progname);
exit (EXIT_FAILURE);
}
|
C
|
// Absolude Beginner's Guide to C, 3rd Edition Kindle
// sample code of Chapter5
// File chapter5_1.c
// This is a sample program that lists three kids and their school supply needs, as well as cost to buy the supplies
#include <stdio.h>
int main(void)
{
// Set up the variables, as well as define a few
char firstInitail,middleInitial;
int number_of_pencils;
int number_of_notebooks;
float pencils = 0.25;
float notebooks = 3.34;
float lunchbox = 5.48;
// The information for the first child
firstInitail = 'J';
middleInitial = 'R';
number_of_pencils = 5;
number_of_notebooks = 4;
printf("%c%c needs %d pencils, %d notebooks, and 1 lunchbox\n",firstInitail,middleInitial,number_of_pencils,number_of_notebooks);
printf("The total cost is $%.2f\n\n",number_of_pencils * pencils + number_of_notebooks * notebooks + lunchbox);
// The information for the second child
firstInitail = 'H';
middleInitial = 'U';
number_of_pencils = 7;
number_of_notebooks = 2;
printf("%c%c needs %d pencils, %d notebooks, and 1 lunchbox\n",firstInitail,middleInitial,number_of_pencils,number_of_notebooks);
printf("The total cost is $%.2f\n\n",number_of_pencils * pencils + number_of_notebooks * notebooks + lunchbox);
// The information for the third child
firstInitail = 'S';
middleInitial = 'A';
number_of_pencils = 2;
number_of_notebooks = 9;
printf("%c%c needs %d pencils, %d notebooks, and 1 lunchbox\n",firstInitail,middleInitial,number_of_pencils,number_of_notebooks);
printf("The total cost is $%.2f\n\n",number_of_pencils * pencils + number_of_notebooks * notebooks + lunchbox);
return 0;
}
|
C
|
#include <stdio.h>
#include <winsock2.h>
#include <process.h>
#include <windows.h>
extern int initWSADATA();
extern SOCKET initSocket();
struct arglist {
char *message;
} args;
unsigned int __stdcall getServMsg(void *args) {
struct arglist *als = (struct arglist *)args;
char *message;
while(1) {
gets(message);
als->message = message;
}
}
void main() {
initWSADATA();
SOCKET sClient = initSocket();
struct sockaddr_in saServer;
saServer.sin_family = AF_INET;
saServer.sin_port = htons(8888);
saServer.sin_addr.S_un.S_addr = inet_addr("192.168.0.104");
int ret = connect(sClient, (struct sockaddr *)&saServer, sizeof(struct sockaddr));
if (ret == SOCKET_ERROR) {
printf("connect() failed! errorCode: %d\n", WSAGetLastError());
closesocket(sClient);
WSACleanup();
return;
}
unsigned long NonBlock = 1;
if(ioctlsocket(sClient, FIONBIO, &NonBlock) == SOCKET_ERROR) {
printf("ioctlsocket failed\n");
return;
}
fflush(stdout);
char recvBuf[100];
char message;
//recv(sClient, recvBuf, 100, 0);
//printf("%s\n", recvBuf);
fd_set rfd;
fd_set wfd;
args.message = "";
HANDLE handle = (HANDLE)_beginthreadex(NULL, 0, getServMsg, &args, 0, NULL);
do {
FD_ZERO(&rfd);
FD_ZERO(&wfd);
FD_SET(sClient, &rfd);
FD_SET(sClient, &wfd);
ret = select(0, &rfd, &wfd, NULL, NULL);
if(ret == SOCKET_ERROR) {
closesocket(sClient);
break;
}
if(ret > 0) {
if(FD_ISSET(sClient, &rfd)) {
if(recv(sClient, recvBuf, 100, 0) == SOCKET_ERROR) {
printf("connect failed! \n");
break;
}
printf("server recv:%s\n", recvBuf);
}
if(FD_ISSET(sClient, &wfd)) {
if(strlen(args.message) > 0) {
char *msg = args.message;
send(sClient, msg, strlen(msg) + 1, 0);
args.message = "";
}
}
}
fflush(stdout);
} while(1);
WSACleanup();
}
|
C
|
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include "c_avltree.h"
char clearBuffer()
{
char c;
char wereChars=0;
while((c=getchar())!='\n' && c!=EOF) //let's clear a buffer!
wereChars=1;
return !wereChars; //let's return if there were unised chars in a buffer
}
int cgetValidatedConInt(const char *stringToWrite, int min, int max)
{ //min - minimum possible number, max- maximum.
int rc, num;
while(1)
{
printf("%s", stringToWrite);
rc=scanf("%7d", &num); // maximum of 7 chars
char clearRet = clearBuffer();
if(rc!=1 || num<min || num>max || !clearRet) //if scanf failed, number is wrong, or were unused chars
{
printf("Tai blogas skaicius. (Per didelis, per mazas, arba isvis nesamone.)\n");
}
else
break; //get out of da loop
}
return num;
}
//Void secshon.
char elemEvaluator_voidInt( void* el1, void* el2)
{
if(!el1 || !el2) return 2;
if(*((int*)el1) > *((int*)el2)) return 1;
if(*((int*)el1) < *((int*)el2)) return -1;
return 0; //el1 = el2
}
void valDest_voidInt(void** val)
{
if(!val ? 1 : !(*val)) return; //non-existent.
//printf("[valueDestructor()]: valDest called with **val = %d, *val = %p, and val = %p\n", *((int*)(*val)), *val, val);
free(*val);
*val = NULL;
//printf("[valueDestructor()]: *val delete'd. *val = NULL. Done!\n");
}
const char* elemToString(void* val)
{
char* st = (char*)malloc(16*sizeof(char));
sprintf(st, "%d\0", *((int*)val));
return st;
}
void* voidifyInt(int val)
{
void* patr = malloc(sizeof(int));
*((int*)patr) = val;
return patr;
}
void C_Test_VoidPointr(C_AVLTree* cavl)
{
if(!cavl) return;
avl_setCallbacks(cavl, valDest_voidInt, elemEvaluator_voidInt, elemToString);
int n = cgetValidatedConInt("\nEnter how many nums you'll write.\n>> ", 1, 20);
for(int i=0; i<n; i++)
{
printf("[%d]: ", i);
int tm = cgetValidatedConInt("", INT_MIN+1, INT_MAX-1);
avl_addElement( cavl, voidifyInt(tm), 0, 1 );
}
avl_showTree(*cavl, 4, 0, 0);
printf("\n* - * - * - * - * - * - * -\n");
int elem2delete = cgetValidatedConInt("\nEnter elem2delete\n>> ", INT_MIN+1, INT_MAX-1);
printf("\nDeleting elem: %d\n", elem2delete);
avl_deleteElement( cavl, voidifyInt(elem2delete) );
avl_showTree(*cavl, 4, 0, 0);
int searchFor = cgetValidatedConInt("\nEnter elem2search\n>> ", INT_MIN+1, INT_MAX-1);
printf("\nSearhing for element: %d\n", searchFor);
if(avl_findElement(*cavl, voidifyInt(searchFor)))
printf("Element F O U N D !!!\n");
else
printf("Element not found.\n");
}
const char* intToString_Callbk(int val)
{
char* st = (char*)malloc(16*sizeof(char));
sprintf(st, "%d\0", val);
return st;
}
void C_Test_Int(C_AVLTree* cavl)
{
if(!cavl) return;
//avl_setCallbacks(cavl, valDest_voidInt, elemEvaluator_voidInt, elemToString);
avl_setCallbacks(cavl, NULL, NULL, intToString_Callbk);
int n = cgetValidatedConInt("\nEnter how many nums you'll write.\n>> ", 1, 20);
for(int i=0; i<n; i++)
{
printf("[%d]: ", i);
int tm = cgetValidatedConInt("", INT_MIN+1, INT_MAX-1);
//avl_addElement( cavl, voidifyInt(tm), 0, 1 );
avl_addElement(cavl, tm, 0, 1);
}
avl_showTree(*cavl, 4, 0, 0);
printf("\n* - * - * - * - * - * - * -\n");
int elem2delete = cgetValidatedConInt("\nEnter elem2delete\n>> ", INT_MIN+1, INT_MAX-1);
printf("\nDeleting elem: %d\n", elem2delete);
//avl_deleteElement( cavl, voidifyInt(elem2delete) );
avl_deleteElement(cavl, elem2delete);
avl_showTree(*cavl, 4, 0, 0);
int searchFor = cgetValidatedConInt("\nEnter elem2search\n>> ", INT_MIN+1, INT_MAX-1);
printf("\nSearhing for element: %d\n", searchFor);
if(avl_findElement(*cavl, searchFor))
printf("Element F O U N D !!!\n");
else
printf("Element not found.\n");
}
int main()
{
C_AVLTree cavl;
avl_initTree(&cavl);
C_Test_Int(&cavl);
avl_clearTree(&cavl, 1);
return 0;
}
|
C
|
/*
* Fails when adding double + integer.
*/
/*
* test13 - check to see if op2 works
*/
main()
{
int i, j, k;
double a, b, c;
j = 25;
k = 5;
i = j + k; /* integer arithmetic */
printf("i is %d\n", i);
i = j * k; /* integer arithmetic */
printf("i is %d\n", i);
i = j / k; /* integer arithmetic */
printf("i is %d\n", i);
i = j - k; /* integer arithmetic */
printf("i is %d\n", i);
b = 12;
c = 6;
a = b + c; /* double arithmetic */
printf("a is %f\n", a);
a = b * c; /* double arithmetic */
printf("a is %f\n", a);
a = b / c; /* double arithmetic */
printf("a is %f\n", a);
a = b - c; /* double arithmetic */
printf("a is %f\n", a);
a = i + b; /* mixed mode */
printf("a is %f\n", a);
a = b + i; /* mixed mode */
printf("a is %f\n", a);
}
|
C
|
#pragma systemFile
#if !defined(TRAPEZOIDALPROFILE_C_)
#define TRAPEZOIDALPROFILE_C_
typedef struct {
float maxVel;
float maxAcc;
float v0;
float v1;
} TrapezoidalProfile;
TrapezoidalProfile *newTrapezoidalProfile(TrapezoidalProfile *this, float maxVel,
float maxAcc, float v0, float v1) {
if (this) {
this->maxVel = maxVel;
this->maxAcc = maxAcc;
this->v0 = v0;
this->v1 = v1;
}
return this;
}
float getMaxVel(TrapezoidalProfile *this) {
return this ? this->maxVel : 0.0;
}
void setMaxVel(TrapezoidalProfile *this, float maxVel) {
if (this) {
this->maxVel = maxVel;
}
}
float getMaxAcc(TrapezoidalProfile *this) {
return this ? this->maxAcc : 0.0;
}
void setMaxAcc(TrapezoidalProfile *this, float maxAcc) {
if (this) {
this->maxAcc = maxAcc;
}
}
float getV0(TrapezoidalProfile *this) {
return this ? this->v0 : 0.0;
}
void setV0(TrapezoidalProfile *this, float v0) {
if (this) {
this->v0 = v0;
}
}
float getV1(TrapezoidalProfile *this) {
return this ? this->v1 : 0.0;
}
void setV1(TrapezoidalProfile *this, float v1) {
if (this) {
this->v1 = v1;
}
}
float update(TrapezoidalProfile *this, float error, float t) {
if (this == NULL) {
return 0.0;
}
// Find target velocity based on time (acceleration).
float v = this->v0 + this->maxAcc * t; // v = v0 + a*t
// Keep target velocity within its limit.
if (v > this->maxVel) {
v = sgn(v) * this->maxVel;
}
// If it is time to decelerate (use v1 in place of v0 to decelerate).
// ds = (v^2 - v0^2) / (2*a) derived from v^2 = v0^2 + 2*a*ds.
if (error <= (pow(v, 2.0) - pow(this->v1, 2.0)) / (2.0 * this->maxAcc)) {
// Find target velocity based on error (deceleration).
// v = sqrt(v0^2 + 2*a*ds) derived from v^2 = v0^2 + 2*a*ds.
v = sgn(this->maxAcc * error)
* sqrt(fabs(pow(this->v1, 2.0) + 2 * this->maxAcc * error));
}
return v; // Return target velocity.
}
#endif // TRAPEZOIDALPROFILE_C_
|
C
|
#include<stdio.h>
#pragma warning(disable:4996)
int main() {
char code[16];
int time = 0;
scanf("%s", code);
for (int i = 0; i < 16; i++) {
if (code[i] == '\0')
break;
int k = code[i]-'A';
switch (k)
{
case 0: case 1: case 2:
time = time + 3;
break;
case 3: case 4: case 5:
time = time + 4;
break;
case 6: case 7: case 8:
time = time + 5;
break;
case 9: case 10: case 11:
time = time + 6;
break;
case 12: case 13: case 14:
time = time + 7;
break;
case 15: case 16: case 17: case 18:
time = time + 8;
break;
case 19: case 20: case 21:
time = time + 9;
break;
case 22: case 23: case 24: case 25:
time = time + 10;
break;
default:
break;
}
}
printf("%d", time);
}
|
C
|
#include<stdio.h>
int main ( int argc, char * argv[] ) {
int i;
puts ( "This function, reads three words arguments(strings) and then it prints it back..." );
if ( argc != 4 )
puts ( "You need to type something like:'./function_param string1 string2 string3 ' this will run the command line tool..." );
else {
for ( i = 1; i <= 3; i++ )
printf ( "The #%i argument you type is: %s\n", i, argv[i] );
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "tf_qf.h"
typedef struct {
uint8_t *data;
uint32_t len;
} inputs_t;
int main(void){
unlink("/tmp/test.qf");
int i;
uint32_t cnt, dlen;
inputs_t inputs[4];
uint8_t msg1[512];
uint16_t msg1sz = 512;
for( i=0; i<msg1sz; i++){ msg1[i] = (uint8_t)rand(); }
inputs[0].data = msg1;
inputs[0].len = msg1sz;
uint8_t msg2[250];
uint16_t msg2sz = 250;
for( i=0; i<msg2sz; i++){ msg2[i] = (uint8_t)rand(); }
inputs[1].data = msg2;
inputs[1].len = msg2sz;
uint8_t msg3[1];
uint16_t msg3sz = 1;
for( i=0; i<msg3sz; i++){ msg3[i] = (uint8_t)rand(); }
inputs[2].data = msg3;
inputs[2].len = msg3sz;
uint8_t msg4[] = "DDDDDDDDDDDD";
uint16_t msg4sz = 12;
for( i=0; i<msg4sz; i++){ msg4[i] = (uint8_t)rand(); }
inputs[3].data = msg4;
inputs[3].len = msg4sz;
uint32_t expected_cnt = 0;
uint32_t expected_len = 0;
printf("-- Basic push fill\n");
TFQF_QueueFile_t qf;
if( TFQF_Open( &qf, "/tmp/test.qf" ) != 0 ){
printf("ERR: open\n");
return 1;
}
cnt = dlen = 0; TFQF_Stats( &qf, &cnt, &dlen );
if( cnt != expected_cnt || dlen != expected_len ){
printf("ERR: stats0\n"); return 1; }
for( i=0; i<4; i++ ){
if( TFQF_Push( &qf, inputs[i].data, inputs[i].len ) != 0 ){
printf("ERR: push inp=%d\n", i); return 2; }
expected_cnt++;
expected_len += inputs[i].len;
cnt = dlen = 0; TFQF_Stats( &qf, &cnt, &dlen );
if( cnt != expected_cnt || dlen != expected_len ){
printf("ERR: stats inp=%d c=%d d=%d\n", i, cnt, dlen); return 1; }
}
printf("-- Memory iterate\n");
#ifndef NO_MEMORY
TFQF_MemoryItem_t items[4];
memset( items, 0, sizeof(items) );
if( TFQF_Memory_Open( &qf, items, 4 ) != 4 ){
printf("ERR: memopen\n"); return 9; }
for( i=0; i<4; i++ ){
printf("- item[%d] len=%d\n", i, items[i].data_len);
if( items[i].data == NULL ){
printf("ERR: mem%d null\n", i); return 8; }
if( items[i].data_len != inputs[3-i].len ){
printf("ERR: mem%d sz\n", i); return 8; }
if( memcmp(items[i].data, inputs[3-i].data, items[i].data_len) != 0 ){
printf("ERR: mem%d data\n", i); return 8; }
}
TFQF_Memory_Close( &qf );
#endif
uint8_t buff[0xffff];
uint16_t len = 0;
printf("-- Basic pop drain\n");
for( i=3; i>=0; i-- ){
len = 0xffff;
if( TFQF_Pop( &qf, buff, &len ) != 0 ){
printf("ERR: pop%d len=%d qflmp=%d qfnxt=%d\n",
i, len, qf.lmp, qf.nxt); return 3; }
if( len != inputs[i].len || memcmp(buff, inputs[i].data, len) != 0 ){
printf("ERR: pop%d data\n", i); return 4; }
expected_cnt--;
expected_len -= len;
cnt = dlen = 0; TFQF_Stats( &qf, &cnt, &dlen );
if( cnt != expected_cnt || dlen != expected_len ){
printf("ERR: stats%dp\n", i); return 1; }
}
cnt = dlen = 0; TFQF_Stats( &qf, &cnt, &dlen );
if( cnt != 0 || dlen != 0 ){ printf("ERR: stats0p\n"); return 1; }
len = 0xffff;
if( TFQF_Pop( &qf, buff, &len ) == 0 && len != 0 ){
printf("ERR: expected empty\n"); return 5; }
TFQF_Close( &qf );
printf("-- Add/close/open/check\n");
if( TFQF_Open( &qf, "/tmp/test.qf" ) != 0 ){
printf("ERR: open2\n");
return 1;
}
cnt = dlen = 0; TFQF_Stats( &qf, &cnt, &dlen );
if( cnt != 0 || dlen != 0 ){ printf("ERR: stats0.2\n"); return 1; }
if( TFQF_Push( &qf, msg1, msg1sz ) != 0 ){
printf("ERR: push1.2\n"); return 2; }
TFQF_Close( &qf );
if( TFQF_Open( &qf, "/tmp/test.qf" ) != 0 ){
printf("ERR: open3\n");
return 1;
}
cnt = dlen = 0; TFQF_Stats( &qf, &cnt, &dlen );
if( cnt != 1 || dlen != msg1sz ){
printf("ERR: stats1.3 c=%d d=%d\n", cnt, dlen); return 1; }
len = 0xffff;
if( TFQF_Pop( &qf, buff, &len ) != 0 ){
printf("ERR: pop1.3 len=%d\n", len); return 3; }
if( len != msg1sz || memcmp(buff, msg1, len) != 0 ){
printf("ERR: pop1.3 data\n"); return 4; }
TFQF_Close( &qf );
printf("--- Pre-prune fill\n");
if( TFQF_Open( &qf, "/tmp/test.qf" ) != 0 ){
printf("ERR: open3\n");
return 1;
}
for( i=0; i<12; i++ ){
if( TFQF_Push( &qf, inputs[0].data, inputs[0].len ) != 0 ){
printf("ERR: prune push %d\n", i); return 12; }
}
cnt = dlen = 0; TFQF_Stats( &qf, &cnt, &dlen );
if( cnt != 12 ){
printf("ERR: prune stats c=%d d=%d\n", cnt, dlen); return 1; }
printf("--- Prune drain\n");
for( i=0; i<4; i++ ){
if( TFQF_Prune( &qf, 3 ) != 3 ){
printf("ERR: prune%d\n", i); return 14; }
cnt = dlen = 0; TFQF_Stats( &qf, &cnt, &dlen );
if( cnt != (9 - (i*3)) ){
printf("ERR: post-prune stats %d c=%d d=%d\n", i, cnt, dlen);
return 14; }
}
printf("--- OK\n");
return 0;
}
|
C
|
#include <stdlib.h>
#include <math.h>
int calcDamage(int srcLevel, int srcAttack, int movePower, int trgDefense, int stab, float typeMod){
float final;
int randnum = rand() % 38 + 217;
int a = ((2*srcLevel)/5+2);
final = (((((a*srcAttack*movePower)/trgDefense)+2)*stab)*typeMod)/255;
return floor(final);
}
|
C
|
/*Erik Grunnr
25/09/2017
Labs 2 */
#include <stdio.h>
int main ()
{
float radius,pi,area;
radius = 4.8;
pi = 3.14;
area = pi*radius*radius;
printf("area of the circle is %f", area);
getchar();
return 0;
}
|
C
|
/**
* @file ready_queue.h
* @author Ahmed Ashraf, Mohamed Hassanin
* @brief A mocking of the ready queue which contains the porcess that have already arrived to the scheduler
* @version 0.1
* @date 2020-12-30
*/
#ifndef _READY_QUEUE_H
#define _READY_QUEUE_H
#include "pcb.h"
struct Queue {
int front, rear, size;
unsigned capacity;
PCB** array;
};
struct Queue* CreateQueue(unsigned capacity);
int IsFull(struct Queue* queue);
int IsEmpty(struct Queue* queue);
void Enqueue(struct Queue* queue, PCB* item);
PCB* Dequeue(struct Queue* queue);
PCB* Front(struct Queue* queue);
PCB* Rear(struct Queue* queue);
#endif /* _READY_QUEUE_H */
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char ** argv)
{
int a,b,c,vcm;
printf("Entre com a pontuacao dos concorrentes:");
scanf(" %d %d %d", &a, &b, &c);
vcm = 0;
if(a>b && a<c || a<b && a>c)
{
vcm = a;
}else if(b>a && b<c || b<a && b>c)
{
vcm = b;
}else
{
vcm = c;
}
printf("Segundo Colocado: %d\n", vcm);
system("pause");
return 0;
}
|
C
|
/*
* optimize nullifying loops
* such as '[-]' into a single
* cell-zeroing instruction: *
*/
#include <stddef.h>
#include <stdlib.h>
#include "instructions.h"
#include "options.h"
#include "opt-nloops.h"
#include "status.h"
void
optimize_nloops(struct Options *opts, struct Instruction *head)
{
usize i = 0;
if (opts->verbose)
status_init("optimizing nullification loops");
for (struct Instruction *c = head; c != NULL; c = c->next, ++i) {
if (opts->verbose)
status_update("optimizing nullification loops",
i, STATUS_UNKNOWN);
if (c->command == '['
&& (c->next->command == '-'
|| c->next->command == '+')
&& c->next->next->command == ']'
) {
c->command = '*';
if (c->next->next->next != NULL) {
struct Instruction *tmp = c->next->next->next;
free(c->next->next);
free(c->next);
c->next = tmp;
tmp->prev = c;
} else {
free(c->next->next);
free(c->next);
c->next = NULL;
}
}
}
if (opts->verbose)
status_complete("optimizing nullification loops");
}
|
C
|
/*Both of these files are filled with unoptimized code. I ran out of time, and had to stick with my brute force code. Sorry for the delay it will cause.*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
//initialize definition for rooms
struct room {
int id;
char* name;
int numCons;
char* conRooms[6];
};
/********************************************
* function name: IsGraphFull()
* Description: this function checks
* if each room in the array of room
* structs has at least 3 room connections.
**********************************************/
int IsGraphFull(struct room* myRooms[]) //takes an array of structs
{
int i;
for (i = 0; i < 7; i++){
if (myRooms[i]->numCons < 3){
return 0;
}
}
return 1;
}
/***********************************************
* function name: CanAddConnectionFrom()
* Description: this function checks if the
* room passed can be connected to.
***********************************************/
int CanAddConnectionFrom(struct room* a){
if (a->numCons < 6){ //if the room has less than 6 rooms, return
return 1;
}
//else, return
return 0;
}
/************************************************
* function name: ConnectionAlreadyExists
* Description: this function checks if the
* two rooms passed have already been connected.
*************************************************/
int ConnectionAlreadyExists(struct room* x, struct room* y){
int n;
for (n = 0; n < x->numCons; n++){
if (strcmp(x->conRooms[n], y->name) == 0){
return 1;
}
}
return 0;
}
/*******************************************
* function name: ConnectRoom
* Description: this function connects two
* rooms together forward and back
*********************************************/
void ConnectRoom(struct room* x, struct room* y){
int num1 = x->numCons;
int num2 = y->numCons;
x->conRooms[num1] = y->name;
y->conRooms[num2] = x->name;
x->numCons += 1;
y->numCons += 1;
}
/************************************************
* function description: IsSameRoom
* Description: this function checks if the two
* rooms passed are actually the same room
************************************************/
int IsSameRoom(struct room* x, struct room* y){
if (x->id == y->id){//if both ids are the same, same room
return 1;
}
return 0;
}
/*****************************************************
* function name: AddRaondomConnection
* Description: this function finds two random rooms
* from an array of rooms and tries to connect them
******************************************************/
void AddRandomConnection(struct room* myRooms[7]){
struct room a;
struct room b;
int num1;
while(1){
num1 = rand()%(7); //find a random room
a = *myRooms[num1];//dereference the pointer to the room chosen
if (CanAddConnectionFrom(&a) == 1){ //check if it can be added from
break;//if yes, quit loop, else keep looking
}
}
int num2;
do {
num2 = rand()%(7); //second room to add
b = *myRooms[num2];
//while the rooms aren't the same, room 2 can add a connection
// and the connection doesn't already exist
}while ((num2 == num1) || (CanAddConnectionFrom(&b) == 0) || (ConnectionAlreadyExists(&a, &b) == 1));
ConnectRoom(&a, &b); //connect the rooms
int num3 = myRooms[num1]->numCons;
int num4 = myRooms[num2]->numCons;
//connect the map's rooms to the temp room struct info
myRooms[num1]->conRooms[num3] = a.conRooms[num3];
myRooms[num2]->conRooms[num4] = b.conRooms[num4];
myRooms[num1]->numCons = a.numCons;
myRooms[num2]->numCons = b.numCons;
}
int main() {
srand((unsigned)time(NULL)); //to randomize numbers
int myRoomCons[7] = {0};
//make new directory
int dirID = getpid();
char idString[8] = "";
sprintf(idString, "%d", dirID);
char direct[32] = "";
strcat(direct, "merrinea.rooms.");
strcat(direct, idString);//create directory string
mkdir(direct, 0755);
//make files for each room
char file1[50] = "";
strcat(file1, direct);
strcat(file1, "/room1"); //create string for file 1
int fileDes1;
fileDes1 = open(file1, O_RDWR | O_CREAT, 0755);
char file2[50] = "";
strcat(file2, direct);
strcat(file2, "/room2"); //create string for file 2
int fileDes2;
fileDes2 = open(file2, O_RDWR | O_CREAT, 0755);
char file3[50] = "";
strcat(file3, direct);
strcat(file3, "/room3"); //create string for file 3
int fileDes3;
fileDes3 = open(file3, O_RDWR | O_CREAT, 0755);
char file4[50] = "";
strcat(file4, direct);
strcat(file4, "/room4"); //create string for file 4
int fileDes4;
fileDes4 = open(file4, O_RDWR | O_CREAT, 0755);
char file5[50] = "";
strcat(file5, direct);
strcat(file5, "/room5"); //create string for file 5
int fileDes5;
fileDes5 = open(file5, O_RDWR | O_CREAT, 0755);
char file6[50] = "";
strcat(file6, direct);
strcat(file6, "/room6"); //create string for file 6
int fileDes6;
fileDes6 = open(file6, O_RDWR | O_CREAT, 0755);
char file7[50] = "";
strcat(file7, direct);
strcat(file7, "/room7"); //create string for file 7
int fileDes7;
fileDes7 = open(file7, O_RDWR | O_CREAT, 0755);
//hardcode room names
char rName1[9] = "bedroom";
char rName2[9] = "yard";
char rName3[9] = "office";
char rName4[9] = "kitchen";
char rName5[9] = "bathroom";
char rName6[9] = "garage";
char rName7[9] = "foyer";
char rName8[9] = "TVRoom";
char rName9[9] = "nursery";
char rName10[9] = "library";
//enter room names into an array of strings
char* myRoomNames[10];
myRoomNames[0] = rName1;
myRoomNames[1] = rName2;
myRoomNames[2] = rName3;
myRoomNames[3] = rName4;
myRoomNames[4] = rName5;
myRoomNames[5] = rName6;
myRoomNames[6] = rName7;
myRoomNames[7] = rName8;
myRoomNames[8] = rName9;
myRoomNames[9] = rName10;
//hardcode room types
char rType1[11] = "START_ROOM";
char rType2[11] = "MID_ROOM";
char rType3[11] = "END_ROOM";
//put room types into array of strings
char* myRoomTypes[7];
myRoomTypes[0] = rType1;
myRoomTypes[1] = rType2;
myRoomTypes[2] = rType2;
myRoomTypes[3] = rType2;
myRoomTypes[4] = rType2;
myRoomTypes[5] = rType2;
myRoomTypes[6] = rType3;
//initialize map arrays
int roomNums[7] = {[0 ... 6] = 0};
struct room* myRooms[7] = {[0 ... 6] = NULL};
//initialize room structs
struct room firstRoom;
firstRoom.id = 0;
firstRoom.name = calloc(16, sizeof(char)); //make space for room name
firstRoom.numCons = 0;
ssize_t nwrittenN1; //initialize variables for writing to files
ssize_t nwrittenT1;
int rand1 = rand()%(10); //pick a random room name
strcpy(firstRoom.name, myRoomNames[rand1]); //copy it to room's name
char rn1[20] = "";
strcat(rn1, "ROOM NAME: ");
strcat(rn1, myRoomNames[rand1]);
strcat(rn1, "\n"); // create string to write to file
nwrittenN1 = write(fileDes1, rn1, strlen(rn1) * sizeof(char)); //write room name to room's file
int rtype1 = rand()%(7); //randomize room types
char rt1[20] = "";
strcat(rt1, "ROOM TYPE: ");
strcat(rt1, myRoomTypes[rtype1]);
strcat(rt1, "\n"); //create string for room type to write to file
myRooms[0] = &firstRoom; //save to map array
//initialize second room
struct room secRoom;
secRoom.id = 1;
secRoom.numCons = 0;
secRoom.name = calloc(16, sizeof(char));
ssize_t nwrittenN2;
ssize_t nwrittenT2;
int rand2 = rand()%(10);
while (rand2 == rand1){ //make sure the rooms are different
rand2 = rand()%(10);
}
strcpy(secRoom.name, myRoomNames[rand2]);
char rn2[20] = "";
strcat(rn2, "ROOM NAME: ");
strcat(rn2, myRoomNames[rand2]);
strcat(rn2, "\n");
nwrittenN2 = write(fileDes2, rn2, strlen(rn2) * sizeof(char));
int rtype2 = rand()%7;
while (rtype2 == rtype1){
rtype2 = rand()%(7); //get unique room type
}
char rt2[20] = "";
strcat(rt2, "ROOM TYPE: ");
strcat(rt2, myRoomTypes[rtype2]);
strcat(rt2, "\n");
myRooms[1] = &secRoom; //save to room array
//initialize third room
struct room thirdRoom;
thirdRoom.id = 2;
thirdRoom.numCons= 0;
thirdRoom.name = calloc(16, sizeof(char));
ssize_t nwrittenN3;
ssize_t nwrittenT3;
int rand3 = rand()%(10);
while ((rand3 == rand1) || (rand3 == rand2)){
rand3 = rand()%(10); //get unique room names
}
strcpy(thirdRoom.name, myRoomNames[rand3]);
char rn3[20] = "";
strcat(rn3, "ROOM NAME: ");
strcat(rn3, myRoomNames[rand3]);
strcat(rn3, "\n");
nwrittenN3 = write(fileDes3, rn3, strlen(rn3) * sizeof(char));
int rtype3 = rand()%(7);
while ((rtype3 == rtype2) || (rtype3 == rtype1)){
rtype3 = rand()%(7); //get unique room type
}
char rt3[20] = "";
strcat(rt3, "ROOM TYPE: ");
strcat(rt3, myRoomTypes[rtype3]);
strcat(rt3, "\n");
myRooms[2] = &thirdRoom; //save to room array
//initialize fourth room
struct room fourthRoom;
fourthRoom.id = 3;
fourthRoom.numCons = 0;
fourthRoom.name = calloc(16, sizeof(char));
ssize_t nwrittenN4;
ssize_t nwrittenT4;
int rand4 = rand()%(10);
while ((rand4 == rand1) || (rand4 == rand2) || (rand4 == rand3)){
rand4 = rand()%(10); //get unique rooms
}
strcpy(fourthRoom.name, myRoomNames[rand4]);
char rn4[20] = "";
strcat(rn4, "ROOM NAME: ");
strcat(rn4, myRoomNames[rand4]);
strcat(rn4, "\n");
nwrittenN4 = write(fileDes4, rn4, strlen(rn4) * sizeof(char));
int rtype4 = rand()%(7);
while ((rtype4 == rtype3) || (rtype4 == rtype2) || (rtype4 == rtype1)){
rtype4 = rand()%(7); //get unique type
}
char rt4[20] = "";
strcat(rt4, "ROOM TYPE: ");
strcat(rt4, myRoomTypes[rtype4]);
strcat(rt4, "\n");
myRooms[3] = &fourthRoom; //save to room array
//initialize fifth room
struct room fifthRoom;
fifthRoom.id = 4;
fifthRoom.numCons = 0;
fifthRoom.name = calloc(16, sizeof(char));
ssize_t nwrittenN5;
ssize_t nwrittenT5;
int rand5 = rand()%(10);
while ((rand5 == rand4) || (rand5 == rand3) || (rand5 == rand2) || (rand5 == rand1)){
rand5 = rand()%(10); //get unique rooms
}
strcpy(fifthRoom.name, myRoomNames[rand5]);
char rn5[20] = "";
strcat(rn5, "ROOM NAME: ");
strcat(rn5, myRoomNames[rand5]);
strcat(rn5, "\n");
nwrittenN5 = write(fileDes5, rn5, strlen(rn5) * sizeof(char));
int rtype5 = rand()%(7);
while ((rtype5 == rtype4) || (rtype5 == rtype3) || (rtype5 == rtype2) || (rtype5 == rtype1)){
rtype5 = rand()%(7); //get unique type
}
char rt5[20] = "";
strcat(rt5, "ROOM TYPE: ");
strcat(rt5, myRoomTypes[rtype5]);
strcat(rt5, "\n");
myRooms[4] = &fifthRoom; //save to rooms array
//initialize sixth room
struct room sixthRoom;
sixthRoom.id = 5;
sixthRoom.numCons = 0;
sixthRoom.name = calloc(16, sizeof(char));
ssize_t nwrittenN6;
ssize_t nwrittenT6;
int rand6 = rand()%(10);
while ((rand6 == rand5) || (rand6 == rand4) || (rand6 == rand3) || (rand6 == rand2) || (rand6 == rand1)){
rand6 = rand()%(10); //get unique room
}
strcpy(sixthRoom.name, myRoomNames[rand6]);
char rn6[20] = "";
strcat(rn6, "ROOM NAME: ");
strcat(rn6, myRoomNames[rand6]);
strcat(rn6, "\n");
nwrittenN6 = write(fileDes6, rn6, strlen(rn6) * sizeof(char));
int rtype6 = rand()%(7);
while ((rtype6 == rtype5) || (rtype6 == rtype4) || (rtype6 == rtype3) || (rtype6 == rtype2) || (rtype6 == rtype1)){
rtype6 = rand()%(7); //get unique type
}
char rt6[20] = "";
strcat(rt6, "ROOM TYPE: ");
strcat(rt6, myRoomTypes[rtype6]);
strcat(rt6, "\n");
myRooms[5] = &sixthRoom; //save to map array
//initialize seventh room
struct room sevRoom;
sevRoom.id = 6;
sevRoom.numCons = 0;
sevRoom.name = calloc(16, sizeof(char));
ssize_t nwrittenN7;
ssize_t nwrittenT7;
int rand7 = rand()%(10);
while ((rand7 == rand6) || (rand7 == rand5) || (rand7 == rand4) || (rand7 == rand3) || (rand7 == rand2) || (rand7 == rand1)){
rand7 = rand()%(10); //get unique room
}
strcpy(sevRoom.name, myRoomNames[rand7]);
char rn7[20] = "";
strcat(rn7, "ROOM NAME: ");
strcat(rn7, myRoomNames[rand7]);
strcat(rn7, "\n");
nwrittenN7 = write(fileDes7, rn7, strlen(rn7) * sizeof(char));
int rtype7 = rand()%(7);
while ((rtype7 == rtype6) || (rtype7 == rtype5) || (rtype7 == rtype4) || (rtype7 == rtype3) || (rtype7 == rtype2) || (rtype7 == rtype1)){
rtype7 = rand()%(7); //get unique room type
}
char rt7[20] = "";
strcat(rt7, "ROOM TYPE: ");
strcat(rt7, myRoomTypes[rtype7]);
strcat(rt7, "\n");
myRooms[6] = &sevRoom;//save to map array
//while the graph is not full, keep adding connections
while (IsGraphFull(myRooms) == 0){
AddRandomConnection(myRooms); //pass room array
}
//print connections to files for all rooms
int i;
ssize_t nwrittenC1; //room1 connection variable
for (i = 0; i < myRooms[0]->numCons; i++){
int num = i;
num += 1;
char castNum[3] = "";
sprintf(castNum, "%d", num);
char rc1[20] = "";
strcat(rc1, "CONNECTION ");
strcat(rc1, castNum);
strcat(rc1, ": ");
strcat(rc1, myRooms[0]->conRooms[i]);
strcat(rc1, "\n");//create formatted connection string
//write to file
nwrittenC1 = write(fileDes1, rc1, strlen(rc1) * sizeof(char));
}
int j;
ssize_t nwrittenC2; //connection for room 2
for ( j = 0; j < myRooms[1]->numCons; j++){ //for all connections
int num = j;
num += 1;
char castNum2[3] = "";
sprintf(castNum2, "%d", num);
char rc2[20] = "";
strcat(rc2, "CONNECTION ");
strcat(rc2, castNum2);
strcat(rc2, ": ");
strcat(rc2, myRooms[1]->conRooms[j]);
strcat(rc2, "\n");//create connection string to write
//write connections to room 2 file
nwrittenC2 = write(fileDes2, rc2, strlen(rc2) * sizeof(char));
}
int k;
ssize_t nwrittenC3; //connection var for room3
for (k = 0; k < myRooms[2]->numCons; k++){
int num = k;
num += 1;
char castNum3[3] ="";
sprintf(castNum3, "%d", num);
char rc3[20] = "";
strcat(rc3, "CONNECTION ");
strcat(rc3, castNum3);
strcat(rc3, ": ");
strcat(rc3, myRooms[2]->conRooms[k]);
strcat(rc3, "\n");// create connection string
//write string to room 3 file
nwrittenC3 = write(fileDes3, rc3, strlen(rc3) * sizeof(char));
}
int m;
ssize_t nwrittenC4; //connection var for room 4
for (m = 0; m < myRooms[3]->numCons; m++){
int num = m;
num += 1;
char castNum4[3] = "";
sprintf(castNum4, "%d", num);
char rc4[20] = "";
strcat(rc4, "CONNECTION ");
strcat(rc4, castNum4);
strcat(rc4, ": ");
strcat(rc4, myRooms[3]->conRooms[m]);
strcat(rc4, "\n"); //create connection string for room 4
//write string to room 4 file
nwrittenC4 = write(fileDes4, rc4, strlen(rc4) * sizeof(char));
}
int n;
ssize_t nwrittenC5; //connection var for room 5
for (n = 0; n < myRooms[4]->numCons; n++){
int num = n;
num += 1;
char castNum5[3] = "";
sprintf(castNum5, "%d", num);
char rc5[20] = "";
strcat(rc5, "CONNECTION ");
strcat(rc5, castNum5);
strcat(rc5, ": ");
strcat(rc5, myRooms[4]->conRooms[n]);
strcat(rc5, "\n");//create connection string for room 5
//write string to room 5 file
nwrittenC5 = write(fileDes5, rc5, strlen(rc5) * sizeof(char));
}
int p;
ssize_t nwrittenC6; //connection var for room 6
for (p = 0; p < myRooms[5]->numCons; p++){
int num = p;
num += 1;
char castNum6[3] = "";
sprintf(castNum6, "%d", num);
char rc6[20] = "";
strcat(rc6, "CONNECTION ");
strcat(rc6, castNum6);
strcat(rc6, ": ");
strcat(rc6, myRooms[5]->conRooms[p]);
strcat(rc6, "\n"); //create connection string for room 6
//write string to room 6 file
nwrittenC6 = write(fileDes6, rc6, strlen(rc6) * sizeof(char));
}
int q;
ssize_t nwrittenC7; //connection var for room 7
for (q = 0; q < myRooms[6]->numCons; q++){
int num = q;
num += 1;
char castNum7[3] = "";
sprintf(castNum7, "%d", num);
char rc7[20] = "";
strcat(rc7, "CONNECTION ");
strcat(rc7, castNum7);
strcat(rc7, ": ");
strcat(rc7, myRooms[6]->conRooms[q]);
strcat(rc7, "\n"); //create connection string for room 7
//write string to room 7 file
nwrittenC7 = write(fileDes7, rc7, strlen(rc7) * sizeof(char));
}
//write room type to each file
nwrittenT1 = write(fileDes1, rt1, strlen(rt1) * sizeof(char));
nwrittenT2 = write(fileDes2, rt2, strlen(rt2) * sizeof(char));
nwrittenT3 = write(fileDes3, rt3, strlen(rt3) * sizeof(char));
nwrittenT4 = write(fileDes4, rt4, strlen(rt4) * sizeof(char));
nwrittenT5 = write(fileDes5, rt5, strlen(rt5) * sizeof(char));
nwrittenT6 = write(fileDes6, rt6, strlen(rt6) * sizeof(char));
nwrittenT7 = write(fileDes7, rt7, strlen(rt7) * sizeof(char));
//close all files
close(fileDes1);
close(fileDes2);
close(fileDes3);
close(fileDes4);
close(fileDes5);
close(fileDes6);
close(fileDes7);
//free allocated memory
free(firstRoom.name);
free(secRoom.name);
free(thirdRoom.name);
free(fourthRoom.name);
free(fifthRoom.name);
free(sixthRoom.name);
free(sevRoom.name);
return 0;
}
|
C
|
#include "twi_utils.h"
/*
* read bytes from chip register
*/
int8_t wire_read_reg_bytes(uint8_t addr, uint8_t reg, uint8_t length, uint8_t *data)
{
wire_begin_transmission(addr);
wire_write_byte(reg);
wire_end_transmission();
wire_request_from(addr, length, 1);
for (uint8_t i = 0; i < length; i++)
{
data[i] = wire_read();
}
return 0;
}
/*
* read bytes from chip register
*/
int8_t wire_read_reg_byte(uint8_t addr, uint8_t regAddr, uint8_t *data)
{
wire_begin_transmission(addr);
wire_write_byte(regAddr);
wire_end_transmission();
wire_request_from(addr, 1, 1);
*data = wire_read();
return 1;
}
/*
* read bytes from chip register
*/
int8_t wire_read_reg_16(uint8_t addr, uint8_t regAddr, uint16_t *data)
{
wire_begin_transmission(addr);
wire_write_byte(regAddr);
wire_end_transmission();
wire_request_from(addr, 2, 1);
*data = wire_read();
*data = (*data << 8) + wire_read();
return 1;
}
/*
* write bytes from chip register
*/
void wire_write_reg_bytes(uint8_t addr, uint8_t regAddr, uint8_t length, uint8_t *data)
{
if (length > 0)
{
wire_begin_transmission(addr);
wire_write_byte(regAddr);
for (uint8_t i = 0; i < length; i++)
{
wire_write_byte(data[i]);
}
wire_end_transmission();
}
}
/*
* write byte to chip register
*/
void wire_write_reg_byte(uint8_t addr, uint8_t regAddr, uint8_t data)
{
wire_begin_transmission(addr);
wire_write_byte(regAddr);
wire_write_byte(data);
wire_end_transmission();
}
/*
* write 2 bytes to chip register
*/
void wire_write_reg_16(uint8_t addr, uint8_t regAddr, uint16_t data)
{
wire_begin_transmission(addr);
wire_write_byte(regAddr);
wire_write_byte((uint8_t)(data >> 8));
wire_write_byte((uint8_t)(data & 0xFF));
wire_end_transmission();
}
|
C
|
#include <stdio.h>
#include <math.h>
float x;
float a;
float d;
int areaofCircle(float r)
{
a = M_PI*r*r;
printf("the area of the circle with radius %f is %f\n", r, a);
return 0;
}
int main()
{
for (d = 3.5; d <= 12.5; d++)
{
x = areaofCircle(d);
}
return 0;
}
|
C
|
#ifndef __ERROR_H
#define __ERROR_H
#include <stdlib.h>
/*
* Error codes
*/
typedef enum status status_t;
typedef enum ogg_status ogg_status_t;
/* Codes liés au flux Vorbis */
enum status {
VBS_EOS = 1,
VBS_SUCCESS = 0,
VBS_OUTOFMEMORY = -127,
VBS_BADSTREAM = -128,
VBS_EOP = -129,
VBS_FATAL = -130,
VBS_BADVERSION = -131,
VBS_UNUSED = -132,
};
/* Codes liés au conteneur Ogg */
enum ogg_status {
OGG_END = 1, /* Fin de (fichier, flux, page, ...):
pas un code d'erreur. */
OGG_OK = 0, /* Ok! */
OGG_ERR_CORRUPT = -1, /* Flux corrompu */
OGG_ERR_MEM_ERROR = -2, /* Problème d'allocation */
OGG_ERR_IO_ERROR = -3, /* Problème d'accès au fichier */
OGG_ERR_UNEXP_EOF = -4, /* Fin de fichier non attendue */
OGG_ERR_ILL_ARG = -5, /* Argument illégal */
OGG_ERR_ILL_OP = -6, /* Opération illégale */
OGG_ERR_UNIMPLEM = -7, /* Opération non implémtentée */
OGG_ERR_DECODER = -8, /* Erreur au décodage */
OGG_ERR_INTERNAL = -9, /* Erreur interne */
};
/*
* Function declarations
*/
#endif /* __VORBIS_PACKET_H */
|
C
|
#include <stdio.h>
int main()
{
int x=5;
printf("%d\n",x);
printf("%d\n",&x);
printf("%d\n",*&x);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
#include "collatz.h"
#include "dbg.h"
// Program written by kaelen carling and maxwell weiss
bool collatz_upload(int array[])
{
FILE* collatz_file;
int number, collatz;
// open file
collatz_file = fopen(COLLATZ_FILE, "r");
probe(collatz_file, "Opening file %s failed", COLLATZ_FILE);
// read collatz numbers from file
while(fscanf(collatz_file, "%d - %d", &number, &collatz) == 2)
{
array[number-1] = collatz;
} // terminate array by setting last element to 0
array[number] = 0;
// close file
fclose(collatz_file);
return true;
error:
return false;
}
void collatz_print_array( int (*array_copy)[2] )
{
int index = 0;
while(array_copy[index][0] != 0)
{
printf("%d - %d\n", array_copy[index][0], array_copy[index][1]);
index++;
}
}
void collatz_copy_array(int array[], int (*array_copy)[2])
{
int index = 1;
//copies the collatz data from the old array to the new array
while(array[index] != 0)
{
array_copy[index][0]=index+1;
array_copy[index][1]=array[index];
index++;
}
//create first row
array_copy[0][0]=1;
array_copy[0][1]=0;
//create last row 0-0
array_copy[index][0]=0;
array_copy[index][1]=0;
}
void collatz_selection_sort(int (*array_copy)[2])
{
int array_length = 0;
int all_index = 0;
int current_min_index;
int min_index;
int aux;
//finds array length
while(array_copy[array_length][0] != 0)
{
array_length++;
}
// loops through whole array to build sorted array array
for(all_index = 0; all_index < array_length -1; all_index++)
{
current_min_index = all_index;
// searches through array for the lowest value in the not sorted section of the array
for (min_index = all_index + 1; min_index < array_length; min_index++)
{
//checks to see if current index is less than the current minimum if it is replaces
//the old current min with the new current minimum
if(array_copy[min_index][1] <= array_copy[current_min_index][1])
{
current_min_index = min_index;
}
}
// swaps the original indices number / base number
aux = array_copy[all_index][0];
array_copy[all_index][0] = array_copy[current_min_index][0];
array_copy[current_min_index][0] = aux;
// swaps collatz iterations of the orignal indices number / base number
aux = array_copy[all_index][1];
array_copy[all_index][1] = array_copy[current_min_index][1];
array_copy[current_min_index][1] = aux;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
// ʣһڴռ
// ൱ƺţڴ൱ڷ
int a;
int* p;
// ֱӸֵ
a = 10;
printf("a = %d\n", a);
// Ӹֵ
printf("&a = %d\n", &a);
p = &a;
printf(" p = %d\n", p);
*p = 11;
printf("a = %d, *p = %d\n", a, *p);
printf("\n");
return 0;
}
|
C
|
/**
*
* 给你一个整数 n,请你帮忙计算并返回该整数「各位数字之积」与「各位数字之和」的差。
示例 1:
输入:n = 234
输出:15
解释:
各位数之积 = 2 * 3 * 4 = 24
各位数之和 = 2 + 3 + 4 = 9
结果 = 24 - 9 = 15
示例 2:
输入:n = 4421
输出:21
解释:
各位数之积 = 4 * 4 * 2 * 1 = 32
各位数之和 = 4 + 4 + 2 + 1 = 11
结果 = 32 - 11 = 21
提示:
1 <= n <= 10^5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
**/
int subtractProductAndSum(int n){
int sum = 0, multi = 1, tmp;
if (n == 0) return 0;
while (n > 0) {
tmp = n % 10;
sum += tmp;
if (multi != 0) multi *= tmp;
n /= 10;
}
return multi - sum;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
float tinhtong(int n){
if (n==1)
return 1;
return sqrt(n+tinhtong(n-1));
}
int main()
{
int n;
printf("nhap n:");
scanf("%d",&n);
printf("tong la :%f",tinhtong(n));
return 0;
}
|
C
|
#include "bankingClient.h"
#include <regex.h>
/**************************************************************
* Banking Client
*
* main:
* make connection to server
* spawn user_input_runner and server_response threads
*
* user_input_runner:
* read input from stdin
* validate input
* send message to server
*
* server_response_runner:
* receive response from server
* print response to stdout
***************************************************************/
int main(int argc, char** argv)
{
if(argc != 3) {
fprintf(stderr, "wrong number of arguments\n");
exit(EXIT_FAILURE);
}
int sockfd = connect_to_server(argv[1], argv[2]);
if(sockfd == -1) {
fprintf(stderr, "failed to connect to server\n");
exit(EXIT_FAILURE);
}
server server_info;
server_info.server_name = argv[1];
server_info.port_num = argv[2];
server_info.sockfd = sockfd;
pthread_t input_runner_id;
pthread_t server_runner_id;
pthread_create(&input_runner_id, NULL, user_input_runner, &server_info);
pthread_create(&server_runner_id, NULL, server_response_runner, &server_info);
pthread_join(server_runner_id, NULL);
pthread_join(input_runner_id, NULL);
return 0;
}
/* Attempt to connect to server every 3 seconds
*
* @param1 server_name the domain name for the server
* @param2 port_num the string representation of the port number
*
* @return int the file descriptor for the server
*/
int connect_to_server(char server_name[256], char port_num[10])
{
int sockfd, ret;
struct addrinfo hints, *server_addr_info, *ptr;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
ret = getaddrinfo(server_name, port_num, &hints, &server_addr_info);
if(ret != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(ret));
}
ptr = server_addr_info;
while(ptr) {
sockfd = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if(sockfd == -1) {
perror("socket: ");
ptr = ptr->ai_next;
continue;
}
while(1) {
int connect_ret = connect(sockfd, ptr->ai_addr, ptr->ai_addrlen);
if(connect_ret != -1) break;
sleep(3);
}
//made connection
printf("connected to server\n");
freeaddrinfo(server_addr_info);
return sockfd;
}
//failed to connect
return -1;
}
/* Thread runner to accpet user input.
* Checks that input is valid then sends the message to the server
*
* @param1 arg a void pointer to a server struct containing
* the server name, port number, and file descriptor for the server
*/
void * user_input_runner(void* arg)
{
server *server_info = (server*) arg;
while(1) {
char user_input[263] = {'\0'};
get_user_input(user_input);
if(!input_is_valid(user_input)) {
printf("Invalid input. Correct usage:\n\tcreate <accountname (char) >\n\tserve <accountname (char) >"
"\n\tdeposit <amount (double) >\n\twithdraw <amount (double) >"
"\n\tquery\n\tend\n\tquit\n");
continue;
}
if(strcmp(user_input, "quit") == 0) {
printf("disconnecting from server\n");
break;
}
send_message_to_server(user_input, server_info);
sleep(2);
}
_exit(EXIT_SUCCESS);
return;
}
/* Read input from stdin
*
* @param1 user_input char pointer in which to put the input
*/
void get_user_input(char user_input[263])
{
printf("What would you like to do: \n");
char *buffer = malloc(263);
size_t input_size = 263;
getline(&buffer, &input_size, stdin);
int i = 0;
while(buffer[i] != '\0' && i < 263) {
user_input[i] = buffer[i];
i++;
}
free(buffer);
user_input[strlen(user_input) -1 ] = '\0';
}
/* Checks that the user input is valid by the rules defined in proj description
*
* @param1 user_input the input read from stdin
*
* @return 1 if input is valid; 0 otherwise
*/
int input_is_valid(char user_input[263])
{
regex_t regex;
int reti;
reti = regcomp(®ex, "(^(create|serve)[ ].+)"
"|^(end|query|quit)$"
"|(^(deposit|withdraw)[ ][0-9]+((\\.[0-9]+)?)|(\\.[0-9]+))$", REG_EXTENDED);
if(reti) {
fprintf(stderr, "Could not compile regex");
exit(EXIT_FAILURE);
}
reti = regexec(®ex, user_input, 0, NULL, 0);
regfree(®ex);
return !reti;
}
/* Send valid input to the server
*
* @param1 user_input the input read from stdin
* @param2 server_info server struct containing info on the server
*/
void send_message_to_server(char user_input[263], server *server_info)
{
int ret = send(server_info->sockfd, user_input, 263, 0);
if(ret <= 0) {
fprintf(stderr, "failed to send message to server\n");
}
return;
}
/* Thread runner to receive responses from server and print them to stdout
*
* @param1 arg void pointer to server struct containing info pertaining to the server
*/
void * server_response_runner(void* arg)
{
int ret;
server *server_info = (server*) arg;
char server_response[320];
while(1) {
ret = recv(server_info->sockfd, server_response, sizeof(server_response), 0);
if(ret == -1) {
perror("receive: ");
pthread_exit(NULL);
return;
}
if(strcmp(server_response, "Server has been shutdown") == 0) {
printf("server has disconnected from client\n");
_exit(EXIT_SUCCESS);
}
printf("response from sever: %s\n", server_response);
}
return;
}
|
C
|
#include <stdio.h>
int main(int argc, char *argv[]) {
int i = 1;
int j = 2;
int *p = &i;
printf("i / j / p / *p = %2d / %2d / %p / %2d\n", i, j, p, *p);
*p = -1;
printf("i / j / p / *p = %2d / %2d / %p / %2d\n", i, j, p, *p);
p = &j;
printf("i / j / p / *p = %2d / %2d / %p / %2d\n", i, j, p, *p);
return 0;
}
|
C
|
#include <vector>
#include <algorithm>
#include <future>
#include <iostream>
#include <numeric>
using namespace std;
template <typename RDIter, typename T>
T parallel_sum(RDIter beg, RDIter end){
auto diff = end-beg;
if(diff < 100){
return accumulate(beg, end, T());
}
auto mid = beg + diff/2;
future<T> sndHalf = async(launch::async, parallel_sum<RDIter, T>, mid, end);// note the template instantiation syntax
T firstHalf = parallel_sum<RDIter, T>(beg, mid);
return firstHalf + sndHalf.get();
}
int main(){
vector<int> testdata;
fill_n(back_inserter(testdata), 10000, 1);
cout<<parallel_sum<vector<int>::iterator, int>(testdata.begin(), testdata.end())<<endl;//note the template instantiation syntax
return 0;
}
|
C
|
#include <stdio.h>
#include <stdio_ext.h>
#include <stdlib.h>
#include <string.h>
#include "utn.h"
#include "Cachorros.h"
static int isValidId(int *id);
static int isValidIdString(char *id);
static int isValidNombre(char *nombre);
static int isValidDias(int *dias);
static int isValidDiasString(char *dias);
static int isValidRaza(char *raza);
static int isValidReservado(char *reservado);
static int isValidGenero(char *genero);
Cachorro* cachorro_new()
{
return malloc(sizeof(Cachorro));
}
void cachorro_delete(Cachorro *this)
{
free(this);
}
int cachorro_setId(Cachorro* this,int id)
{
int retorno = EXIT_ERROR;
if(this != NULL && isValidId(&id) == EXIT_SUCCESS)
{
this->id=id;
retorno = EXIT_SUCCESS;
}
return retorno;
}
int cachorro_getId(Cachorro* this,int* id)
{
int retorno = EXIT_ERROR;
if(this != NULL && id != NULL)
{
*id=this->id;
retorno = EXIT_SUCCESS;
}
return retorno;
}
static int isValidId(int *id)
{
int retorno = EXIT_ERROR;
if(id != NULL)
{
if(id > 0)
{
retorno = EXIT_SUCCESS;
}
}
return retorno;
}
int cachorro_setIdString(Cachorro *this,char *id)
{
int retorno = EXIT_ERROR;
if(this != NULL && isValidIdString(id)==EXIT_SUCCESS)
{
this->id=atoi(id);
retorno = EXIT_SUCCESS;
}
return retorno;
}
static int isValidIdString(char *id)
{
int retorno = EXIT_ERROR;
if(id != NULL)
{
//if(esSoloNumerosPositivos(id,"\nERROR"))
//{
retorno = EXIT_SUCCESS;
//}
}
return retorno;
}
int cachorro_setNombre(Cachorro *this,char *nombre)
{
int retorno = EXIT_ERROR;
if(this != NULL && isValidNombre(nombre)==EXIT_SUCCESS)
{
strcpy(this->nombre,nombre);
retorno = EXIT_SUCCESS;
}
return retorno;
}
int cachorro_getNombre(Cachorro *this,char *nombre)
{
int retorno = EXIT_ERROR;
if(this != NULL && nombre != NULL)
{
strcpy(nombre,this->nombre);
retorno = EXIT_SUCCESS;
}
return retorno;
}
static int isValidNombre(char *nombre)
{
int retorno = EXIT_ERROR;
if(nombre != NULL)
{
//esNombreOApellido(nombre,"\nERROR");
retorno = EXIT_SUCCESS;
}
return retorno;
}
int cachorro_setDias(Cachorro* this,int dias)
{
int retorno = EXIT_ERROR;
if(this != NULL && isValidDias(&dias) == EXIT_SUCCESS)
{
this->dias=dias;
retorno = EXIT_SUCCESS;
}
return retorno;
}
int cachorro_getDias(Cachorro* this,int* dias)
{
int retorno = EXIT_ERROR;
if(this != NULL && dias != NULL)
{
*dias=this->dias;
retorno = EXIT_SUCCESS;
}
return retorno;
}
static int isValidDias(int *dias)
{
int retorno = EXIT_ERROR;
if(dias != NULL)
{
if(dias >= 0)
{
retorno = EXIT_SUCCESS;
}
}
return retorno;
}
int cachorro_setDiasString(Cachorro *this,char *dias)
{
int retorno = EXIT_ERROR;
if(this != NULL && isValidDiasString(dias)==EXIT_SUCCESS)
{
this->dias=atoi(dias);
retorno = EXIT_SUCCESS;
}
return retorno;
}
static int isValidDiasString(char *dias)
{
int retorno = EXIT_ERROR;
if(dias != NULL)
{
//if(esSoloNumerosPositivos(dias,"\nERROR"))
//{
retorno = EXIT_SUCCESS;
//}
}
return retorno;
}
int cachorro_setRaza(Cachorro *this,char *raza)
{
int retorno = EXIT_ERROR;
if(this != NULL && isValidRaza(raza)==EXIT_SUCCESS)
{
strcpy(this->raza,raza);
retorno = EXIT_SUCCESS;
}
return retorno;
}
int cachorro_getRaza(Cachorro *this,char *raza)
{
int retorno = EXIT_ERROR;
if(this != NULL && raza != NULL)
{
strcpy(raza,this->raza);
retorno = EXIT_SUCCESS;
}
return retorno;
}
static int isValidRaza(char *raza)
{
int retorno = EXIT_ERROR;
if(raza != NULL)
{
//esNombreOApellido(raza,"\nERROR");
retorno = EXIT_SUCCESS;
}
return retorno;
}
int cachorro_setReservado(Cachorro *this,char *reservado)
{
int retorno = EXIT_ERROR;
if(this != NULL && isValidReservado(reservado)==EXIT_SUCCESS)
{
strcpy(this->reservado,reservado);
retorno = EXIT_SUCCESS;
}
return retorno;
}
int cachorro_getReservado(Cachorro *this,char *reservado)
{
int retorno = EXIT_ERROR;
if(this != NULL && reservado != NULL)
{
strcpy(reservado,this->reservado);
retorno = EXIT_SUCCESS;
}
return retorno;
}
static int isValidReservado(char *reservado)
{
int retorno = EXIT_ERROR;
if(reservado != NULL)
{
//esNombreOApellido(reservado,"\nERROR");
retorno = EXIT_SUCCESS;
}
return retorno;
}
int cachorro_setGenero(Cachorro *this,char *genero)
{
int retorno = EXIT_ERROR;
if(this != NULL && isValidGenero(genero)==EXIT_SUCCESS)
{
strcpy(this->genero,genero);
retorno = EXIT_SUCCESS;
}
return retorno;
}
int cachorro_getGenero(Cachorro *this,char *genero)
{
int retorno = EXIT_ERROR;
if(this != NULL && genero != NULL)
{
strcpy(genero,this->genero);
retorno = EXIT_SUCCESS;
}
return retorno;
}
static int isValidGenero(char *genero)
{
int retorno = EXIT_ERROR;
if(genero != NULL)
{
//esNombreOApellido(genero,"\nERROR");
retorno = EXIT_SUCCESS;
}
return retorno;
}
Cachorro* cachorro_buscaPorId(LinkedList* pArrayListCachorro,int id)
{
Cachorro* this = NULL;
int i;
if(pArrayListCachorro!=NULL && id>0)
{
for(i=0;i<ll_len(pArrayListCachorro);i++)
{
this = ll_get(pArrayListCachorro,i);
if(this->id == id)
{
return this;
}
}
}
return this;
}
int cachorro_ordenoPorId(void* pElementUno,void* pElementDos)
{
int retorno = 0;
if(((Cachorro*)pElementUno)->id > ((Cachorro*)pElementDos)->id)
{
retorno = 1;
}
if(((Cachorro*)pElementUno)->id < ((Cachorro*)pElementDos)->id)
{
retorno = -1;
}
return retorno;
}
int cachorro_ordenoPorDias(void* pElementUno,void* pElementDos)
{
int retorno = 0;
if(((Cachorro*)pElementUno)->dias > ((Cachorro*)pElementDos)->dias)
{
retorno = 1;
}
if(((Cachorro*)pElementUno)->dias < ((Cachorro*)pElementDos)->dias)
{
retorno = -1;
}
return retorno;
}
int cachorro_ordenoPorNombre(void* pElementUno,void* pElementDos)
{
int retorno = 0;
if(strncmp(((Cachorro *)pElementUno)->nombre,((Cachorro *)pElementDos)->nombre,CANT_CARACTERES)>0)
{
retorno = 1;
}
if(strncmp(((Cachorro *)pElementUno)->nombre,((Cachorro *)pElementDos)->nombre,CANT_CARACTERES)<0)
{
retorno = -1;
}
return retorno;
}
int cachorro_filtrarListaMenores45dias(void* p)
{
int retorno = -1;
if(p != NULL)
{
if(((Cachorro*)p)->dias >= 45)
{
retorno = 1;
}
else
{
retorno = 0;
}
}
return retorno;
}
int cachorro_filtrarListaPorMacho(void* p)
{
int retorno = -1;
if(p != NULL)
{
if(strncmp(((Cachorro *)p)->genero,"H",CANT_CARACTERES)==0)
{
retorno = 1;
}
else
{
retorno = 0;
}
}
return retorno;
}
int cachorro_filtrarListaPorCallejero(void* p)
{
int retorno = -1;
if(p != NULL)
{
if(strncmp(((Cachorro *)p)->raza,"Callejero",CANT_CARACTERES)==0)
{
retorno = 1;
}
else
{
retorno = 0;
}
}
return retorno;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
char line[1024];
if (argc == 1 || strcmp(argv[1], "-p") == 0) {
while (gets(line))
puts(line);
}
else if (strcmp(argv[1], "-u") == 0) {
while (gets(line)) {
for (int i = 0; i < strlen(line); i++)
putchar(toupper(line[i]));
putchar('\n');
}
}
else if (strcmp(argv[1], "-l") == 0) {
while (gets(line)) {
for (int i = 0; i < strlen(line); i++)
putchar(tolower(line[i]));
putchar('\n');
}
}
else {
printf("Parameter(s) invalid!\n");
}
return 0;
}
|
C
|
/*
* ======== UART_Task.c ========
* Author: Michael Kramer / Matthias Wenzl
*/
#include <stdbool.h>
#include <stdint.h>
#include <inc/hw_memmap.h>
/* XDCtools Header files */
#include <xdc/std.h>
#include <xdc/cfg/global.h>
#include <xdc/runtime/System.h>
#include <xdc/runtime/Error.h>
#include <xdc/runtime/Memory.h>
/* BIOS Header files */
#include <ti/sysbios/BIOS.h>
#include <ti/sysbios/knl/Task.h>
/* TI-RTOS Header files */
#include <driverlib/sysctl.h>
#include <ti/drivers/UART.h>
/* Driverlib headers */
#include <driverlib/gpio.h>
#include <driverlib/pin_map.h>
/*Board Header files */
#include <Board.h>
#include <EK_TM4C1294XL.h>
/* Application headers */
#include "UART_Task.h"
/*
* ======== UART ========
* Echo Characters recieved and show reception on Port N Led 0
*/
void UARTFxn(UArg arg0, UArg arg1)
{
UART_Handle uart;
UART_Params uartParams;
const char echoPrompt[] = "\fEchoing characters:\r\n";
/* Create a UART with data processing off. */
UART_Params_init(&uartParams);
uartParams.writeDataMode = UART_DATA_BINARY;
uartParams.readDataMode = UART_DATA_BINARY;
uartParams.readReturnMode = UART_RETURN_FULL;
uartParams.readEcho = UART_ECHO_OFF;
uartParams.baudRate = 9600;
uart = UART_open(Board_UART0, &uartParams);
if (uart == NULL) {
System_abort("Error opening the UART");
}
UART_write(uart, echoPrompt, sizeof(echoPrompt));
/* Loop forever echoing */
while (1) {
char input;
UART_read(uart, &input, 1);
GPIOPinWrite(GPIO_PORTN_BASE, GPIO_PIN_0, 1);
UART_write(uart, &input, 1); // Remove this line to stop echoing!
Task_sleep(5);
GPIOPinWrite(GPIO_PORTN_BASE, GPIO_PIN_0, 0);
}
}
/*
* Setup task function
*/
int setup_UART_Task(void)
{
Task_Params taskUARTParams;
Task_Handle taskUART;
Error_Block eb;
/* Enable and configure the peripherals used by the UART0 */
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
SysCtlPeripheralEnable(SYSCTL_PERIPH_UART0);
GPIOPinConfigure(GPIO_PA0_U0RX);
GPIOPinConfigure(GPIO_PA1_U0TX);
GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);
UART_init();
/* Setup PortN LED1 activity signaling */
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPION);
GPIOPinTypeGPIOOutput(GPIO_PORTN_BASE, GPIO_PIN_0);
Error_init(&eb);
Task_Params_init(&taskUARTParams);
taskUARTParams.stackSize = 1024; /* stack in bytes */
taskUARTParams.priority = 15; /* 0-15 (15 is highest priority on default -> see RTOS Task configuration) */
taskUART = Task_create((Task_FuncPtr)UARTFxn, &taskUARTParams, &eb);
if (taskUART == NULL) {
System_abort("TaskUART create failed");
}
return (0);
}
|
C
|
#include <stdio.h>
void alter(int *, int *);
int main(void)
{
int a = 14, b = 129;
printf("Ordinary a = %d, b = %d.\n", a, b);
alter(&a, &b);
printf("Now a = %d and b = %d.\n", a, b);
return 0;
}
void alter(int * x, int * y)
{
int one, two;
one = *x + *y;
two = *x - *y;
*x = one;
*y = two;
}
|
C
|
#include<stdio.h>
/*
文字列に特定文字が含まれているかどうか調べる
(添え字を返却)
*/
int str_ch(const char *s, int ch){
int index = 0;
while(*s){
if(*s++ == ch)
return index;
index++;
}
return -1;
}
int main(void){
char string[256];
char ch[10];
int index;
scanf("%s",string);
scanf("%s",ch);
printf("%s \n %s \n",string,ch);
if((index =str_ch(string,ch[0])) == -1){
printf("err");
}else{
printf("%d",index);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int i;//ȫֱʼĬֵΪ0
int main()
{
i--;//iֵΪ-1;
if (i > sizeof(i))
//sizeof()---͵ĴСֵĬϴ.
//õunsigned int,ͣʱintunsigned int бȽϼ
//intתintתΪunsigned int
//1000000000000000000000000000001
//1111111111111111111111111111110
//1111111111111111111111111111111
//תΪͣ
//1111111111111111111111111111111
//2ʮηһ
{
printf(">\n");
}
else
{
printf("<\n");
}
system("pause");//systemһ⺯system⺯ִϵͳpauseͣ˼
return 0;
}
//#include<stdio.h>
//int main()
//{
// int a = 0x11223344;
// char* pc = (char*)&a;
// *pc = 0;
// printf("%x\n", a);
// return 0;
//}
//#include<stdio.h>
//int main()
//{
// int arr[] = { 1, 2, 3, 4, 5 };
// short* p = (short*)arr;
// int i = 0;
// for (i = 0; i < 4; i++)
// {
// *(p + i) = 0;
// }
// for (i = 0; i < 5; i++)
// {
// printf("%d ", arr[i]);
// }
// return 0;
//}
////һð
//#include<stdio.h>
//void Print(int arr[], int sz)
//{
// int i = 0;
// for (i = 0; i < sz; i++)
// {
// printf("%d ", arr[i]);
// }
//}
//void MPPX(int arr[], int sz)
//{
// int i = 0;
// int j = 0;
// for (i = 0; i < sz-1; i++)
// {
// for (j = 0; j < sz - 1 - i; j++)
// {
// if (arr[j]>arr[j + 1])
// {
// int tmp = arr[j];
// arr[j] = arr[j + 1];
// arr[j + 1] = tmp;
// }
// }
// }
//}
//int main()
//{
// int arr[10] = { 14, 2, 3, 45, 6, 7, 89, 43, 233, 34 };
// int sz = sizeof(arr) / sizeof(arr[0]);
// Print(arr, sz);
// MPPX(arr, sz);
// printf("\n\n\n");
// Print(arr, sz);
// return 0;
//}
////
////abݣһ
//#include<stdio.h>
//int main()
//{
// int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// int b[10] = { 0 };
// int tmp = 0;
// int sz = sizeof(a) / sizeof(a[0]);//һ,ͬԪظͬ
// int i = 0;
// for (i = 0; i < sz; i++)
// {
// printf("a%d = %-2d b%d = %-2d\n", i, a[i], i, b[i]);
// }
// for (i = 0; i < sz; i++)
// {
// tmp = a[i];
// a[i] = b[i];
// b[i] = tmp;
// }
// printf("\n");
// for (i = 0; i < sz; i++)
// {
// printf("a%d = %-2d b%d = %-2d\n", i, a[i], i, b[i]);
// }
// return 0;
//}
//void Initialize_arr(int arr[], int sz)
//{
// int i = 0;
// for (i = 0; i < sz; i++)
// {
// arr[i] = 0;
// }
//}
//void Print(int* arr, int sz)
//{
// int i = 0;
// for (i = 0; i < sz; i++)
// {
// printf("%d ", arr[i]);
// }
//}
//void Reverse(int* arr, int sz)
//{
// int left = 0;
// int right = sz - 1;
// while (left<right)
// {
// int tmp = arr[left];
// arr[left] = arr[right];
// arr[right] = tmp;
// left++;
// right--;
// }
//}
////һӡ
//int main()
//{
// int arr[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// int sz = sizeof(arr) / sizeof(arr[0]);
// /*Initialize_arr(arr, sz);*/
// Print(arr, sz);
// Reverse(arr, sz);
// Print(arr, sz);
// return 0;
//}
//ָ飺ָ顣
//#include<stdio.h>
//int main()
//{
// int a = 3;
// int b = 5;
// int c = 8;
// int d = 9;
// int* arr[] = { &a, &b, &c, &d };
// int i = 0;
// for (i = 0; i < 4; i++)
// {
// printf("%d ",*arr[i]);
// }
// return 0;
//}
//ָ룺
//int main()
//{
// int a = 10;
// int* pa = &a;
// //洢aַһָpaĵַ洢ָppa
// int** ppa = &pa;
// //ppaָ룩ȡpa(һָ)
// printf("%p\n", &a);
// printf("%p\n", *ppa);
// //öָӡһָָı
// printf("%d\n", **ppa);
// ////ָ룺
// //int*** pppa = &ppa;
// ////ļָ룺
// //int**** ppppa = &pppa;
// return 0;
//}
//ַŵһָУ
//#include<stdio.h>
//int main()
//{
// int arr[10] = { 0 };
// int* p = arr;
// int i = 0;
// for (i = 0; i < 10; i++)
// {
// *(p + i) = i;
// /*printf("%d ", arr[i]);*/
// printf("%d ", *(p + i));
// }
// /*for (i = 0; i < 10; i++)
// {
// printf("%d ", arr[i]);
// }*/
// //for (i = 0; i < 10; i++)
// //{
// // //ָ飺
// // printf("%p ====== %p\n", &arr[i], p + i);
// //}
// return 0;
//}
//Ԫصĵַ
//⣺
//1.&(),ȡַʱԪصĵַ飬ȡĵַ
//2.sizeof()sizeof()ʱҲԪصĵַĴСsizeofĴС
//#include<stdio.h>
//int main()
//{
// int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// //Ƚ Ԫصַ ĵַСͬ˵Ԫصĵַ
// /*printf("%p\n", arr);
// printf("%p\n", &arr[0]);*/
// //Ƚ&
// /*printf("%p\n", arr);
// printf("%p\n", &arr);*/
// //ͬ&ͬģ
// /*printf("%p\n", arr+1);
// printf("%p\n", &arr + 1);*/
// //ͬ+1ַΪڶԪصĵַ
// //&+1ַΪһԪغһڴռĵַ
// //Ծĵַ&ȡĵַ
// //Ƚarrarr[0]ĴС
// /*printf("%d\n", sizeof(arr));
// printf("%d\n", sizeof(arr[0]));*/
// //arr[0]ĴСΪ4ֽڣintͣarrĴСΪ40=4*10ֽڣarrʱռڴС
// return 0;
//}
//#include<stdio.h>
//#define N_VALUES 5
//int main()
//{
// float values[N_VALUES];
// float* vp;
// /*for (vp = &values[N_VALUES]; vp > &values[0];)
// {
// *--vp = 0;
// }*/
// for (vp = &values[N_VALUES - 1]; vp >= &values[0]; vp--)
// {
// *vp = 0;
// }
//}
//#include<stdio.h>
//int my_strlen(char* str)
//{
// char* start = str;
// char* end = str;
// while (*end != '\0')
// {
// end++;
// }
// return end - start;
//}
//int main()
//{
// char arr[] = "yqlzhenshuai";
// int len = my_strlen(arr);
// printf("%d\n", len);
// return 0;
//}
//int main()
//{
// int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// printf("%d\n", &arr[9] - &arr[0]);
// return 0;
//}
|
C
|
/*===============================================================
* Copyright (C) 2019 All rights reserved.
*
* 文件名称:const.c
* 创 建 者:pengtangtang
* 创建日期:2019年10月28日
* 描 述:
*
* 更新日志:
*
================================================================*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
int main()
{
const int i = 2;/*i 应该被初始化 否则编译器自动初始化为随机值*/
printf("i = %d\n",i);
/*i = 100;i readonly*/
int *p = (int *)&i;
*p = 100;/*可以通过地址间接改变const变量的值*/
printf("i = %d\n",i);
return 0;
}
|
C
|
#include "philosophers.h"
void ft_philosophers_one(t_data *philo, int i)
{
int status;
int thread_num_array[philo->number_of_philosophers];
int block_at_start[philo->number_of_philosophers];
pthread_t pthread[philo->number_of_philosophers];
t_time prev_eat[philo->number_of_philosophers];
i = 0;
ft_start_init(philo, thread_num_array, block_at_start, prev_eat);
ft_init_mutexes(philo);
if ((status = pthread_create(&(philo->monitor), NULL, ft_monitor_life, \
(void *)philo)) != 0)
ft_monitor_error_exit(philo->monitor, philo);
while (i < philo->number_of_philosophers)
{
if ((status = pthread_create(&pthread[i], NULL, ft_philo_life, \
(void *)philo)) != 0)
ft_error_exit(pthread, philo->monitor, philo, i);
i++;
}
ft_success_exit(pthread, philo->monitor, philo);
}
void ft_fill_state_time(t_data *philo)
{
int i;
i = 0;
while (i < philo->number_of_philosophers)
{
philo->current_state[i] = THINKING;
i++;
}
philo->start.sec = -1;
philo->start.usec = -1;
}
int ft_fill_struct(t_data *philo, char **argv)
{
if (!(philo->number_of_philosophers = ft_atoi(argv[1])) || \
!(philo->time_to_die = ft_atoi(argv[2])) || \
!(philo->time_to_eat = ft_atoi(argv[3])) || \
!(philo->time_to_sleep = ft_atoi(argv[4])))
return (-1);
if (argv[5] == NULL)
philo->number_of_times_each_philosopher_must_eat = -1;
else if (!(philo->number_of_times_each_philosopher_must_eat = \
ft_atoi(argv[5])))
return (-1);
if (!(philo->current_state = malloc(sizeof(int) * \
philo->number_of_philosophers)))
return (-1);
if (!(philo->forks = malloc(sizeof(pthread_mutex_t) * \
philo->number_of_philosophers)))
{
free(philo->current_state);
return (-1);
}
ft_fill_state_time(philo);
return (0);
}
int ft_check_arguments(char **argv)
{
int i;
int j;
i = 1;
while (argv[i])
{
j = 0;
while (argv[i][j])
{
if (!ft_isdigit(argv[i][j]))
return (-1);
j++;
}
i++;
}
return (0);
}
int main(int argc, char **argv)
{
int i;
t_data philo;
i = 0;
if (argc < 5 || argc > 6)
{
ft_putstr("error: wrong number of arguments\n");
return (1);
}
if (ft_check_arguments(argv) == -1)
{
ft_putstr("error: wrong arguments\n");
return (1);
}
if (ft_fill_struct(&philo, argv) == -1)
{
if (!philo.current_state)
ft_putstr("error: cannot allocate memory\n");
else
ft_putstr("error: wrong arguments\n");
return (1);
}
ft_philosophers_one(&philo, i);
return (0);
}
|
C
|
# include <stdio.h>
# include <stdlib.h>
# include "6.h"
int main(void) {
Lista *l;
int qtde;
int i;
float peso,mala_p,max_permitido,somaT;
printf("Quantos itens deseja colocar?\n");
scanf("%d",&qtde);
printf("Informe o peso da mala:\n");
scanf("%f",&mala_p);
printf("Informe o maximo permitido:\n");
scanf("%f",&max_permitido);
printf("Foi criada a lista vazia.\n");
l = cria_lista_vazia();
for (i=0;i<qtde;i++)
{
printf("Informe o peso do objeto: %d\n",i+1);
scanf("%f",&peso);
adiciona_item(l,peso);
}
somaT = verifica_peso(l,mala_p);
imprime_lista(l);
while (somaT > max_permitido)
{
printf("Maximo permitido alcancado, retirando mais pesado...\n");
remove_item(l,mais_pesado(l,qtde));
somaT = verifica_peso(l,mala_p);
imprime_lista(l);
}
printf("Mala despachada com o peso total de %.3f kg\n", verifica_peso(l,mala_p));
return(0);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* valid.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: okovalov <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/07/04 14:26:04 by okovalov #+# #+# */
/* Updated: 2018/08/13 12:34:22 by okovalov ### ########.fr */
/* */
/* ************************************************************************** */
#include "lem_in.h"
void compare(t_lmn *lmn, int i)
{
t_list *begin;
t_list *bg;
begin = lmn->way;
while (begin)
{
if (lenfre((t_list *)begin->content, i))
{
bg = begin->next;
while (bg)
{
if (!bg->next)
return ;
if (lenfre((t_list *)bg->content, i))
{
lenlist(begin->content) < lenlist(bg->content) ?
dellist(((t_list **)&(bg->content))) :
dellist(((t_list **)&(begin->content)));
return ;
}
bg = begin->next;
}
}
begin = begin->next;
}
}
int strtend(t_lmn *lmn, char *buf)
{
char c;
char *loc;
if (!ft_strcmp(buf, "##start") || !ft_strcmp(buf, "##end"))
{
c = (!ft_strcmp(buf, "##start") ? 's' : 'e');
get_next_line(0, &loc);
ft_lstpushback(&lmn->all, loc, ft_strlen(loc) + 1);
if (loc[0] == 'L' || loc[0] == '#' || analyze(loc) != 0
|| !ft_strcmp(loc, "##start") || !ft_strcmp(loc, "##end")
|| !roomfnd(loc, lmn, c))
{
free(loc);
return (0);
}
free(loc);
}
else
{
if (buf[0] == 'L' || buf[0] == '#' || !roomfnd(buf, lmn, 'o'))
return (0);
}
return (1);
}
int linkorroom(t_lmn *lmn, int *n, char *buf)
{
int rez;
if ((rez = analyze(buf)) == -1
|| (rez == 1 && *n == -1) || (rez == 0 && *n == 1))
return (0);
else if (rez == 0)
{
*n = 0;
if (!strtend(lmn, buf))
return (0);
}
else if (rez == 1)
{
*n = 1;
if (linkfnd(buf, lmn) < 2)
return (0);
}
return (1);
}
int numofants(t_lmn *lmn, char *buf, int *n)
{
int i;
if (get_next_line(0, &buf))
{
i = -1;
while (buf[++i])
if (ft_isalpha(buf[i]))
{
free(buf);
return (0);
}
if ((*n = ft_atoi(buf)) > 0)
lmn->nmbr = *n;
else
{
free(buf);
return (0);
}
}
free(buf);
*n = -1;
return (1);
}
int valid(t_lmn *lmn)
{
char *buf;
int n;
buf = NULL;
if (!numofants(lmn, buf, &n))
return (0);
while (get_next_line(0, &buf))
{
ft_lstpushback(&lmn->all, buf, ft_strlen(buf) + 1);
if (buf[0] == '#' && (ft_strcmp(buf, "##start")
&& ft_strcmp(buf, "##end")))
{
free(buf);
continue;
}
if (!linkorroom(lmn, &n, buf))
{
free(buf);
return (0);
}
free(buf);
}
if (lmn->end == -1 || lmn->str == -1 || n != 1)
return (0);
return (1);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MAX_QUEUE 100 // Max amount of requests that can be pending for the listen call
#define BUF_SIZE 1024
int main(int argc, char **argv) {
int sockfd;
int connfd;
int return_code; // Variable for intermediate results
ssize_t data_len;
unsigned long port_num;
socklen_t client_addr_len;
char buf[BUF_SIZE];
char *host;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
if (argc != 3) {
fprintf(stderr, "Invalid command format\nUsage: %s [host] [port]\n", argv[0]);
exit(EXIT_FAILURE);
}
host = argv[1];
port_num = strtoul(argv[2], (char **)NULL, 10);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
fprintf(stderr, "Socket creation failed\n");
exit(EXIT_FAILURE);
}
memset(&server_addr, 0, sizeof(struct sockaddr_in));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(host);
server_addr.sin_port = htons(port_num);
return_code = bind(sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in));
if (return_code != 0) {
fprintf(stderr, "Bind failed\n");
exit(EXIT_FAILURE);
}
return_code = listen(sockfd, MAX_QUEUE);
if (return_code != 0) {
fprintf(stderr, "Listen failed\n");
exit(EXIT_FAILURE);
}
printf("Waiting for incoming connections...\n");
connfd = accept(sockfd, (struct sockaddr *)&client_addr, &client_addr_len);
if (connfd == -1) {
fprintf(stderr, "Accept failed\n");
exit(EXIT_FAILURE);
}
printf("Accepted new connection from the client\nWaiting for data...\n");
// Get (BUF_SIZE - 1) number of bytes.
// Last byte of the buffer is used for the stop character.
data_len = recv(connfd, buf, BUF_SIZE - 1, 0);
if (data_len == -1) {
fprintf(stderr, "Receive from the client failed\n");
exit(EXIT_FAILURE);
}
buf[data_len] = '\0';
printf("Received %ld bytes from the client\nData: \"%s\"\n", data_len, buf);
close(connfd);
close(sockfd);
return 0;
}
|
C
|
/*Brandon Snow hw05 .c file*/
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "stack.h"
/*
typedef double stackElementT;
struct stackCDT {
stackElementT *elements;
int count;
int size;
};*/
static stackADT stack;
void Displaystack();
char* read_tag(FILE *fp);
int main(int nargs, char *argv[])
{
FILE *fp;
stack=NewStack();
int j=0;
char *htmlfile;
char *tmp2;
/*open file*/
fp = fopen(argv[1], "r");
if (fp == NULL)
{
fprintf(stderr, "Can't open!\n");
exit(1);
}
/*read everything into a file and push tag */
while((htmlfile = read_tag(fp)))
{
if(htmlfile[j] != '/' )
{
Push(stack,htmlfile);
}
else {
tmp2 = (char *) Pop(stack);
if(strcmp(tmp2, htmlfile+1) == 0)
continue;
else{
printf("Your file wasn't correctly nested.These tags Do not match :%s %s \n",tmp2, htmlfile);
break;
}
}
}
if(StackDepth(stack) == 0)
{
printf("Your file is correctly nested");
}
free(tmp2);
printf("\n");
FreeStack(stack);
fclose(fp);
return (0);
}
/*this function will read in */
char* read_tag(FILE *fp)
{
int i=0;
int ch;
char tmp[1024];
char *tag;
int flag1=0, flag2=0;
/*read tag in to string*/
while((ch = fgetc(fp)) != EOF )
{
if(ch == '<')
{
flag1 = 1;
}
if(ch == '>')
{
if (tmp[i-1] != '/') {
break;
}
tmp[i+2]='\0';
i=0;flag1=0;flag2=0;
continue;
}
if(flag1 == 1 ) /* && flag2 != 1) */
tmp[i++]=ch;
if( tmp[i-1] == '<')
i--;
}
if(ch == EOF)
{
return NULL;
}
tmp[i] = '\0';
tag = malloc(strlen(tmp) + 1);
strcpy(tag,tmp);
return(tag);
}
/*return true if <title></title> match*/
/*print what i got*/
void Displaystack()
{
int i, depth;
depth = StackDepth(stack);
printf("STACK: ");
for(i=depth-1;i>=0;i--)
{
if(i<depth-1) printf(" ,");
printf("%s",GetStackElement(stack,i));
}
printf("\n");
}
|
C
|
/*Used with main.c,profile.c in profile graph
Finds freq helices in 1000 structs; finds their LCA
Creates Hasse diagram with these vertices
*/
#include "hashtbl.h"
#include "summaryGraph.h"
#include "profile.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "memoryDFS.h"
static HASHTBL *edges;
static HASHTBL **graph1;
static HASHTBL *input;
static char **table;
static char **profileID;
static char **modprofileID;
static unsigned long *sums;
static int most;
static int graphsize;
//runs through nodes in cluster, finding their LCA's
int insert_graph(FILE *fp,char *file,int gsize) {
int i,*freq,k = 0,numkeys,total,size=1;
char *profile,*copy,*diff,*parent;
KEY *node;
struct hashnode_s *begin;
if (!(edges = hashtbl_create(HASHSIZE,NULL))) {
fprintf(stderr, "ERROR: hashtbl_create() failed");
exit(EXIT_FAILURE);
}
fputs("digraph G {\n",fp);
fprintf(fp,"\tlabel = \"%s\";\n",file);
fprintf(fp,"\tpad = 0.5;\n");
fprintf(fp,"\tnodesep = 0.5;\n");
//fprintf(fp,"\"\" [label=\"(0/%d)\"]\n",NUMSTRUCTS);
//fputs("{ node [shape = plaintext]; ",fp);
graphsize = gsize;
if (INPUT) {
i = process_one_input(fp);
if (i > gsize)
graphsize = i;
}
//printf("graphsize is %d for %s\n",*count,node->data);
graph1 = malloc(sizeof(HASHTBL*)*(graphsize+1));
for (i = 0; i <= graphsize; i++) graph1[i] = NULL;
numkeys = hashtbl_numkeys(freqprofs);
while (numkeys >= ARRAYSIZE*size) size++;
sums = malloc(sizeof(unsigned long)*ARRAYSIZE*size);
k = numkeys-1;
profileID = malloc(sizeof(char*)*ARRAYSIZE*size);
modprofileID = malloc(sizeof(char*)*ARRAYSIZE*size);
most = 0;
//for each profile, insert with freq
for (node = hashtbl_getkeys(freqprofs); node; node = node->next) {
//printf("node data is %s with k = %d\n",node->data,k);
freq = hashtbl_get(freqprofs,node->data);
//need to insert into graph
if (freq) {
if (most < *freq)
most = *freq;
profile = malloc(strlen(node->data)+1);
sums[k] = insert_and_binary(node->data,profile,*freq);
profileID[k] = node->data;
modprofileID[k--] = profile;
if (*freq > 0)
fprintf(fp,"\"%s\" [shape = box];\n",profile);
}
else
fprintf(stderr,"No entry for %s\n",node->data);
//printf("for profile %s binary rep is %d with ID %d\n",node->data,sums[k+1],k+1);
}
//make_key();
sums[numkeys] = 0;
modprofileID[numkeys] = " ";
total = find_LCAs(fp,numkeys+1,&size);
//printf("found %d vertices\n",total);
calc_gfreq(fp,total);
//total = print_vertices(fp);
printf("Total number of vertices: %d\n",total);
if (hashtbl_numkeys(edges) > 1) {
start_trans_reductn(edges,total);
print_edges(fp);
//printGraph();
} else {
node = hashtbl_getkeys(edges);
copy = mystrdup(node->data);
printf("copy is %s\n",copy);
diff = hashtbl_get(edges,copy);
parent = strtok(copy,"->");
copy = strtok(NULL,"->");
fprintf(fp,"\"%s\" -> \"%s\" [label = \"%s\", arrowhead = vee];\n",parent,copy,diff);
}
if (INPUT)
hashtbl_destroy(input);
for (i = 0; i < graphsize; i++) {
if (graph1[i])
hashtbl_destroy(graph1[i]);
}
freeGraph();
free(sums);
free(table);
free(profileID);
free(modprofileID);
hashtbl_destroy(edges);
return 0;
}
//inserts key into graph and converts from rep struct to binary notation
unsigned long insert_and_binary(char *key,char *profile,int freq) {
char *blank = " ",*helix,*copy = strdup(key);
unsigned long sum = 0;
int i,length = atoi(strtok(copy,blank)),*val;
HASHTBL *hash = graph1[length-1];
profile[0] = '\0';
for (i = 0; i < length; i++) {
helix = strtok(NULL,blank);
strcat(profile,helix);
strcat(profile," ");
sum += *((unsigned long*) hashtbl_get(binary,helix));
//printf("sum is now %d\n",sum);
}
//printf("profile is %s\n",profile);
if (!hash) {
if (!(hash = hashtbl_create(HASHSIZE,NULL))) {
fprintf(stderr, "ERROR: hashtbl_create() failed");
exit(EXIT_FAILURE);
}
graph1[length-1] = hash;
}
val = malloc(sizeof(int));
*val = 0;
hashtbl_insert(hash,profile,val);
//printf("profile %sinserted with length %d and freq %d\n",profile,length,*val);
return sum;
}
//table[freq id] = helix id
//produces table,where ith element is val
//where (1<<i) = hash_get(binary,val)
void make_key() {
int count;
KEY *node = hashtbl_getkeys(binary);
count = hashtbl_numkeys(binary);
//for (count = 0; (*num & (1<<count)) == 0; count++) ;
table = malloc(sizeof(char*)*count);
for (count--; count >= 0; count--) {
printf("table[%d] id is %s\n",count,node->data);
table[count] = node->data;
node = node->next;
}
}
/* finished profiles = [0 start-1]
present LCA to be intersected = [start oldk]
newly generated LCA = [oldk k]
returns k, the number of vertices in graph
*/
int find_LCAs(FILE *fp,int k,int *size) {
int new,oldk,go,start,count,firsttime = 0;
unsigned long num;
char *profile,*prof;
start = 0;
for (oldk = k; start != k; oldk = k) {
for (new = start; new != oldk; new++) {
for (go = advance(new,oldk); go != start; go = advance(go,oldk)) {
num = sums[new] & sums[go];
//printf("num is %u of s[%d] = %u and s[%d] = %u\n",num,new,sums[new],go,sums[go]);
if (not_in_sums(num,k)) {
//printf("found new profile for %s and %s\n",modprofileID[new],modprofileID[go]);
profile = convert_binary(num,&count);
fprintf(fp,"\"%s\" [style = dashed];\n",profile);
insert_prof(count,profile);
if (k >= ARRAYSIZE*(*size)) {
sums = realloc(sums,sizeof(unsigned long)*ARRAYSIZE*++*size);
modprofileID = realloc(modprofileID,sizeof(char*)*ARRAYSIZE*(*size));
profileID = realloc(profileID,sizeof(char*)*ARRAYSIZE*(*size));
}
//printf("k is %d\n",k);
modprofileID[k] = profile;
if (count > 999) fprintf(stderr,"count > 999 in find_LCAs\n");
prof = malloc(sizeof(char)*strlen(profile)+5);
sprintf(prof,"%d %s",count,profile);
profileID[k] = prof;
sums[k] = num;
firsttime = found_edge(fp,new,k);
firsttime = found_edge(fp,go,k);
k++;
} else if (num == sums[new]) {
firsttime = found_edge(fp,go,new);
}
else if (num == sums[go])
firsttime = found_edge(fp,new,go);
}
}
start = oldk;
}
return k;
}
//wraps around like mod function
int advance(int new, int oldk) {
if (new+1 != oldk)
return new+1;
else
return 0;
}
//returns 1 if num doesn't match anything in sums up to oldk
//returns 0 otherwise
int not_in_sums(unsigned long num, int k) {
int i;
for (i = 0; i < k; i++) {
if (sums[i] == num)
return 0;
}
return 1;
}
//converts binary rep to string of helices (profile)
char* convert_binary(unsigned long binary,int *count) {
int k,size = 1,num=0;
char val[ARRAYSIZE],*profile;
profile = malloc(sizeof(char)*ARRAYSIZE);
profile[0] = '\0';
for (k = 0; binary > 0; binary >>= 1, k++) {
//printf("binary is %u\n",binary);
if ((binary & 1) == 1) {
sprintf(val,"%d",k+1);
if (strlen(profile)+strlen(val) > ARRAYSIZE*size-2)
profile = realloc(profile,sizeof(char)*ARRAYSIZE*++size);
//printf("adding %s, with k %d, binary is %u, shifted is %u\n",table[k],k,binary,binary>>1);
strcat(profile,val);
strcat(profile," ");
num++;
}
}
*count = num;
return profile;
}
void insert_prof(int k, char *profile) {
int *val;
HASHTBL *hash = graph1[k-1];
if (!hash) {
if (!(hash = hashtbl_create(HASHSIZE,NULL))) {
fprintf(stderr, "ERROR: hashtbl_create() failed");
exit(EXIT_FAILURE);
}
graph1[k-1] = hash;
}
val = malloc(sizeof(int));
*val = 0;
hashtbl_insert(hash,profile,val);
//return val;
}
/*make edge
update parents' general freq in graph[] with child's spec. freq if exists
helix set difference = edge label
child and parent are indices
returns 1 if inserted into edge hash, 0 otherwise
*/
int found_edge(FILE *fp,int child,int parent) {
int count;
unsigned long xor;
char *edge,*childprof,*parentprof,*diff;
childprof = modprofileID[child];
parentprof = modprofileID[parent];
//printf("child is %s and parent is %s\n",childprof,parentprof);
edge = malloc(sizeof(char)*(strlen(childprof)+strlen(parentprof)+3));
sprintf(edge,"%s->%s",parentprof,childprof);
if (!hashtbl_get(edges,edge)) {
xor = sums[child] ^ sums[parent];
diff = convert_binary(xor,&count);
hashtbl_insert(edges,edge,diff);
//fprintf(fp,"\"%s\" -> \"%s\" [label = \"%s\", arrowhead = vee];\n",parentprof,childprof,diff);
return 1;
}
//printf("Found %d is child of %d\n",child,parent);
return 0;
}
void calc_gfreq(FILE *fp,int total) {
int i,j=0,length,*val,k,*freq;
unsigned long *sum;
char *fprof,*orig,*blank = " ",*helix,*copy;
KEY *node,*vert;
HASHTBL *hash;
sum = malloc(sizeof(unsigned long)*hashtbl_numkeys(cluster));
for (node = hashtbl_getkeys(cluster); node; node = node->next) {
orig = mystrdup(node->data);
length = atoi(strtok(orig,blank));
sum[j] = 0;
//find its binary rep
for (k = 0; k < length; k++) {
helix = strtok(NULL,blank);
//all helices are freq helices in binary hash
sum[j] += *((unsigned long*) hashtbl_get(binary,helix));
}
j++;
}
for (i = 0; i < total; i++) {
if (!strcmp(modprofileID[i]," ")) {
fprintf(fp,"\" \" [label =\"0\"];\n");
continue;
}
j=0;
for (node = hashtbl_getkeys(cluster); node; node = node->next) {
//printf("investigating %s and prof[%d] = %s\n",node->data,i,profileID[i]);
//printf("%u & %u = %u\n",sum[j],sums[i],sum[j]&sums[i]);
if ((sum[j++] & sums[i]) == sums[i]) {
fprof = profileID[i];
//printf("found parent[%d] %s of %s,adding %d\n",i,fprof,node->data,*((int*)hashtbl_get(cluster,node->data)));
copy = mystrdup(fprof);
length = atoi(strtok(copy,blank));
hash = graph1[length-1];
fprof = modprofileID[i];
val = hashtbl_get(hash,fprof);
if (val)
*val += *((int*)hashtbl_get(cluster,node->data));
else
fprintf(stderr,"error:val not found in hash()\n");
free(copy);
}
}
freq = hashtbl_get(cluster,profileID[i]);
helix = hashtbl_get(bracket,modprofileID[i]);
if (!freq)
fprintf(fp,"\"%s\" [label = \"0/%d\"];\n",modprofileID[i],*val);
else
fprintf(fp,"\"%s\" [label = \"%s\\n%d/%d\"];\n",modprofileID[i],helix,*freq,*val);
}
}
void print_edges(FILE *fp) {
int i, j,size = 2,oldsize;
char *edge,*diff=NULL;
edge = malloc(sizeof(char)*ARRAYSIZE*size);
for(i = 0; i < GRAPHSIZE; i++) {
if(graph[i].label != NULL) {
if (VERBOSE)
printf("node: '%s'\n", graph[i].label);
for(j = 0; j < graph[i].numNeighbors; j++) {
oldsize = size;
while (strlen(graph[i].label) + strlen(graph[i].neighbors[j]->label) + 3 > ARRAYSIZE*size)
size++;
if (oldsize != size)
edge = realloc(edge,sizeof(char)*ARRAYSIZE*size);
sprintf(edge,"%s->%s",graph[i].label,graph[i].neighbors[j]->label);
diff = hashtbl_get(edges,edge);
if (diff) {
fprintf(fp,"\"%s\" -> \"%s\" [label = \"%s\", arrowhead = vee];\n",graph[i].label,graph[i].neighbors[j]->label,diff);
} else {
fprintf(stderr, "edge %s found in graph not found in hash: print_edges()\n",edge);
}
//printf("'%s', ", graph[i].neighbors[j]->label);
}
}
}
}
//processes native helices if necessary; called by process_input
//returns id for i,j,k helix
int* process_native(int i, int j, int k) {
int *id = NULL,l;
char *key,tmp[ARRAYSIZE];
for (l=1; l < k; l++) {
sprintf(tmp,"%d %d",i+l,j-l);
id = hashtbl_get(bp,tmp);
if (id) {
for (l-- ; l >= 0; l--) {
sprintf(tmp,"%d %d",i+l,j+l);
hashtbl_insert(bp,tmp,id);
}
return id;
}
}
//printf("helix %d %d %d doesn't exist in sfold sample\n",i,j,k);
id = malloc(sizeof(int));
*id = hashtbl_numkeys(idhash)+1;
hashtbl_insert(bp,tmp,id);
sprintf(tmp,"%d",*id);
key = malloc(sizeof(char)*ARRAYSIZE);
sprintf(key,"%d %d %d",i,j,k);
hashtbl_insert(idhash,tmp,key);
return id;
}
//process input into three profiles Hs,Hu,Hn
//s = selected profiles, u = unselected in sample,n=in native only
//connects them, puts Hs in cluster with freq = 0 if not already there
int process_one_input(FILE *fp) {
HASHTBL *halfbrac;
FILE *file;
char temp[100],tmp[ARRAYSIZE],*profile,*fullprofile,*diff,*native,*diffn,*dup;
int i,j,k,*id,last=0,insample;
int numhelix = 0,fullnum = 0,natnum = 0;
int size = INIT_SIZE,size2 = INIT_SIZE,size3 = INIT_SIZE,size4 = INIT_SIZE,size5 = INIT_SIZE;
if (!(halfbrac = hashtbl_create(HASHSIZE,NULL))) {
fprintf(stderr, "ERROR: hashtbl_create() for halfbrac failed");
exit(EXIT_FAILURE);
}
if (!(input = hashtbl_create(HASHSIZE,NULL))) {
fprintf(stderr, "ERROR: hashtbl_create() for input failed");
exit(EXIT_FAILURE);
}
//longest = hashtbl_get(max,"longest");
profile = malloc(sizeof(char)*ARRAYSIZE*size);
fullprofile = malloc(sizeof(char)*ARRAYSIZE*size2);
diff = malloc(sizeof(char)*ARRAYSIZE*size3);
native = malloc(sizeof(char)*ARRAYSIZE*size4);
diffn = malloc(sizeof(char)*ARRAYSIZE*size5);
profile[0] = '\0';
fullprofile[0] = '\0';
diff[0] = '\0';
native[0] = '\0';
diffn[0] = '\0';
if (!(file = fopen(INPUT,"r")))
fprintf(stderr,"Cannot open %s\n",INPUT);
while (fgets(temp,100,file)) {
// if (sscanf(temp,"Structure %d (%d)",&i,&prob) == 2)
if (sscanf(temp,"%d %d %d",&i,&j,&k) == 3) {
insample = 1;
sprintf(tmp,"%d %d",i,j);
id = hashtbl_get(bp,tmp);
if (!id) {
id = process_native(i,j,k);
//printf("number in marginals %d\n",hashtbl_numkeys(marginals));
if (*id > hashtbl_numkeys(marginals))
insample = 0;
}
if (*id != last) {
sprintf(tmp,"%d",*id);
if (strlen(native)+strlen(tmp) > (ARRAYSIZE*size4-2))
native = realloc(native,ARRAYSIZE*(++size4));
sprintf(native,"%s%s ",native,tmp);
natnum++;
if (insample) {
fullnum++;
if (strlen(fullprofile)+strlen(tmp) > (ARRAYSIZE*size2-2))
fullprofile = realloc(fullprofile,ARRAYSIZE*(++size2));
sprintf(fullprofile,"%s%s ",fullprofile,tmp);
if (hashtbl_get(freq,tmp)) { //is a freq helix, save to profile
numhelix++;
if (strlen(profile)+strlen(tmp) > (ARRAYSIZE*size-2))
profile = realloc(profile,ARRAYSIZE*(++size));
//printf("adding %d to profile\n",*id);
sprintf(profile,"%s%s ",profile,tmp);
}
else { //if not freq record diff
if (strlen(diff)+strlen(tmp)+2 > ARRAYSIZE*size3)
diff = realloc(diff,ARRAYSIZE*(++size3));
sprintf(diff,"%s%s ",diff,tmp);
//printf("printing diff %s\n",diff);
}
}
else {
if (strlen(diffn)+strlen(tmp)+2 > ARRAYSIZE*size5)
diffn = realloc(diffn,ARRAYSIZE*(++size5));
sprintf(diffn,"%s%s ",diffn,tmp);
}
last = *id;
make_brackets(halfbrac,i,j,*id);
}
else if (VERBOSE)
printf("helix %d %d %d is duplicate with id %d: process_input()\n",i,j,k,*id);
}
}
native = sort_input(native,natnum);
//printf("native is now %s\n",native);
make_bracket_rep(halfbrac,native);
hashtbl_destroy(halfbrac);
fullprofile = sort_input(fullprofile,fullnum);
profile = sort_input(profile,numhelix);
//printf("native %s, fullprofile %s, profile %s, diff %s, diffn %s\n",native,fullprofile,profile,diff,diffn);
if (fullnum != natnum)
make_edge_and_node(fp,fullprofile,native,diffn,natnum);
if (numhelix != fullnum)
make_edge_and_node(fp,profile,fullprofile,diff,fullnum);
fprintf(fp,"\"%s\" [style = filled, fillcolor = gray60];\n",profile);
sprintf(tmp,"%d ",numhelix);
if (strlen(tmp)+strlen(profile) > ARRAYSIZE*size+1)
profile = realloc(profile,ARRAYSIZE*(++size));
dup = mystrdup(profile);
sprintf(profile,"%s%s",tmp,dup);
id = hashtbl_get(cluster,profile);
free(dup);
if (!id) {
id = malloc(sizeof(int));
*id = 0;
hashtbl_insert(cluster,profile,id);
//printf("inserting input %s into cluster\n",profile);
}
free(profile);
return numhelix;
}
//writes the destination node and edge to output file
void make_edge_and_node(FILE *fp,char *from, char *to,char *diff,int fullnum) {
char *brac;
HASHTBL *temp;
if (!(temp = hashtbl_create(HASHSIZE,NULL))) {
fprintf(stderr, "ERROR: hashtbl_create() for temp in make_edge_and_node() failed");
exit(EXIT_FAILURE);
}
fprintf(fp,"\"%s\" [style = filled,fillcolor = gray70];\n",to);
//how to handle getting general frequency?
diff = insert_diff(temp,diff);
//printf("diff is %s\n",diff);
brac = edge_label(temp,from,to,fullnum);
fprintf(fp,"\"%s\"-> \"%s\" [label =\" %s\\n%s \",fontsize=8];\n",from,to,diff,brac);
hashtbl_destroy(temp);
}
//processes input file containing structures of interest, in triplet form
//similar code to make_cluster: converts triplet to profile,
void process_input(FILE *fp) {
HASHTBL *halfbrac;
FILE *file;
char temp[100],tmp[ARRAYSIZE],*profile,*fullprofile,*diff;
int i,j,k,*id,last=0,lastprob;
int numhelix = 0,fullnum = 0,size = INIT_SIZE,size2 = INIT_SIZE,size3 = INIT_SIZE;
if (!(halfbrac = hashtbl_create(HASHSIZE,NULL))) {
fprintf(stderr, "ERROR: hashtbl_create() for halfbrac failed");
exit(EXIT_FAILURE);
}
if (!(input = hashtbl_create(HASHSIZE,NULL))) {
fprintf(stderr, "ERROR: hashtbl_create() for input failed");
exit(EXIT_FAILURE);
}
//longest = hashtbl_get(max,"longest");
profile = malloc(sizeof(char)*ARRAYSIZE*size);
fullprofile = malloc(sizeof(char)*ARRAYSIZE*size2);
diff = malloc(sizeof(char)*ARRAYSIZE*size3);
profile[0] = '\0';
fullprofile[0] = '\0';
diff[0] = '\0';
if (!(file = fopen(INPUT,"r")))
fprintf(stderr,"Cannot open %s\n",INPUT);
while (fgets(temp,100,file)) {
if (sscanf(temp,"%d %d %d",&i,&j,&k) == 3) {
sprintf(tmp,"%d %d",i,j);
id = hashtbl_get(bp,tmp);
//printf("id is %d for %d %d %d\n",id,i,j,k);
if (!id)
id = process_native(i,j,k);
if (*id != last) {
sprintf(tmp,"%d",*id);
if (hashtbl_get(freq,tmp)) { //is a freq helix, save to profile
numhelix++;
if (strlen(profile)+strlen(tmp) > (ARRAYSIZE*size-2))
profile = resize(&size,strlen(profile)+strlen(tmp)+1,profile);
//printf("adding %d to profile\n",*id);
sprintf(profile,"%s%s ",profile,tmp);
}
else {
if (strlen(diff)+strlen(tmp)+2 > ARRAYSIZE*size3)
diff = resize(&size3,strlen(diff)+strlen(tmp)+2,diff);
sprintf(diff,"%s%s ",diff,tmp);
//printf("printing diff %s\n",diff);
}
fullnum++;
if (strlen(fullprofile)+strlen(tmp) > (ARRAYSIZE*size-2))
fullprofile = resize(&size2,strlen(fullprofile)+strlen(tmp)+2,fullprofile);
sprintf(fullprofile,"%s%s ",fullprofile,tmp);
//printf("helix %d added is %s\n",fullnum,tmp);
last = *id;
make_brackets(halfbrac,i,j,*id);
}
else //if id == last
printf("helix %d %d %d is duplicate with id %d: process_input()\n",i,j,k,*id);
}
else if (sscanf(temp,"Structure %d (%d)",&i,&j) == 2) {
if (strlen(fullprofile) == 0) {
lastprob = j;
continue;
}
//printf("profile is %s, fullprofile %s with diff %s\n\n",profile,fullprofile,diff);
halfbrac = process_input_profile(fp,halfbrac,fullprofile,fullnum,profile,numhelix,diff,lastprob);
numhelix = 0;
fullnum = 0;
profile[0] = '\0';
fullprofile[0] = '\0';
diff[0] = '\0';
lastprob = j;
}
}
//printf("input profile is %s with fullprofile %s and diff %s\n",profile,fullprofile,diff);
halfbrac = process_input_profile(fp,halfbrac,fullprofile,fullnum,profile,numhelix,diff,lastprob);
free(profile);
hashtbl_destroy(halfbrac);
//finds edges between centroids
find_centroid_edges(fp);
}
//takes input profile and checks if in graph
//if so, changes node shape to hexagon
//if not, insert new vertex
HASHTBL* process_input_profile(FILE *fp,HASHTBL *brac,char *fullprofile, int fullnum,char *profile,int numhelix, char *diff, int prob) {
HASHTBL *hash, *temp=NULL;
char *diff1,*bracket,*difftrip;
int *val,k1=0,k2=0;
KEY *parent,*next;
if (!(temp = hashtbl_create(HASHSIZE,NULL))) {
fprintf(stderr, "ERROR: hashtbl_create() failed");
exit(EXIT_FAILURE);
}
make_bracket_rep(brac,fullprofile);
hashtbl_destroy(brac);
profile = sort_input(profile,numhelix);
//printf("(sorted) profile is %s with fullprofile %s and diff %s\n",profile,fullprofile,diff);
if ((hash = graph1[numhelix-1]) && (hashtbl_get(hash,profile))) {
if (numhelix == fullnum) {
//printf("case 1: full profile found in graph\n");
fullprofile = sort_input(fullprofile,numhelix);
} else {
//cannot use find_diff because fullprofile has helices not in table[]
//puts("case 2: profile found in graph");
diff = insert_diff(temp,diff);
bracket = edge_label(temp,profile,fullprofile,fullnum);
fprintf(fp,"\"%s\"-> \"%s\" [label =\" %s\\n%s \",fontsize=8,style = dotted];\n",profile,fullprofile,diff,bracket);
}
}
else {
/*
if (numhelix == fullnum)
puts("case 3: full profile not found");
else
puts("case 4: profile not found");
*/
for (parent = find_parents(profile); parent; parent = next) {
diff1 = find_diff(temp,parent->data,profile,&k1,&k2);
if (numhelix != fullnum) {
difftrip = insert_diff(temp,diff);
diff1 = realloc(diff1,strlen(diff1)+strlen(difftrip)+4);
//printf("for parent %s, diff1 is now %s, diff is %s and difftrip is %s\n",parent->data,diff1,diff,difftrip);
sprintf(diff1,"%s\\n%s",diff1,difftrip);
//printf("Diff is %s for parent %s of profile %s; diff %s for %s\n",diff1,parent->data,profile,difftrip,fullprofile);
}
bracket = edge_label(temp,parent->data,fullprofile,fullnum);
fprintf(fp,"\"%s\"-> \"%s\" [label =\" %s\\n%s \",fontsize=8,style = dotted];\n",parent->data,fullprofile,bracket,diff1);
next = parent->next;
free(parent);
}
}
//printf("%s has size %d and prob %d\n",fullprofile,fullnum,prob);
fprintf(fp,"\"%s\" [shape = hexagon];\n",fullprofile);
val = malloc(sizeof(int)*2);
val[0] = fullnum;
val[1] = prob;
hashtbl_insert(input,fullprofile,val);
hashtbl_destroy(temp);
if (!(brac = hashtbl_create(HASHSIZE,NULL))) {
fprintf(stderr, "ERROR: hashtbl_create() failed");
exit(EXIT_FAILURE);
}
return brac;
}
//find all parents of profile in graph; profile has only freq helices
//transitive reduction to the rescue again
KEY* find_parents(char *profile) {
int i,b1,b2,N,num = 0,k = 0;
HASHTBL *hash;
KEY *node,*parent,*begin = NULL;
begin = malloc(sizeof(KEY));
begin->data = "";
begin->next = NULL;
b2 = make_binary(profile,&num);
//printf("finding parents for %s of length %d and binary %d\n",profile,num,b2);
for (i = 0; i < num-1; i++) {
if (!(hash = graph1[i])) continue;
for (node = hashtbl_getkeys(hash); node; node = node->next) {
b1 = make_binary(node->data,&k);
//printf("investigating %sof size %d with binary %d\n",node->data,i+1,b1);
N = b1 & b2;
if (N == b1) {
//printf("found parent %sof size %d with binary %d\n",node->data,i+1,b1);
parent = malloc(sizeof(KEY));
parent->data = node->data;
parent->next = begin;
begin = parent;
}
}
}
return begin;
}
//diff contains helix nums that are inserted into a hash
//to be used before edge_label
//add triplet info to diff
char* insert_diff(HASHTBL *temp,char *diff) {
int size = INIT_SIZE;
char *blank = " ", *copy,*k,*val;
if (strlen(diff) == 0) return "";
copy = malloc(sizeof(char)*ARRAYSIZE*size);
copy[0] = '\0';
for (k = strtok(diff,blank); k; k = strtok(NULL,blank)) {
hashtbl_insert(temp,k,"1");
//printf("insert_diff: inserting %s into hash\n",k);
val = hashtbl_get(idhash,k);
if (strlen(copy)+strlen(k)+strlen(val)+5 > ARRAYSIZE*size)
copy = resize(&size,strlen(copy)+strlen(k)+strlen(val)+5,copy);
if (strlen(copy)> 0)
strcat(copy,"\\n");
sprintf(copy,"%s%s: %s",copy,k,val);
}
//free(diff);
return copy;
}
//sorts input profile; code similar to quicksort()
char* sort_input(char *profile,int length) {
int *array,i=0;
char *blank = " ", *k,*copy = mystrdup(profile);
array = malloc(sizeof(int)*length);
for (k = strtok(copy,blank); k ; k = strtok(NULL,blank))
array[i++] = atoi(k);
qsort(array,length,sizeof(int),compare);
profile[0] = '\0';
for (i = 0; i < length; i++) {
sprintf(profile,"%s%d ",profile,array[i]);
}
// printf("input profile sorted now %s\n",profile);
free(copy);
free(array);
return profile;
}
//inserts centroids into graph
//finds and prints edges between them
void find_centroid_edges(FILE *fp) {
int *i,*zero;
KEY *node;
HASHTBL *hash = NULL;
zero = malloc(sizeof(int));
*zero = 0;
for (node = hashtbl_getkeys(input); node; node = node->next) {
i = hashtbl_get(input,node->data);
if (*i-1 > graphsize)
*i = graphsize+1;
//printf("inserting %s into graph[%d]\n",node->data,*i-1);
if (!(hash = graph1[*i-1])) {
if (!(hash = hashtbl_create(HASHSIZE,NULL))) {
fprintf(stderr, "ERROR: hashtbl_create() for input failed");
exit(EXIT_FAILURE);
}
graph1[*i-1] = hash;
}
if (!hashtbl_get(hash,node->data))
hashtbl_insert(hash,node->data,zero);
}
}
int print_vertices(FILE *fp) {
int i,*val,size = 5,total = 0,size2=INIT_SIZE,*frq = NULL,zero = 0,start,end;
char *rank,*v;;
HASHTBL *hash;
KEY *node = NULL;
rank = malloc(sizeof(char)*ARRAYSIZE*size);
v = malloc(sizeof(char)*ARRAYSIZE*size2);
for (i = 0; !graph1[i]; i++) ;
start = i;
//for (node = hashtbl_getkeys(graph[i]); node; node = node->next)
//check_insert_edge(fp,"",node->data);
//print ranks
fputs("{ node [shape = plaintext]; ",fp);
if (graph1[graphsize])
end = graphsize;
else
end = graphsize-1;
for ( ; i <= end; i++) {
if (!graph1[i]) continue;
fprintf(fp,"%d",i+1);
if (i == end)
fprintf(fp,"; }\n");
else
fprintf(fp,"->");
}
for (i = start; i <= end; i++) {
if (!(hash = graph1[i])) continue;
//printf("printing level %d\n",i+1);
node = hashtbl_getkeys(hash);
sprintf(rank,"{ rank = same; %d;",i+1);
for (; node; node = node->next) {
if (strlen(node->data)+ 4 > ARRAYSIZE*size2-1) {
v = resize(&size2,strlen(node->data)+5,v);
//printf("resizing v of size %d to %d\n",strlen(v),size2);
}
sprintf(v,"%d %s",i+1,node->data);
frq = hashtbl_get(cluster,v);
if (!frq)
frq = &zero;
sprintf(v," \"%s\";",node->data);
val = hashtbl_get(hash,node->data);
// printf("found %s for %s\n",hashtbl_get(bracket,node->data),node->data);
if (VERBOSE)
printf("Vertex %swith frequency %d, originally %d\n",node->data,*val,*frq);
if (strlen(rank)+strlen(v) > ARRAYSIZE*size-1) {
// printf("resizing rank %s and v %s of size %d to %d\n",rank,v,strlen(rank)+strlen(v),size);
rank = resize(&size,strlen(rank)+strlen(v)+1,rank);
}
strcat(rank,v);
//fprintf(fp,"\"%s\" [label = \"%s ",node->data,hashtbl_get(bracket,node->data));
fprintf(fp,"\"%s\" [label = \"(%d/%d)\"];",node->data,*frq,*val);
/*
if (*frq == most)
fprintf(fp,"**");
fprintf(fp,"%s",hashtbl_get(bracket,node->data));
fprintf(fp,"(%d/%d)",*frq,*val);
if (*frq == most)
fprintf(fp,"**");
if (INPUT && (val = hashtbl_get(input,node->data)))
fprintf(fp,"\\n(%d)",val[1]);
fprintf(fp,"\",shape = box,style=filled,color=black,fillcolor=grey%d];",(1000-*frq)/20+49);
fprintf(fp,"\"%s\" [shape = box, label = \"%s (%d)\",style=filled,color=black,fillcolor=grey%d];\n",node->data,*val,(1000-*frq)/20+49);
*/
}
fprintf(fp,"%s }\n",rank);
total += hashtbl_numkeys(hash);
//v]0] = '\0';
}
return total;
}
//edges[LCA ID] = profile ID
//profile is LCA found, found[] is array of contributing originals, count their number
int find_edges(FILE *fp,char *profile, int *found, int count) {
int i;
char *origprof;
//for each contributing original profile...
for (i = 0; i < count; i++) {
origprof = modprofileID[found[i]];
//printf("original profile is %s, and subprofile is %swith total length %d\n",origprof,profile,strlen(profile)+strlen(origprof));
if (!strcmp(profile,origprof)) continue;
check_insert_edge(fp,profile,origprof);
}
return 0;
}
//checks whether edge exists and inserts if not
//ie insert if profile -> origprof doesn't exist yet
void check_insert_edge(FILE *fp,char *profile,char *origprof) {
int k1=0,k2=0; //*f1,*f2;
//double ratio;
char *diff,*copy,*brac;
HASHTBL *hash = NULL;
/*
hash = graph[k1-1];
f1 = hashtbl_get(hash,profile);
hash = graph[k2-1];
f2 = hashtbl_get(hash,origprof);
ratio = ((double)*f2)/((double)*f1);
// printf("ratio for %s and %s is %d/%d = %.2f\n",origprof,profile,*f2,*f1,ratio);
*/
if (strlen(profile) == 0)
profile = " ";
copy = malloc(sizeof(char)*(strlen(profile)+strlen(origprof)+4));
// if (strlen(profile)+strlen(origprof) > (ARRAYSIZE*size-4))
//copy = resize(&size,strlen(profile)+strlen(origprof)+4,copy);
sprintf(copy,"%s->%s",profile,origprof);
//printf("edge %s->%s\n",profile,origprof);
if (hashtbl_get(edges,copy)) return;
hashtbl_insert(edges,copy,"1");
if (!(hash = hashtbl_create(HASHSIZE,NULL))) {
fprintf(stderr, "ERROR: hashtbl_create() failed");
exit(EXIT_FAILURE);
}
diff = find_diff(hash,profile,origprof,&k1,&k2);
brac = edge_label(hash,profile,origprof,k2);
//color=gray%.0f,100-(ratio*100);
if (strlen(brac) > 1)
fprintf(fp,"\"%s\"-> \"%s\" [label=\" %s\\n%s \",fontsize=8];\n",profile,origprof,brac,diff);
//if (VERBOSE)
//printf("inserting edge %s\n",copy);
free(copy);
free(diff);
free(brac);
hashtbl_destroy(hash);
}
//finds helical difference between profile -> origprof
//k1 and k2 are num of helices in profile and origprof
//return difference with triplets
char* find_diff(HASHTBL *hash,char *profile, char *origprof, int *k1, int *k2) {
int size = INIT_SIZE,b1,b2,xor,i;
char *diff,*id;
diff = malloc(sizeof(char)*ARRAYSIZE*size);
diff[0] = '\0';
b1 = make_binary(profile,k1);
b2 = make_binary(origprof,k2);
xor = b1 ^ b2;
//printf("b1 is %d, b2 is %d, and xor is %d\n",b1,b2,xor);
for (i = 0; xor > 0; xor>>=1,i++) {
if ((xor & 1)==1) {
hashtbl_insert(hash,table[i],"1");
id = hashtbl_get(idhash,table[i]);
if (strlen(diff)+strlen(table[i])+strlen(id)+6 > ARRAYSIZE*size)
diff = resize(&size,strlen(diff)+strlen(table[i])+strlen(id)+6,diff);
if (strlen(diff)>1)
strcat(diff,"\\n");
sprintf(diff,"%s%s: %s",diff,table[i],id);
}
}
//printf("diff is %s between %s and %s\n",diff,origprof,profile);
return diff;
}
//finds the bracket notation for profile->origprof based on originating profile of size k
//difference between profile and origprof is in hash
//make sure origprof has a bracket rep (should be done in make_bracket_rep)
char* edge_label(HASHTBL *hash,char *profile, char *origprof,int k) {
int i=0,count = 0,j=0,num=0,*diff,*save,ind=0,m=0;
char *origbrac,*brac,*blank = "[]",*copy,*val;
char **array;
if (!(origbrac = hashtbl_get(bracket,origprof))) {
fprintf(stderr,"Error: origprof %s has no bracket representation in bracket: edge_label()\n",origprof);
return "";
}
// if (strlen(profile) == 0)
copy = mystrdup(origbrac);
brac = malloc(strlen(origbrac));
//printf("finding edge label between %s and %s\n",origbrac,profile);
array = malloc(sizeof(char*)*k);
diff = malloc(sizeof(int)*hashtbl_numkeys(hash));
save = malloc(sizeof(int)*hashtbl_numkeys(hash));
//put helices of origprof into array; array in chron order
for (val = strtok(copy,blank); val; val = strtok(NULL,blank)) {
//printf("val is %s\n",val);
if (i >= k) fprintf(stderr,"mismatch between k=%d and number of helices %d for %s: edge_label\n",k,i,origprof);
array[i++] = val;
//printf("val %s is at %d\n",val,i-1);
}
//save index in origprof of all diff helices; in ascending order
for (count = 0; count < i; count++) {
if (hashtbl_get(hash,array[count])) {
//printf("saving %s at %d to index %d\n",array[count],count,j);
diff[j++] = count;
}
}
copy[0] = '\0';
brac[0] = '\0';
count = 0;
j = -1;
//i is index for origbrac, j is index for what level we need to match ']'
//ind is index for level that increases for '[' and decreases for ']'
//num is number of '[' encountered
//count is index of different helix being proecessed
//m is index for array of origprof helices, to print out ones not in diff
for (i = 0; origbrac[i] != '\0'; i++) {
//keep track of how many '['s
if (origbrac[i] == '[') {
ind++;
val = mystrdup(array[m]);
if (diff[count] == num++) {
count++;
save[++j] = ind;
//printf("\nsaving %d to j=%d\n",ind,j);
strcat(copy,"{");
}
else {
//strcat(brac,"[");
//strcat(brac,array[m]);
sprintf(brac,"%s[%s",brac,array[m]);
strcat(copy,"[");
}
strcat(copy,val);
free(val);
m++;
}
//keep track of which level brackets are at
else if (origbrac[i] == ']') {
//printf("\nchecking ind %d against %d at %d\n",ind,save[j] puts("after check insert edge");,j);
if (j >= 0 && save[j] == ind--) {
j--;
strcat(copy,"}");
}
else {
strcat(brac,"]");
strcat(copy,"]");
}
}
}
if (!(hashtbl_get(bracket,profile))) {
hashtbl_insert(bracket,profile,brac);
//printf("new brac is %s for (%s ->) %s with copy %s\n",brac,origprof,profile,copy);
}
free(array);
free(diff);
free(save);
return copy;
}
int make_binary(char *profile,int *k) {
int sum=0,*bin = NULL;
char *blank = " ";
char *copy = strdup(profile);
char *helix;
for (helix = strtok(copy,blank); helix; helix = strtok(NULL,blank)) {
bin = hashtbl_get(binary,helix);
(*k)++;
if (!bin) continue;
sum += *bin;
}
free(copy);
return sum;
}
char* print_edge(KEY *node,char **table,int v,int* sum) {
int count = 0,val;
char *v1 = malloc(sizeof(char)*30);
v1[0] = '\0';
if (v == 0) {
printf("%s-- %s\n",node->data,"E ");
return v1;
}
for (val = (v & 1); v > 0; v >>= 1, count++, val = (v & 1))
if (val == 1) {
*sum += *((int*) hashtbl_get(binary,table[count]));
strcat(v1,table[count]);
strcat(v1," ");
}
printf("%s-- %s\n",node->data,v1);
return v1;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "tokens.h"
#include "../utils/utils.h"
Token* new_token(int* value, int col, int line)
{
Token* output = (Token*) malloc(sizeof(Token));
output->value = value;
output->line_index = line;
output->col_index = col;
output->tokenstream = NULL; // Set by tokenizer
return output;
}
void free_token(Token* token)
{
free_utf8_string(token->value);
free(token);
}
|
C
|
/**
* File: memory_manager.h
* ---------------
* Defines the interface for the memory manager module.
*
* This module handles memory operations.
*/
#ifndef memory_manager_h
#define memory_manager_h
//Language Libraries
#include <stdio.h>
//Data Structures Libraries
#include "../../datastructures/singly_linked_list/singly_linked_list.h"
struct Memory {
SinglyLinkedList *map;
};
//since this is global variable. then map will be NULL initially.
struct Memory Global_Memory_Storage;
/**
* Function: smalloc
* ---------------
* malloc the needed size of bytes and return the address
*/
void *smalloc(size_t size);
/**
* Function: sfree
* ---------------
* free the give pointer of data
*/
void sfree(void *ptr);
/**
* Function: memory_clear
* ---------------
* clear all the malloced data
*/
void memory_clear();
/**
* Function: srealloc
* ---------------
* re alloc the memory to different size.
*/
void *srealloc(void *ptr, uint64_t newSize);
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.